From 2fc3029a861a46afeec0ef488d731b5d195e7521 Mon Sep 17 00:00:00 2001 From: NiJingzhe <1448976235@qq.com> Date: Thu, 20 Aug 2026 14:52:07 +0800 Subject: [PATCH] refactor: split operator facade and public connectors --- .../src/generated/normalized_product.ts | 16 +- scene-contract/src/generated/scene.ts | 15 +- scene-contract/src/resources.ts | 2 +- scene-contract/src/validation.ts | 125 +- scene-contract/test/corpus.test.ts | 8 +- src/simplecadapi/__init__.py | 9 +- src/simplecadapi/_operation_support.py | 2208 ++++ src/simplecadapi/_operators_boolean.py | 603 + src/simplecadapi/_operators_features.py | 952 ++ src/simplecadapi/_operators_geometry.py | 3345 +++++ src/simplecadapi/_operators_product.py | 1129 ++ src/simplecadapi/_operators_selection.py | 177 + src/simplecadapi/_operators_sketch.py | 1612 +++ src/simplecadapi/_operators_transform.py | 432 + .../artifacts/assembly_definition.py | 4 +- src/simplecadapi/artifacts/assembly_io.py | 64 +- src/simplecadapi/artifacts/references.py | 54 +- src/simplecadapi/assembly.py | 138 +- src/simplecadapi/assembly_solver.py | 179 +- src/simplecadapi/auto_tools/auto_docs_gen.py | 14 + src/simplecadapi/auto_tools/make_export.py | 27 +- src/simplecadapi/boolean.py | 603 + src/simplecadapi/build/assembly_builder.py | 33 +- src/simplecadapi/build/dependency_graph.py | 14 +- src/simplecadapi/build/part_builder.py | 8 - src/simplecadapi/connector.py | 210 +- .../assembly-definition-2.schema.json | 2 +- .../contracts/part-definition-2.schema.json | 5 +- src/simplecadapi/core.py | 2 +- src/simplecadapi/evolve.py | 10 +- src/simplecadapi/geometry.py | 4394 +++++++ src/simplecadapi/operations.py | 10674 +--------------- src/simplecadapi/scene/compiler.py | 140 +- .../profiles/scene-1.0-ocp-glb-2.profile.json | 5 +- .../contracts/rules/scene-1.0-rules.json | 2 +- .../schemas/normalized-product-1.schema.json | 59 +- .../schemas/render-profile-2.schema.json | 5 +- .../contracts/schemas/scene-1.0.schema.json | 21 +- .../contracts/schemas/scene-2.0.schema.json | 2 +- .../scene/generated/normalized_product.py | 14 +- src/simplecadapi/scene/generated/scene.py | 12 +- src/simplecadapi/scene/product_scene.py | 62 +- src/simplecadapi/scene/resources.py | 2 +- src/simplecadapi/scene/validation.py | 144 +- src/simplecadapi/selection.py | 326 + src/simplecadapi/serializer.py | 81 +- src/simplecadapi/sketch.py | 16 +- src/simplecadapi/std/bearing.py | 15 +- src/simplecadapi/surface.py | 8 +- src/simplecadapi/transform.py | 433 + test/fixtures/scene-contract/corpus.json | 1334 +- test/test_artifact_contract.py | 18 +- test/test_assembly_builder.py | 33 +- test/test_part_interface.py | 1 - test/test_product_assembly.py | 232 +- test/test_product_packages.py | 12 +- test/test_scene_compiler.py | 20 +- test/test_scene_contract.py | 10 +- test/test_serialization.py | 61 +- test/test_stdlib_bearing.py | 55 +- tools/generate_scene_contract_fixtures.py | 2 +- .../scene_contract_fixtures/authored_cases.py | 30 +- .../scene_contract_fixtures/package_cases.py | 31 +- .../scene_contract_fixtures/resource_cases.py | 20 +- tools/scene_contract_fixtures/scene_cases.py | 37 +- .../schema_field_matrix.py | 3 +- 66 files changed, 18123 insertions(+), 12191 deletions(-) create mode 100644 src/simplecadapi/_operation_support.py create mode 100644 src/simplecadapi/_operators_boolean.py create mode 100644 src/simplecadapi/_operators_features.py create mode 100644 src/simplecadapi/_operators_geometry.py create mode 100644 src/simplecadapi/_operators_product.py create mode 100644 src/simplecadapi/_operators_selection.py create mode 100644 src/simplecadapi/_operators_sketch.py create mode 100644 src/simplecadapi/_operators_transform.py create mode 100644 src/simplecadapi/boolean.py create mode 100644 src/simplecadapi/geometry.py create mode 100644 src/simplecadapi/selection.py create mode 100644 src/simplecadapi/transform.py diff --git a/scene-contract/src/generated/normalized_product.ts b/scene-contract/src/generated/normalized_product.ts index b64de3ec..8c292e8e 100644 --- a/scene-contract/src/generated/normalized_product.ts +++ b/scene-contract/src/generated/normalized_product.ts @@ -14,7 +14,7 @@ export type Connector = { } & { connector_id: ProductId; name: string | null; - anchor: GeometryAnchor | PlacementAnchor | ForwardedAnchor; + anchor: GeometryAnchor | PlacementAnchor; geometry_ref?: null | GeometryRef; }; /** @@ -77,18 +77,12 @@ export interface Transform { y_axis: Vec3; z_axis: Vec3; } -export interface ForwardedAnchor { - anchor_kind: "forwarded"; - source_component_id: ProductId; - source_connector_id: ProductId; - offset: null | Transform; -} export interface Assembly { kind: "assembly"; assembly_id: ProductId; name: string | null; components: Component[]; - connectors: Connector[]; + public_connectors: PublicConnector[]; constraints: Constraint[]; grounded_component_ids: ProductId[]; metadata: { @@ -101,6 +95,12 @@ export interface Component { definition_ref: StructuralId; local_placement: Transform; } +export interface PublicConnector { + public_connector_id: ProductId; + component_id: ProductId; + connector_id: ProductId; + name: string | null; +} export interface Constraint { constraint_id: ProductId; constraint_kind: "fixed" | "revolute" | "prismatic" | "gear" | "belt" | "rack_pinion"; diff --git a/scene-contract/src/generated/scene.ts b/scene-contract/src/generated/scene.ts index f9d85dc3..beaeca00 100644 --- a/scene-contract/src/generated/scene.ts +++ b/scene-contract/src/generated/scene.ts @@ -112,10 +112,10 @@ export type Connector = { owner_definition_id: StructuralId; connector_id: ProductId; name: string | null; - anchor_kind: "geometry" | "placement" | "forwarded"; + anchor_kind: "geometry" | "placement" | "public"; local_transform: Transform; target?: ConnectorTarget; - forwarded_from?: ForwardedFrom; + source_connector_snapshot_id: null | StructuralId; source: null | ModelOperationSource | ManualConnectorSource | ProductPackageConnectorSource; sdk_metadata: { [k: string]: unknown; @@ -482,17 +482,6 @@ export interface ConnectorTarget { entity_asset_id: Hash; entity_id: string; } -/** - * This interface was referenced by `SceneDocument`'s JSON-Schema - * via the `definition` "forwardedFrom". - */ -export interface ForwardedFrom { - source_component_id: ProductId; - source_definition_id: StructuralId; - source_connector_id: ProductId; - source_connector_snapshot_id: StructuralId; - offset: null | Transform; -} /** * This interface was referenced by `SceneDocument`'s JSON-Schema * via the `definition` "modelOperationSource". diff --git a/scene-contract/src/resources.ts b/scene-contract/src/resources.ts index f801cfc7..e988aa3a 100644 --- a/scene-contract/src/resources.ts +++ b/scene-contract/src/resources.ts @@ -20,7 +20,7 @@ export const BASE_LIMITS = { connectors: 100_000, cameras: 1000, hierarchy_depth: 256, - forwarded_connector_depth: 64, + public_connector_depth: 64, entities_per_sidecar: 500_000, entities_total: 2_000_000, triangle_vertices_per_asset: 2_000_000, diff --git a/scene-contract/src/validation.ts b/scene-contract/src/validation.ts index 058f7471..49b80e51 100644 --- a/scene-contract/src/validation.ts +++ b/scene-contract/src/validation.ts @@ -9,7 +9,6 @@ import { import { type GlbInfo, preflightGlb } from "./glb.js"; import { hasRootPointerPolicy, issue, pointer, report, type ValidationArtifact, type ValidationIssue, type ValidationReport } from "./report.js"; import { BASE_LIMITS, preflightResourceCount, type SceneResourceLimits } from "./resources.js"; -import { composeRigidTransforms, rigidTransformsEqual } from "./transforms.js"; import type { ValidateFunction } from "ajv"; import { schemaErrors, @@ -257,22 +256,22 @@ export function resourceCountIssues( } }); const connectors = Array.isArray(value.connectors) ? value.connectors.filter(isRecord) : []; - const forwardEdges = new Map(); + const publicEdges = new Map(); for (const connector of connectors) { - if (connector.anchor_kind === "forwarded" && isRecord(connector.forwarded_from)) { - forwardEdges.set(connector.connector_snapshot_id, connector.forwarded_from.source_connector_snapshot_id); + if (connector.anchor_kind === "public" && connector.source_connector_snapshot_id !== null && connector.source_connector_snapshot_id !== undefined) { + publicEdges.set(connector.connector_snapshot_id, connector.source_connector_snapshot_id); } } - for (const start of forwardEdges.keys()) { + for (const start of publicEdges.keys()) { const seen = new Set(); let current: unknown = start; let depth = 0; - while (forwardEdges.has(current) && !seen.has(current)) { + while (publicEdges.has(current) && !seen.has(current)) { seen.add(current); - current = forwardEdges.get(current); + current = publicEdges.get(current); depth += 1; - if (depth > limits.forwarded_connector_depth) { - issues.push(issue("resource_limit_exceeded", "/connectors", "forwarded connector depth exceeds resource limit", "budget")); + if (depth > limits.public_connector_depth) { + issues.push(issue("resource_limit_exceeded", "/connectors", "public connector depth exceeds resource limit", "budget")); break; } } @@ -685,7 +684,7 @@ function sceneSemanticIssues(scene: JsonRecord): ValidationIssue[] { } const connectorMap = new Map(connectors.map((record) => [record.connector_snapshot_id, record])); const connectorIdsByOwner = new Map>(); - const forwardEdges = new Map(); + const publicEdges = new Map(); connectors.forEach((connector, index) => { const path = `/connectors/${index}`; const owner = definitionMap.get(connector.owner_definition_id); @@ -711,11 +710,11 @@ function sceneSemanticIssues(scene: JsonRecord): ValidationIssue[] { if (anchorKind === "geometry" && owner.kind !== "part") { issues.push(issue("connector_invalid", `${path}/owner_definition_id`, "geometry connector owner must be a Part")); } - if (anchorKind === "placement" && owner.kind !== "part" && owner.kind !== "assembly") { - issues.push(issue("connector_invalid", `${path}/owner_definition_id`, "connector owner must be a Product definition")); + if (anchorKind === "placement" && owner.kind !== "part") { + issues.push(issue("connector_invalid", `${path}/owner_definition_id`, "placement connector owner must be a Part")); } - if (anchorKind === "forwarded" && owner.kind !== "assembly") { - issues.push(issue("connector_invalid", `${path}/owner_definition_id`, "forwarded connector owner must be an Assembly")); + if (anchorKind === "public" && owner.kind !== "assembly") { + issues.push(issue("connector_invalid", `${path}/owner_definition_id`, "public connector owner must be an Assembly")); } const connectorSource = connector.source; if (sourceKind === "model") { @@ -735,90 +734,33 @@ function sceneSemanticIssues(scene: JsonRecord): ValidationIssue[] { } const transform = transformIssue(connector.local_transform, `${path}/local_transform`); if (transform !== null) issues.push(transform); - if (anchorKind === "forwarded") { - const forwarded = isRecord(connector.forwarded_from) ? connector.forwarded_from : {}; - const sourceSnapshot = forwarded.source_connector_snapshot_id; + const sourceSnapshot = connector.source_connector_snapshot_id; + if (anchorKind === "public") { const sourceConnector = connectorMap.get(sourceSnapshot); - if ( - sourceConnector === undefined || - sourceConnector.owner_definition_id !== forwarded.source_definition_id || - sourceConnector.connector_id !== forwarded.source_connector_id - ) { - issues.push(issue("connector_invalid", `${path}/forwarded_from`, "forwarded connector source snapshot ownership is invalid")); - } - forwardEdges.set(connector.connector_snapshot_id, sourceSnapshot); - if (forwarded.offset !== null && forwarded.offset !== undefined) { - const offset = transformIssue(forwarded.offset, `${path}/forwarded_from/offset`); - if (offset !== null) issues.push(offset); - } - if (owner.kind === "assembly") { - const ownerNodes = nodes.filter((node) => - node.definition_id === connector.owner_definition_id && - isRecord(node.source) && - node.source.kind === "product_occurrence" - ); - const sourceChildren: JsonRecord[] = []; - for (const ownerNode of ownerNodes) { - const ownerNodeSource = ownerNode.source as JsonRecord; - const expectedPath = [ - ...(Array.isArray(ownerNodeSource.component_path) ? ownerNodeSource.component_path : []), - forwarded.source_component_id, - ]; - const matches = nodes.filter((node) => - isRecord(node.source) && - node.source.kind === "product_occurrence" && - node.source.root_id === ownerNodeSource.root_id && - Array.isArray(node.source.component_path) && - node.source.component_path.length === expectedPath.length && - node.source.component_path.every((component, componentIndex) => component === expectedPath[componentIndex]) && - node.parent_node_id === ownerNode.node_id - ); - if (matches.length !== 1 || matches[0].definition_id !== forwarded.source_definition_id) { - issues.push(issue("connector_invalid", `${path}/forwarded_from`, "forwarded connector source component is not one exact direct child")); - } else { - sourceChildren.push(matches[0]); - } + if (sourceConnector === undefined) { + issues.push(issue("connector_invalid", `${path}/source_connector_snapshot_id`, "public connector source snapshot does not exist")); + } else { + if (sourceConnector.anchor_kind === "public") { + publicEdges.set(connector.connector_snapshot_id, sourceSnapshot); } - if (sourceChildren.length > 1) { - const expected = canonicalJsonBytes(sourceChildren[0].transform); - if (sourceChildren.slice(1).some((child) => !canonicalJsonBytes(child.transform).equals(expected))) { - issues.push(issue("connector_invalid", `${path}/forwarded_from`, "forwarded connector source child transforms differ between owner occurrences")); - } - } - if (sourceChildren.length > 0 && sourceConnector !== undefined) { - const childTransform = sourceChildren[0].transform; - const sourceTransform = sourceConnector.local_transform; - const offset = forwarded.offset ?? { - origin: [0, 0, 0], - x_axis: [1, 0, 0], - y_axis: [0, 1, 0], - z_axis: [0, 0, 1], - }; - if ( - isRecord(childTransform) && transformIssue(childTransform, "") === null && - isRecord(sourceTransform) && transformIssue(sourceTransform, "") === null && - isRecord(offset) && transformIssue(offset, "") === null && - isRecord(connector.local_transform) && transformIssue(connector.local_transform, "") === null - ) { - const expected = composeRigidTransforms(composeRigidTransforms(childTransform, sourceTransform), offset); - if (!rigidTransformsEqual(connector.local_transform, expected)) { - issues.push(issue("connector_invalid", `${path}/local_transform`, "forwarded connector transform does not match child, source, and offset composition")); - } - } + if (sourceConnector.owner_definition_id === connector.owner_definition_id) { + issues.push(issue("connector_invalid", `${path}/source_connector_snapshot_id`, "public connector source must belong to a child definition")); } } + } else if (sourceSnapshot !== null && sourceSnapshot !== undefined) { + issues.push(issue("connector_invalid", `${path}/source_connector_snapshot_id`, "non-public connector cannot reference a source snapshot")); } }); - for (const start of forwardEdges.keys()) { + for (const start of publicEdges.keys()) { const seen = new Set(); let current: unknown = start; - while (forwardEdges.has(current)) { + while (publicEdges.has(current)) { if (seen.has(current)) { - issues.push(issue("connector_invalid", "/connectors", "forwarded connector graph contains a cycle")); + issues.push(issue("connector_invalid", "/connectors", "public connector graph contains a cycle")); break; } seen.add(current); - current = forwardEdges.get(current); + current = publicEdges.get(current); } } const cameras = Array.isArray(scene.cameras) ? scene.cameras.filter(isRecord) : []; @@ -1046,7 +988,6 @@ function normalizedProductSemanticIssues(value: JsonRecord): ValidationIssue[] { issues.push(issue("id_duplicate", "/connectors", "connector IDs must be unique")); } if (value.kind !== "assembly") return issues; - const components = Array.isArray(value.components) ? value.components.filter(isRecord) : []; const componentIds = components.map((component) => component.component_id); if (new Set(componentIds).size !== componentIds.length) { @@ -1057,6 +998,16 @@ function normalizedProductSemanticIssues(value: JsonRecord): ValidationIssue[] { if (grounded.some((componentId) => !componentSet.has(componentId))) { issues.push(issue("reference_missing", "/grounded_component_ids", "grounded component does not exist")); } + const publicConnectors = Array.isArray(value.public_connectors) ? value.public_connectors.filter(isRecord) : []; + const publicIds = publicConnectors.map((connector) => connector.public_connector_id); + if (new Set(publicIds).size !== publicIds.length) { + issues.push(issue("id_duplicate", "/public_connectors", "public connector IDs must be unique")); + } + publicConnectors.forEach((connector, index) => { + if (!componentSet.has(connector.component_id)) { + issues.push(issue("reference_missing", `/public_connectors/${index}/component_id`, "public connector component does not exist")); + } + }); const constraints = Array.isArray(value.constraints) ? value.constraints.filter(isRecord) : []; const constraintIds = constraints.map((constraint) => constraint.constraint_id); if (new Set(constraintIds).size !== constraintIds.length) { diff --git a/scene-contract/test/corpus.test.ts b/scene-contract/test/corpus.test.ts index 0728093d..ec9ab067 100644 --- a/scene-contract/test/corpus.test.ts +++ b/scene-contract/test/corpus.test.ts @@ -154,7 +154,7 @@ test("shared positive case names cannot drift to negative expectations", () => { if (Object.hasOwn(record, "error")) assert.equal(record.error, null, label); } } - assert.equal(positiveNames.length, 30); + assert.equal(positiveNames.length, 29); }); test("strict JSON rejects duplicate keys and protects ordinary object semantics", () => { @@ -1006,12 +1006,12 @@ test("resource profile and exact boundary cases match Python", async (context) = let value: JsonRecord; if (kind === "collection") value = { [field!]: Array(count).fill(null) }; else if (kind === "hierarchy") value = { nodes: [{ source: { component_path: Array(count).fill("x") } }] }; - else if (kind === "forwarded") { + else if (kind === "public") { value = { connectors: Array.from({ length: count }, (_unused, index) => ({ - anchor_kind: "forwarded", + anchor_kind: "public", connector_snapshot_id: `c${index}`, - forwarded_from: { source_connector_snapshot_id: `c${index + 1}` }, + source_connector_snapshot_id: `c${index + 1}`, })), }; } else throw new Error(`unknown resource count kind: ${kind}`); diff --git a/src/simplecadapi/__init__.py b/src/simplecadapi/__init__.py index 58b961eb..c4b65c88 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -106,7 +106,6 @@ from .operations import ( # 基础几何创建; 变换操作; 3D操作; 标签 add_bspline_rsketch, add_circle_rsketch, add_component_rassembly, - add_connector_rassembly, add_connector_rpart, add_fixed_constraint_rassembly, add_gear_constraint_rassembly, @@ -145,7 +144,7 @@ from .operations import ( # 基础几何创建; 变换操作; 3D操作; 标签 explain_tag, extrude_rsolid, fillet_rsolid, - forward_connector_rassembly, + set_public_connector_rassembly, get_sketch_entity_rsketchref, get_sketch_point_rsketchref, ground_component_rassembly, @@ -221,7 +220,7 @@ from .operations import ( # 基础几何创建; 变换操作; 3D操作; 标签 unground_component_rassembly, union_rsolid, ) -from .assembly import Assembly, Component +from .assembly import Assembly, Component, PublicConnectorRef from .connector import Connector, ConnectorAnchor, ConnectorRef, GeometryRef from .constraint import Constraint, ConstraintReport, ConstraintResidual, ScalarLimit from .material import Material @@ -485,8 +484,7 @@ __all__ = [ "make_vertex_connector_rconnector", "make_placement_connector_rconnector", "add_connector_rpart", - "add_connector_rassembly", - "forward_connector_rassembly", + "set_public_connector_rassembly", "make_connector_ref_rconnectorref", "make_scalar_limit_rscalarlimit", "ground_component_rassembly", @@ -740,6 +738,7 @@ __all__ = [ "SimpleCADError", "Assembly", "Component", + "PublicConnectorRef", "Connector", "ConnectorAnchor", "ConnectorRef", diff --git a/src/simplecadapi/_operation_support.py b/src/simplecadapi/_operation_support.py new file mode 100644 index 00000000..47c3e835 --- /dev/null +++ b/src/simplecadapi/_operation_support.py @@ -0,0 +1,2208 @@ +"""Shared imports, constants, and helpers for operator modules.""" + +from __future__ import annotations + +import re + +import uuid + +from pathlib import Path + +from typing import ( + Any, + Callable, + Dict, + List, + Mapping, + Optional, + Sequence, + Set, + Tuple, + Union, + cast, +) + +from dataclasses import dataclass, asdict + +import math + +import numpy as np + +from ._vendor_warning_filters import suppress_vendor_deprecation_warnings + +from .errors import SimpleCADError, raise_harness_error + +suppress_vendor_deprecation_warnings() + +from OCP.BRepCheck import BRepCheck_Analyzer + +from OCP.BRepBuilderAPI import BRepBuilderAPI_MakeVertex + +from OCP.Precision import Precision + +from OCP.gp import gp_Ax2, gp_Dir, gp_Pnt + +from OCP.TopoDS import TopoDS + +from .core import ( + Vertex, + Edge, + Wire, + Face, + Shell, + Solid, + Compound, + AnyShape, + WORLD_CS, + clone_semantic_shape_view, + _same_semantic_topology, + get_current_cs, + use_coordinate_system, +) + +from .autotag import apply_tracking_tags_to_delta + +from .expr import ScalarLike, evaluate_scalar, evaluate_value + +from .units import DIMENSIONLESS, LENGTH, expression_uses_units, infer_dimension + +from .graph import ( + attach_graph_node, + attach_semantic_graph_node, + get_active_session, + record_operation, + record_operation_if_active, + suspend_graph_recording, +) + +from .ql import ShapeSelector, output_role + +from .assembly import Assembly, Component, PublicConnectorRef + +from .assembly_solver import ( + coupling_phase_offset, + inspect_assembly_constraints, + measure_constraint_residual, + solve_assembly_constraints, +) + +from .connector import Connector, ConnectorAnchor, ConnectorRef, GeometryRef + +from .constraint import Constraint, ConstraintReport, ConstraintResidual, ScalarLimit + +from .material import Material + +from .part import Part + +from .placement import Placement, compose_placements, identity_placement + +from .sketch import Sketch, SketchRef, SketchSolveResult + +from .tagging import ( + LineagePolicy, + SemanticCapabilityError, + TagBinding, + TagBindingScope, + TagCertainty, + TagEvidence, + TagLifecycle, + TagProducer, + TagProducerKind, + TagPropagation, + TagScope, + TagTarget, + TagTargetKind, + TagEvidenceKind, + TopologyPropagation, + lineage_policy_allows, + normalize_tag, + normalize_tag_scope, +) + +from .topology import ( + SemanticDelta, + SemanticRef, + TopoDelta, + TopoRoleEntry, + TopoEntry, + TopoKind, + TopoRef, + topo_ref_to_dict, +) + +from .tracking import ( + TrackingPolicy, + TrackedBooleanResult, + TrackedResult, + _topo_id, + current_tracking_policy, + tracked_box, + tracked_chamfer, + tracked_cone, + tracked_cylinder, + tracked_cut, + tracked_extrude, + tracked_fillet, + tracked_intersect, + tracked_mirror, + tracked_loft, + tracked_revolve, + tracked_rotate, + tracked_shell, + tracked_sweep, + tracked_twisted_sweep, + tracked_translate, + track_union_history, +) + +from .kernel.ocp_builders import ( + make_sphere_solid, +) + +from ._brep_region import read_artifact + +from .kernel.ocp_curves import ( + make_arc_angle_edge, + make_arc_three_point_edge, + make_bspline_edge, + make_circle_edge, + make_helix_wire, + make_interpolated_bspline_edge, + make_line_edge, + make_polyline_wire, + make_wire_from_edges as make_wire_from_edges_ocp, +) + +from .kernel.ocp_features import ( + make_face_from_wire as make_face_from_wire_ocp, + make_face_from_wires as make_face_from_wires_ocp, + make_helical_sweep_solid, + make_loft_solid, + make_sweep_solid, +) + +from .kernel.ocp_transforms import ( + mirror_shape_ocp, + rotate_shape_ocp, + place_shape_ocp, + translate_shape_ocp, +) + +from .kernel.ocp_booleans import ( + common_shapes, + cut_shapes, + fuse_shapes, + fuse_shapes_with_history, + solids_of, +) + +from .kernel.ocp_topology import faces_of as faces_of_ocp + +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, + free_boundaries as free_boundaries_ocp, + make_bezier_surface, + make_cylindrical_surface, + make_filling_face, + make_gordon_surface, + make_loft_shell, + make_ruled_face, + sew_faces_with_history as sew_faces_with_history_ocp, + shell_from_face, + trim_surface_face, +) + +from .kernel.ocp_mesh import solid_from_shell + +from .kernel.ocp_mesh import tessellate_face + +from .kernel.ocp_properties import bounding_box, distance as ocp_distance + +_DEFAULT_UNION_GLUE = False + +_DEFAULT_UNION_TOL_FACTOR = 1e-7 + +_DEFAULT_UNION_TOL_MIN = 1e-7 + +_DEFAULT_UNION_TOL_MAX = 1e-5 + +_OP_MAKE_POINT_RVERTEX = "make_point_rvertex" + +_OP_LOAD_BREP_REGION_RSOLID = "load_brep_region_rsolid" + +_OP_LOAD_BREP_REGION_RSHELL = "load_brep_region_rshell" + +_OP_MAKE_LINE_REDGE = "make_line_redge" + +_OP_MAKE_CIRCLE_REDGE = "make_circle_redge" + +_OP_MAKE_THREE_POINT_ARC_REDGE = "make_three_point_arc_redge" + +_OP_MAKE_ANGLE_ARC_REDGE = "make_angle_arc_redge" + +_OP_MAKE_SPLINE_REDGE = "make_spline_redge" + +_OP_MAKE_INTERPOLATED_SPLINE_REDGE = "make_interpolated_spline_redge" + +_OP_MAKE_HELIX_REDGE = "make_helix_redge" + +_OP_MAKE_WIRE_FROM_EDGES_RWIRE = "make_wire_from_edges_rwire" + +_OP_MAKE_FACE_FROM_WIRE_RFACE = "make_face_from_wire_rface" + +_OP_MAKE_FACE_FROM_WIRES_RFACE = "make_face_from_wires_rface" + +_OP_MAKE_TRANSLATE_RSHAPE = "make_translate_rshape" + +_OP_MAKE_ROTATE_RSHAPE = "make_rotate_rshape" + +_OP_MAKE_MIRROR_RSHAPE = "make_mirror_rshape" + +_OP_MAKE_EXTRUDE_RSOLID = "make_extrude_rsolid" + +_OP_MAKE_REVOLVE_RSOLID = "make_revolve_rsolid" + +_OP_MAKE_LOFT_RSOLID = "make_loft_rsolid" + +_OP_MAKE_SWEEP_RSOLID = "make_sweep_rsolid" + +_OP_MAKE_TWISTED_SWEEP_RSOLID = "make_twisted_sweep_rsolid" + +_OP_MAKE_UNION_RSOLID = "make_union_rsolid" + +_OP_MAKE_CUT_RSOLID = "make_cut_rsolid" + +_OP_MAKE_INTERSECT_RSOLID = "make_intersect_rsolid" + +_OP_MAKE_CUT_RFACE = "make_2d_cut_rface" + +_OP_MAKE_UNION_RFACE = "make_2d_union_rface" + +_OP_MAKE_INTERSECT_RFACE = "make_2d_intersect_rface" + +_OP_MAKE_FILLET_RSOLID = "make_fillet_rsolid" + +_OP_MAKE_CHAMFER_RSOLID = "make_chamfer_rsolid" + +_OP_MAKE_SHELL_RSOLID = "make_shell_rsolid" + +_OP_MAKE_SELECT_RVERTEX = "make_select_rvertex" + +_OP_MAKE_SELECT_REDGE = "make_select_redge" + +_OP_MAKE_SELECT_RWIRE = "make_select_rwire" + +_OP_MAKE_SELECT_RFACE = "make_select_rface" + +_OP_MAKE_SELECT_RSHELL = "make_select_rshell" + +_OP_MAKE_SELECT_RSOLID = "make_select_rsolid" + +_OP_APPLY_TAG_RSELECTION = "apply_tag_rselection" + +_OP_MAKE_SKETCH_RSKETCH = "make_sketch_rsketch" + +_OP_ADD_POINT_RSKETCH = "add_point_rsketch" + +_OP_ADD_LINE_RSKETCH = "add_line_rsketch" + +_OP_ADD_CIRCLE_RSKETCH = "add_circle_rsketch" + +_OP_ADD_ARC_RSKETCH = "add_arc_rsketch" + +_OP_ADD_BSPLINE_RSKETCH = "add_bspline_rsketch" + +_OP_MAKE_WIRE_FROM_SKETCH_RWIRE = "make_wire_from_sketch_rwire" + +_OP_MAKE_FACE_FROM_SKETCH_RFACE = "make_face_from_sketch_rface" + +_OP_MAKE_MATERIAL_RMATERIAL = "make_material_rmaterial" + +_OP_MAKE_PLACEMENT_RPLACEMENT = "make_placement_rplacement" + +_OP_MAKE_IDENTITY_PLACEMENT_RPLACEMENT = "make_identity_placement_rplacement" + +_OP_MAKE_PART_RPART = "make_part_rpart" + +_OP_MAKE_ASSIGN_MATERIAL_RPART = "make_assign_material_rpart" + +_OP_MAKE_ASSEMBLY_RASSEMBLY = "make_assembly_rassembly" + +_OP_MAKE_ADD_COMPONENT_RASSEMBLY = "make_add_component_rassembly" + +_OP_MAKE_PLACE_COMPONENT_RASSEMBLY = "make_place_component_rassembly" + +_OP_MAKE_COMPOUND_FROM_ASSEMBLY_RCOMPOUND = "make_compound_from_assembly_rcompound" + +_OP_MAKE_FACE_CONNECTOR_RCONNECTOR = "make_face_connector_rconnector" + +_OP_MAKE_EDGE_CONNECTOR_RCONNECTOR = "make_edge_connector_rconnector" + +_OP_MAKE_VERTEX_CONNECTOR_RCONNECTOR = "make_vertex_connector_rconnector" + +_OP_MAKE_PLACEMENT_CONNECTOR_RCONNECTOR = "make_placement_connector_rconnector" + +_OP_MAKE_ADD_CONNECTOR_RPART = "make_add_connector_rpart" + +_OP_MAKE_SET_PUBLIC_CONNECTOR_RASSEMBLY = "make_set_public_connector_rassembly" + +_OP_MAKE_CONNECTOR_REF_RCONNECTORREF = "make_connector_ref_rconnectorref" + +_OP_MAKE_SCALAR_LIMIT_RSCALARLIMIT = "make_scalar_limit_rscalarlimit" + +_OP_MAKE_GROUND_COMPONENT_RASSEMBLY = "make_ground_component_rassembly" + +_OP_MAKE_UNGROUND_COMPONENT_RASSEMBLY = "make_unground_component_rassembly" + +_OP_MAKE_FIXED_CONSTRAINT_RASSEMBLY = "make_fixed_constraint_rassembly" + +_OP_MAKE_REVOLUTE_CONSTRAINT_RASSEMBLY = "make_revolute_constraint_rassembly" + +_OP_MAKE_PRISMATIC_CONSTRAINT_RASSEMBLY = "make_prismatic_constraint_rassembly" + +_OP_MAKE_GEAR_CONSTRAINT_RASSEMBLY = "make_gear_constraint_rassembly" + +_OP_MAKE_BELT_CONSTRAINT_RASSEMBLY = "make_belt_constraint_rassembly" + +_OP_MAKE_RACK_PINION_CONSTRAINT_RASSEMBLY = "make_rack_pinion_constraint_rassembly" + +_OP_MAKE_SOLVE_ASSEMBLY_CONSTRAINTS_RASSEMBLY = ( + "make_solve_assembly_constraints_rassembly" +) + +_OPERATION_OUTPUT_ROLE_CARDINALITY: Dict[str, Tuple[Tuple[str, str], ...]] = { + "make_box_rsolid": ( + ("box.bottom", "one"), + ("box.top", "one"), + ("box.front", "one"), + ("box.back", "one"), + ("box.left", "one"), + ("box.right", "one"), + ), + "make_cylinder_rsolid": ( + ("cylinder.start", "one"), + ("cylinder.end", "one"), + ("cylinder.side", "one"), + ("cylinder.start_boundary", "one"), + ("cylinder.end_boundary", "one"), + ("cylinder.seam", "one"), + ), + "make_cone_rsolid": ( + ("cone.start", "one"), + ("cone.end", "one"), + ("cone.side", "one"), + ("cone.start_boundary", "one"), + ("cone.end_boundary", "one"), + ("cone.seam", "one"), + ), + _OP_MAKE_EXTRUDE_RSOLID: ( + ("extrusion.start", "one"), + ("extrusion.end", "one"), + ("extrusion.side", "many"), + ), + _OP_MAKE_REVOLVE_RSOLID: ( + ("revolution.start", "one"), + ("revolution.end", "one"), + ("revolution.side", "many"), + ), + _OP_MAKE_FILLET_RSOLID: (("fillet.patch", "many"),), + _OP_MAKE_CHAMFER_RSOLID: (("chamfer.patch", "many"),), + _OP_MAKE_SHELL_RSOLID: ( + ("shell.body_face", "many"), + ("shell.offset_face", "many"), + ("shell.closing_descendant", "many"), + ("shell.wall", "many"), + ), + _OP_MAKE_LOFT_RSOLID: ( + ("loft.start", "one"), + ("loft.end", "one"), + ("loft.side", "many"), + ), + _OP_MAKE_SWEEP_RSOLID: ( + ("sweep.start", "one"), + ("sweep.end", "one"), + ("sweep.side", "many"), + ), + "make_loft_rshell": ( + ("loft.start_wire", "one"), + ("loft.end_wire", "one"), + ("loft.side", "many"), + ), + _OP_MAKE_TWISTED_SWEEP_RSOLID: ( + ("twisted_sweep.start", "one"), + ("twisted_sweep.end", "one"), + ("twisted_sweep.side", "many"), + ), +} + +_SKETCH_CONSTRAINT_OPS = { + "coincident": "make_constrain_coincident_rsketch", + "connect": "make_constrain_coincident_rsketch", + "point_on": "make_constrain_point_on_rsketch", + "horizontal": "make_constrain_horizontal_rsketch", + "vertical": "make_constrain_vertical_rsketch", + "parallel": "make_constrain_parallel_rsketch", + "perpendicular": "make_constrain_perpendicular_rsketch", + "collinear": "make_constrain_collinear_rsketch", + "tangent": "make_constrain_tangent_rsketch", + "concentric": "make_constrain_concentric_rsketch", + "midpoint": "make_constrain_midpoint_rsketch", + "symmetric": "make_constrain_symmetric_rsketch", + "equal_length": "make_constrain_equal_length_rsketch", + "equal_radius": "make_constrain_equal_radius_rsketch", + "distance": "make_constrain_distance_rsketch", + "distance_x": "make_constrain_distance_x_rsketch", + "distance_y": "make_constrain_distance_y_rsketch", + "length": "make_constrain_length_rsketch", + "angle": "make_constrain_angle_rsketch", + "radius": "make_constrain_radius_rsketch", + "diameter": "make_constrain_diameter_rsketch", + "fix": "make_constrain_fix_rsketch", +} + +def _orthonormal_plane_axes( + normal: Tuple[float, float, float], +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + normal_vec = np.array(normal, dtype=float) + norm = float(np.linalg.norm(normal_vec)) + if norm <= 1e-12: + raise ValueError("法向量不能是零向量") + z_axis = normal_vec / norm + ref_vec = ( + np.array([1.0, 0.0, 0.0]) if abs(z_axis[2]) > 0.9 else np.array([0.0, 0.0, 1.0]) + ) + x_axis = np.cross(z_axis, ref_vec) + x_norm = float(np.linalg.norm(x_axis)) + if x_norm <= 1e-12: + raise ValueError("无法根据给定法向量构建局部坐标系") + x_axis = x_axis / x_norm + y_axis = np.cross(z_axis, x_axis) + y_axis = y_axis / float(np.linalg.norm(y_axis)) + return z_axis, x_axis, y_axis + +def _sketch_plane_in_current_coordinates( + plane: Any, +) -> Dict[str, Tuple[float, float, float]]: + if isinstance(plane, str): + token = plane.upper() + frames = { + "XY": ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), + "XZ": ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 0.0, 1.0)), + "YZ": ((0.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), + } + if token not in frames: + raise ValueError( + "Sketch plane must be 'XY', 'XZ', 'YZ', or a plane mapping" + ) + origin, x_axis, y_axis = frames[token] + elif isinstance(plane, Mapping): + origin = tuple(plane.get("origin", (0.0, 0.0, 0.0))) + x_axis = tuple(plane.get("x_axis", (1.0, 0.0, 0.0))) + y_axis = tuple(plane.get("y_axis", (0.0, 1.0, 0.0))) + else: + raise ValueError("Sketch plane must be 'XY', 'XZ', 'YZ', or a plane mapping") + + cs = get_current_cs() + global_origin = cs.transform_point(np.asarray(origin, dtype=float)) + global_x_axis = cs.transform_vector(np.asarray(x_axis, dtype=float)) + global_y_axis = cs.transform_vector(np.asarray(y_axis, dtype=float)) + return { + "origin": tuple(float(value) for value in global_origin), + "x_axis": tuple(float(value) for value in global_x_axis), + "y_axis": tuple(float(value) for value in global_y_axis), + } + +def _wrap_public_api_error( + *, + operation: str, + what_happened: str, + possible_causes: Sequence[str], + how_to_fix: Sequence[str], + error: BaseException, +) -> None: + raise_harness_error( + operation=operation, + what_happened=what_happened, + possible_causes=possible_causes, + how_to_fix=how_to_fix, + error=error, + ) + +def _semantic_id_registry(kind: str) -> Set[str]: + session = get_active_session() + if session is None: + return set() + registry = getattr(session, "_simplecad_semantic_ids", None) + if registry is None: + registry = {} + setattr(session, "_simplecad_semantic_ids", registry) + return cast(Set[str], registry.setdefault(kind, set())) + +def _reserve_semantic_id(kind: str, value: str) -> None: + session = get_active_session() + if session is None: + return + registry = _semantic_id_registry(kind) + if value in registry: + raise ValueError(f"duplicate {kind} id in active GraphSession: {value}") + registry.add(value) + +def _semantic_created( + entity_type: str, entity_id: str, metadata: Optional[Dict[str, Any]] = None +) -> SemanticDelta: + return SemanticDelta( + created=( + SemanticRef( + graph_id="pending", + node_id="pending", + entity_type=entity_type, + entity_id=entity_id, + ), + ), + metadata=dict(metadata or {}), + ) + +def _semantic_modified( + entity_type: str, entity_id: str, metadata: Optional[Dict[str, Any]] = None +) -> SemanticDelta: + return SemanticDelta( + modified=( + SemanticRef( + graph_id="pending", + node_id="pending", + entity_type=entity_type, + entity_id=entity_id, + ), + ), + metadata=dict(metadata or {}), + ) + +def _material_params(material: Material) -> Dict[str, object]: + return material.to_dict() + +def _part_params(part: Part) -> Dict[str, object]: + return {"part_id": part.part_id, "name": part.name} + +def _assembly_params(assembly: Assembly) -> Dict[str, object]: + return {"assembly_id": assembly.assembly_id, "name": assembly.name} + +def _connector_params(connector: Connector) -> Dict[str, object]: + return connector.to_dict() + +def _connector_ref_params(connector_ref: ConnectorRef) -> Dict[str, object]: + return connector_ref.to_dict() + +def _scalar_limit_params(limit: ScalarLimit) -> Dict[str, object]: + return limit.to_dict() + +def _constraint_params(constraint: Constraint) -> Dict[str, object]: + return constraint.to_dict() + +def _resolve_union_tol( + solids: Sequence[Solid], tol: Optional[float] +) -> Optional[float]: + """Resolve and validate the fuzzy tolerance for boolean union. + + The default is scale-aware and intentionally conservative. An explicit + tolerance is accepted only when it is finite and non-negative; silently + forwarding NaN or a negative fuzzy value to OCC makes failures difficult + to diagnose and can vary across kernel versions. + """ + + if tol is not None: + resolved = float(tol) + if not math.isfinite(resolved) or resolved < 0.0: + raise ValueError("tol must be a finite non-negative number") + return resolved + + bbox_min = np.array([np.inf, np.inf, np.inf], dtype=float) + bbox_max = np.array([-np.inf, -np.inf, -np.inf], dtype=float) + + for solid in solids: + bb = bounding_box(solid.wrapped) + bbox_min = np.minimum(bbox_min, np.array([bb.xmin, bb.ymin, bb.zmin])) + bbox_max = np.maximum(bbox_max, np.array([bb.xmax, bb.ymax, bb.zmax])) + + span = float(np.linalg.norm(bbox_max - bbox_min)) + if not np.isfinite(span) or span <= 0: + return _DEFAULT_UNION_TOL_MIN + + return min( + max(span * _DEFAULT_UNION_TOL_FACTOR, _DEFAULT_UNION_TOL_MIN), + _DEFAULT_UNION_TOL_MAX, + ) + +def _union_separation_diagnostic( + results: Sequence[Solid], tol: Optional[float] +) -> Optional[str]: + """Return a short diagnostic for multi-solid union results.""" + + if len(results) < 2: + return None + + effective_tol = float(tol or 0.0) + nearest_gap_above_tol: Optional[float] = None + + for i in range(len(results)): + for j in range(i + 1, len(results)): + gap = float(ocp_distance(results[i].wrapped, results[j].wrapped)) + if gap > effective_tol: + if nearest_gap_above_tol is None or gap < nearest_gap_above_tol: + nearest_gap_above_tol = gap + + if nearest_gap_above_tol is None: + return None + + return ( + f"union produced {len(results)} separated solids; " + f"nearest detected gap is about {nearest_gap_above_tol:.6g}, " + f"which exceeds tol={effective_tol:.6g}" + ) + +def _require_union_solid(result_shape: Any, effective_tol: Optional[float]) -> Solid: + result_shapes = solids_of(result_shape) + if len(result_shapes) == 1: + return Solid(result_shapes[0]) + + failure_reason = "union did not produce a valid solid" + diagnostic = _union_separation_diagnostic( + [Solid(result) for result in result_shapes], effective_tol + ) + if diagnostic: + failure_reason = diagnostic + elif len(result_shapes) > 1: + failure_reason = ( + f"union produced {len(result_shapes)} solids at zero detected gap; " + "the inputs likely meet only along an edge, vertex, tangent point, " + "or tangent curve, which is not one manifold solid" + ) + raise ValueError(failure_reason) + +def _evaluate_tracked_union( + solids: Sequence[Solid], + *, + glue: bool, + tol: Optional[float], + clean: bool, +) -> TrackedBooleanResult: + fused = fuse_shapes_with_history( + [solid.wrapped for solid in solids], + glue=glue, + tol=tol, + clean=clean, + ) + result = _require_union_solid(fused.shape, tol) + return track_union_history(solids, result, fused.history, fused.section_edges) + +def _flatten_boolean_solids( + args: Sequence[Union[Solid, Sequence[Solid]]], operation_name: str +) -> List[Solid]: + """Flatten nested boolean inputs into a validated solid list.""" + + def _flatten(values: Sequence[Union[Solid, Sequence[Solid]]]) -> List[Solid]: + flattened: List[Solid] = [] + for value in values: + if isinstance(value, Solid): + flattened.append(value) + elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + flattened.extend( + _flatten(cast(Sequence[Union[Solid, Sequence[Solid]]], value)) + ) + else: + raise ValueError(f"{operation_name}函数只接受Solid类型的对象") + return flattened + + return _flatten(args) + +def _require_single_boolean_solid( + result_shapes: Sequence[Any], + *, + operation: str, + failure_reason: str, +) -> Solid: + if not result_shapes: + raise ValueError(failure_reason) + if len(result_shapes) != 1: + raise ValueError( + f"{operation} 期望得到单个Solid结果,但内核返回了 {len(result_shapes)} 个实体。" + ) + return Solid(result_shapes[0]) + +def _merge_topo_deltas(deltas: Sequence[TopoDelta]) -> Optional[TopoDelta]: + if not deltas: + return None + preserved: List[TopoRef] = [] + modified: List[TopoRef] = [] + generated: List[TopoRef] = [] + deleted: List[TopoRef] = [] + section_edges: List[TopoRef] = [] + entries: List[TopoEntry] = [] + raw_event: Dict[str, Any] = {"steps": []} + + for idx, delta in enumerate(deltas): + preserved.extend(delta.preserved) + modified.extend(delta.modified) + generated.extend(delta.generated) + deleted.extend(delta.deleted) + section_edges.extend(delta.section_edges) + entries.extend(delta.entries) + raw_event["steps"].append( + { + "index": idx, + "preserved": len(delta.preserved), + "modified": len(delta.modified), + "generated": len(delta.generated), + "deleted": len(delta.deleted), + "section_edges": len(delta.section_edges), + } + ) + + return TopoDelta( + preserved=tuple(preserved), + modified=tuple(modified), + generated=tuple(generated), + deleted=tuple(deleted), + section_edges=tuple(section_edges), + entries=tuple(entries), + raw_event=raw_event, + ) + +def _copy_runtime_state(source: AnyShape, target: AnyShape) -> AnyShape: + runtime = getattr(source, "_runtime", None) + if isinstance(runtime, dict): + # A transformed BRep owns a new evaluated geometry. Copy semantic and + # graph provenance, but never carry the source's geometry-dependent + # mesh or mesh error into the new wrapper. + target._runtime = { + key: value + for key, value in runtime.items() + if not key == "mesh.error" + and not key == "mesh.default" + and not key.startswith("mesh:") + } + return target + +def _attach_lineage_from_source( + source: AnyShape, + target: AnyShape, + *, + derivation: str, + op: str, + coverage: str = "complete", +) -> None: + coverage_rank = {"complete": 0, "partial": 1, "none": 2} + + def aggregate(*values: object) -> str: + normalized = [str(value) for value in values if value in coverage_rank] + return ( + max(normalized, key=coverage_rank.__getitem__) if normalized else "complete" + ) + + effective_coverage = aggregate( + coverage, + source._get_runtime("semantic.lineage.coverage"), + ) + bindings = { + binding.binding_id: (binding, effective_coverage) + for binding in source._local_tag_bindings() + if lineage_policy_allows(binding.propagation, derivation) + } + for witness in source._tag_lineage: + if not lineage_policy_allows( + witness.binding.propagation, witness.derivation + ) or not lineage_policy_allows(witness.binding.propagation, derivation): + continue + existing = bindings.get(witness.binding.binding_id) + witness_coverage = aggregate(effective_coverage, witness.coverage) + bindings[witness.binding.binding_id] = ( + witness.binding, + aggregate(existing[1], witness_coverage) if existing else witness_coverage, + ) + for binding, binding_coverage in bindings.values(): + evidence = TagEvidence( + "topology_change", + { + "op": op, + "derivation": derivation, + "coverage": binding_coverage, + }, + ) + target._add_tag_lineage( + binding, + derivation=derivation, + source_topo_id=source.topo_id, + evidence=evidence, + coverage=binding_coverage, + ) + target._set_runtime( + "semantic.lineage.coverage", + aggregate( + target._get_runtime("semantic.lineage.coverage"), + effective_coverage, + ), + ) + +def _current_context_metadata() -> Dict[str, Tuple[float, float, float]]: + cs = get_current_cs() + return { + "origin": (float(cs.origin[0]), float(cs.origin[1]), float(cs.origin[2])), + "x_axis": (float(cs.x_axis[0]), float(cs.x_axis[1]), float(cs.x_axis[2])), + "y_axis": (float(cs.y_axis[0]), float(cs.y_axis[1]), float(cs.y_axis[2])), + "z_axis": (float(cs.z_axis[0]), float(cs.z_axis[1]), float(cs.z_axis[2])), + } + +def _attach_track_summary( + shape: AnyShape, + *, + op: str, + delta: Optional[object] = None, + delta_entries: Optional[Dict[str, Dict[str, object]]] = None, +) -> AnyShape: + track_payload: Dict[str, object] = {"op": op} + if delta is not None: + track_payload["has_delta"] = True + track_payload["preserved"] = len(getattr(delta, "preserved", ())) + track_payload["modified"] = len(getattr(delta, "modified", ())) + track_payload["generated"] = len(getattr(delta, "generated", ())) + track_payload["deleted"] = len(getattr(delta, "deleted", ())) + if delta_entries: + track_payload["entry_count"] = len(delta_entries) + shape.set_metadata("track", track_payload) + return shape + +def _vector_like_to_tuple(value: Any) -> Optional[Tuple[float, float, float]]: + if value is None: + return None + if hasattr(value, "x") and hasattr(value, "y") and hasattr(value, "z"): + return (float(value.x), float(value.y), float(value.z)) + if isinstance(value, (list, tuple)) and len(value) == 3: + return (float(value[0]), float(value[1]), float(value[2])) + return None + +def _make_selector_hint(shape: AnyShape) -> Dict[str, object]: + hint: Dict[str, object] = { + "kind": type(shape).__name__.lower(), + "tags": shape._list_tags(), + } + + if isinstance(shape, Edge): + hint["length"] = float(shape.get_length()) + try: + hint["start"] = tuple( + float(v) for v in shape.get_start_vertex().get_coordinates() + ) + hint["end"] = tuple( + float(v) for v in shape.get_end_vertex().get_coordinates() + ) + except Exception: + center = getattr(shape.wrapped, "Center", lambda: None)() + center_tuple = _vector_like_to_tuple(center) + if center_tuple is not None: + hint["center"] = center_tuple + elif isinstance(shape, Face): + hint["area"] = float(shape.get_area()) + center_tuple = _vector_like_to_tuple(shape.get_center()) + normal_tuple = _vector_like_to_tuple(shape.get_normal_at()) + if center_tuple is not None: + hint["center"] = center_tuple + if normal_tuple is not None: + hint["normal"] = normal_tuple + elif isinstance(shape, Wire): + hint["edge_count"] = len(shape.get_edges()) + hint["closed"] = bool(shape.is_closed()) + elif isinstance(shape, Vertex): + hint["coordinates"] = tuple(float(v) for v in shape.get_coordinates()) + elif isinstance(shape, Shell): + hint["face_count"] = len(shape.get_faces()) + bb = bounding_box(shape.wrapped) + hint["bbox"] = { + "min": (float(bb.xmin), float(bb.ymin), float(bb.zmin)), + "max": (float(bb.xmax), float(bb.ymax), float(bb.zmax)), + } + elif isinstance(shape, Solid): + hint["volume"] = float(shape.get_volume()) + bb = bounding_box(shape.wrapped) + hint["bbox"] = { + "min": (float(bb.xmin), float(bb.ymin), float(bb.zmin)), + "max": (float(bb.xmax), float(bb.ymax), float(bb.zmax)), + } + elif isinstance(shape, Compound): + hint["volume"] = float(shape.get_volume()) + hint["solid_count"] = len(shape.get_solids()) + bb = bounding_box(shape.wrapped) + hint["bbox"] = { + "min": (float(bb.xmin), float(bb.ymin), float(bb.zmin)), + "max": (float(bb.xmax), float(bb.ymax), float(bb.zmax)), + } + + return hint + +def _jsonable_geo_value(value: object) -> object: + if value is None or isinstance(value, (str, bool)): + return value + if isinstance(value, np.integer): + return int(value) + if isinstance(value, np.floating): + return float(value) + if isinstance(value, (int, float)): + return value + if hasattr(value, "to_tuple"): + try: + return [float(v) for v in value.to_tuple()] + except Exception: + pass + if hasattr(value, "x") and hasattr(value, "y") and hasattr(value, "z"): + try: + return [float(value.x), float(value.y), float(value.z)] + except Exception: + pass + if isinstance(value, dict): + return {str(k): _jsonable_geo_value(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_jsonable_geo_value(v) for v in value] + return str(value) + +def _bbox_selector_payload(shape: AnyShape) -> Optional[Dict[str, List[float]]]: + try: + bb = bounding_box(shape.wrapped) + return { + "min": [float(bb.xmin), float(bb.ymin), float(bb.zmin)], + "max": [float(bb.xmax), float(bb.ymax), float(bb.zmax)], + } + except Exception: + return None + +def _shape_geom_type(shape: AnyShape) -> Optional[str]: + try: + from OCP.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Surface + from OCP.GeomAbs import ( + GeomAbs_BSplineCurve, + GeomAbs_BSplineSurface, + GeomAbs_BezierCurve, + GeomAbs_BezierSurface, + GeomAbs_Circle, + GeomAbs_Cone, + GeomAbs_Cylinder, + GeomAbs_Line, + GeomAbs_Plane, + GeomAbs_Sphere, + GeomAbs_Torus, + ) + + if isinstance(shape, Edge): + curve_type = BRepAdaptor_Curve(shape.wrapped).GetType() + mapping = { + GeomAbs_Line: "LINE", + GeomAbs_Circle: "CIRCLE", + GeomAbs_BSplineCurve: "BSPLINE", + GeomAbs_BezierCurve: "BEZIER", + } + return mapping.get( + curve_type, + str(curve_type).replace("GeomAbs_CurveType.GeomAbs_", "").upper(), + ) + if isinstance(shape, Face): + surface_type = BRepAdaptor_Surface(shape.wrapped).GetType() + mapping = { + GeomAbs_Plane: "PLANE", + GeomAbs_Cylinder: "CYLINDER", + GeomAbs_Cone: "CONE", + GeomAbs_Sphere: "SPHERE", + GeomAbs_Torus: "TORUS", + GeomAbs_BSplineSurface: "BSPLINE", + GeomAbs_BezierSurface: "BEZIER", + } + return mapping.get( + surface_type, + str(surface_type).replace("GeomAbs_SurfaceType.GeomAbs_", "").upper(), + ) + except Exception: + return None + return None + +def _shape_kind_token(shape: AnyShape) -> str: + if isinstance(shape, Vertex): + return "vertex" + if isinstance(shape, Edge): + return "edge" + if isinstance(shape, Wire): + return "wire" + if isinstance(shape, Face): + return "face" + if isinstance(shape, Shell): + return "shell" + if isinstance(shape, Solid): + return "solid" + if isinstance(shape, Compound): + return "compound" + return type(shape).__name__.lower() + +def _selection_op_for_shape(shape: AnyShape) -> Optional[str]: + if isinstance(shape, Vertex): + return _OP_MAKE_SELECT_RVERTEX + if isinstance(shape, Edge): + return _OP_MAKE_SELECT_REDGE + if isinstance(shape, Wire): + return _OP_MAKE_SELECT_RWIRE + if isinstance(shape, Face): + return _OP_MAKE_SELECT_RFACE + if isinstance(shape, Shell): + return _OP_MAKE_SELECT_RSHELL + if isinstance(shape, Solid): + return _OP_MAKE_SELECT_RSOLID + return None + +def _candidate_shapes_for_selection(source: AnyShape, kind: str) -> List[AnyShape]: + if kind == "edge": + if hasattr(source, "get_edges"): + return list(source.get_edges()) + return [source] if isinstance(source, Edge) else [] + if kind == "face": + if isinstance(source, (Shell, Solid, Compound)): + return list(source.get_faces()) + return [source] if isinstance(source, Face) else [] + if kind == "wire": + if isinstance(source, Face): + return [source.get_outer_wire(), *source.get_inner_wires()] + if hasattr(source, "get_children"): + return [ + cast(AnyShape, child) + for child in source.get_children() + if isinstance(child, Wire) + ] + return [source] if isinstance(source, Wire) else [] + if kind == "vertex": + if isinstance(source, Edge): + return cast(List[AnyShape], source.get_children()) + if hasattr(source, "get_children"): + return [ + cast(AnyShape, child) + for child in source.get_children() + if isinstance(child, Vertex) + ] + return [source] if isinstance(source, Vertex) else [] + if kind == "shell": + if isinstance(source, Compound): + return [ + cast(AnyShape, child) + for child in source.get_children() + if isinstance(child, Shell) + ] + return [source] if isinstance(source, Shell) else [] + if kind == "solid": + if isinstance(source, Compound): + return cast(List[AnyShape], source.get_solids()) + return [source] if isinstance(source, Solid) else [] + if kind == "compound": + return [source] if isinstance(source, Compound) else [] + return [] + +def _source_selection_index( + source: AnyShape, selected: AnyShape, *, kind: str +) -> Optional[int]: + for idx, candidate in enumerate(_candidate_shapes_for_selection(source, kind)): + try: + if candidate.same_topology(selected): + return idx + except Exception: + pass + if getattr(candidate, "topo_id", None) == getattr(selected, "topo_id", None): + return idx + return None + +def _make_geo_selector( + shape: AnyShape, + *, + source_shape: Optional[AnyShape] = None, +) -> Dict[str, object]: + kind = _shape_kind_token(shape) + selector: Dict[str, object] = { + "mode": "geo_exact", + "kind": kind, + "metadata_geo": _jsonable_geo_value(shape.get_metadata("geo", {})), + } + provenance = shape.get_metadata("provenance") + if isinstance(shape, Face) and isinstance(provenance, dict): + artifact_sha256 = provenance.get("artifact_sha256") + source_face_id = provenance.get("source_face_id") + if isinstance(artifact_sha256, str) and isinstance(source_face_id, str): + selector["brep_region_ref"] = { + "artifact_sha256": artifact_sha256, + "source_face_id": source_face_id, + } + # `source_shape` is intentionally not serialized as a source index. The + # canonical selector is geometry-based; source lineage comes from graph inputs. + + bbox_payload = _bbox_selector_payload(shape) + if bbox_payload is not None: + selector["bbox"] = bbox_payload + + geom_type = _shape_geom_type(shape) + if geom_type is not None: + selector["geom_type"] = geom_type + + if isinstance(shape, Vertex): + selector["coordinates"] = [float(v) for v in shape.get_coordinates()] + elif isinstance(shape, Edge): + selector["length"] = float(shape.get_length()) + center = shape.get_center() + selector["center"] = [float(center.x), float(center.y), float(center.z)] + try: + selector["start"] = [ + float(v) for v in shape.get_start_vertex().get_coordinates() + ] + selector["end"] = [ + float(v) for v in shape.get_end_vertex().get_coordinates() + ] + except Exception: + pass + elif isinstance(shape, Wire): + selector["edge_count"] = len(shape.get_edges()) + selector["closed"] = bool(shape.is_closed()) + elif isinstance(shape, Face): + selector["area"] = float(shape.get_area()) + center = shape.get_center() + normal = shape.get_normal_at() + selector["center"] = [float(center.x), float(center.y), float(center.z)] + selector["normal"] = [float(normal.x), float(normal.y), float(normal.z)] + selector["edge_count"] = len(shape.get_edges()) + selector["inner_wire_count"] = len(shape.get_inner_wires()) + elif isinstance(shape, Shell): + selector["face_count"] = len(shape.get_faces()) + elif isinstance(shape, Solid): + selector["volume"] = float(shape.get_volume()) + center = shape.get_center() if hasattr(shape, "get_center") else None + if center is not None: + selector["center"] = [float(center.x), float(center.y), float(center.z)] + elif isinstance(shape, Compound): + selector["volume"] = float(shape.get_volume()) + selector["solid_count"] = len(shape.get_solids()) + return selector + +def _record_geo_selection_nodes( + source_shape: AnyShape, + selected_shapes: Sequence[AnyShape], +) -> List[str]: + session = get_active_session() + if session is None: + return [] + source_node = source_shape._get_runtime("graph.node") + if source_node is None: + return [] + + node_ids: List[str] = [] + for selected in selected_shapes: + op = _selection_op_for_shape(selected) + if op is None: + continue + kind = _shape_kind_token(selected) + selected_node = _active_graph_node_for_shape(selected) + inputs = [source_node] + if ( + selected_node is not None + and getattr(selected_node, "op", None) == _OP_APPLY_TAG_RSELECTION + and selected_node is not source_node + ): + inputs.append(selected_node) + node = record_operation( + op=op, + params={ + "target_kind": kind, + "geo_selector": _make_geo_selector( + selected, + source_shape=source_shape, + ), + }, + inputs=inputs, + output_count=1, + semantic_delta=_semantic_delta_for_output(op, entity_type="Selection"), + context=_current_context_metadata(), + ) + attach_graph_node( + selected, + node, + output_slot=0, + graph_id=session.graph.graph_id, + ) + node_ids.append(node.node_id) + return node_ids + +_GEO_SELECT_OPS = { + _OP_MAKE_SELECT_RVERTEX, + _OP_MAKE_SELECT_REDGE, + _OP_MAKE_SELECT_RWIRE, + _OP_MAKE_SELECT_RFACE, + _OP_MAKE_SELECT_RSHELL, + _OP_MAKE_SELECT_RSOLID, +} + +def _is_geo_select_node(node: object) -> bool: + return getattr(node, "op", None) in _GEO_SELECT_OPS + +def _ensure_source_shape_has_own_selection_node( + source_shape: AnyShape, +) -> Optional[object]: + source_node = _active_graph_node_for_shape(source_shape) + if ( + source_node is None + or _is_geo_select_node(source_node) + or getattr(source_node, "op", None) == _OP_APPLY_TAG_RSELECTION + ): + return source_node + + parent_source = _selection_source_for_shape(source_shape) + if parent_source is None: + return source_node + + _ensure_geo_selection_node_ids(parent_source, [source_shape]) + return _active_graph_node_for_shape(source_shape) + +def _ensure_geo_selection_node_ids( + source_shape: AnyShape, + selected_shapes: Sequence[AnyShape], +) -> List[str]: + session = get_active_session() + if session is None: + return [] + source_node = _ensure_source_shape_has_own_selection_node(source_shape) + if source_node is None: + return [] + + node_ids: List[str] = [] + for selected in selected_shapes: + existing_node = _active_graph_node_for_shape(selected) + existing_op = getattr(existing_node, "op", None) + if existing_node is not None and existing_op in _GEO_SELECT_OPS: + node_ids.append(str(existing_node.node_id)) + continue + node_ids.extend(_record_geo_selection_nodes(source_shape, [selected])) + return node_ids + +def _active_graph_node_for_shape(shape: AnyShape) -> Optional[object]: + session = get_active_session() + if session is None: + return None + node = shape._get_runtime("graph.node") + node_id = getattr(node, "node_id", None) + if node_id is None: + return None + if session.graph.get_node(str(node_id)) is None: + return None + return node + +def _parent_shapes(shape: AnyShape) -> List[AnyShape]: + parents: List[AnyShape] = [] + get_parent = getattr(shape, "get_parent", None) + if callable(get_parent): + parent = get_parent() + if parent is not None: + parents.append(cast(AnyShape, parent)) + get_parents = getattr(shape, "get_parents", None) + if callable(get_parents): + for parent in get_parents(): + if parent is not None: + parents.append(cast(AnyShape, parent)) + return parents + +def _selection_source_for_shape(shape: AnyShape) -> Optional[AnyShape]: + kind = _shape_kind_token(shape) + seen: Set[int] = set() + stack = _parent_shapes(shape) + + while stack: + source = stack.pop(0) + marker = id(source) + if marker in seen or source is shape: + continue + seen.add(marker) + + if _source_selection_index(source, shape, kind=kind) is not None: + if _active_graph_node_for_shape(source) is not None: + return source + + stack.extend(_parent_shapes(source)) + + return None + +def _ensure_geo_selection_input_nodes( + input_shapes: Optional[Sequence[AnyShape]], +) -> Optional[Sequence[AnyShape]]: + if not input_shapes: + return input_shapes + + for shape in input_shapes: + if _active_graph_node_for_shape(shape) is not None: + continue + source = _selection_source_for_shape(shape) + if source is not None: + _ensure_geo_selection_node_ids(source, [shape]) + return input_shapes + +def _serialize_shape_ref(shape: AnyShape) -> Optional[Dict[str, object]]: + topo_ref = shape._get_runtime("topo.ref") + if isinstance(topo_ref, TopoRef): + data = cast(Dict[str, object], topo_ref_to_dict(topo_ref)) + data["selector_hint"] = _make_selector_hint(shape) + return data + + topo_ref_meta = shape.get_metadata("topo_ref") + if isinstance(topo_ref_meta, dict): + data = cast(Dict[str, object], dict(topo_ref_meta)) + data["selector_hint"] = _make_selector_hint(shape) + return data + + return None + +def _serialize_shape_refs(shapes: Sequence[AnyShape]) -> List[Dict[str, object]]: + refs: List[Dict[str, object]] = [] + for shape in shapes: + ref = _serialize_shape_ref(shape) + if ref is not None: + refs.append(ref) + return refs + +def _shape_ref_topo_id(shape: AnyShape) -> Optional[str]: + ref = _serialize_shape_ref(shape) + if ref is None: + return None + topo_id = ref.get("topo_id") + return str(topo_id) if topo_id is not None else None + +def _serialize_selection_indices( + selected_shapes: Sequence[AnyShape], + candidates: Sequence[AnyShape], +) -> List[int]: + candidate_index_by_topo_id: Dict[str, int] = {} + for idx, candidate in enumerate(candidates): + topo_id = _shape_ref_topo_id(candidate) + if topo_id is not None and topo_id not in candidate_index_by_topo_id: + candidate_index_by_topo_id[topo_id] = idx + + result: List[int] = [] + for selected in selected_shapes: + topo_id = _shape_ref_topo_id(selected) + if topo_id is None: + continue + if topo_id in candidate_index_by_topo_id: + result.append(candidate_index_by_topo_id[topo_id]) + return result + +def _resolve_selector_or_shapes( + scope: AnyShape, + selection: Union[Sequence[AnyShape], ShapeSelector], +) -> List[AnyShape]: + if isinstance(selection, ShapeSelector): + return cast(List[AnyShape], selection.resolve(scope)) + return list(selection) + +def _semantic_delta_for_output( + op: str, output_count: int = 1, entity_type: Optional[str] = None +) -> SemanticDelta: + resolved_entity_type = entity_type + if resolved_entity_type is None: + if op in { + "make_point", + _OP_MAKE_POINT_RVERTEX, + }: + resolved_entity_type = "Point" + elif op in { + _OP_MAKE_SKETCH_RSKETCH, + _OP_ADD_POINT_RSKETCH, + _OP_ADD_LINE_RSKETCH, + _OP_ADD_CIRCLE_RSKETCH, + _OP_ADD_ARC_RSKETCH, + _OP_ADD_BSPLINE_RSKETCH, + _OP_MAKE_WIRE_FROM_SKETCH_RWIRE, + _OP_MAKE_FACE_FROM_SKETCH_RFACE, + *_SKETCH_CONSTRAINT_OPS.values(), + }: + resolved_entity_type = "Sketch" + elif op in { + "make_line", + "make_circle_edge", + "make_circle_wire", + "make_circle_face", + "make_rectangle_wire", + "make_rectangle_face", + "make_segment_wire", + "make_three_point_arc", + "make_three_point_arc_wire", + "make_angle_arc", + "make_angle_arc_wire", + "make_spline", + "make_spline_wire", + "make_polyline_wire", + "make_helix", + "make_helix_wire", + "make_face_from_wire", + "make_wire_from_edges", + _OP_MAKE_LINE_REDGE, + _OP_MAKE_CIRCLE_REDGE, + _OP_MAKE_THREE_POINT_ARC_REDGE, + _OP_MAKE_ANGLE_ARC_REDGE, + _OP_MAKE_SPLINE_REDGE, + _OP_MAKE_HELIX_REDGE, + _OP_MAKE_FACE_FROM_WIRE_RFACE, + _OP_MAKE_WIRE_FROM_EDGES_RWIRE, + }: + if op.endswith("_face") or op in { + "make_face_from_wire", + _OP_MAKE_FACE_FROM_WIRE_RFACE, + }: + resolved_entity_type = "Sketch" + else: + resolved_entity_type = "Profile" + elif op in { + "make_box", + "make_cylinder", + "make_cone", + "make_sphere", + "make_box_rsolid", + "make_cylinder_rsolid", + "make_cone_rsolid", + "make_sphere_rsolid", + "extrude", + "revolve", + "loft", + "sweep", + "helical_sweep", + "fillet", + "chamfer", + "shell", + "cut", + "union", + "intersect", + "translate", + "rotate", + "mirror", + _OP_MAKE_EXTRUDE_RSOLID, + _OP_MAKE_REVOLVE_RSOLID, + _OP_MAKE_LOFT_RSOLID, + _OP_MAKE_SWEEP_RSOLID, + _OP_MAKE_TWISTED_SWEEP_RSOLID, + _OP_MAKE_FILLET_RSOLID, + _OP_MAKE_CHAMFER_RSOLID, + _OP_MAKE_SHELL_RSOLID, + _OP_MAKE_CUT_RSOLID, + _OP_MAKE_UNION_RSOLID, + _OP_MAKE_INTERSECT_RSOLID, + _OP_MAKE_TRANSLATE_RSHAPE, + _OP_MAKE_ROTATE_RSHAPE, + _OP_MAKE_MIRROR_RSHAPE, + _OP_LOAD_BREP_REGION_RSOLID, + }: + if op in { + "extrude", + "revolve", + "loft", + "sweep", + "fillet", + "chamfer", + "shell", + "cut", + "union", + "intersect", + _OP_MAKE_EXTRUDE_RSOLID, + _OP_MAKE_REVOLVE_RSOLID, + _OP_MAKE_LOFT_RSOLID, + _OP_MAKE_SWEEP_RSOLID, + _OP_MAKE_TWISTED_SWEEP_RSOLID, + _OP_MAKE_FILLET_RSOLID, + _OP_MAKE_CHAMFER_RSOLID, + _OP_MAKE_SHELL_RSOLID, + _OP_MAKE_CUT_RSOLID, + _OP_MAKE_UNION_RSOLID, + _OP_MAKE_INTERSECT_RSOLID, + }: + resolved_entity_type = "Feature" + else: + resolved_entity_type = "Body" + else: + resolved_entity_type = "ShapeOutput" + + refs = tuple( + SemanticRef( + graph_id="pending", + node_id="pending", + entity_type=resolved_entity_type, + entity_id=f"{op}:{slot}", + ) + for slot in range(output_count) + ) + return SemanticDelta(created=refs, metadata={"op": op}) + +def _finalize_primitive_shape( + shape: AnyShape, + *, + op: str, + params: Dict[str, object], + tags: Optional[Set[str]] = None, +) -> AnyShape: + _attach_track_summary(shape, op=op) + record_operation_if_active( + op=op, + params=params, + outputs=shape, + semantic_delta=_semantic_delta_for_output(op), + context=_current_context_metadata(), + tags=tags, + ) + return shape + +def _finalize_primitive_solid( + solid: Solid, + *, + op: str, + params: Dict[str, object], + tags: Optional[Set[str]] = None, +) -> Solid: + return cast( + Solid, + _finalize_primitive_shape(solid, op=op, params=params, tags=tags), + ) + +def _topology_identity_payload(binding: TagBinding) -> Optional[Dict[str, Any]]: + for key in ("topology_name", "source_topology_name"): + value = binding.evidence.data.get(key) + if isinstance(value, dict): + return value + return None + +def _copy_exact_topology_identity_tags( + target: AnyShape, + sources: Sequence[AnyShape], + *, + operation: str, +) -> AnyShape: + source_members = [ + member + for source in sources + for member in (source.get_edges() if hasattr(source, "get_edges") else [source]) + if isinstance(member, Edge) + ] + target_members = target.get_edges() if hasattr(target, "get_edges") else [target] + result = target + for target_member in target_members: + if not isinstance(target_member, Edge): + continue + matches = [ + source + for source in source_members + if source.wrapped.IsSame(target_member.wrapped) + ] + if len(matches) != 1: + continue + source = matches[0] + for binding in source._local_tag_bindings(): + topology_identity = _topology_identity_payload(binding) + if topology_identity is None: + continue + local_name = topology_identity.get("local_name") + if not isinstance(local_name, str) or not local_name: + continue + result = _apply_topology_identity_tag( + result, + [target_member], + binding.tag, + kind="edge", + local_name=local_name, + authoring_source=f"simplecadapi.{operation}.identity_tag", + ) + return result + +def _apply_topology_identity_tag( + scope: AnyShape, + targets: Union[ShapeSelector, Sequence[AnyShape]], + tag: str, + *, + kind: str, + local_name: str, + authoring_source: str, +) -> AnyShape: + normalized = normalize_tag(tag, strict=True) + return _apply_tag_rselection( + scope, + targets, + normalized, + (TopologyPropagation.DOWNWARD if kind == "face" else TopologyPropagation.LOCAL), + LineagePolicy.CONTINUATION_FRAGMENT, + authoring_source=authoring_source, + extra_evidence={ + "topology_name": { + "kind": kind, + "name": normalized, + "local_name": normalize_tag(local_name, strict=True), + } + }, + ) + +def _apply_shape_tag_prefix( + shape: AnyShape, + tag_prefix: Optional[str], + *, + kind: str, + authoring_source: str, +) -> AnyShape: + if tag_prefix is None: + return shape + prefix = normalize_tag(tag_prefix, strict=True) + tag = f"{prefix}.{kind}" + return _apply_topology_identity_tag( + shape, + ShapeSelector(kind).exactly(1), + tag, + kind=kind, + local_name=kind, + authoring_source=authoring_source, + ) + +def _apply_profile_tag_prefix( + shape: Union[Wire, Face], + tag_prefix: Optional[str], + edge_tags: Optional[Sequence[str]], + *, + authoring_source: str, +) -> Union[Wire, Face]: + if tag_prefix is None and edge_tags is None: + return shape + prefix = normalize_tag(tag_prefix, strict=True) if tag_prefix is not None else None + result: AnyShape = ( + _apply_shape_tag_prefix( + shape, + prefix, + kind=shape.__class__.__name__.lower(), + authoring_source=authoring_source, + ) + if prefix is not None + else shape + ) + edges = list(shape.get_edges()) + local_names = ( + [str(value) for value in edge_tags] + if edge_tags is not None + else [f"line{index + 1}" for index in range(len(edges))] + ) + if len(local_names) != len(edges): + raise ValueError( + f"edge_tags must contain exactly {len(edges)} tags, got {len(local_names)}" + ) + for edge, raw_local_name in zip(edges, local_names): + local_name = normalize_tag(raw_local_name, strict=True) + edge_tag = f"{prefix}.edge.{local_name}" if prefix else local_name + result = _apply_topology_identity_tag( + result, + [edge], + edge_tag, + kind="edge", + local_name=local_name, + authoring_source=authoring_source, + ) + return cast(Union[Wire, Face], result) + +def _finalize_derived_shape( + shape: AnyShape, + *, + op: str, + params: Dict[str, object], + input_shapes: Sequence[AnyShape], + tags: Optional[Set[str]] = None, + topo_delta: Optional[TopoDelta] = None, +) -> AnyShape: + _attach_track_summary(shape, op=op) + prepared_inputs = list(_ensure_geo_selection_input_nodes(input_shapes) or ()) + recorded_params = dict(params) + if get_active_session() is not None and op in { + "make_ruled_surface_rface", + "make_gordon_surface_rface", + "make_surface_patch_rface", + "trim_surface_rface", + "make_loft_rshell", + "sew_faces_rshell", + "make_solid_from_shell_rsolid", + "fill_holes_rshell", + }: + input_refs = _serialize_shape_refs(prepared_inputs) + if len(input_refs) != len(prepared_inputs): + raise ValueError( + f"{op} requires every ordered input to have a graph reference" + ) + recorded_params["input_refs"] = input_refs + record_operation_if_active( + op=op, + params=recorded_params, + outputs=shape, + input_shapes=prepared_inputs, + semantic_delta=_semantic_delta_for_output(op), + topo_delta=topo_delta, + context=_current_context_metadata(), + tags=tags, + ) + return shape + +def _finalize_runtime_object( + output: object, + *, + op: str, + params: Dict[str, object], + input_objects: Optional[Sequence[object]] = None, + tags: Optional[Set[str]] = None, + entity_type: str = "Sketch", +) -> object: + record_operation_if_active( + op=op, + params=params, + outputs=output, + input_shapes=input_objects, + semantic_delta=_semantic_delta_for_output(op, entity_type=entity_type), + context=_current_context_metadata(), + tags=tags, + ) + return output + +def _finalize_tracked_solid( + solid: Solid, + *, + op: str, + params: Dict[str, object], + source_solid: Optional[Solid] = None, + source_solids: Optional[Sequence[Solid]] = None, + delta: Optional[object] = None, + delta_entries: Optional[Dict[str, Dict[str, object]]] = None, + input_shapes: Optional[Sequence[AnyShape]] = None, +) -> Solid: + if current_tracking_policy() == TrackingPolicy.GRAPH: + delta = None + delta_entries = None + if delta is not None: + apply_tracking_tags_to_delta( + solid, + cast(TopoDelta, delta), + cast(Optional[Dict[str, Dict[str, Any]]], delta_entries), + op=op, + source_solid=source_solid, + source_solids=source_solids, + source_shapes=input_shapes, + ) + _attach_track_summary( + solid, + op=op, + delta=delta, + delta_entries=delta_entries, + ) + record_operation_if_active( + op=op, + params=params, + outputs=solid, + input_shapes=_ensure_geo_selection_input_nodes(input_shapes), + semantic_delta=_semantic_delta_for_output(op), + topo_delta=cast(Optional[TopoDelta], delta), + context=_current_context_metadata(), + ) + return solid + +def _normalize_operation_role_tags( + op: str, + named_tags: Sequence[Tuple[str, Optional[str]]], +) -> List[Tuple[str, str, str]]: + role_specs = _OPERATION_OUTPUT_ROLE_CARDINALITY[op] + cardinality_by_role = dict(role_specs) + requested: Dict[str, str] = {} + + for role, raw_tag in named_tags: + if raw_tag is None: + continue + if role in requested: + raise ValueError(f"duplicate role tag assignment: {role}") + requested[role] = normalize_tag(raw_tag, strict=True) + + unknown = sorted(set(requested) - set(cardinality_by_role)) + if unknown: + raise ValueError( + f"unsupported output role(s) for {op}: {', '.join(unknown)}; " + f"expected one of {', '.join(cardinality_by_role)}" + ) + return [ + (role, cardinality, requested[role]) + for role, cardinality in role_specs + if role in requested + ] + +def _validate_operation_output_roles( + delta: TopoDelta, + assignments: Sequence[Tuple[str, str, str]], +) -> Dict[str, str]: + target_kinds: Dict[str, str] = {} + for role, cardinality, _tag in assignments: + role_entries = { + (entry.ref, entry.ref.kind.name.lower()) + for entry in delta.roles + if entry.role == role + and str(entry.metadata.get("coverage", "complete")).lower() == "complete" + and str(entry.metadata.get("status", "proven")).lower() == "proven" + } + refs = {ref for ref, _kind in role_entries} + kinds = {kind for _ref, kind in role_entries} + if cardinality == "one" and len(refs) != 1: + raise SemanticCapabilityError( + f"operation output role '{role}' requires exactly one kernel-proven result, got {len(refs)}" + ) + if cardinality == "many" and not refs: + raise SemanticCapabilityError( + f"operation output role '{role}' requires at least one kernel-proven result" + ) + if len(kinds) != 1: + raise SemanticCapabilityError( + f"operation output role '{role}' does not resolve to one topology kind" + ) + target_kinds[role] = next(iter(kinds)) + return target_kinds + +def _apply_operation_role_tags( + shape: AnyShape, + *, + op: str, + assignments: Sequence[Tuple[str, str, str]], + target_kinds: Mapping[str, str], + result_tag: Optional[str] = None, +) -> AnyShape: + if not assignments and result_tag is None: + return shape + + role_source_node = _active_graph_node_for_shape(shape) + role_source_slot = int(shape._get_runtime("graph.output_slot", 0)) + result: AnyShape = shape + for role, cardinality, tag in assignments: + selector = ShapeSelector(target_kinds[role]).where(output_role(role)) + selector = selector.exactly(1) if cardinality == "one" else selector.at_least(1) + result = _apply_tag_rselection( + result, + selector, + tag, + TopologyPropagation.LOCAL, + LineagePolicy.CONTINUATION_FRAGMENT, + authoring_source=f"simplecadapi.{op}.role_tag", + extra_evidence={ + "operation_output_role": { + "source_node_id": ( + role_source_node.node_id + if role_source_node is not None + else None + ), + "source_output_slot": role_source_slot, + "operation": op, + "role": role, + "cardinality": cardinality, + } + }, + ) + if result_tag is not None: + result = _apply_tag_rselection( + result, + ShapeSelector(_shape_kind_token(shape)).exactly(1), + result_tag, + TopologyPropagation.LOCAL, + LineagePolicy.CONTINUATION_FRAGMENT, + authoring_source=f"simplecadapi.{op}.result_tag", + extra_evidence={ + "operation_result": { + "source_node_id": ( + role_source_node.node_id + if role_source_node is not None + else None + ), + "source_output_slot": role_source_slot, + "operation": op, + } + }, + ) + return result + +def _topology_identity_local_name(shape: AnyShape) -> Optional[str]: + for binding in shape._local_tag_bindings(): + payload = _topology_identity_payload(binding) + if ( + payload is not None + and payload.get("kind") == shape.__class__.__name__.lower() + ): + local_name = payload.get("local_name") + if isinstance(local_name, str) and local_name: + return local_name + return None + +def _apply_feature_tag_prefix( + solid: Solid, + *, + tag_prefix: Optional[str], + op: str, + delta: TopoDelta, + start_role: Optional[str] = None, + end_role: Optional[str] = None, + side_role: Optional[str] = None, + source_shapes: Sequence[AnyShape] = (), + edge_roles: Sequence[Tuple[str, str]] = (), + face_roles: Sequence[Tuple[str, str]] = (), +) -> Solid: + if tag_prefix is None: + return solid + prefix = normalize_tag(tag_prefix, strict=True) + result: AnyShape = _apply_topology_identity_tag( + solid, + ShapeSelector("solid").exactly(1), + f"{prefix}.solid", + kind="solid", + local_name="solid", + authoring_source=f"simplecadapi.{op}.tag_prefix", + ) + + for role, local_name in ( + (start_role, "start"), + (end_role, "end"), + (side_role, "side"), + ): + if role is None: + continue + cardinality = "one" if local_name in {"start", "end"} else "many" + selector = ShapeSelector("face").where(output_role(role)) + selector = selector.exactly(1) if cardinality == "one" else selector.at_least(1) + result = _apply_topology_identity_tag( + cast(Solid, result), + selector, + f"{prefix}.face.{local_name}", + kind="face", + local_name=local_name, + authoring_source=f"simplecadapi.{op}.tag_prefix", + ) + + source_edges = { + _topo_id(edge.wrapped): edge + for source in source_shapes + for edge in ( + source.get_edges() + if hasattr(source, "get_edges") + else ([source] if isinstance(source, Edge) else []) + ) + } + result_faces = { + _topo_id(face.wrapped): face for face in cast(Solid, result).get_faces() + } + if side_role is not None: + # A side Face may have multiple source profile Edges (for example, a + # loft side joins the corresponding Edges from two sections). A + # A topology-identity tag is safe only when kernel history proves a bijection. + side_correspondence: List[Tuple[str, str]] = [] + for role_entry in delta.roles: + if role_entry.role != side_role: + continue + parent_edges = [ + parent + for parent in role_entry.parent_refs + if parent.kind == TopoKind.EDGE + ] + if len(parent_edges) != 1: + continue + side_correspondence.append( + (role_entry.ref.topo_id, parent_edges[0].topo_id) + ) + + target_sources: Dict[str, Set[str]] = {} + source_targets: Dict[str, Set[str]] = {} + for target_id, source_id in side_correspondence: + target_sources.setdefault(target_id, set()).add(source_id) + source_targets.setdefault(source_id, set()).add(target_id) + + for target_id, source_id in side_correspondence: + if len(target_sources[target_id]) != 1: + continue + if len(source_targets[source_id]) != 1: + continue + source_edge = source_edges.get(source_id) + target_face = result_faces.get(target_id) + if source_edge is None or target_face is None: + continue + edge_local_name = _topology_identity_local_name(source_edge) + if edge_local_name is None: + continue + result = _apply_topology_identity_tag( + cast(Solid, result), + [target_face], + f"{prefix}.face.side.{edge_local_name}", + kind="face", + local_name=f"side.{edge_local_name}", + authoring_source=f"simplecadapi.{op}.profile_edge_tag", + ) + + for role, local_name in edge_roles: + result = _apply_topology_identity_tag( + cast(Solid, result), + ShapeSelector("edge").where(output_role(role)).exactly(1), + f"{prefix}.edge.{local_name}", + kind="edge", + local_name=local_name, + authoring_source=f"simplecadapi.{op}.tag_prefix", + ) + for role, local_name in face_roles: + result = _apply_topology_identity_tag( + cast(Solid, result), + ShapeSelector("face").where(output_role(role)).exactly(1), + f"{prefix}.face.{local_name}", + kind="face", + local_name=local_name, + authoring_source=f"simplecadapi.{op}.tag_prefix", + ) + return cast(Solid, result) + +def _semantic_view_target(view: AnyShape, target: AnyShape) -> AnyShape: + candidates = [ + wrapper + for entity in view._topology_cache.entities() + if entity.kind == target._entity.kind + for wrapper in entity.wrappers + if isinstance(wrapper, type(target)) + ] + matches = [] + for candidate in candidates: + try: + if _same_semantic_topology( + target._entity.kind, + candidate.wrapped, + target.wrapped, + ): + matches.append(candidate) + except Exception: + continue + unique = {candidate.topo_id: candidate for candidate in matches} + if not unique: + raise ValueError("tag target does not belong to the assignment scope") + if len(unique) != 1: + raise ValueError("tag target resolves ambiguously inside the assignment scope") + return cast(AnyShape, next(iter(unique.values()))) + +def _apply_tag_rselection( + scope: AnyShape, + targets: Union[ShapeSelector, Sequence[AnyShape]], + tag: str, + topology_propagation: str | TopologyPropagation, + lineage_policy: str | LineagePolicy, + *, + authoring_source: str = "simplecadapi.apply_tag_rselection", + extra_evidence: Optional[Dict[str, Any]] = None, + clone_scope: bool = True, +) -> AnyShape: + normalized_tag = normalize_tag(tag, strict=True) + topology = TopologyPropagation(topology_propagation) + lineage = LineagePolicy(lineage_policy) + session = get_active_session() + source_node = _active_graph_node_for_shape(scope) + source_output_slot = int(scope._get_runtime("graph.output_slot", 0)) + if session is not None and source_node is None: + raise ValueError("assignment scope is not produced by the active GraphSession") + + view = clone_semantic_shape_view(scope) if clone_scope else scope + if isinstance(targets, ShapeSelector): + selector = targets + if source_node is not None: + if selector.source_node_id is None: + selector = selector.from_source(source_node.node_id, source_output_slot) + elif ( + selector.source_node_id != source_node.node_id + or int(selector.source_output_slot or 0) != source_output_slot + ): + raise ValueError( + "tag selector source does not match the assignment scope" + ) + selected = cast(List[AnyShape], selector.resolve(view)) + target = TagTarget("selection_query", selector=selector.to_dict()) + else: + if isinstance(targets, (str, bytes)): + raise TypeError("targets must be a ShapeSelector or shape sequence") + target_shapes = list(targets) + if not target_shapes: + raise ValueError("tag assignment targets cannot be empty") + if not all( + isinstance(item, (Vertex, Edge, Wire, Face, Shell, Solid, Compound)) + for item in target_shapes + ): + raise TypeError("tag assignment targets must contain only shapes") + selected = [ + _semantic_view_target(view, cast(AnyShape, item)) for item in target_shapes + ] + refs = tuple( + ref for ref in _serialize_shape_refs(target_shapes) if isinstance(ref, dict) + ) + if len(refs) != len(target_shapes): + refs = tuple( + {"kind": _shape_kind_token(item), "topo_id": item.topo_id} + for item in target_shapes + ) + target = TagTarget("explicit_refs", refs=refs) + + selected_by_topo_id = {item.topo_id: item for item in selected} + if len(selected_by_topo_id) != len(selected): + raise ValueError("tag assignment targets contain ambiguous duplicate entities") + selected = list(selected_by_topo_id.values()) + if not selected: + raise ValueError("tag assignment resolved no targets") + + selected_refs = _serialize_shape_refs(selected) + if len(selected_refs) != len(selected): + selected_refs = [ + {"kind": _shape_kind_token(item), "topo_id": item.topo_id} + for item in selected + ] + + assignment_node_id = ( + session.graph.allocate_node_id("n") + if source_node is not None and session is not None + else None + ) + evidence_data = { + "authoring_source": authoring_source, + "selected_count": len(selected), + "selected_refs": selected_refs, + **dict(extra_evidence or {}), + } + binding = TagBinding( + tag=normalized_tag, + producer=TagProducer("user_operation", node_id=assignment_node_id), + scope=TagBindingScope( + node_id=(source_node.node_id if source_node is not None else None), + output_slot=source_output_slot, + ), + target=target, + propagation=TagPropagation(topology=topology, lineage=lineage), + evidence=TagEvidence("query_execution", evidence_data), + certainty=TagCertainty.ASSERTED, + lifecycle=TagLifecycle.ASSERTION, + binding_id=( + f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, f'simplecad:user-tag:{session.graph.graph_id}:{assignment_node_id}:{normalized_tag}').hex}" + if assignment_node_id is not None and session is not None + else f"tag_binding_{uuid.uuid4().hex}" + ), + ) + + for selected_shape in selected: + selected_shape._add_tag_binding(binding) + + if source_node is not None and session is not None: + node = record_operation( + op=_OP_APPLY_TAG_RSELECTION, + params={"tag_binding": binding.to_dict()}, + inputs=[source_node], + node_id=assignment_node_id, + output_count=1, + context=_current_context_metadata(), + ) + attach_semantic_graph_node( + view, + node, + output_slot=0, + graph_id=session.graph.graph_id, + ) + return view + +_EXPORTABLE_TYPES = (Compound, Solid, Shell, Face, Wire, Edge, Vertex) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/_operators_boolean.py b/src/simplecadapi/_operators_boolean.py new file mode 100644 index 00000000..c2f83497 --- /dev/null +++ b/src/simplecadapi/_operators_boolean.py @@ -0,0 +1,603 @@ +"""Boolean operator implementations.""" + +from __future__ import annotations + +from ._operation_support import * + +def union_rsolid( + *solids: Union[Solid, Sequence[Solid]], + clean: bool = True, + glue: bool = _DEFAULT_UNION_GLUE, + tol: Optional[float] = None, + tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, +) -> Solid: + """Compute the boolean union and return one manifold solid. + + Face-area contact and positive-volume overlap can produce one solid without + artificial embedding. Edge-only, vertex-only, and point/curve tangencies + are non-manifold connections and cannot satisfy the one-Solid contract. + + ``glue`` is an OCC optimization for compatible touching or coincident + topology, not a geometry repair switch. If the optimized pass does not + return one solid, SimpleCAD automatically retries the normal fuse algorithm. + + Args: + solids: One or more Solid objects or sequences of Solid. Nested sequences are + flattened before processing. + clean: Unify same-domain faces and remove splitter edges when possible. + glue: Try OCC glue optimization first, then fall back to normal fuse if + necessary. Defaults to False. + tol: Optional finite non-negative fuzzy-boolean tolerance used by OCC. It + may intentionally bridge a small gap but cannot make a non-manifold + point or edge contact into a valid solid. + tracking_policy: FULL computes topology history and lineage. GRAPH keeps + the replayable operation node without computing a TopoDelta. + + Returns: + Solid: The merged union result. + + Usage: + Accepts standalone `Solid` objects, lists of `Solid`, and nested sequences, + but always returns exactly one `Solid`. If the kernel cannot produce + exactly one solid result, the API raises a clear error instead of + returning multiple pieces. + + Examples: + body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) + rib = make_box_rsolid(2, 4, 4, bottom_face_center=(4, 0, 0)) + merged = union_rsolid(body, rib) + print(merged.get_volume()) + """ + + try: + policy = ( + TrackingPolicy.GRAPH + if current_tracking_policy() == TrackingPolicy.GRAPH + else TrackingPolicy(tracking_policy) + ) + remaining = _flatten_boolean_solids(solids, "union_rsolid") + + if not remaining: + raise ValueError("union_rsolid 至少需要一个Solid输入") + + for solid in remaining: + if solid.wrapped.IsNull(): + raise ValueError("输入实体无效,无法进行并集运算。") + + if len(remaining) == 1 and not clean: + return remaining[0] + + effective_tol = _resolve_union_tol(remaining, tol) + tracked_union_result: Optional[TrackedBooleanResult] = None + if policy == TrackingPolicy.FULL and len(remaining) >= 2: + tracked_union_result = cast( + TrackedBooleanResult, + _evaluate_tracked_union( + remaining, + glue=glue, + tol=effective_tol, + clean=clean, + ), + ) + if tracked_union_result.solid is None: + raise ValueError("union did not produce a valid solid") + fused_solid = tracked_union_result.solid + else: + fused_solid = cast( + Solid, + _require_union_solid( + fuse_shapes( + [solid.wrapped for solid in remaining], + glue=glue, + tol=effective_tol, + clean=clean, + ), + effective_tol, + ), + ) + + all_metadata = {} + for solid in remaining: + all_metadata.update(solid._metadata) + + fused_solid._metadata = all_metadata.copy() + + params: Dict[str, object] = { + "input_count": len(remaining), + "clean": clean, + "glue": glue, + "tol": effective_tol, + "tracking_policy": policy.value, + } + if tracked_union_result is not None: + fused_solid = _finalize_tracked_solid( + fused_solid, + op=_OP_MAKE_UNION_RSOLID, + params=params, + source_solids=remaining, + delta=tracked_union_result.delta, + delta_entries=cast( + Dict[str, Dict[str, object]], + tracked_union_result.delta_entries, + ), + input_shapes=remaining, + ) + elif policy == TrackingPolicy.GRAPH: + fused_solid = cast( + Solid, + _finalize_derived_shape( + fused_solid, + op=_OP_MAKE_UNION_RSOLID, + params=params, + input_shapes=remaining, + ), + ) + else: + _attach_track_summary(fused_solid, op=_OP_MAKE_UNION_RSOLID) + record_operation_if_active( + op=_OP_MAKE_UNION_RSOLID, + params=params, + outputs=fused_solid, + input_shapes=remaining, + context=_current_context_metadata(), + ) + + return fused_solid + except Exception as e: + _wrap_public_api_error( + operation="union_rsolid", + what_happened=( + str(e) + if isinstance(e, ValueError) and str(e).startswith("union produced ") + else "Failed to compute the boolean union." + ), + possible_causes=[ + "One or more inputs are not Solid objects.", + "At least one input solid is null or invalid.", + "The inputs are separated beyond tol, so the kernel cannot produce exactly one solid.", + "The inputs meet only along an edge, vertex, tangent point, or tangent curve, so their union is not one manifold solid.", + ], + how_to_fix=[ + "Pass only valid Solid objects or sequences of Solid objects.", + "For intended face contact, make the solids share a finite-area face and retry; no artificial overlap is required.", + "For a real small gap, pass an explicit tol only when approximating that gap is acceptable.", + "Do not expect glue or tol to turn point-, edge-, or tangent-only contact into a valid single solid.", + ], + error=e, + ) + +def cut_rsolid( + *solids: Union[Solid, Sequence[Solid]], + skip_non_intersecting: bool = True, + tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, +) -> Solid: + """Compute the boolean difference of solids. + + Args: + solids: One or more Solid objects or sequences of Solid. Nested sequences are + flattened before processing; the first solid is the base, the rest are + subtracted in order. + skip_non_intersecting: When True, tools with no meaningful intersection are + ignored for interactive convenience. Graph replay records this flag and + should use False for strict diagnostic workflows. + tracking_policy: FULL computes topology history and lineage. GRAPH keeps + the replayable operation node without computing a TopoDelta. + + Returns: + Solid: The cut result solid. + + Usage: + Accepts a base solid followed by one or more tool solids, including nested + sequences, and returns a single `Solid`. + """ + try: + policy = ( + TrackingPolicy.GRAPH + if current_tracking_policy() == TrackingPolicy.GRAPH + else TrackingPolicy(tracking_policy) + ) + remaining = _flatten_boolean_solids(solids, "cut_rsolid") + + if not remaining: + raise ValueError("cut_rsolid 至少需要一个Solid输入") + + if len(remaining) == 1: + return remaining[0] + + # 从第一个实体开始,依次减去其他实体 + result_solid = remaining[0] + deltas: List[TopoDelta] = [] + merged_delta_entries: Dict[str, Dict[str, object]] = {} + cut_performed = False + + for i in range(1, len(remaining)): + candidate = remaining[i] + + s1 = result_solid.wrapped + s2 = candidate.wrapped + + if s1.IsNull() or s2.IsNull(): + raise ValueError("输入实体无效,无法进行差集运算。") + + # 检查是否有交集 + intersection = common_shapes([s1, s2]) + intersection_solids = solids_of(intersection) + if not intersection_solids: + if skip_non_intersecting: + continue + raise ValueError("差集工具实体与当前实体没有交集。") + intersection_obj = Solid(intersection_solids[0]) + + if intersection_obj.get_volume() < 1e-12: + # 没有有效的交集,跳过此次切割 + if skip_non_intersecting: + continue + raise ValueError("差集工具实体与当前实体交集体积过小。") + + tracked = ( + cast( + TrackedBooleanResult, + tracked_cut(result_solid, candidate), + ) + if policy == TrackingPolicy.FULL and len(remaining) == 2 + else ( + tracked_cut(result_solid, candidate) + if policy == TrackingPolicy.FULL + else None + ) + ) + if tracked is not None: + if tracked.solid is None: + raise ValueError("差集运算失败: OCC 未返回有效实体") + new_result = tracked.solid + else: + new_result = _require_single_boolean_solid( + solids_of(cut_shapes(s1, [s2])), + operation="cut_rsolid", + failure_reason="差集运算失败: OCC 未返回有效实体", + ) + new_result._metadata = result_solid._metadata.copy() + result_solid = new_result + if tracked is not None: + deltas.append(tracked.delta) + merged_delta_entries.update( + cast(Dict[str, Dict[str, object]], tracked.delta_entries) + ) + cut_performed = True + + result_solid._metadata = remaining[0]._metadata.copy() + result_solid._apply_tag("solid.boolean.cut", propagate=False) + + merged_delta = _merge_topo_deltas(deltas) + params: Dict[str, object] = { + "tool_count": len(remaining) - 1, + "skip_non_intersecting": bool(skip_non_intersecting), + "tracking_policy": policy.value, + } + if cut_performed and merged_delta is not None: + result_solid = _finalize_tracked_solid( + result_solid, + op=_OP_MAKE_CUT_RSOLID, + params=params, + source_solids=remaining, + delta=merged_delta, + delta_entries=merged_delta_entries or None, + input_shapes=remaining, + ) + elif policy == TrackingPolicy.GRAPH: + result_solid = cast( + Solid, + _finalize_derived_shape( + result_solid, + op=_OP_MAKE_CUT_RSOLID, + params=params, + input_shapes=remaining, + ), + ) + else: + _attach_track_summary(result_solid, op=_OP_MAKE_CUT_RSOLID) + record_operation_if_active( + op=_OP_MAKE_CUT_RSOLID, + params=params, + outputs=result_solid, + input_shapes=remaining, + context=_current_context_metadata(), + ) + + return result_solid + except Exception as e: + _wrap_public_api_error( + operation="cut_rsolid", + what_happened="Failed to compute the boolean cut.", + possible_causes=[ + "One or more inputs are not Solid objects.", + "The base solid or tool solids are invalid.", + "The kernel could not compute a valid cut result for the current geometry.", + ], + how_to_fix=[ + "Pass a valid base solid followed by valid tool solids.", + "Check whether the tool geometry actually intersects the base solid.", + "If the cut depends on earlier union results, verify those results first.", + ], + error=e, + ) + +def intersect_rsolid(*solids: Union[Solid, Sequence[Solid]]) -> Solid: + """Compute the boolean intersection of solids. + + Args: + solids: One or more Solid objects or sequences of Solid. Nested sequences are + flattened before processing. + + Returns: + Solid: The overlap region as a single solid. + + Usage: + Accepts one or more solids, including nested sequences, and returns a single + `Solid`. If the inputs do not overlap meaningfully, the API raises a clear + error instead of returning an empty list. + """ + try: + remaining = _flatten_boolean_solids(solids, "intersect_rsolid") + + if not remaining: + raise ValueError("intersect_rsolid 至少需要一个Solid输入") + + if len(remaining) == 1: + return remaining[0] + + # 从第一个实体开始,依次与后续实体进行交集运算 + result_solid = remaining[0] + deltas: List[TopoDelta] = [] + merged_delta_entries: Dict[str, Dict[str, object]] = {} + intersect_performed = False + + for i in range(1, len(remaining)): + candidate = remaining[i] + + s1 = result_solid.wrapped + s2 = candidate.wrapped + + if s1.IsNull() or s2.IsNull(): + raise ValueError("输入实体无效,无法进行交集运算。") + + tracked = ( + cast( + TrackedBooleanResult, + tracked_intersect(result_solid, candidate), + ) + if len(remaining) == 2 + else tracked_intersect(result_solid, candidate) + ) + if tracked.solid is None: + raise ValueError("交集结果为空或 OCC 未返回有效实体") + + result_solid = tracked.solid + deltas.append(tracked.delta) + merged_delta_entries.update( + cast(Dict[str, Dict[str, object]], tracked.delta_entries) + ) + intersect_performed = True + + # 检查交集是否为空 + if result_solid.get_volume() < 1e-12: + raise ValueError("交集结果为空或体积过小") + + all_metadata: dict = {} + for solid in remaining: + all_metadata.update(solid._metadata) + + result_solid._metadata = all_metadata + result_solid._apply_tag("solid.boolean.intersect", propagate=False) + + merged_delta = _merge_topo_deltas(deltas) + if intersect_performed and merged_delta is not None: + result_solid = _finalize_tracked_solid( + result_solid, + op=_OP_MAKE_INTERSECT_RSOLID, + params={"input_count": len(remaining)}, + source_solids=remaining, + delta=merged_delta, + delta_entries=merged_delta_entries or None, + input_shapes=remaining, + ) + else: + _attach_track_summary(result_solid, op=_OP_MAKE_INTERSECT_RSOLID) + record_operation_if_active( + op=_OP_MAKE_INTERSECT_RSOLID, + params={"input_count": len(remaining)}, + outputs=result_solid, + input_shapes=remaining, + context=_current_context_metadata(), + ) + + return result_solid + except Exception as e: + _wrap_public_api_error( + operation="intersect_rsolid", + what_happened="Failed to compute the boolean intersection.", + possible_causes=[ + "One or more inputs are not Solid objects.", + "At least one input solid is invalid.", + "The solids do not overlap enough to produce a non-empty single solid.", + "The kernel could not compute a stable overlap region.", + ], + how_to_fix=[ + "Pass only valid Solid objects.", + "Verify that the solids truly overlap in space.", + "Move the solids so they share a meaningful overlap volume before intersecting.", + ], + error=e, + ) + +def _extract_single_face(shape_ocp, operation: str) -> Face: + """Extract exactly one Face from an OCP shape result.""" + result_faces = faces_of_ocp(shape_ocp) + if len(result_faces) != 1: + raise ValueError( + f"{operation} expected exactly 1 face in the result, got {len(result_faces)}" + ) + return Face(result_faces[0]) + +def make_2d_cut_rface(body: Face, tool: Face) -> Face: + """Subtract one 2D face from another (2D boolean difference). + + Parameters + ---------- + body : Face + The face to subtract from. + tool : Face + The face to subtract (the cutter). + + Returns + ------- + Face + The resulting face after subtraction. The result may contain + inner wires (holes) if the tool was fully inside the body. + """ + try: + if not isinstance(body, Face): + raise ValueError("body must be a Face") + if not isinstance(tool, Face): + raise ValueError("tool must be a Face") + + result_shape = cut_shapes(body.wrapped, [tool.wrapped]) + result_face = _extract_single_face(result_shape, "make_2d_cut_rface") + + result_face._metadata = body._metadata.copy() + + return cast( + Face, + _finalize_derived_shape( + result_face, + op=_OP_MAKE_CUT_RFACE, + params={}, + input_shapes=[body, tool], + tags={"derived", "face"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_2d_cut_rface", + what_happened="Failed to subtract one face from another.", + possible_causes=[ + "The body or tool is not a Face.", + "The faces do not overlap or are not coplanar.", + "The kernel could not compute a stable 2D difference.", + ], + how_to_fix=[ + "Pass two valid Face objects.", + "Ensure both faces lie on the same plane.", + "Verify the tool face overlaps the body face.", + ], + error=e, + ) + +def make_2d_union_rface(face_a: Face, face_b: Face) -> Face: + """Compute the boolean union of two 2D faces. + + Parameters + ---------- + face_a : Face + First face. + face_b : Face + Second face. + + Returns + ------- + Face + The merged face. Both inputs must overlap or touch so that the + result is a single connected face. + """ + try: + if not isinstance(face_a, Face): + raise ValueError("face_a must be a Face") + if not isinstance(face_b, Face): + raise ValueError("face_b must be a Face") + + result_shape = fuse_shapes([face_a.wrapped, face_b.wrapped], clean=True) + result_face = _extract_single_face(result_shape, "make_2d_union_rface") + + result_face._metadata = {**face_a._metadata, **face_b._metadata} + + return cast( + Face, + _finalize_derived_shape( + result_face, + op=_OP_MAKE_UNION_RFACE, + params={}, + input_shapes=[face_a, face_b], + tags={"derived", "face"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_2d_union_rface", + what_happened="Failed to union two faces.", + possible_causes=[ + "One or both inputs are not Face objects.", + "The faces do not overlap or touch.", + "The faces are not coplanar.", + ], + how_to_fix=[ + "Pass two valid Face objects.", + "Ensure the faces overlap or share a boundary.", + "Ensure both faces lie on the same plane.", + ], + error=e, + ) + +def make_2d_intersect_rface(face_a: Face, face_b: Face) -> Face: + """Compute the boolean intersection of two 2D faces. + + Parameters + ---------- + face_a : Face + First face. + face_b : Face + Second face. + + Returns + ------- + Face + The overlapping region of the two faces. + """ + try: + if not isinstance(face_a, Face): + raise ValueError("face_a must be a Face") + if not isinstance(face_b, Face): + raise ValueError("face_b must be a Face") + + result_shape = common_shapes([face_a.wrapped, face_b.wrapped]) + result_face = _extract_single_face(result_shape, "make_2d_intersect_rface") + + result_face._metadata = {**face_a._metadata, **face_b._metadata} + + return cast( + Face, + _finalize_derived_shape( + result_face, + op=_OP_MAKE_INTERSECT_RFACE, + params={}, + input_shapes=[face_a, face_b], + tags={"derived", "face"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_2d_intersect_rface", + what_happened="Failed to intersect two faces.", + possible_causes=[ + "One or both inputs are not Face objects.", + "The faces do not overlap.", + "The faces are not coplanar.", + ], + how_to_fix=[ + "Pass two valid Face objects.", + "Ensure the faces have a non-empty overlap region.", + "Ensure both faces lie on the same plane.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/_operators_features.py b/src/simplecadapi/_operators_features.py new file mode 100644 index 00000000..0df93f25 --- /dev/null +++ b/src/simplecadapi/_operators_features.py @@ -0,0 +1,952 @@ +"""Features operator implementations.""" + +from __future__ import annotations + +from ._operation_support import * +from ._operators_geometry import ( + _default_plane_x_direction, + _validated_loft_sections, + make_face_from_wire_rface, + make_helix_rwire, +) + +def extrude_rsolid( + profile: Union[Wire, Face], + direction: Tuple[float, float, float], + distance: ScalarLike, + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Create a solid by extruding a profile, with optional role-based tags.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_EXTRUDE_RSOLID, + ( + ("extrusion.start", start_face_tag), + ("extrusion.end", end_face_tag), + ("extrusion.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + distance_value = evaluate_scalar(distance) + if distance_value <= 0: + raise ValueError("拉伸距离必须大于0") + + cs = get_current_cs() + direction_value = cast(Tuple[float, float, float], evaluate_value(direction)) + global_direction = cs.transform_vector(np.array(direction_value)) + + direction_norm = float(np.linalg.norm(global_direction)) + if direction_norm <= 1e-15: + raise ValueError("拉伸方向不能是零向量") + direction_vec = tuple( + (global_direction / direction_norm * distance_value).tolist() + ) + + if isinstance(profile, Wire): + # 如果是线,先转换为面 + if profile.is_closed(): + face = Face(make_face_from_wire_ocp(profile.wrapped)) + else: + raise ValueError( + "如果传入线框作为拉伸对象,那么线框必须是闭合的, 而你的线框没有闭合,请检查构成线框的点是否正确" + ) + elif isinstance(profile, Face): + face = profile + else: + raise ValueError("只能拉伸线或面") # type: ignore[unreachable] + + resolved_direction = tuple(float(value) for value in global_direction) + tracked = cast( + TrackedResult, + tracked_extrude( + face, + resolved_direction, + distance_value, + ), + ) + solid = cast(Solid, tracked.shape) + + solid._apply_tag("solid.extrusion", propagate=False) + solid._metadata = profile._metadata.copy() + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op=_OP_MAKE_EXTRUDE_RSOLID, + params={ + "direction": direction, + "distance": distance, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[profile], + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_EXTRUDE_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_EXTRUDE_RSOLID, + delta=tracked.delta, + start_role="extrusion.start", + end_role="extrusion.end", + side_role="extrusion.side", + source_shapes=[profile], + ) + except Exception as e: + _wrap_public_api_error( + operation="extrude_rsolid", + what_happened="Failed to extrude the profile into a solid.", + possible_causes=[ + "The distance is not a positive finite scalar.", + "The direction vector is invalid.", + "A wire profile was provided but it is not closed.", + "The kernel rejected the profile or the extrusion direction.", + ], + how_to_fix=[ + "Use a distance greater than zero.", + "Pass a valid finite direction vector.", + "If you extrude a wire, make sure the wire is closed or convert it to a face first.", + "Inspect the evaluated profile and direction before retrying.", + ], + error=e, + ) + +def revolve_rsolid( + profile: Union[Wire, Face], + axis: Tuple[float, float, float] = (0, 0, 1), + angle: ScalarLike = 360, + origin: Tuple[float, float, float] = (0, 0, 0), + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Create a revolved solid, with optional kernel-role-based tags.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_REVOLVE_RSOLID, + ( + ("revolution.start", start_face_tag), + ("revolution.end", end_face_tag), + ("revolution.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + angle_value = evaluate_scalar(angle) + if angle_value <= 0: + raise ValueError("旋转角度必须大于0") + + cs = get_current_cs() + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) + global_axis = cs.transform_vector(np.array(axis_value)) + global_origin = cs.transform_point(np.array(origin_value)) + + # 获取轮廓对应的面 + if isinstance(profile, Wire): + # 如果是线,先转换为面 + if profile.is_closed(): + face = Face(make_face_from_wire_ocp(profile.wrapped)) + else: + raise ValueError("旋转的线必须是闭合的") + elif isinstance(profile, Face): + face = profile + else: + raise ValueError("只能旋转线或面") + + resolved_axis = tuple(float(value) for value in global_axis) + resolved_origin = tuple(float(value) for value in global_origin) + tracked = cast( + TrackedResult, + tracked_revolve( + face, + resolved_axis, + resolved_origin, + angle_value, + ), + ) + solid = cast(Solid, tracked.shape) + + solid._metadata = profile._metadata.copy() + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op=_OP_MAKE_REVOLVE_RSOLID, + params={ + "axis": axis, + "angle": angle, + "origin": origin, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[profile], + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_REVOLVE_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_REVOLVE_RSOLID, + delta=tracked.delta, + start_role="revolution.start" if angle_value < 360.0 else None, + end_role="revolution.end" if angle_value < 360.0 else None, + side_role="revolution.side", + source_shapes=[profile], + ) + except Exception as e: + _wrap_public_api_error( + operation="revolve_rsolid", + what_happened="Failed to revolve the profile into a solid.", + possible_causes=[ + "The angle is not a positive finite scalar.", + "The axis or origin is invalid.", + "A wire profile was provided but it is not closed.", + "The kernel rejected the revolve definition.", + ], + how_to_fix=[ + "Use an angle greater than zero.", + "Pass a valid non-zero axis vector and a valid origin point.", + "If you revolve a wire, ensure it is closed or convert it to a face first.", + "Inspect the evaluated axis, origin, and profile before retrying.", + ], + error=e, + ) + +def _normalize_shape_input( + shapes: Union[AnyShape, Sequence[AnyShape]], +) -> List[AnyShape]: + """Normalize rendering input into a flat list of shapes.""" + + if isinstance(shapes, _EXPORTABLE_TYPES): + return [shapes] + + if isinstance(shapes, Sequence) and not isinstance(shapes, (str, bytes)): + normalized: List[AnyShape] = [] + for item in shapes: + normalized.extend(_normalize_shape_input(cast(AnyShape, item))) + return normalized + + raise ValueError( + "rendering accepts Compound, Solid, Shell, Face, Wire, Edge, Vertex, or nested sequences of those types" + ) + +def render_screenshot_rpath( + shapes: Union[Solid, Sequence[Solid]], + output_path: str, + highlight_tags: Optional[Sequence[str]] = None, + tag_labels: Optional[Dict[str, str]] = None, + image_size: Tuple[int, int] = (1400, 900), + view: Union[Tuple[float, float], str] = "auto", + show_axes: bool = True, + show_legend: bool = True, + zoom: float = 4.0, + show_callouts: bool = True, +) -> str: + """Render SDK solids through the shared OCCT/VTK BREP renderer.""" + try: + from .inspect.brep.render import _render_sdk_screenshot_rpath + + shape_list = _normalize_shape_input(shapes) + solids = [shape for shape in shape_list if isinstance(shape, Solid)] + if len(solids) != len(shape_list) or not solids: + raise ValueError("render_screenshot_rpath only supports Solid inputs") + return str( + _render_sdk_screenshot_rpath( + solids, + output_path, + highlight_tags=tuple(highlight_tags or ()), + tag_labels=tag_labels, + image_size=image_size, + view=view, + show_axes=show_axes, + show_legend=show_legend, + zoom=zoom, + show_callouts=show_callouts, + ) + ) + except Exception as e: + _wrap_public_api_error( + operation="render_screenshot_rpath", + what_happened="Failed to render the screenshot.", + possible_causes=[ + "The input does not contain any valid Solid objects.", + "The rendering view or zoom configuration is invalid.", + "The output path is invalid or not writable.", + ], + how_to_fix=[ + "Pass a Solid or a sequence of Solid objects.", + "Use a supported view preset or a valid (elev, azim) tuple.", + "Check that the output path is writable.", + ], + error=e, + ) + +def fillet_rsolid( + solid: Solid, + edges: Union[Sequence[Edge], ShapeSelector], + radius: ScalarLike, + *, + result_tag: Optional[str] = None, + generated_faces_tag: Optional[str] = None, +) -> Solid: + """Apply fillets, with optional tagging of kernel-proven patch faces.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_FILLET_RSOLID, + (("fillet.patch", generated_faces_tag),), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + radius_value = evaluate_scalar(radius) + if radius_value <= 0: + raise ValueError("圆角半径必须大于0") + + selected_edges = cast(List[Edge], _resolve_selector_or_shapes(solid, edges)) + if not selected_edges: + raise ValueError("圆角操作至少需要一条边") + + tracked = cast( + TrackedResult, + tracked_fillet(solid, selected_edges, radius_value), + ) + result = cast(Solid, tracked.shape) + + result._metadata = solid._metadata.copy() + + selected_edge_refs = _serialize_shape_refs(selected_edges) + selected_edge_node_ids = _ensure_geo_selection_node_ids(solid, selected_edges) + + selection_params: Dict[str, object] = { + "radius": radius, + "edge_count": len(selected_edges), + "selected_edges": selected_edge_refs, + } + if selected_edge_node_ids: + selection_params["selected_edge_node_ids"] = selected_edge_node_ids + else: + selection_params["selected_edge_indices"] = _serialize_selection_indices( + selected_edges, solid.get_edges() + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_FILLET_RSOLID, + params=selection_params, + source_solid=solid, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[solid, *selected_edges], + ) + return _apply_operation_role_tags( + finalized, + op=_OP_MAKE_FILLET_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + except Exception as e: + _wrap_public_api_error( + operation="fillet_rsolid", + what_happened="Failed to apply the fillet operation.", + possible_causes=[ + "The radius is not a positive finite scalar.", + "No valid edges were selected.", + "The selected edges are incompatible with the requested fillet radius.", + ], + how_to_fix=[ + "Use a positive fillet radius.", + "Select at least one valid edge or use a selector that resolves to edges.", + "If the kernel rejects the fillet, try a smaller radius or a simpler edge set.", + ], + error=e, + ) + +def chamfer_rsolid( + solid: Solid, + edges: Union[Sequence[Edge], ShapeSelector], + distance: ScalarLike, + *, + result_tag: Optional[str] = None, + generated_faces_tag: Optional[str] = None, +) -> Solid: + """Apply chamfers, with optional tagging of kernel-proven patch faces.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_CHAMFER_RSOLID, + (("chamfer.patch", generated_faces_tag),), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + distance_value = evaluate_scalar(distance) + if distance_value <= 0: + raise ValueError("倒角距离必须大于0") + + selected_edges = cast(List[Edge], _resolve_selector_or_shapes(solid, edges)) + if not selected_edges: + raise ValueError("倒角操作至少需要一条边") + + tracked = cast( + TrackedResult, + tracked_chamfer(solid, selected_edges, distance_value), + ) + result = cast(Solid, tracked.shape) + + result._metadata = solid._metadata.copy() + + selected_edge_refs = _serialize_shape_refs(selected_edges) + selected_edge_node_ids = _ensure_geo_selection_node_ids(solid, selected_edges) + + selection_params: Dict[str, object] = { + "distance": distance, + "edge_count": len(selected_edges), + "selected_edges": selected_edge_refs, + } + if selected_edge_node_ids: + selection_params["selected_edge_node_ids"] = selected_edge_node_ids + else: + selection_params["selected_edge_indices"] = _serialize_selection_indices( + selected_edges, solid.get_edges() + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_CHAMFER_RSOLID, + params=selection_params, + source_solid=solid, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[solid, *selected_edges], + ) + return _apply_operation_role_tags( + finalized, + op=_OP_MAKE_CHAMFER_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + except Exception as e: + _wrap_public_api_error( + operation="chamfer_rsolid", + what_happened="Failed to apply the chamfer operation.", + possible_causes=[ + "The distance is not a positive finite scalar.", + "No valid edges were selected.", + "The selected edges are incompatible with the requested chamfer size.", + ], + how_to_fix=[ + "Use a positive chamfer distance.", + "Select at least one valid edge or use a selector that resolves to edges.", + "If the kernel rejects the chamfer, try a smaller distance or fewer edges.", + ], + error=e, + ) + +def shell_rsolid( + solid: Solid, + faces_to_remove: Union[Sequence[Face], ShapeSelector], + thickness: ScalarLike, + *, + result_tag: Optional[str] = None, + body_faces_tag: Optional[str] = None, + offset_faces_tag: Optional[str] = None, + closing_faces_tag: Optional[str] = None, + wall_edges_tag: Optional[str] = None, +) -> Solid: + """Shell a solid, with optional kernel-role-based face tags.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_SHELL_RSOLID, + ( + ("shell.body_face", body_faces_tag), + ("shell.offset_face", offset_faces_tag), + ("shell.closing_descendant", closing_faces_tag), + ("shell.wall", wall_edges_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + thickness_value = evaluate_scalar(thickness) + if thickness_value <= 0: + raise ValueError("壁厚必须大于0") + + selected_faces = cast( + List[Face], _resolve_selector_or_shapes(solid, faces_to_remove) + ) + if not selected_faces: + raise ValueError("抽壳操作至少需要一个待移除面") + + tracked = cast( + TrackedResult, + tracked_shell(solid, selected_faces, thickness_value), + ) + result = cast(Solid, tracked.shape) + + result._metadata = solid._metadata.copy() + + selected_face_refs = _serialize_shape_refs(selected_faces) + selected_face_node_ids = _ensure_geo_selection_node_ids(solid, selected_faces) + + selection_params: Dict[str, object] = { + "thickness": thickness, + "removed_face_count": len(selected_faces), + "selected_faces": selected_face_refs, + } + if selected_face_node_ids: + selection_params["selected_face_node_ids"] = selected_face_node_ids + else: + selection_params["selected_face_indices"] = _serialize_selection_indices( + selected_faces, solid.get_faces() + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_SHELL_RSOLID, + params=selection_params, + source_solid=solid, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[solid, *selected_faces], + ) + return _apply_operation_role_tags( + finalized, + op=_OP_MAKE_SHELL_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + except Exception as e: + _wrap_public_api_error( + operation="shell_rsolid", + what_happened="Failed to apply the shell operation.", + possible_causes=[ + "The thickness is not a positive finite scalar.", + "No valid faces were selected for removal.", + "The requested shell thickness is incompatible with the current solid.", + ], + how_to_fix=[ + "Use a positive shell thickness.", + "Select at least one valid face to remove.", + "If the shell fails, try a smaller thickness or a different face selection.", + ], + error=e, + ) + +def loft_rsolid( + profiles: Sequence[Union[Wire, Vertex]], + ruled: bool = False, + *, + tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Create a lofted solid, with optional kernel-role-based tags.""" + try: + profile_list = _validated_loft_sections(profiles, operation="loft_rsolid") + if start_face_tag is not None and isinstance(profile_list[0], Vertex): + raise ValueError("start_face_tag requires a Wire start section") + if end_face_tag is not None and isinstance(profile_list[-1], Vertex): + raise ValueError("end_face_tag requires a Wire end section") + policy = ( + TrackingPolicy.GRAPH + if current_tracking_policy() == TrackingPolicy.GRAPH + else TrackingPolicy(tracking_policy) + ) + assignments = _normalize_operation_role_tags( + _OP_MAKE_LOFT_RSOLID, + ( + ("loft.start", start_face_tag), + ("loft.end", end_face_tag), + ("loft.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + profiles = profile_list + + if policy == TrackingPolicy.GRAPH and (assignments or tag_prefix is not None): + raise ValueError( + "GRAPH tracking does not provide loft face-role evidence; " + "use FULL tracking for tag_prefix, start_face_tag, end_face_tag, " + "or side_faces_tag" + ) + + tracked = ( + cast( + TrackedResult, + tracked_loft(profiles, ruled=ruled), + ) + if policy == TrackingPolicy.FULL + else None + ) + result = ( + cast(Solid, tracked.shape) + if tracked is not None + else Solid( + make_loft_solid((profile.wrapped for profile in profiles), ruled=ruled) + ) + ) + + all_metadata = {} + for profile in profiles: + all_metadata.update(profile._metadata) + + result._metadata = all_metadata + + params: Dict[str, object] = { + "profile_count": len(profiles), + "ruled": ruled, + "tracking_policy": policy.value, + } + if tracked is not None: + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_LOFT_RSOLID, + params=params, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=profiles, + ) + else: + target_kinds = {} + finalized = cast( + Solid, + _finalize_derived_shape( + result, + op=_OP_MAKE_LOFT_RSOLID, + params=params, + input_shapes=profiles, + ), + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_LOFT_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + if tracked is None: + return tagged + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_LOFT_RSOLID, + delta=tracked.delta, + start_role=("loft.start" if isinstance(profiles[0], Wire) else None), + end_role=("loft.end" if isinstance(profiles[-1], Wire) else None), + side_role="loft.side", + source_shapes=profiles, + ) + except Exception as e: + _wrap_public_api_error( + operation="loft_rsolid", + what_happened="Failed to loft the input profiles into a solid.", + possible_causes=[ + "Fewer than two sections were provided.", + "A Vertex section was used away from the start or end.", + "One or more Wire/Vertex sections are invalid or incompatible.", + "The kernel rejected the loft because the section geometry is inconsistent.", + ], + how_to_fix=[ + "Pass at least two Wire or endpoint Vertex sections.", + "Keep Wire topology compatible across sections.", + "If loft fails, inspect each section individually and simplify its geometry.", + ], + error=e, + ) + +def sweep_rsolid( + profile: Face, + path: Wire, + is_frenet: bool = False, + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Create a swept solid, with optional kernel-role-based tags.""" + make_solid = True # 默认创建实体 + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_SWEEP_RSOLID, + ( + ("sweep.start", start_face_tag), + ("sweep.end", end_face_tag), + ("sweep.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + tracked = cast( + TrackedResult, + tracked_sweep(profile, path, is_frenet=is_frenet), + ) + result = cast(Solid, tracked.shape) + + result._metadata = {**profile._metadata, **path._metadata} + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_SWEEP_RSOLID, + params={"is_frenet": bool(is_frenet)}, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[profile, path], + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_SWEEP_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_SWEEP_RSOLID, + delta=tracked.delta, + start_role="sweep.start", + end_role="sweep.end", + side_role="sweep.side", + source_shapes=[profile], + ) + except Exception as e: + _wrap_public_api_error( + operation="sweep_rsolid", + what_happened="Failed to sweep the profile along the path.", + possible_causes=[ + "The profile face is invalid.", + "The path wire is invalid or unsuitable for sweep.", + "The kernel rejected the sweep orientation or geometry.", + ], + how_to_fix=[ + "Pass a valid Face profile and a valid Wire path.", + "Check that the path wire is continuous and geometrically reasonable.", + "If sweep fails, simplify the profile or path before retrying.", + ], + error=e, + ) + +def twisted_sweep_rsolid( + profile: Face, + distance: ScalarLike, + twist_angle: ScalarLike, + axis: Tuple[float, float, float] = (0.0, 0.0, 1.0), + origin: Tuple[float, float, float] = (0.0, 0.0, 0.0), + *, + guide_radius: ScalarLike = 1.0, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Sweep a planar profile along a straight axis with linear rotation. + + ``twist_angle`` is the signed total rotation in degrees. The operation uses + a cylindrical auxiliary spine to define a continuous rotation law, yielding + one continuous side face per profile edge instead of a segmented ruled loft. + """ + try: + if not isinstance(profile, Face): + raise TypeError("profile must be a Face") + distance_value = float(evaluate_scalar(distance)) + twist_value = float(evaluate_scalar(twist_angle)) + guide_radius_value = float(evaluate_scalar(guide_radius)) + if not math.isfinite(distance_value) or distance_value <= 0.0: + raise ValueError("distance must be a finite positive number") + if not math.isfinite(twist_value): + raise ValueError("twist_angle must be finite") + if not math.isfinite(guide_radius_value) or guide_radius_value <= 0.0: + raise ValueError("guide_radius must be a finite positive number") + + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) + if len(axis_value) != 3 or len(origin_value) != 3: + raise ValueError("axis and origin must each contain three values") + cs = get_current_cs() + global_axis = cs.transform_vector(np.asarray(axis_value, dtype=float)) + global_origin = cs.transform_point(np.asarray(origin_value, dtype=float)) + axis_norm = float(np.linalg.norm(global_axis)) + if not math.isfinite(axis_norm) or axis_norm <= 1.0e-15: + raise ValueError("axis must be a finite non-zero vector") + global_axis /= axis_norm + resolved_axis = tuple(float(value) for value in global_axis) + resolved_origin = tuple(float(value) for value in global_origin) + + assignments = _normalize_operation_role_tags( + _OP_MAKE_TWISTED_SWEEP_RSOLID, + ( + ("twisted_sweep.start", start_face_tag), + ("twisted_sweep.end", end_face_tag), + ("twisted_sweep.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + tracked = cast( + TrackedResult, + tracked_twisted_sweep( + profile, + axis=resolved_axis, + origin=resolved_origin, + distance=distance_value, + twist_angle=twist_value, + guide_radius=guide_radius_value, + ), + ) + result = cast(Solid, tracked.shape) + kernel_metadata = result.get_metadata("twisted_sweep.kernel", {}) + result._metadata = profile._metadata.copy() + result.set_metadata("twisted_sweep.kernel", kernel_metadata) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_TWISTED_SWEEP_RSOLID, + params={ + "axis": axis, + "origin": origin, + "distance": distance, + "twist_angle": twist_angle, + "guide_radius": guide_radius, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[profile], + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_TWISTED_SWEEP_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_TWISTED_SWEEP_RSOLID, + delta=tracked.delta, + start_role="twisted_sweep.start", + end_role="twisted_sweep.end", + side_role="twisted_sweep.side", + source_shapes=[profile], + ) + except Exception as e: + _wrap_public_api_error( + operation="twisted_sweep_rsolid", + what_happened="Failed to sweep the profile with a linear axial rotation.", + possible_causes=[ + "The profile is invalid or contains inner wires.", + "The distance, twist angle, axis, or guide radius is invalid.", + "The requested twist causes self-intersection or kernel failure.", + ], + how_to_fix=[ + "Pass a valid planar Face without inner wires.", + "Use a positive distance and guide radius with a non-zero axis.", + "Reduce the twist angle or simplify the profile.", + ], + error=e, + ) + +def helical_sweep_rsolid( + profile: Wire, + pitch: float, + height: float, + radius: float, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Solid: + """Create a solid by sweeping a profile along a helical path.""" + try: + if get_active_session() is not None: + helix = make_helix_rwire(pitch, height, radius, center=center, dir=dir) + return sweep_rsolid( + make_face_from_wire_rface(profile), helix, is_frenet=True + ) + + if pitch <= 0: + raise ValueError("螺距必须大于0") + if height <= 0: + raise ValueError("高度必须大于0") + if radius <= 0: + raise ValueError("半径必须大于0") + + cs = get_current_cs() + global_center = cs.transform_point(np.array(center)) + global_dir = cs.transform_vector(np.array(dir)) + global_x_direction = cs.transform_vector(_default_plane_x_direction(dir)) + + result_shape = make_helical_sweep_solid( + profile.wrapped, + pitch, + height, + radius, + global_center, + global_dir, + x_direction=global_x_direction, + ) + result = Solid(result_shape) + + result._metadata = profile._metadata.copy() + result._apply_tag("solid.feature.helical_sweep", propagate=False) + + return result + except Exception as e: + _wrap_public_api_error( + operation="helical_sweep_rsolid", + what_happened="Failed to create the helical sweep solid.", + possible_causes=[ + "Pitch, height, or radius is not positive.", + "The input profile wire is invalid or cannot form a face.", + "The center or direction vector is invalid.", + "The underlying helix or sweep construction failed.", + ], + how_to_fix=[ + "Use positive pitch, height, and radius values.", + "Pass a valid profile wire that can be turned into a face.", + "Validate the center and direction inputs before retrying.", + "If the sweep still fails, try the explicit macro path: helix wire -> face from profile -> sweep.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/_operators_geometry.py b/src/simplecadapi/_operators_geometry.py new file mode 100644 index 00000000..ed24fa8f --- /dev/null +++ b/src/simplecadapi/_operators_geometry.py @@ -0,0 +1,3345 @@ +"""Geometry operator implementations.""" + +from __future__ import annotations + +from ._operation_support import * + +@dataclass(frozen=True) +class SurfaceBoundary: + """One edge constraint used by ``make_surface_patch_rface``.""" + + edge: Edge + continuity: str = "C0" + support: Optional[Face] = None + + def __post_init__(self) -> None: + if not isinstance(self.edge, Edge): + raise TypeError("SurfaceBoundary.edge must be an Edge") + if self.support is not None and not isinstance(self.support, Face): + raise TypeError("SurfaceBoundary.support must be a Face or None") + if str(self.continuity).upper() not in {"C0", "G1", "G2"}: + raise ValueError("SurfaceBoundary.continuity must be C0, G1, or G2") + + def as_dict(self) -> Dict[str, object]: + return { + "continuity": str(self.continuity).upper(), + "has_support": self.support is not None, + } + +@dataclass(frozen=True) +class SurfaceFillingSettings: + """Explicit OCCT filling controls; units are model units and radians.""" + + degree: int = 3 + points_per_curve: int = 15 + iterations: int = 2 + anisotropic: bool = False + tolerance_2d: float = 1e-5 + tolerance_3d: float = 1e-4 + angular_tolerance: float = 0.01 + curvature_tolerance: float = 0.1 + max_degree: int = 8 + max_segments: int = 9 + + def __post_init__(self) -> None: + if self.degree < 1 or self.points_per_curve < 2 or self.iterations < 1: + raise ValueError( + "filling degree, points_per_curve, and iterations must be positive" + ) + if self.max_degree < self.degree or self.max_segments < 1: + raise ValueError( + "max_degree must cover degree and max_segments must be positive" + ) + for name in ( + "tolerance_2d", + "tolerance_3d", + "angular_tolerance", + "curvature_tolerance", + ): + value = float(getattr(self, name)) + if not np.isfinite(value) or value <= 0: + raise ValueError(f"{name} must be a positive finite value") + + def as_dict(self) -> Dict[str, object]: + return cast(Dict[str, object], asdict(self)) + +def _surface_tag_output(shape: AnyShape, tag_prefix: Optional[str]) -> AnyShape: + if tag_prefix is None: + return shape + normalized = normalize_tag(tag_prefix, strict=True) + shape._apply_tag(f"{normalized}.{_shape_kind_token(shape)}", propagate=False) + return shape + +def _surface_point_grid( + points: Sequence[Sequence[Sequence[float]]], +) -> List[List[Tuple[float, float, float]]]: + rows = [ + [tuple(float(component) for component in point) for point in row] + for row in points + ] + if len(rows) < 2 or any(len(row) < 2 for row in rows): + raise ValueError("surface point grids require at least 2 rows and 2 columns") + width = len(rows[0]) + if any(len(row) != width for row in rows): + raise ValueError("surface point grids must be rectangular") + if any(len(point) != 3 for row in rows for point in row): + raise ValueError("surface points must contain exactly three coordinates") + if not all(np.isfinite(value) for row in rows for point in row for value in point): + raise ValueError("surface points must be finite") + return rows + +def _surface_global_point_grid( + points: Sequence[Sequence[Sequence[float]]], +) -> List[List[Tuple[float, float, float]]]: + cs = get_current_cs() + grid = _surface_point_grid(points) + return [ + [ + tuple(float(value) for value in cs.transform_point(np.asarray(point))) + for point in row + ] + for row in grid + ] + +def _surface_global_points( + points: Sequence[Sequence[float]], +) -> List[Tuple[float, float, float]]: + cs = get_current_cs() + result = [] + for point in points: + values = tuple(float(value) for value in point) + if len(values) != 3 or not all(np.isfinite(value) for value in values): + raise ValueError("surface constraint points must be finite 3D points") + result.append( + tuple(float(value) for value in cs.transform_point(np.asarray(values))) + ) + return result + +def _surface_local_point_grid( + points: Sequence[Sequence[Sequence[float]]], +) -> List[List[Tuple[float, float, float]]]: + return _surface_point_grid(points) + +def make_bezier_surface_rface( + control_points: Sequence[Sequence[Sequence[float]]], + weights: Optional[Sequence[Sequence[float]]] = None, + *, + tag_prefix: Optional[str] = None, +) -> Face: + """Create a trimmed Face carrying a tensor-product Bezier surface.""" + try: + local_points = _surface_local_point_grid(control_points) + global_points = _surface_global_point_grid(local_points) + global_weights = ( + None if weights is None else [list(map(float, row)) for row in weights] + ) + if global_weights is not None: + if len(global_weights) != len(local_points) or any( + len(row) != len(local_points[0]) for row in global_weights + ): + raise ValueError("Bezier weights must match the control-point grid") + if any( + weight <= 0 or not np.isfinite(weight) + for row in global_weights + for weight in row + ): + raise ValueError("Bezier weights must be positive finite values") + result = Face(make_bezier_surface(global_points, global_weights)) + result = cast( + Face, + _finalize_primitive_shape( + result, + op="make_bezier_surface_rface", + params={ + "control_points": local_points, + "weights": global_weights, + "tag_prefix": tag_prefix, + }, + tags={"primitive", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_bezier_surface_rface", + what_happened="Failed to create the Bezier surface face.", + possible_causes=[ + "The control-point grid is invalid or degenerate.", + "The kernel rejected the Bezier surface.", + ], + how_to_fix=[ + "Pass a rectangular finite grid with at least two rows and columns.", + "Use positive finite weights with the same dimensions as the grid.", + ], + error=e, + ) + +def make_cylindrical_surface_rface( + radius: ScalarLike, + u_range: Tuple[ScalarLike, ScalarLike], + v_range: Tuple[ScalarLike, ScalarLike], + origin: Tuple[float, float, float] = (0, 0, 0), + axis: Tuple[float, float, float] = (0, 0, 1), + x_direction: Optional[Tuple[float, float, float]] = None, + *, + tolerance: ScalarLike = 1e-7, + tag_prefix: Optional[str] = None, +) -> Face: + """Create a finite cylindrical carrier Face over explicit U/V ranges. + + ``radius``, V values, and ``tolerance`` use model length units. U values + are unitless raw radians, must increase, and may span at most one + revolution. Unit-aware angle expressions are not accepted for U because + the existing expression evaluator returns canonical angles in degrees. + """ + + try: + if expression_uses_units(radius) and infer_dimension(radius) != LENGTH: + raise ValueError("radius must use model length units") + if any( + expression_uses_units(value) and infer_dimension(value) != DIMENSIONLESS + for value in u_range + ): + raise ValueError( + "u_range must use unitless raw radians; unit-aware angle values " + "evaluate in degrees" + ) + if any( + expression_uses_units(value) and infer_dimension(value) != LENGTH + for value in v_range + ): + raise ValueError("v_range must use model length units") + if expression_uses_units(tolerance) and infer_dimension(tolerance) != LENGTH: + raise ValueError("tolerance must use model length units") + radius_value = evaluate_scalar(radius) + u_values = tuple(evaluate_scalar(value) for value in u_range) + v_values = tuple(evaluate_scalar(value) for value in v_range) + tolerance_value = float(evaluate_scalar(tolerance)) + if not np.isfinite(radius_value) or radius_value <= 0.0: + raise ValueError("radius must be a positive finite value") + if len(u_values) != 2 or not all(np.isfinite(value) for value in u_values): + raise ValueError("u_range must contain two finite values") + if len(v_values) != 2 or not all(np.isfinite(value) for value in v_values): + raise ValueError("v_range must contain two finite values") + u_span = u_values[1] - u_values[0] + v_span = v_values[1] - v_values[0] + if ( + u_span <= Precision.PConfusion_s() + or u_span > 2.0 * math.pi + Precision.Angular_s() + ): + raise ValueError( + "u_range must be increasing and span at most one revolution" + ) + if v_span <= Precision.Confusion_s(): + raise ValueError("v_range must be increasing beyond kernel confusion") + if not np.isfinite(tolerance_value) or tolerance_value <= 0.0: + raise ValueError("tolerance must be a positive finite value") + + origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + x_value = ( + tuple(float(value) for value in _default_plane_x_direction(axis_value)) + if x_direction is None + else cast(Tuple[float, float, float], evaluate_value(x_direction)) + ) + vectors = [ + tuple(float(value) for value in item) + for item in (origin_value, axis_value, x_value) + ] + if any( + len(item) != 3 or not all(np.isfinite(value) for value in item) + for item in vectors + ): + raise ValueError("origin, axis, and x_direction must be finite 3D values") + axis_norm = float(np.linalg.norm(vectors[1])) + x_norm = float(np.linalg.norm(vectors[2])) + if axis_norm <= 1e-12 or x_norm <= 1e-12: + raise ValueError("axis and x_direction must be non-zero") + parallel = abs(float(np.dot(vectors[1], vectors[2])) / (axis_norm * x_norm)) + if parallel >= 1.0 - 1e-12: + raise ValueError("axis and x_direction must not be parallel") + + cs = get_current_cs() + global_origin = cs.transform_point(np.asarray(vectors[0], dtype=float)) + global_axis = cs.transform_vector(np.asarray(vectors[1], dtype=float)) + global_x_direction = cs.transform_vector(np.asarray(vectors[2], dtype=float)) + result = cast( + Face, + _finalize_primitive_shape( + Face( + make_cylindrical_surface( + radius_value, + cast(Tuple[float, float], u_values), + cast(Tuple[float, float], v_values), + origin=global_origin, + axis=global_axis, + x_direction=global_x_direction, + tolerance=tolerance_value, + ) + ), + op="make_cylindrical_surface_rface", + params={ + "radius": radius, + "u_range": u_range, + "v_range": v_range, + "origin": origin, + "axis": axis, + "x_direction": x_direction, + "tolerance": tolerance, + "tag_prefix": tag_prefix, + }, + tags={"primitive", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_cylindrical_surface_rface", + what_happened="Failed to create the cylindrical surface face.", + possible_causes=[ + "The radius, U/V ranges, or tolerance is invalid.", + "The axis frame is degenerate or parallel.", + "The kernel rejected the bounded cylindrical surface.", + ], + how_to_fix=[ + "Use model length units for radius, V, and tolerance.", + "Pass increasing finite U bounds as unitless raw radians.", + "Keep the U span at or below one revolution and provide non-parallel axis directions.", + ], + error=e, + ) + +def fit_point_grid_rface( + points: Sequence[Sequence[Sequence[float]]], + *, + tolerance: float = 1e-3, + degree_min: int = 3, + degree_max: int = 8, + smoothing: Optional[Tuple[float, float, float]] = None, + tag_prefix: Optional[str] = None, +) -> Face: + """Fit a B-spline Face through a rectangular 3D point grid.""" + try: + tolerance_value = float(tolerance) + if not np.isfinite(tolerance_value) or tolerance_value <= 0: + raise ValueError("tolerance must be a positive finite value") + degree_min_value, degree_max_value = int(degree_min), int(degree_max) + if degree_min_value < 1 or degree_max_value < degree_min_value: + raise ValueError("degree_max must be greater than or equal to degree_min") + smoothing_values = ( + None if smoothing is None else tuple(float(v) for v in smoothing) + ) + if smoothing_values is not None and ( + len(smoothing_values) != 3 + or any(not np.isfinite(v) or v < 0 for v in smoothing_values) + ): + raise ValueError("smoothing must contain three finite non-negative weights") + local_points = _surface_local_point_grid(points) + global_points = _surface_global_point_grid(local_points) + result = Face( + fit_point_grid_surface( + global_points, + tolerance=tolerance_value, + degree_min=degree_min_value, + degree_max=degree_max_value, + smoothing=smoothing_values, + ) + ) + result = cast( + Face, + _finalize_primitive_shape( + result, + op="fit_point_grid_rface", + params={ + "points": local_points, + "tolerance": tolerance_value, + "degree_min": degree_min_value, + "degree_max": degree_max_value, + "smoothing": smoothing_values, + "tag_prefix": tag_prefix, + }, + tags={"primitive", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="fit_point_grid_rface", + what_happened="Failed to fit a B-spline surface face.", + possible_causes=[ + "The point grid or fitting controls are invalid.", + "The kernel fitting algorithm did not converge.", + ], + how_to_fix=[ + "Pass a rectangular finite point grid and positive tolerance.", + "Keep degree_min <= degree_max and use non-negative smoothing weights.", + ], + error=e, + ) + +def make_ruled_surface_rface( + edge_a: Edge, edge_b: Edge, *, tag_prefix: Optional[str] = None +) -> Face: + """Create a ruled Face spanning two compatible edges.""" + try: + if not isinstance(edge_a, Edge) or not isinstance(edge_b, Edge): + raise TypeError("make_ruled_surface_rface requires two Edge objects") + result = cast( + Face, + _finalize_derived_shape( + Face(make_ruled_face(edge_a.wrapped, edge_b.wrapped)), + op="make_ruled_surface_rface", + params={"tag_prefix": tag_prefix}, + input_shapes=[edge_a, edge_b], + tags={"derived", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_ruled_surface_rface", + what_happened="Failed to create the ruled surface face.", + possible_causes=[ + "The inputs are not edges.", + "The two edges cannot define a ruled surface.", + ], + how_to_fix=[ + "Pass two valid Edge objects with compatible parameterization." + ], + error=e, + ) + +def make_gordon_surface_rface( + profiles: Sequence[Edge], + guides: Sequence[Edge], + *, + tolerance: float = 1e-3, + tag_prefix: Optional[str] = None, +) -> Face: + """Create a Gordon Face from intersecting profile and guide edge networks.""" + try: + profile_list, guide_list = list(profiles), list(guides) + if len(profile_list) < 2 or len(guide_list) < 2: + raise ValueError( + "Gordon surfaces require at least two profiles and two guides" + ) + if not all(isinstance(edge, Edge) for edge in [*profile_list, *guide_list]): + raise TypeError("Gordon profiles and guides must contain only Edge objects") + if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: + raise ValueError("tolerance must be a positive finite value") + result = cast( + Face, + _finalize_derived_shape( + Face( + make_gordon_surface( + [edge.wrapped for edge in profile_list], + [edge.wrapped for edge in guide_list], + tolerance=float(tolerance), + ) + ), + op="make_gordon_surface_rface", + params={ + "profile_count": len(profile_list), + "guide_count": len(guide_list), + "tolerance": float(tolerance), + "tag_prefix": tag_prefix, + }, + input_shapes=[*profile_list, *guide_list], + tags={"derived", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_gordon_surface_rface", + what_happened="Failed to create the Gordon surface face.", + possible_causes=[ + "The curve network is too small, non-intersecting, or inconsistent.", + "The kernel Gordon interpolation failed.", + ], + how_to_fix=[ + "Pass at least two profiles and two guides whose endpoints form a compatible network.", + "Increase tolerance only when the source curves are numerically noisy.", + ], + error=e, + ) + +def make_surface_patch_rface( + boundaries: Sequence[SurfaceBoundary], + *, + points: Sequence[Sequence[float]] = (), + settings: Optional[SurfaceFillingSettings] = None, + holes: Sequence[Wire] = (), + tag_prefix: Optional[str] = None, +) -> Face: + """Fill a constrained boundary network into one Face, optionally with holes.""" + try: + boundary_list = list(boundaries) + if not boundary_list or not all( + isinstance(item, SurfaceBoundary) for item in boundary_list + ): + raise ValueError("boundaries must be a non-empty SurfaceBoundary sequence") + settings_value = settings or SurfaceFillingSettings() + if not isinstance(settings_value, SurfaceFillingSettings): + raise TypeError("settings must be SurfaceFillingSettings") + hole_list = list(holes) + if not all(isinstance(wire, Wire) for wire in hole_list): + raise TypeError("holes must contain only Wire objects") + support_shapes = [ + item.support for item in boundary_list if item.support is not None + ] + interleaved_inputs: List[AnyShape] = [] + for item in boundary_list: + interleaved_inputs.append(item.edge) + if item.support is not None: + interleaved_inputs.append(item.support) + input_shapes: List[AnyShape] = [*interleaved_inputs, *hole_list] + local_points = [tuple(float(v) for v in point) for point in points] + global_points = _surface_global_points(local_points) + result = cast( + Face, + _finalize_derived_shape( + Face( + make_filling_face( + [ + ( + item.edge.wrapped, + item.support.wrapped if item.support else None, + str(item.continuity).upper(), + ) + for item in boundary_list + ], + global_points, + settings=settings_value.as_dict(), + holes=[wire.wrapped for wire in hole_list], + ) + ), + op="make_surface_patch_rface", + params={ + "boundary_count": len(boundary_list), + "support_count": len(support_shapes), + "hole_count": len(hole_list), + "boundaries": [item.as_dict() for item in boundary_list], + "points": local_points, + "settings": settings_value.as_dict(), + "tag_prefix": tag_prefix, + }, + input_shapes=input_shapes, + tags={"derived", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_surface_patch_rface", + what_happened="Failed to fill the constrained surface patch.", + possible_causes=[ + "A boundary is invalid, open, or incompatible with its support face.", + "The filling controls are invalid or the kernel did not converge.", + ], + how_to_fix=[ + "Pass non-empty SurfaceBoundary values with valid Edge objects.", + "Use C0/G1/G2 continuity and explicit positive filling tolerances.", + ], + error=e, + ) + +def _validated_loft_sections( + sections: Sequence[Union[Wire, Vertex]], *, operation: str +) -> List[Union[Wire, Vertex]]: + section_list = list(sections) + if len(section_list) < 2: + raise ValueError(f"{operation} requires at least two sections") + if not all(isinstance(section, (Wire, Vertex)) for section in section_list): + raise TypeError( + f"{operation} sections must contain only Wire or Vertex objects" + ) + if not any(isinstance(section, Wire) for section in section_list): + raise ValueError(f"{operation} requires at least one Wire section") + if any(isinstance(section, Vertex) for section in section_list[1:-1]): + raise ValueError(f"{operation} allows Vertex sections only at the start or end") + return section_list + +def _pending_loft_role(shape: AnyShape, role: str, method: str) -> TopoRoleEntry: + return TopoRoleEntry( + ref=TopoRef( + "pending", + "pending", + 0, + { + "wire": TopoKind.WIRE, + "face": TopoKind.FACE, + }[_shape_kind_token(shape)], + _topo_id(shape.wrapped), + ), + role=role, + metadata={ + "coverage": "complete", + "status": "proven", + "evidence_kind": "kernel_operation_role", + "evidence_method": method, + }, + ) + +def _matching_shell_boundary(shell: Shell, profile: Wire) -> Wire: + profile_edges = list(profile.get_edges()) + matches = [ + boundary + for boundary in shell.get_wires() + if len(boundary.get_edges()) == len(profile_edges) + and all( + any( + edge.wrapped.IsSame(profile_edge.wrapped) + for edge in boundary.get_edges() + ) + for profile_edge in profile_edges + ) + ] + if len(matches) != 1: + raise ValueError( + f"loft endpoint profile must match exactly one result boundary, got {len(matches)}" + ) + return matches[0] + +def _apply_loft_role_metadata( + shape: AnyShape, delta: TopoDelta, *, op: str +) -> AnyShape: + candidates: Dict[Tuple[TopoKind, str], AnyShape] = {} + for kind, members in ( + (TopoKind.FACE, shape.get_faces() if hasattr(shape, "get_faces") else []), + (TopoKind.WIRE, shape.get_wires() if hasattr(shape, "get_wires") else []), + ): + for member in members: + candidates[(kind, _topo_id(member.wrapped))] = member + for entry in delta.roles: + member = candidates.get((entry.ref.kind, entry.ref.topo_id)) + if member is None: + continue + track = dict(member.get_metadata("track", {})) + roles = sorted({*track.get("result_roles", ()), entry.role}) + track.update( + { + "op": op, + "topo_id": entry.ref.topo_id, + "kind": entry.ref.kind.name, + "coverage": "complete", + "status": "proven", + "result_roles": roles, + } + ) + member.set_metadata("track", track) + return shape + +def _apply_shell_loft_tag_prefix( + shell: Shell, *, tag_prefix: Optional[str], has_start: bool, has_end: bool +) -> Shell: + if tag_prefix is None: + return shell + prefix = normalize_tag(tag_prefix, strict=True) + result: AnyShape = _apply_topology_identity_tag( + shell, + ShapeSelector("shell").exactly(1), + f"{prefix}.shell", + kind="shell", + local_name="shell", + authoring_source="simplecadapi.loft_rshell.tag_prefix", + ) + for present, role, local_name in ( + (has_start, "loft.start_wire", "start"), + (has_end, "loft.end_wire", "end"), + ): + if not present: + continue + result = _apply_topology_identity_tag( + cast(Shell, result), + ShapeSelector("wire").where(output_role(role)).exactly(1), + f"{prefix}.wire.{local_name}", + kind="wire", + local_name=local_name, + authoring_source="simplecadapi.loft_rshell.tag_prefix", + ) + result = _apply_topology_identity_tag( + cast(Shell, result), + ShapeSelector("face").where(output_role("loft.side")).at_least(1), + f"{prefix}.face.side", + kind="face", + local_name="side", + authoring_source="simplecadapi.loft_rshell.tag_prefix", + ) + return cast(Shell, result) + +def trim_surface_rface( + carrier: Face, + outer: Wire, + holes: Sequence[Wire] = (), + *, + tolerance: float = 1e-7, + tag_prefix: Optional[str] = None, +) -> Face: + """Trim a carrier Face to exactly one connected Face. + + Existing carrier bounds and holes are preserved by intersecting them with + the requested closed, simple outer loop and optional closed, simple holes. + Empty or disconnected intersections are rejected. Every trim curve must + lie on the carrier within ``tolerance``. Periodic carriers do not support + holes; their outer loop must fit within one seam period without crossing + the seam. + """ + + try: + if not isinstance(carrier, Face): + raise TypeError("carrier must be a Face") + if not isinstance(outer, Wire): + raise TypeError("outer must be a Wire") + hole_list = list(holes) + if not all(isinstance(wire, Wire) for wire in hole_list): + raise TypeError("holes must contain only Wire objects") + tolerance_value = float(tolerance) + if not np.isfinite(tolerance_value) or tolerance_value <= 0.0: + raise ValueError("tolerance must be a positive finite value") + result = Face( + trim_surface_face( + carrier.wrapped, + outer.wrapped, + [wire.wrapped for wire in hole_list], + tolerance=tolerance_value, + ) + ) + for source in (carrier, outer, *hole_list): + _attach_lineage_from_source( + source, + result, + derivation="fragment", + op="trim_surface_rface", + coverage="partial", + ) + result = cast( + Face, + _finalize_derived_shape( + result, + op="trim_surface_rface", + params={ + "hole_count": len(hole_list), + "tolerance": tolerance_value, + "tag_prefix": tag_prefix, + }, + input_shapes=[carrier, outer, *hole_list], + tags={"derived", "surface", "face", "trimmed"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="trim_surface_rface", + what_happened="Failed to trim the carrier surface face.", + possible_causes=[ + "A trim wire is open, invalid, or does not lie on the carrier.", + "A periodic trim crosses the carrier seam.", + "A hole intersects the outer boundary or another hole.", + "The bounded intersection is empty or has multiple connected regions.", + ], + how_to_fix=[ + "Pass one closed, simple outer Wire and optional closed, simple hole Wires.", + "Keep every trim curve on the carrier within tolerance and inside one periodic seam.", + "Choose boundaries whose carrier intersection is exactly one connected Face.", + ], + error=e, + ) + +def loft_rshell( + sections: Sequence[Union[Wire, Vertex]], + *, + ruled: bool = False, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_wire_tag: Optional[str] = None, + end_wire_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Shell: + """Create an open loft Shell with endpoint-Wire and side-Face naming.""" + try: + section_list = _validated_loft_sections(sections, operation="loft_rshell") + start_is_wire = isinstance(section_list[0], Wire) + end_is_wire = isinstance(section_list[-1], Wire) + if start_wire_tag is not None and not start_is_wire: + raise ValueError("start_wire_tag requires a Wire start section") + if end_wire_tag is not None and not end_is_wire: + raise ValueError("end_wire_tag requires a Wire end section") + assignments = _normalize_operation_role_tags( + "make_loft_rshell", + ( + ("loft.start_wire", start_wire_tag), + ("loft.end_wire", end_wire_tag), + ("loft.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + result = Shell( + make_loft_shell( + [section.wrapped for section in section_list], ruled=bool(ruled) + ) + ) + roles = [ + _pending_loft_role(face, "loft.side", "ResultSideFace") + for face in result.get_faces() + ] + if start_is_wire: + roles.append( + _pending_loft_role( + _matching_shell_boundary(result, cast(Wire, section_list[0])), + "loft.start_wire", + "EndpointBoundary", + ) + ) + if end_is_wire: + roles.append( + _pending_loft_role( + _matching_shell_boundary(result, cast(Wire, section_list[-1])), + "loft.end_wire", + "EndpointBoundary", + ) + ) + delta = TopoDelta(roles=tuple(roles)) + _apply_loft_role_metadata(result, delta, op="make_loft_rshell") + finalized = cast( + Shell, + _finalize_derived_shape( + result, + op="make_loft_rshell", + params={ + "section_count": len(section_list), + "ruled": bool(ruled), + "tag_prefix": tag_prefix, + }, + input_shapes=section_list, + tags={"derived", "surface", "shell"}, + topo_delta=delta, + ), + ) + target_kinds = _validate_operation_output_roles(delta, assignments) + tagged = cast( + Shell, + _apply_operation_role_tags( + finalized, + op="make_loft_rshell", + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ), + ) + return _apply_shell_loft_tag_prefix( + tagged, + tag_prefix=tag_prefix, + has_start=start_is_wire, + has_end=end_is_wire, + ) + except Exception as e: + _wrap_public_api_error( + operation="loft_rshell", + what_happened="Failed to create the surface loft shell.", + possible_causes=[ + "Sections are incompatible or a Vertex was used away from an endpoint.", + "The kernel loft algorithm failed.", + ], + how_to_fix=[ + "Pass at least two Wire or endpoint Vertex sections in loft order." + ], + error=e, + ) + +def sew_faces_rshell( + faces: Sequence[Face], *, tolerance: float = 1e-6, tag_prefix: Optional[str] = None +) -> Shell: + """Sew faces into exactly one connected Shell.""" + try: + face_list = list(faces) + if not face_list or not all(isinstance(face, Face) for face in face_list): + raise ValueError("sew_faces_rshell requires a non-empty Face sequence") + if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: + raise ValueError("tolerance must be a positive finite value") + sewn, result_face_indices = sew_faces_with_history_ocp( + [face.wrapped for face in face_list], tolerance=float(tolerance) + ) + result = cast( + Shell, + _finalize_derived_shape( + Shell(sewn), + op="sew_faces_rshell", + params={ + "face_count": len(face_list), + "tolerance": float(tolerance), + "tag_prefix": tag_prefix, + }, + input_shapes=face_list, + tags={"derived", "surface", "shell"}, + ), + ) + _carry_face_provenance( + result, face_list, result_face_indices=result_face_indices + ) + return cast(Shell, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="sew_faces_rshell", + what_happened="Failed to sew faces into one shell.", + possible_causes=[ + "Faces are disconnected or their gaps exceed tolerance.", + "The sewing result contains multiple shell components.", + ], + how_to_fix=["Pass connected Face objects and a positive sewing tolerance."], + error=e, + ) + +def make_solid_from_shell_rsolid( + shell: Shell, *, tag_prefix: Optional[str] = None +) -> Solid: + """Create an oriented Solid from one valid closed Shell.""" + + try: + if not isinstance(shell, Shell): + raise TypeError("make_solid_from_shell_rsolid requires a Shell") + solid = Solid(solid_from_shell(shell.wrapped)) + source_entities = shell._topology_cache.entities() + for target_entity in solid._topology_cache.entities(): + matches = [ + source_entity + for source_entity in source_entities + if source_entity.kind == target_entity.kind + and _same_semantic_topology( + source_entity.kind, + source_entity.representative, + target_entity.representative, + ) + ] + if len(matches) == 1 and matches[0].wrappers and target_entity.wrappers: + target_entity.wrappers[0]._copy_semantic_state_from( + matches[0].wrappers[0] + ) + _attach_lineage_from_source( + shell, + solid, + derivation="continuation", + op="make_solid_from_shell_rsolid", + coverage="partial", + ) + result = cast( + Solid, + _finalize_derived_shape( + solid, + op="make_solid_from_shell_rsolid", + params={"tag_prefix": tag_prefix}, + input_shapes=[shell], + tags={"derived", "surface", "solid"}, + ), + ) + _carry_face_provenance( + result, + shell.get_faces(), + allow_orientation_change=True, + replace_local_bindings=False, + ) + return cast(Solid, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_solid_from_shell_rsolid", + what_happened="Failed to create a solid from the shell.", + possible_causes=[ + "The input is not a Shell.", + "The shell is open, invalid, or cannot be oriented as one material boundary.", + ], + how_to_fix=[ + "Sew a valid closed shell before converting it to a solid.", + "Inspect free boundaries and face orientation when conversion fails.", + ], + error=e, + ) + +def free_boundaries_rwirelist(shell: Shell, *, tolerance: float = 1e-6) -> List[Wire]: + """Return unique closed and open free boundary wires of a Shell.""" + try: + if not isinstance(shell, Shell): + raise TypeError("free_boundaries_rwirelist requires a Shell") + if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: + raise ValueError("tolerance must be a positive finite value") + result = [ + Wire(wire) + for wire in free_boundaries_ocp(shell.wrapped, tolerance=float(tolerance)) + ] + record_operation_if_active( + op="free_boundaries_rwirelist", + params={"tolerance": float(tolerance)}, + outputs=result, + input_shapes=[shell], + semantic_delta=_semantic_delta_for_output( + "free_boundaries_rwirelist", + output_count=len(result), + entity_type="Profile", + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="free_boundaries_rwirelist", + what_happened="Failed to extract free boundary wires.", + possible_causes=[ + "The input is not a valid Shell.", + "The boundary analysis tolerance is invalid.", + ], + how_to_fix=["Pass a Shell and a positive finite tolerance."], + error=e, + ) + +def fill_holes_rshell( + shell: Shell, + hole_indices: Optional[Sequence[int]] = None, + *, + tolerance: float = 1e-6, + settings: Optional[SurfaceFillingSettings] = None, + tag_prefix: Optional[str] = None, +) -> Shell: + """Fill selected closed free boundaries and return a sewn Shell.""" + try: + if not isinstance(shell, Shell): + raise TypeError("fill_holes_rshell requires a Shell") + if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: + raise ValueError("tolerance must be a positive finite value") + settings_value = settings or SurfaceFillingSettings() + if not isinstance(settings_value, SurfaceFillingSettings): + raise TypeError("settings must be SurfaceFillingSettings") + indices = ( + None if hole_indices is None else [int(index) for index in hole_indices] + ) + result = cast( + Shell, + _finalize_derived_shape( + Shell( + fill_shell_holes_ocp( + shell.wrapped, + hole_indices=indices, + tolerance=float(tolerance), + settings=settings_value.as_dict(), + ) + ), + op="fill_holes_rshell", + params={ + "hole_indices": indices, + "tolerance": float(tolerance), + "settings": settings_value.as_dict(), + "tag_prefix": tag_prefix, + }, + input_shapes=[shell], + tags={"derived", "surface", "shell"}, + ), + ) + return cast(Shell, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="fill_holes_rshell", + what_happened="Failed to fill selected shell holes.", + possible_causes=[ + "A selected boundary is not a closed hole or the index is out of range.", + "The filling or sewing operation failed.", + ], + how_to_fix=[ + "Use free_boundaries_rwirelist() to inspect valid boundary indices before filling." + ], + error=e, + ) + +def _default_plane_x_direction(normal: Sequence[float]) -> np.ndarray: + """Return OCP's canonical in-plane X axis for a local normal.""" + normal_vec = np.asarray(normal, dtype=float) + axis = gp_Ax2( + gp_Pnt(0.0, 0.0, 0.0), + gp_Dir(float(normal_vec[0]), float(normal_vec[1]), float(normal_vec[2])), + ) + direction = axis.XDirection() + return np.asarray(direction.Coord(), dtype=float) + +def _pick_perpendicular_unit(axis: Tuple[float, float, float]) -> np.ndarray: + axis_vec = np.array(axis, dtype=float) + axis_norm = float(np.linalg.norm(axis_vec)) + if axis_norm <= 1e-12: + raise ValueError("轴向量不能是零向量") + axis_unit = axis_vec / axis_norm + ref_vec = ( + np.array([1.0, 0.0, 0.0]) + if abs(axis_unit[2]) > 0.9 + else np.array([0.0, 0.0, 1.0]) + ) + radial = np.cross(axis_unit, ref_vec) + radial_norm = float(np.linalg.norm(radial)) + if radial_norm <= 1e-12: + raise ValueError("无法根据给定轴向量构建旋转剖面") + return radial / radial_norm + +def _offset_point_expr( + center: Tuple[ScalarLike, ScalarLike, ScalarLike], + x_axis: Sequence[float], + y_axis: Sequence[float], + dx: ScalarLike, + dy: ScalarLike, +) -> Tuple[ScalarLike, ScalarLike, ScalarLike]: + return ( + center[0] + dx * float(x_axis[0]) + dy * float(y_axis[0]), + center[1] + dx * float(x_axis[1]) + dy * float(y_axis[1]), + center[2] + dx * float(x_axis[2]) + dy * float(y_axis[2]), + ) + +def _make_closed_profile_rwire( + points: Sequence[Tuple[ScalarLike, ScalarLike, ScalarLike]], +) -> Wire: + edges = [ + make_line_redge(points[index], points[(index + 1) % len(points)]) + for index in range(len(points)) + ] + return make_wire_from_edges_rwire(edges) + +def _make_closed_profile_rface( + points: Sequence[Tuple[ScalarLike, ScalarLike, ScalarLike]], + *, + normal: Tuple[float, float, float] = (0.0, 0.0, 1.0), +) -> Face: + return make_face_from_wire_rface(_make_closed_profile_rwire(points), normal=normal) + +def make_point_rvertex(x: ScalarLike, y: ScalarLike, z: ScalarLike) -> Vertex: + """Create a point in 3D space and return it as a vertex.""" + try: + cs = get_current_cs() + point_value = cast(Tuple[float, float, float], evaluate_value((x, y, z))) + global_point = cs.transform_point(np.array(point_value)) + vertex_shape = BRepBuilderAPI_MakeVertex( + gp_Pnt( + float(global_point[0]), float(global_point[1]), float(global_point[2]) + ) + ).Vertex() + return cast( + Vertex, + _finalize_primitive_shape( + Vertex(vertex_shape), + op=_OP_MAKE_POINT_RVERTEX, + params={"x": x, "y": y, "z": z}, + tags={"primitive", "vertex"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_point_rvertex", + what_happened="Failed to create a point vertex.", + possible_causes=[ + "One or more coordinate values are not valid finite scalars.", + "The current coordinate system rejected the transformed point.", + ], + how_to_fix=[ + "Pass numeric x, y, and z values or valid scalar expressions.", + "Inspect the coordinate values and the active workplane before retrying.", + ], + error=e, + ) + +def make_line_redge( + start: Tuple[ScalarLike, ScalarLike, ScalarLike], + end: Tuple[ScalarLike, ScalarLike, ScalarLike], + *, + tag_prefix: Optional[str] = None, +) -> Edge: + """Create a straight edge between two points.""" + try: + cs = get_current_cs() + start_value = cast(Tuple[float, float, float], evaluate_value(start)) + end_value = cast(Tuple[float, float, float], evaluate_value(end)) + start_global = cs.transform_point(np.array(start_value)) + end_global = cs.transform_point(np.array(end_value)) + + edge_shape = make_line_edge(start_global, end_global) + edge = cast( + Edge, + _finalize_primitive_shape( + Edge(edge_shape), + op=_OP_MAKE_LINE_REDGE, + params={"start": start, "end": end}, + tags={"primitive", "edge"}, + ), + ) + return cast( + Edge, + _apply_shape_tag_prefix( + edge, + tag_prefix, + kind="edge", + authoring_source="simplecadapi.make_line_redge.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_line_redge", + what_happened="Failed to create a line edge.", + possible_causes=[ + "The start or end point is not a valid finite 3D point.", + "The transformed points are degenerate or rejected by the kernel.", + ], + how_to_fix=[ + "Pass start and end as 3-element numeric tuples or valid expressions.", + "Ensure the two points are distinct and finite.", + ], + error=e, + ) + +def make_segment_redge( + start: Tuple[float, float, float], end: Tuple[float, float, float] +) -> Edge: + """Alias of `make_line_redge` that returns a straight edge.""" + return make_line_redge(start, end) + +def make_segment_rwire( + start: Tuple[float, float, float], end: Tuple[float, float, float] +) -> Wire: + """Create a wire containing a single straight segment.""" + try: + if get_active_session() is not None: + edge = make_line_redge(start, end) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_line_redge(start, end) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_segment_wire", + params={"start": start, "end": end}, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_segment_rwire", + what_happened="Failed to create a single-segment wire.", + possible_causes=[ + "The segment endpoints are invalid.", + "The kernel could not assemble the segment into a wire.", + ], + how_to_fix=[ + "Pass two valid 3D endpoints.", + "If the segment is computed dynamically, log the two endpoints before retrying.", + ], + error=e, + ) + +def make_circle_redge( + center: Tuple[float, float, float], + radius: ScalarLike, + normal: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, +) -> Edge: + """Create a circular edge.""" + try: + radius_value = evaluate_scalar(radius) + if radius_value <= 0: + raise ValueError("半径必须大于0") + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) + center_global = cs.transform_point(np.array(center_value)) + normal_global = cs.transform_vector(np.array(normal_value)) + x_direction_global = cs.transform_vector( + _default_plane_x_direction(normal_value) + ) + + edge_shape = make_circle_edge( + center_global, + radius_value, + normal_global, + x_direction=x_direction_global, + ) + edge = cast( + Edge, + _finalize_primitive_shape( + Edge(edge_shape), + op=_OP_MAKE_CIRCLE_REDGE, + params={"center": center, "radius": radius, "normal": normal}, + tags={"primitive", "edge"}, + ), + ) + return cast( + Edge, + _apply_shape_tag_prefix( + edge, + tag_prefix, + kind="edge", + authoring_source="simplecadapi.make_circle_redge.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_circle_redge", + what_happened="Failed to create a circular edge.", + possible_causes=[ + "The radius is not a positive finite scalar.", + "The center or normal is not a valid finite 3D vector.", + "The kernel rejected the circle definition.", + ], + how_to_fix=[ + "Use a radius greater than zero.", + "Pass finite center and normal vectors.", + "If the normal is computed dynamically, verify it is not zero-length.", + ], + error=e, + ) + +def make_circle_rwire( + center: Tuple[float, float, float], + radius: ScalarLike, + normal: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + edge_tag: Optional[str] = None, +) -> Wire: + """Create a circular wire.""" + try: + if get_active_session() is not None: + edge = make_circle_redge(center, radius, normal) + wire = make_wire_from_edges_rwire([edge]) + local_edge_tag = edge_tag or "circle" + return cast( + Wire, + _apply_profile_tag_prefix( + wire, + tag_prefix, + ( + [local_edge_tag] + if tag_prefix is not None or edge_tag is not None + else None + ), + authoring_source="simplecadapi.make_circle_rwire.tag_prefix", + ), + ) + + with suspend_graph_recording(): + edge = make_circle_redge(center, radius, normal) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + wire = cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_circle_wire", + params={"center": center, "radius": radius, "normal": normal}, + tags={"primitive", "wire"}, + ), + ) + local_edge_tag = edge_tag or "circle" + return cast( + Wire, + _apply_profile_tag_prefix( + wire, + tag_prefix, + ( + [local_edge_tag] + if tag_prefix is not None or edge_tag is not None + else None + ), + authoring_source="simplecadapi.make_circle_rwire.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_circle_rwire", + what_happened="Failed to create a circular wire.", + possible_causes=[ + "The circle edge could not be created.", + "The wire assembly step rejected the generated edge.", + ], + how_to_fix=[ + "Check the center, radius, and normal inputs.", + "Retry with a positive radius and a valid normal vector.", + ], + error=e, + ) + +def make_circle_rface( + center: Tuple[float, float, float], + radius: ScalarLike, + normal: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + edge_tag: Optional[str] = None, +) -> Face: + """Create a circular face.""" + try: + if get_active_session() is not None: + wire = make_circle_rwire( + center, + radius, + normal, + tag_prefix=tag_prefix, + edge_tag=edge_tag, + ) + return make_face_from_wire_rface(wire, normal=normal, tag_prefix=tag_prefix) + + with suspend_graph_recording(): + wire = make_circle_rwire( + center, + radius, + normal, + tag_prefix=tag_prefix, + edge_tag=edge_tag, + ) + face_shape = make_face_from_wire_ocp(wire.wrapped) + face = Face(face_shape) + face._metadata = wire._metadata.copy() + result = cast( + Face, + _finalize_primitive_shape( + face, + op="make_circle_face", + params={"center": center, "radius": radius, "normal": normal}, + tags={"primitive", "face"}, + ), + ) + result = cast( + Face, + _copy_exact_topology_identity_tags( + result, [wire], operation="make_circle_rface" + ), + ) + return cast( + Face, + _apply_shape_tag_prefix( + result, + tag_prefix, + kind="face", + authoring_source="simplecadapi.make_circle_rface.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_circle_rface", + what_happened="Failed to create a circular face.", + possible_causes=[ + "The underlying circular wire could not be created.", + "The kernel could not create a face from the wire.", + ], + how_to_fix=[ + "Verify the center, radius, and normal values.", + "Use a positive radius and a valid non-zero normal vector.", + ], + error=e, + ) + +def make_rectangle_rwire( + width: ScalarLike, + height: ScalarLike, + center: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 0), + normal: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + edge_tags: Optional[Sequence[str]] = None, +) -> Wire: + """Create a rectangular wire.""" + try: + width_value = evaluate_scalar(width) + height_value = evaluate_scalar(height) + if width_value <= 0 or height_value <= 0: + raise ValueError("宽度和高度必须大于0") + + if get_active_session() is not None: + normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) + _, x_axis, y_axis = _orthonormal_plane_axes(normal_value) + half_w = width / 2 + half_h = height / 2 + corners = [ + _offset_point_expr(center, x_axis, y_axis, -half_w, -half_h), + _offset_point_expr(center, x_axis, y_axis, half_w, -half_h), + _offset_point_expr(center, x_axis, y_axis, half_w, half_h), + _offset_point_expr(center, x_axis, y_axis, -half_w, half_h), + ] + wire = _make_closed_profile_rwire(corners) + return cast( + Wire, + _apply_profile_tag_prefix( + wire, + tag_prefix, + edge_tags, + authoring_source="simplecadapi.make_rectangle_rwire.tag_prefix", + ), + ) + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) + center_global = cs.transform_point(np.array(center_value)) + normal_global = cs.transform_vector(np.array(normal_value)) + + normal_norm = float(np.linalg.norm(normal_global)) + if normal_norm <= 1e-15 or not np.isfinite(normal_norm): + raise ValueError("法向量不能是零向量") + + _, local_x, local_y = _orthonormal_plane_axes(normal_value) + plane_x = cs.transform_vector(local_x) + plane_y = cs.transform_vector(local_y) + + # 创建矩形的四个顶点(在本地坐标系中) + half_w, half_h = width_value / 2, height_value / 2 + local_points = [ + (-half_w, -half_h), + (half_w, -half_h), + (half_w, half_h), + (-half_w, half_h), + ] + + # 转换到全局坐标系 + global_points = [] + for local_point in local_points: + # 在本地坐标系中的点 + point_3d = ( + center_global + local_point[0] * plane_x + local_point[1] * plane_y + ) + global_points.append(tuple(float(v) for v in point_3d)) + + # 创建边 + wire_points = [ + (float(point[0]), float(point[1]), float(point[2])) + for point in global_points + ] + wire_shape = make_polyline_wire(wire_points, closed=True) + wire = cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_rectangle_wire", + params={ + "width": width, + "height": height, + "center": center, + "normal": normal, + }, + tags={"primitive", "wire"}, + ), + ) + return cast( + Wire, + _apply_profile_tag_prefix( + wire, + tag_prefix, + edge_tags, + authoring_source="simplecadapi.make_rectangle_rwire.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_rectangle_rwire", + what_happened="Failed to create a rectangular wire.", + possible_causes=[ + "Width or height is not a positive finite scalar.", + "The center or normal is not a valid finite 3D vector.", + "The local rectangle basis became degenerate.", + ], + how_to_fix=[ + "Use width and height values greater than zero.", + "Pass a valid center and a non-zero normal vector.", + "If the normal is near zero, normalize or replace it before retrying.", + ], + error=e, + ) + +def make_rectangle_rface( + width: ScalarLike, + height: ScalarLike, + center: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 0), + normal: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + edge_tags: Optional[Sequence[str]] = None, +) -> Face: + """Create a rectangular face.""" + try: + if get_active_session() is not None: + wire = make_rectangle_rwire( + width, + height, + center, + normal, + tag_prefix=tag_prefix, + edge_tags=edge_tags, + ) + return make_face_from_wire_rface( + wire, normal=cast(Any, normal), tag_prefix=tag_prefix + ) + + with suspend_graph_recording(): + wire = make_rectangle_rwire( + width, + height, + center, + normal, + tag_prefix=tag_prefix, + edge_tags=edge_tags, + ) + face_shape = make_face_from_wire_ocp(wire.wrapped) + face = Face(face_shape) + face._metadata = wire._metadata.copy() + result = cast( + Face, + _finalize_primitive_shape( + face, + op="make_rectangle_face", + params={ + "width": width, + "height": height, + "center": center, + "normal": normal, + }, + tags={"primitive", "face"}, + ), + ) + result = cast( + Face, + _copy_exact_topology_identity_tags( + result, [wire], operation="make_rectangle_rface" + ), + ) + return cast( + Face, + _apply_shape_tag_prefix( + result, + tag_prefix, + kind="face", + authoring_source="simplecadapi.make_rectangle_rface.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_rectangle_rface", + what_happened="Failed to create a rectangular face.", + possible_causes=[ + "The rectangular wire could not be created.", + "The face construction step rejected the generated wire.", + ], + how_to_fix=[ + "Verify width, height, center, and normal.", + "Retry with positive dimensions and a valid non-zero normal vector.", + ], + error=e, + ) + +def make_face_from_wire_rface( + wire: Wire, + normal: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, +) -> Face: + """Create a face from a closed wire.""" + try: + if not isinstance(wire, Wire): + raise ValueError("输入必须是Wire类型") + + # 检查Wire是否封闭 + if not wire.is_closed(): + raise ValueError("Wire必须是封闭的才能创建面") + + # The wire is already global geometry; only the requested local normal + # is resolved through the active workplane chain. + cs = get_current_cs() + global_normal = cs.transform_vector(np.array(normal)) + + # 标准化法向量 + normal_vec = global_normal / np.linalg.norm(global_normal) + + # 创建面 + face_shape = make_face_from_wire_ocp(wire.wrapped) + face = Face(face_shape) + + # 检查面的法向量是否与期望方向一致 + face_normal = face.get_normal_at() + face_normal_vec = np.array([face_normal.x, face_normal.y, face_normal.z]) + + # 计算法向量的点积,如果小于0则需要反向 + dot_product = np.dot(normal_vec, face_normal_vec) + + if dot_product < 0: + # 反向面(通过反向Wire的方向) + # OCP Wire 没有直接的 reverse 包装方法,这里重新构建 + # 简单的方法是使用makeFromWires的orientation参数 + # 或者我们接受当前面的方向,添加一个警告 + print(f"警告: 创建的面的法向量与期望方向相反 (点积: {dot_product:.3f})") + + face._metadata = wire._metadata.copy() + + result = cast( + Face, + _finalize_derived_shape( + face, + op=_OP_MAKE_FACE_FROM_WIRE_RFACE, + params={"normal": normal}, + input_shapes=[wire], + tags={"derived", "face"}, + ), + ) + result = cast( + Face, + _copy_exact_topology_identity_tags( + result, [wire], operation="make_face_from_wire_rface" + ), + ) + return cast( + Face, + _apply_shape_tag_prefix( + result, + tag_prefix, + kind="face", + authoring_source="simplecadapi.make_face_from_wire_rface.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_face_from_wire_rface", + what_happened="Failed to create a face from the input wire.", + possible_causes=[ + "The input is not a Wire instance.", + "The wire is open or geometrically invalid.", + "The kernel rejected the closed wire when building a face.", + ], + how_to_fix=[ + "Pass a Wire object, not an Edge or a list of points.", + "Ensure the wire is closed before calling this API.", + "If the wire was assembled from edges, verify the edges connect end-to-end.", + ], + error=e, + ) + +def make_face_from_wires_rface( + outer_wire: Wire, + inner_wires: Sequence[Wire], + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Face: + """Create a face from one outer closed wire and optional inner closed wires.""" + try: + if not isinstance(outer_wire, Wire): + raise ValueError("outer_wire must be a Wire") + if not outer_wire.is_closed(): + raise ValueError("outer_wire must be closed") + + inner_list = list(inner_wires or []) + for inner_wire in inner_list: + if not isinstance(inner_wire, Wire): + raise ValueError("inner_wires must contain only Wire objects") + if not inner_wire.is_closed(): + raise ValueError("inner wires must be closed") + + cs = get_current_cs() + global_normal = cs.transform_vector(np.array(normal)) + normal_norm = float(np.linalg.norm(global_normal)) + if normal_norm <= 1e-15 or not np.isfinite(normal_norm): + raise ValueError("normal must be a non-zero finite vector") + normal_vec = global_normal / normal_norm + + face_shape = make_face_from_wires_ocp( + outer_wire.wrapped, + [inner_wire.wrapped for inner_wire in inner_list], + ) + face = Face(face_shape) + + face_normal = face.get_normal_at() + face_normal_vec = np.array([face_normal.x, face_normal.y, face_normal.z]) + dot_product = float(np.dot(normal_vec, face_normal_vec)) + if dot_product < 0: + print(f"警告: 创建的面的法向量与期望方向相反 (点积: {dot_product:.3f})") + + face._metadata = outer_wire._metadata.copy() + + return cast( + Face, + _finalize_derived_shape( + face, + op=_OP_MAKE_FACE_FROM_WIRES_RFACE, + params={"normal": normal, "inner_wire_count": len(inner_list)}, + input_shapes=[outer_wire, *inner_list], + tags={"derived", "face"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_face_from_wires_rface", + what_happened="Failed to create a face from the input outer and inner wires.", + possible_causes=[ + "The outer wire is not a Wire instance or is not closed.", + "One or more inner wires are not Wire instances or are not closed.", + "The inner wires are not contained by the outer wire or are geometrically invalid.", + "The kernel rejected the multi-loop face definition.", + ], + how_to_fix=[ + "Pass one closed outer Wire and zero or more closed inner Wire objects.", + "Ensure every inner wire lies inside the outer wire and does not intersect other loops.", + "Use a valid non-zero normal vector.", + ], + error=e, + ) + +def make_wire_from_edges_rwire( + edges: List[Edge], *, tag_prefix: Optional[str] = None +) -> Wire: + """Create a wire from a list of connected edges.""" + try: + if not edges: + raise ValueError("边列表不能为空") + + wire_shape = make_wire_from_edges_ocp([edge.wrapped for edge in edges]) + result = cast( + Wire, + _finalize_derived_shape( + Wire(wire_shape), + op=_OP_MAKE_WIRE_FROM_EDGES_RWIRE, + params={"edge_count": len(edges)}, + input_shapes=edges, + tags={"derived", "wire"}, + ), + ) + result = cast( + Wire, + _copy_exact_topology_identity_tags( + result, edges, operation="make_wire_from_edges_rwire" + ), + ) + return cast( + Wire, + _apply_shape_tag_prefix( + result, + tag_prefix, + kind="wire", + authoring_source="simplecadapi.make_wire_from_edges_rwire.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_wire_from_edges_rwire", + what_happened="Failed to assemble a wire from the input edges.", + possible_causes=[ + "The edge list is empty.", + "One or more items are invalid edges.", + "The edges do not connect into a valid wire chain.", + ], + how_to_fix=[ + "Pass a non-empty list of Edge objects.", + "Ensure consecutive edges share matching endpoints.", + "Inspect the edge order if the wire should form a closed loop.", + ], + error=e, + ) + +def load_brep_region_rsolid( + path: str | Path, + sha256: str, + *, + tag_prefix: Optional[str] = None, +) -> Solid: + """Load a hash-pinned, target-derived BREP region snapshot as one Solid. + + The complete artifact SHA-256 is verified before native BREP decoding. In a + GraphSession, ``path`` must be relative and is replayed relative to the replay + process working directory. Model JSON records the locator and digest, not the + sidecar bytes. + """ + + try: + return cast( + Solid, + _load_brep_region_rshape( + path, + sha256, + root_kind="solid", + tag_prefix=tag_prefix, + replay_root=(Path.cwd() if get_active_session() is not None else None), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="load_brep_region_rsolid", + what_happened="Failed to load the BREP region snapshot.", + possible_causes=[ + "The snapshot path does not exist or is not readable.", + "The supplied SHA-256 does not match the snapshot bytes.", + "The snapshot is corrupt, unsupported, invalid, or not one solid.", + ], + how_to_fix=[ + "Create the snapshot with copy_step_region_rpath(...).", + "Pass the SHA-256 of the complete .scadbrep file.", + "Keep the sidecar at the same path when replaying model JSON.", + ], + error=e, + ) + +def _carry_face_provenance( + shape: Shell | Solid, + source_faces: Sequence[Face], + *, + result_face_indices: Optional[Sequence[int]] = None, + allow_orientation_change: bool = False, + replace_local_bindings: bool = True, +) -> None: + result_faces = list(shape.get_faces()) + if result_face_indices is None: + mapped_indices = [] + for source in source_faces: + matches = [ + index + for index, result in enumerate(result_faces) + if result.wrapped.IsSame(source.wrapped) + ] + if len(matches) != 1: + raise ValueError("face continuation mapping is incomplete or ambiguous") + mapped_indices.append(matches[0]) + else: + mapped_indices = [int(index) for index in result_face_indices] + if len(mapped_indices) != len(source_faces) or len(set(mapped_indices)) != len( + result_faces + ): + raise ValueError("face continuation mapping is not one-to-one") + for source, result_index in zip(source_faces, mapped_indices): + if result_index < 0 or result_index >= len(result_faces): + raise ValueError( + "face continuation mapping contains an invalid result index" + ) + face = result_faces[result_index] + provenance = source.get_metadata("provenance") + if ( + isinstance(provenance, dict) + and provenance.get("construction") == "exact_transcription" + and not allow_orientation_change + and not face.wrapped.IsEqual(source.wrapped) + ): + raise ValueError("sewing modified an exact-transcription input face") + projected_bindings = [ + binding + for binding in source._local_tag_bindings() + if lineage_policy_allows(binding.propagation, "continuation") + ] + if replace_local_bindings: + face._replace_local_tag_bindings(projected_bindings) + _attach_lineage_from_source( + source, + face, + derivation="continuation", + op="face_continuation", + coverage="complete", + ) + if isinstance(provenance, dict): + face.set_metadata("provenance", dict(provenance)) + face._set_runtime("semantic.lineage.coverage", "complete") + +def load_brep_region_rshell( + path: str | Path, + sha256: str, + *, + tag_prefix: Optional[str] = None, +) -> Shell: + """Load a hash-pinned, target-derived BREP face region as one Shell. + + The Shell keeps target-derived topology and is tagged with imported-sidecar + provenance. Use ordinary replayable surface operations to join it to fitted + or analytic feature faces. GraphSession requires a relative sidecar path. + """ + + try: + return cast( + Shell, + _load_brep_region_rshape( + path, + sha256, + root_kind="shell", + tag_prefix=tag_prefix, + replay_root=(Path.cwd() if get_active_session() is not None else None), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="load_brep_region_rshell", + what_happened="Failed to load the BREP face-region snapshot.", + possible_causes=[ + "The snapshot path or SHA-256 is incorrect.", + "The snapshot is corrupt, unsupported, invalid, or not one Shell.", + ], + how_to_fix=[ + "Create a face-region snapshot with copy_step_region_rpath(..., face_ids=[...]).", + "Pass the SHA-256 of the complete .scadbrep file.", + ], + error=e, + ) + +def _load_brep_region_rshape( + path: str | Path, + sha256: str, + *, + root_kind: str, + tag_prefix: Optional[str], + replay_root: Path | None, +) -> Shell | Solid: + source_path = _brep_region_path(path, for_graph=replay_root is not None) + wrapped, manifest, canonical_hash = read_artifact( + source_path, + sha256, + expected_root_kind=cast(Any, root_kind), + replay_root=replay_root, + ) + shape: Shell | Solid = Solid(wrapped) if root_kind == "solid" else Shell(wrapped) + shape._add_tag("imported") + shape._add_tag("sidecar") + shape._add_tag(root_kind) + normalized_prefix = ( + normalize_tag(tag_prefix, strict=True) if tag_prefix is not None else None + ) + if normalized_prefix is not None: + shape._apply_tag(f"{normalized_prefix}.{root_kind}", propagate=False) + shape.set_metadata( + "brep_region", + { + "artifact_sha256": canonical_hash, + "profile": manifest["profile"], + "provenance": manifest["provenance"], + "source_face_ids": manifest["region"].get("source_face_ids"), + }, + ) + _attach_brep_region_provenance(shape, manifest, canonical_hash) + op = ( + _OP_LOAD_BREP_REGION_RSOLID + if root_kind == "solid" + else _OP_LOAD_BREP_REGION_RSHELL + ) + return cast( + Shell | Solid, + _finalize_primitive_shape( + shape, + op=op, + params={ + "path": source_path, + "sha256": canonical_hash, + "tag_prefix": normalized_prefix, + }, + tags={"imported", "sidecar", root_kind}, + ), + ) + +def _attach_brep_region_provenance( + shape: Shell | Solid, + manifest: Mapping[str, Any], + artifact_sha256: str, +) -> None: + source = manifest["source"] + region = manifest["region"] + evidence = { + "artifact_sha256": artifact_sha256, + "profile": manifest["profile"], + "source_sha256": source["content_hash"], + "source_name": source["name"], + "source_face_ids": region.get("source_face_ids"), + "construction": "exact_transcription", + "topology_origin": "retained", + "runtime_dependency": "embedded_target_derived", + } + root_binding = TagBinding( + tag="provenance.exact_transcription", + producer=TagProducer(TagProducerKind.IMPORTED_SIDECAR), + target=TagTarget(TagTargetKind.SCOPE_ROOT), + propagation=TagPropagation( + topology=TopologyPropagation.DOWNWARD, + lineage=LineagePolicy.CONTINUATION_FRAGMENT, + ), + evidence=TagEvidence(TagEvidenceKind.IMPORTED_SIDECAR, evidence), + certainty=TagCertainty.ASSERTED, + lifecycle=TagLifecycle.SNAPSHOT, + binding_id=f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, '|'.join(('simplecad.brep_region.root', artifact_sha256, str(region['kind'])))).hex}", + ) + shape._add_tag_binding(root_binding) + source_face_ids = tuple(region.get("source_face_ids") or ()) + for index, face in enumerate(shape.get_faces()): + face_evidence = { + **evidence, + "source_face_id": ( + source_face_ids[index] if index < len(source_face_ids) else None + ), + } + face.set_metadata("provenance", face_evidence) + face._add_tag_binding( + TagBinding( + tag="provenance.exact_transcription", + producer=TagProducer(TagProducerKind.IMPORTED_SIDECAR), + target=TagTarget(TagTargetKind.SCOPE_ROOT), + propagation=TagPropagation( + topology=TopologyPropagation.LOCAL, + lineage=LineagePolicy.CONTINUATION_FRAGMENT, + ), + evidence=TagEvidence(TagEvidenceKind.IMPORTED_SIDECAR, face_evidence), + certainty=TagCertainty.ASSERTED, + lifecycle=TagLifecycle.SNAPSHOT, + binding_id=f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, '|'.join(('simplecad.brep_region.face', artifact_sha256, str(face_evidence['source_face_id'])))).hex}", + ) + ) + face._set_runtime("semantic.lineage.coverage", "complete") + +def _brep_region_path(path: str | Path, *, for_graph: bool) -> str: + source = Path(path) + if ":" in source.name: + raise ValueError(".scadbrep filenames must not contain ':'") + if for_graph and source.is_absolute(): + raise ValueError( + "GraphSession requires a relative .scadbrep path so model JSON does " + "not record machine-specific absolute paths" + ) + if for_graph and source.drive: + raise ValueError("GraphSession .scadbrep paths must not contain a drive") + if for_graph and ".." in source.parts: + raise ValueError(".scadbrep paths must not traverse parent directories") + if for_graph and "\\" in str(path): + raise ValueError("GraphSession .scadbrep paths must use '/' separators") + if source.suffix.lower() != ".scadbrep": + raise ValueError("path must end in .scadbrep") + return source.as_posix() if for_graph else str(source) + +def make_box_rsolid( + width: ScalarLike, + height: ScalarLike, + depth: ScalarLike, + bottom_face_center: Tuple[float, float, float] = (0, 0, 0), + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + bottom_face_tag: Optional[str] = None, + top_face_tag: Optional[str] = None, + front_face_tag: Optional[str] = None, + back_face_tag: Optional[str] = None, + left_face_tag: Optional[str] = None, + right_face_tag: Optional[str] = None, +) -> Solid: + """Create a box with native kernel-backed Face topology tags.""" + try: + assignments = _normalize_operation_role_tags( + "make_box_rsolid", + ( + ("box.bottom", bottom_face_tag), + ("box.top", top_face_tag), + ("box.front", front_face_tag), + ("box.back", back_face_tag), + ("box.left", left_face_tag), + ("box.right", right_face_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + width_value = evaluate_scalar(width) + height_value = evaluate_scalar(height) + depth_value = evaluate_scalar(depth) + + if width_value <= 0 or height_value <= 0 or depth_value <= 0: + raise ValueError("宽度、高度和深度必须大于0") + + cs = get_current_cs() + center_value = cast( + Tuple[float, float, float], evaluate_value(bottom_face_center) + ) + center_global = cs.transform_point(np.array(center_value)) + corner_global = ( + center_global + - np.asarray(cs.x_axis, dtype=float) * (width_value / 2.0) + - np.asarray(cs.y_axis, dtype=float) * (height_value / 2.0) + ) + tracked = cast( + TrackedResult, + tracked_box( + tuple(float(value) for value in corner_global), + width_value, + height_value, + depth_value, + x_axis=tuple(float(value) for value in cs.x_axis), + y_axis=tuple(float(value) for value in cs.y_axis), + z_axis=tuple(float(value) for value in cs.z_axis), + ), + ) + solid = cast(Solid, tracked.shape) + + # 自动标记面 + solid.auto_tag_faces("box") + solid._apply_tag("geom.primitive.box", propagate=False) + solid._add_tag("box") + solid.set_metadata( + "geo", + { + "type": "box", + "size": {"x": width_value, "y": height_value, "z": depth_value}, + "bottom_face_center": bottom_face_center, + }, + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op="make_box_rsolid", + params={ + "width": width, + "height": height, + "depth": depth, + "bottom_face_center": bottom_face_center, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + ) + tagged = _apply_operation_role_tags( + finalized, + op="make_box_rsolid", + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op="make_box_rsolid", + delta=tracked.delta, + face_roles=( + ("box.bottom", "bottom"), + ("box.top", "top"), + ("box.front", "front"), + ("box.back", "back"), + ("box.left", "left"), + ("box.right", "right"), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_box_rsolid", + what_happened="Failed to create a box solid.", + possible_causes=[ + "Width, height, or depth is not a positive finite scalar.", + "The bottom face center is not a valid finite 3D point.", + "The kernel rejected the box dimensions or placement.", + ], + how_to_fix=[ + "Use width, height, and depth values greater than zero.", + "Pass bottom_face_center as a finite 3D tuple.", + "If dimensions come from expressions, inspect the evaluated numeric values.", + ], + error=e, + ) + +def make_cylinder_rsolid( + radius: ScalarLike, + height: ScalarLike, + bottom_face_center: Tuple[float, float, float] = (0, 0, 0), + axis: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_face_tag: Optional[str] = None, + start_edge_tag: Optional[str] = None, + end_edge_tag: Optional[str] = None, + seam_edge_tag: Optional[str] = None, +) -> Solid: + """Create a cylinder with native kernel-backed Face and Edge topology tags.""" + try: + assignments = _normalize_operation_role_tags( + "make_cylinder_rsolid", + ( + ("cylinder.start", start_face_tag), + ("cylinder.end", end_face_tag), + ("cylinder.side", side_face_tag), + ("cylinder.start_boundary", start_edge_tag), + ("cylinder.end_boundary", end_edge_tag), + ("cylinder.seam", seam_edge_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + radius_value = evaluate_scalar(radius) + height_value = evaluate_scalar(height) + if radius_value <= 0 or height_value <= 0: + raise ValueError("半径和高度必须大于0") + + cs = get_current_cs() + center_value = cast( + Tuple[float, float, float], evaluate_value(bottom_face_center) + ) + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + center_global = cs.transform_point(np.array(center_value)) + axis_global = cs.transform_vector(np.array(axis_value)) + + resolved_center = tuple(float(value) for value in center_global) + resolved_axis = tuple(float(value) for value in axis_global) + tracked = cast( + TrackedResult, + tracked_cylinder( + resolved_center, + resolved_axis, + radius_value, + height_value, + ), + ) + solid = cast(Solid, tracked.shape) + + # 自动标记面 + solid.auto_tag_faces("cylinder") + solid._apply_tag("geom.primitive.cylinder", propagate=False) + solid._add_tag("cylinder") + solid.set_metadata( + "geo", + { + "type": "cylinder", + "radius": radius_value, + "height": height_value, + "bottom_face_center": bottom_face_center, + "axis": axis, + }, + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op="make_cylinder_rsolid", + params={ + "radius": radius, + "height": height, + "bottom_face_center": bottom_face_center, + "axis": axis, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + ) + tagged = _apply_operation_role_tags( + finalized, + op="make_cylinder_rsolid", + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op="make_cylinder_rsolid", + delta=tracked.delta, + start_role="cylinder.start", + end_role="cylinder.end", + side_role="cylinder.side", + edge_roles=( + ("cylinder.start_boundary", "start"), + ("cylinder.end_boundary", "end"), + ("cylinder.seam", "seam"), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_cylinder_rsolid", + what_happened="Failed to create a cylinder solid.", + possible_causes=[ + "Radius or height is not a positive finite scalar.", + "The bottom face center or axis is not a valid finite 3D vector.", + "The axis is degenerate or rejected by the kernel.", + ], + how_to_fix=[ + "Use radius and height values greater than zero.", + "Pass a valid bottom_face_center and a non-zero axis vector.", + "If the axis is computed dynamically, inspect its evaluated numeric value.", + ], + error=e, + ) + +def make_cone_rsolid( + bottom_radius: ScalarLike, + height: ScalarLike, + top_radius: ScalarLike = 0.0, + bottom_face_center: Tuple[float, float, float] = (0, 0, 0), + axis: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_face_tag: Optional[str] = None, + start_edge_tag: Optional[str] = None, + end_edge_tag: Optional[str] = None, + seam_edge_tag: Optional[str] = None, +) -> Solid: + """Create a cone or frustum with native kernel-backed topology tags.""" + try: + assignments = _normalize_operation_role_tags( + "make_cone_rsolid", + ( + ("cone.start", start_face_tag), + ("cone.end", end_face_tag), + ("cone.side", side_face_tag), + ("cone.start_boundary", start_edge_tag), + ("cone.end_boundary", end_edge_tag), + ("cone.seam", seam_edge_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + bottom_radius_value = evaluate_scalar(bottom_radius) + height_value = evaluate_scalar(height) + top_radius_value = evaluate_scalar(top_radius) + if bottom_radius_value <= 0 or height_value <= 0: + raise ValueError("底面半径和高度必须大于0") + + cs = get_current_cs() + center_value = cast( + Tuple[float, float, float], evaluate_value(bottom_face_center) + ) + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + center_global = cs.transform_point(np.array(center_value)) + axis_global = cs.transform_vector(np.array(axis_value)) + + resolved_center = tuple(float(value) for value in center_global) + resolved_axis = tuple(float(value) for value in axis_global) + tracked = cast( + TrackedResult, + tracked_cone( + resolved_center, + resolved_axis, + bottom_radius_value, + top_radius_value, + height_value, + ), + ) + solid = cast(Solid, tracked.shape) + + # 自动标记面 + solid._apply_tag("geom.primitive.cone", propagate=False) + solid._add_tag("cone") + solid.set_metadata( + "geo", + { + "type": "cone", + "bottom_radius": bottom_radius_value, + "top_radius": top_radius_value, + "height": height_value, + "bottom_face_center": bottom_face_center, + "axis": axis, + }, + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op="make_cone_rsolid", + params={ + "bottom_radius": bottom_radius, + "top_radius": top_radius, + "height": height, + "bottom_face_center": bottom_face_center, + "axis": axis, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + ) + tagged = _apply_operation_role_tags( + finalized, + op="make_cone_rsolid", + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op="make_cone_rsolid", + delta=tracked.delta, + start_role="cone.start", + end_role="cone.end" if top_radius_value > 0.0 else None, + side_role="cone.side", + edge_roles=( + ("cone.start_boundary", "start"), + ("cone.end_boundary", "end"), + ("cone.seam", "seam"), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_cone_rsolid", + what_happened="Failed to create a cone or truncated cone solid.", + possible_causes=[ + "Bottom radius or height is not a positive finite scalar.", + "The bottom face center or axis is not a valid finite 3D vector.", + "The kernel rejected the cone dimensions or orientation.", + ], + how_to_fix=[ + "Use a positive bottom radius and a positive height.", + "Pass a valid center point and non-zero axis vector.", + "If top_radius is used, make sure it is a finite scalar.", + ], + error=e, + ) + +def make_sphere_rsolid( + radius: ScalarLike, center: Tuple[float, float, float] = (0, 0, 0) +) -> Solid: + """Create a sphere solid.""" + try: + radius_value = evaluate_scalar(radius) + if radius_value <= 0: + raise ValueError("半径必须大于0") + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + center_global = cs.transform_point(np.array(center_value)) + + resolved_center = tuple(float(value) for value in center_global) + solid = cast( + Solid, + Solid(make_sphere_solid(resolved_center, radius_value)), + ) + + # 自动标记面 + solid.auto_tag_faces("sphere") + solid._apply_tag("geom.primitive.sphere", propagate=False) + solid._add_tag("sphere") + solid.set_metadata( + "geo", + { + "type": "sphere", + "radius": radius_value, + "center": center, + }, + ) + + return _finalize_primitive_solid( + solid, + op="make_sphere_rsolid", + params={ + "radius": radius, + "center": center, + }, + tags={"primitive", "solid"}, + ) + except Exception as e: + _wrap_public_api_error( + operation="make_sphere_rsolid", + what_happened="Failed to create a sphere solid.", + possible_causes=[ + "The radius is not a positive finite scalar.", + "The center is not a valid finite 3D point.", + "The kernel rejected the sphere definition.", + ], + how_to_fix=[ + "Use a radius greater than zero.", + "Pass center as a finite 3D tuple.", + "If the center is expression-driven, inspect the evaluated coordinates.", + ], + error=e, + ) + +def make_three_point_arc_redge( + start: Tuple[float, float, float], + middle: Tuple[float, float, float], + end: Tuple[float, float, float], +) -> Edge: + """Create an arc edge from three points.""" + try: + cs = get_current_cs() + start_value = cast(Tuple[float, float, float], evaluate_value(start)) + middle_value = cast(Tuple[float, float, float], evaluate_value(middle)) + end_value = cast(Tuple[float, float, float], evaluate_value(end)) + start_global = cs.transform_point(np.array(start_value)) + middle_global = cs.transform_point(np.array(middle_value)) + end_global = cs.transform_point(np.array(end_value)) + + edge_shape = make_arc_three_point_edge(start_global, middle_global, end_global) + return cast( + Edge, + _finalize_primitive_shape( + Edge(edge_shape), + op=_OP_MAKE_THREE_POINT_ARC_REDGE, + params={"start": start, "middle": middle, "end": end}, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_three_point_arc_redge", + what_happened="Failed to create a three-point arc edge.", + possible_causes=[ + "One or more points are invalid.", + "The three points are collinear or nearly collinear.", + "The kernel rejected the derived arc geometry.", + ], + how_to_fix=[ + "Pass three finite 3D points.", + "Make sure the three points do not lie on the same straight line.", + "If points are computed dynamically, log them before retrying.", + ], + error=e, + ) + +def make_three_point_arc_rwire( + start: Tuple[float, float, float], + middle: Tuple[float, float, float], + end: Tuple[float, float, float], +) -> Wire: + """Create a wire containing an arc defined by three points.""" + try: + if get_active_session() is not None: + edge = make_three_point_arc_redge(start, middle, end) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_three_point_arc_redge(start, middle, end) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_three_point_arc_wire", + params={"start": start, "middle": middle, "end": end}, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_three_point_arc_rwire", + what_happened="Failed to create a wire from the three-point arc.", + possible_causes=[ + "The arc edge could not be created.", + "The wire assembly step rejected the generated edge.", + ], + how_to_fix=[ + "Verify the three arc points first.", + "If the edge is valid but the wire still fails, inspect the generated arc geometry.", + ], + error=e, + ) + +def make_angle_arc_redge( + center: Tuple[float, float, float], + radius: ScalarLike, + start_angle: ScalarLike, + end_angle: ScalarLike, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Edge: + """Create an arc edge from a center, radius, and angle range.""" + try: + radius_value = evaluate_scalar(radius) + start_angle_value = evaluate_scalar(start_angle) + end_angle_value = evaluate_scalar(end_angle) + if radius_value <= 0: + raise ValueError("半径必须大于0") + if start_angle_value == end_angle_value: + raise ValueError("起始角度和结束角度不能相同") + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) + center_global = cs.transform_point(np.array(center_value)) + normal_global = cs.transform_vector(np.array(normal_value)) + x_direction_global = cs.transform_vector( + _default_plane_x_direction(normal_value) + ) + + edge_shape = make_arc_angle_edge( + center_global, + radius_value, + start_angle_value, + end_angle_value, + normal_global, + x_direction=x_direction_global, + ) + return cast( + Edge, + _finalize_primitive_shape( + Edge(edge_shape), + op=_OP_MAKE_ANGLE_ARC_REDGE, + params={ + "center": center, + "radius": radius, + "start_angle": start_angle, + "end_angle": end_angle, + "normal": normal, + }, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_angle_arc_redge", + what_happened="Failed to create an angle-defined arc edge.", + possible_causes=[ + "The radius is not positive.", + "The start and end angles collapse to the same value.", + "The center or normal is invalid, or the kernel rejected the arc.", + ], + how_to_fix=[ + "Use a positive radius.", + "Make sure start_angle and end_angle are different.", + "Pass a valid finite center and a non-zero normal vector.", + ], + error=e, + ) + +def make_angle_arc_rwire( + center: Tuple[float, float, float], + radius: float, + start_angle: float, + end_angle: float, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Wire: + """Create a wire containing an arc defined by a center, radius, and angle range.""" + + try: + if get_active_session() is not None: + edge = make_angle_arc_redge(center, radius, start_angle, end_angle, normal) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_angle_arc_redge(center, radius, start_angle, end_angle, normal) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_angle_arc_wire", + params={ + "center": center, + "radius": radius, + "start_angle": start_angle, + "end_angle": end_angle, + "normal": normal, + }, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_angle_arc_rwire", + what_happened="Failed to create a wire from the angle-defined arc.", + possible_causes=[ + "The underlying arc edge could not be created.", + "The wire assembly step rejected the generated edge.", + ], + how_to_fix=[ + "Check the center, radius, angle range, and normal.", + "Retry after validating the arc edge input values.", + ], + error=e, + ) + +def _normalize_bspline_control_points( + control_points: Sequence[Sequence[ScalarLike]], +) -> Tuple[Tuple[float, float, float], ...]: + points = list(control_points) + if not points: + raise ValueError("control_points must contain at least one point") + normalized: List[Tuple[float, float, float]] = [] + for index, point in enumerate(points): + value = cast(Sequence[float], evaluate_value(point)) + if len(value) == 2: + coords = (float(value[0]), float(value[1]), 0.0) + elif len(value) == 3: + coords = (float(value[0]), float(value[1]), float(value[2])) + else: + raise ValueError(f"control point {index} must be 2D or 3D") + if not all(math.isfinite(component) for component in coords): + raise ValueError(f"control point {index} contains a non-finite coordinate") + normalized.append(coords) + return tuple(normalized) + +def _collapse_knot_vector( + knots: Sequence[ScalarLike], +) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: + values = [float(evaluate_scalar(knot)) for knot in knots] + if not values: + raise ValueError("knots must not be empty") + if any(not math.isfinite(value) for value in values): + raise ValueError("knots must contain only finite values") + for previous, current in zip(values, values[1:]): + if current < previous: + raise ValueError( + "knots must be non-decreasing when passed as a full knot vector" + ) + unique: List[float] = [] + multiplicities: List[int] = [] + for value in values: + if unique and abs(value - unique[-1]) <= 1e-12: + multiplicities[-1] += 1 + else: + unique.append(value) + multiplicities.append(1) + return tuple(unique), tuple(multiplicities) + +def _default_bspline_knots( + control_count: int, degree: int, periodic: bool +) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: + if periodic: + knot_count = control_count + 1 + return ( + tuple(index / (knot_count - 1) for index in range(knot_count)), + tuple(1 for _ in range(knot_count)), + ) + knot_count = control_count - degree + 1 + if knot_count < 2: + raise ValueError("control point count must be at least degree + 1") + knots = tuple(index / (knot_count - 1) for index in range(knot_count)) + multiplicities = [degree + 1] + multiplicities.extend(1 for _ in range(max(0, knot_count - 2))) + multiplicities.append(degree + 1) + return knots, tuple(multiplicities) + +def _normalize_bspline_knots( + *, + control_count: int, + degree: int, + periodic: bool, + knots: Optional[Sequence[ScalarLike]], + multiplicities: Optional[Sequence[int]], +) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: + if knots is None: + if multiplicities is not None: + raise ValueError("multiplicities require explicit knots") + unique_knots, mults = _default_bspline_knots(control_count, degree, periodic) + elif multiplicities is None: + unique_knots, mults = _collapse_knot_vector(knots) + else: + unique_knots = tuple(float(evaluate_scalar(knot)) for knot in knots) + mults = tuple(int(value) for value in multiplicities) + + if len(unique_knots) != len(mults): + raise ValueError("knots and multiplicities must have the same length") + if len(unique_knots) < 2: + raise ValueError("at least two unique knots are required") + if any(not math.isfinite(knot) for knot in unique_knots): + raise ValueError("knots must contain only finite values") + for previous, current in zip(unique_knots, unique_knots[1:]): + if current <= previous: + raise ValueError("unique knots must be strictly increasing") + if any(multiplicity <= 0 for multiplicity in mults): + raise ValueError("multiplicities must be positive integers") + if any(multiplicity > degree + 1 for multiplicity in mults): + raise ValueError("multiplicities must not exceed degree + 1") + + expected_sum = control_count + (1 if periodic else degree + 1) + actual_sum = sum(mults) + if actual_sum != expected_sum: + raise ValueError( + "sum(multiplicities) must equal " + f"{expected_sum} for this {'periodic' if periodic else 'non-periodic'} B-spline" + ) + return tuple(unique_knots), tuple(mults) + +def _normalize_bspline_weights( + weights: Optional[Sequence[ScalarLike]], control_count: int +) -> Optional[Tuple[float, ...]]: + if weights is None: + return None + values = tuple(float(evaluate_scalar(weight)) for weight in weights) + if len(values) != control_count: + raise ValueError("weights must contain exactly one value per control point") + if any(not math.isfinite(value) or value <= 0.0 for value in values): + raise ValueError("weights must be finite positive values") + return values + +def make_spline_redge( + *, + control_points: Sequence[Sequence[ScalarLike]], + degree: int = 3, + knots: Optional[Sequence[ScalarLike]] = None, + multiplicities: Optional[Sequence[int]] = None, + weights: Optional[Sequence[ScalarLike]] = None, + periodic: bool = False, +) -> Edge: + """Create an exact B-spline edge from named control-point parameters. + + Pass sampled curve points through `fit_cubic_bspline_control_points(...)` first, + then pass the result fields explicitly as `control_points=...`, `knots=...`, + and `multiplicities=...`. `control_points` are poles, not interpolation + points; the curve generally does not pass through interior poles. + """ + try: + if isinstance(degree, bool) or int(degree) != degree: + raise ValueError("degree must be an integer") + degree_value = int(degree) + if degree_value < 1: + raise ValueError("degree must be at least 1") + if degree_value > 25: + raise ValueError("degree must be 25 or lower") + periodic_value = bool(periodic) + + local_control_points = _normalize_bspline_control_points(control_points) + if len(local_control_points) < degree_value + 1: + raise ValueError("control point count must be at least degree + 1") + resolved_knots, resolved_multiplicities = _normalize_bspline_knots( + control_count=len(local_control_points), + degree=degree_value, + periodic=periodic_value, + knots=knots, + multiplicities=multiplicities, + ) + resolved_weights = _normalize_bspline_weights( + weights, len(local_control_points) + ) + + cs = get_current_cs() + global_control_points = tuple( + tuple(float(component) for component in cs.transform_point(np.array(point))) + for point in local_control_points + ) + edge_shape = make_bspline_edge( + control_points=global_control_points, + degree=degree_value, + knots=resolved_knots, + multiplicities=resolved_multiplicities, + weights=resolved_weights, + periodic=periodic_value, + ) + edge = Edge(edge_shape) + edge.set_metadata( + "geo", + { + "type": "bspline", + "degree": degree_value, + "control_points": [list(point) for point in global_control_points], + "knots": list(resolved_knots), + "multiplicities": list(resolved_multiplicities), + "weights": ( + list(resolved_weights) if resolved_weights is not None else None + ), + "periodic": periodic_value, + }, + ) + + return cast( + Edge, + _finalize_primitive_shape( + edge, + op=_OP_MAKE_SPLINE_REDGE, + params={ + "control_points": control_points, + "degree": degree_value, + "knots": resolved_knots, + "multiplicities": resolved_multiplicities, + "weights": weights, + "periodic": periodic_value, + }, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_spline_redge", + what_happened="Failed to create a spline edge.", + possible_causes=[ + "The exact B-spline definition is inconsistent.", + "Control points, knots, multiplicities, or weights are invalid.", + "A sampled-point list was passed directly instead of fitted control points.", + ], + how_to_fix=[ + "Pass keyword arguments such as control_points=..., degree=3, knots=..., multiplicities=....", + "Use fit_cubic_bspline_control_points(sample_points) for sampled curves, then pass its result fields explicitly.", + "Ensure sum(multiplicities) matches the exact B-spline degree/control-count rule.", + ], + error=e, + ) + +def _normalize_interpolation_points( + points: Sequence[Sequence[ScalarLike]], + *, + periodic: bool, + tolerance: float, +) -> Tuple[Tuple[float, float, float], ...]: + normalized = list(_normalize_bspline_control_points(points)) + if periodic and len(normalized) >= 2: + if ( + np.linalg.norm(np.asarray(normalized[0]) - np.asarray(normalized[-1])) + <= tolerance + ): + normalized.pop() + minimum = 3 if periodic else 2 + if len(normalized) < minimum: + qualifier = "distinct" if periodic else "" + raise ValueError( + f"interpolation requires at least {minimum} {qualifier} points".replace( + " ", " " + ) + ) + adjacent_pairs = list(zip(normalized, normalized[1:])) + if periodic: + adjacent_pairs.append((normalized[-1], normalized[0])) + for index, (first, second) in enumerate(adjacent_pairs): + if np.linalg.norm(np.asarray(first) - np.asarray(second)) <= tolerance: + second_index = (index + 1) % len(normalized) + raise ValueError( + f"interpolation points {index} and {second_index} are within " + f"the interpolation tolerance" + ) + return tuple(normalized) + +def make_interpolated_spline_redge( + *, + points: Sequence[Sequence[ScalarLike]], + periodic: bool = False, + tolerance: ScalarLike = 1.0e-6, +) -> Edge: + """Interpolate an exact B-spline edge through the supplied points.""" + try: + periodic_value = bool(periodic) + tolerance_value = float(evaluate_scalar(tolerance)) + if not math.isfinite(tolerance_value) or tolerance_value <= 0.0: + raise ValueError("tolerance must be a finite positive value") + local_points = _normalize_interpolation_points( + points, + periodic=periodic_value, + tolerance=tolerance_value, + ) + cs = get_current_cs() + global_points = tuple( + tuple(float(component) for component in cs.transform_point(np.array(point))) + for point in local_points + ) + edge = Edge( + make_interpolated_bspline_edge( + global_points, + periodic=periodic_value, + tolerance=tolerance_value, + ) + ) + edge.set_metadata( + "geo", + { + "type": "bspline", + "construction": "interpolated", + "interpolation_points": [list(point) for point in global_points], + "periodic": periodic_value, + "tolerance": tolerance_value, + }, + ) + return cast( + Edge, + _finalize_primitive_shape( + edge, + op=_OP_MAKE_INTERPOLATED_SPLINE_REDGE, + params={ + "points": points, + "periodic": periodic_value, + "tolerance": tolerance, + }, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_interpolated_spline_redge", + what_happened="Failed to interpolate a B-spline edge through the input points.", + possible_causes=[ + "Too few distinct interpolation points were provided.", + "Consecutive points are duplicated or contain invalid coordinates.", + "The requested periodic interpolation is geometrically inconsistent.", + ], + how_to_fix=[ + "Provide at least two open-curve points or three periodic-curve points.", + "Remove consecutive duplicate points; a repeated periodic endpoint is optional.", + "Use a smaller positive tolerance when nearby points must remain distinct.", + ], + error=e, + ) + +def make_interpolated_spline_rwire( + *, + points: Sequence[Sequence[ScalarLike]], + periodic: bool = False, + tolerance: ScalarLike = 1.0e-6, +) -> Wire: + """Create a one-edge wire that interpolates the supplied points.""" + try: + edge_kwargs = { + "points": points, + "periodic": periodic, + "tolerance": tolerance, + } + if get_active_session() is not None: + edge = make_interpolated_spline_redge(**edge_kwargs) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_interpolated_spline_redge(**edge_kwargs) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_interpolated_spline_wire", + params=edge_kwargs, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_interpolated_spline_rwire", + what_happened="Failed to create an interpolated spline wire.", + possible_causes=[ + "The interpolated spline edge could not be created.", + "The kernel rejected the resulting one-edge wire.", + ], + how_to_fix=[ + "Validate the interpolation points and tolerance.", + "Use periodic=True for a closed profile and omit a duplicated final point.", + ], + error=e, + ) + +def make_periodic_spline_rwire( + *, + points: Sequence[Sequence[ScalarLike]], + tolerance: ScalarLike = 1.0e-6, +) -> Wire: + """Create a closed periodic spline wire interpolating the supplied points.""" + return make_interpolated_spline_rwire( + points=points, + periodic=True, + tolerance=tolerance, + ) + +def make_spline_rwire( + *, + control_points: Sequence[Sequence[ScalarLike]], + degree: int = 3, + knots: Optional[Sequence[ScalarLike]] = None, + multiplicities: Optional[Sequence[int]] = None, + weights: Optional[Sequence[ScalarLike]] = None, + periodic: bool = False, +) -> Wire: + """Create a wire containing one exact B-spline edge.""" + try: + edge_kwargs = { + "control_points": control_points, + "degree": degree, + "knots": knots, + "multiplicities": multiplicities, + "weights": weights, + "periodic": periodic, + } + if get_active_session() is not None: + edge = make_spline_redge(**edge_kwargs) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_spline_redge(**edge_kwargs) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + rv = Wire(wire_shape) + return cast( + Wire, + _finalize_primitive_shape( + rv, + op="make_spline_wire", + params=edge_kwargs, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_spline_rwire", + what_happened="Failed to create a spline wire.", + possible_causes=[ + "The spline edge could not be created.", + "The exact B-spline definition is inconsistent.", + "The kernel rejected the resulting wire geometry.", + ], + how_to_fix=[ + "Validate the B-spline control points, degree, knots, multiplicities, and weights first.", + "For sampled curves, call fit_cubic_bspline_control_points(...) and pass the result fields explicitly.", + "Retry after inspecting the evaluated spline inputs.", + ], + error=e, + ) + +def make_polyline_rwire( + points: List[Tuple[ScalarLike, ScalarLike, ScalarLike]], closed: bool = False +) -> Wire: + """Create a polyline wire from a point list.""" + try: + if len(points) < 2: + raise ValueError("至少需要2个点") + + if get_active_session() is not None: + edges = [ + make_line_redge(points[idx], points[idx + 1]) + for idx in range(len(points) - 1) + ] + if closed and len(points) > 2: + edges.append(make_line_redge(points[-1], points[0])) + return make_wire_from_edges_rwire(edges) + + cs = get_current_cs() + + # 转换所有点到全局坐标系 + global_points = [] + for point in points: + point_value = cast(Tuple[float, float, float], evaluate_value(point)) + global_point = cs.transform_point(np.array(point_value)) + global_points.append(tuple(float(v) for v in global_point)) + + wire_shape = make_polyline_wire( + [ + (float(point[0]), float(point[1]), float(point[2])) + for point in global_points + ], + closed=closed, + ) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_polyline_wire", + params={"points": points, "closed": closed}, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_polyline_rwire", + what_happened="Failed to create a polyline wire.", + possible_causes=[ + "Fewer than two points were provided.", + "One or more points are invalid or non-finite.", + "The kernel rejected the resulting polyline geometry.", + ], + how_to_fix=[ + "Pass at least two finite 3D points.", + "If closed=True, ensure the sequence describes a valid loop.", + "Inspect the evaluated points before retrying.", + ], + error=e, + ) + +def make_helix_redge( + pitch: ScalarLike, + height: ScalarLike, + radius: ScalarLike, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Edge: + """Create a helix edge.""" + try: + pitch_value = evaluate_scalar(pitch) + height_value = evaluate_scalar(height) + radius_value = evaluate_scalar(radius) + if pitch_value <= 0: + raise ValueError("螺距必须大于0") + if height_value <= 0: + raise ValueError("高度必须大于0") + if radius_value <= 0: + raise ValueError("半径必须大于0") + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + dir_value = cast(Tuple[float, float, float], evaluate_value(dir)) + global_center = cs.transform_point(np.array(center_value)) + global_dir = cs.transform_vector(np.array(dir_value)) + global_x_direction = cs.transform_vector(_default_plane_x_direction(dir_value)) + + wire_shape = make_helix_wire( + pitch_value, + height_value, + radius_value, + global_center, + global_dir, + x_direction=global_x_direction, + ) + wire = Wire(wire_shape) + edges = wire.get_edges() + if not edges: + raise ValueError("无法从螺旋线中提取边") + helix_edge = edges[0] + return cast( + Edge, + _finalize_primitive_shape( + helix_edge, + op=_OP_MAKE_HELIX_REDGE, + params={ + "pitch": pitch, + "height": height, + "radius": radius, + "center": center, + "dir": dir, + }, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_helix_redge", + what_happened="Failed to create a helix edge.", + possible_causes=[ + "Pitch, height, or radius is not positive.", + "The center or direction vector is invalid.", + "The kernel rejected the helix definition.", + ], + how_to_fix=[ + "Use positive pitch, height, and radius values.", + "Pass a valid center and a non-zero direction vector.", + "Inspect the evaluated helix parameters before retrying.", + ], + error=e, + ) + +def make_helix_rwire( + pitch: float, + height: float, + radius: float, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Wire: + """Create a helix wire.""" + try: + if get_active_session() is not None: + edge = make_helix_redge(pitch, height, radius, center=center, dir=dir) + return make_wire_from_edges_rwire([edge]) + + cs = get_current_cs() + global_center = cs.transform_point(np.array(center)) + global_dir = cs.transform_vector(np.array(dir)) + global_x_direction = cs.transform_vector(_default_plane_x_direction(dir)) + + wire_shape = make_helix_wire( + pitch, + height, + radius, + global_center, + global_dir, + x_direction=global_x_direction, + ) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_helix_wire", + params={ + "pitch": pitch, + "height": height, + "radius": radius, + "center": center, + "dir": dir, + }, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_helix_rwire", + what_happened="Failed to create a helix wire.", + possible_causes=[ + "The helix parameters are invalid.", + "The direction vector is zero or malformed.", + "The kernel rejected the wire geometry.", + ], + how_to_fix=[ + "Use positive pitch, height, and radius values.", + "Pass a valid center and a non-zero direction vector.", + "Retry after logging the evaluated helix parameters.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/_operators_product.py b/src/simplecadapi/_operators_product.py new file mode 100644 index 00000000..0601517f --- /dev/null +++ b/src/simplecadapi/_operators_product.py @@ -0,0 +1,1129 @@ +"""Product operator implementations.""" + +from __future__ import annotations + +from ._operation_support import * + +def make_material_rmaterial( + material_id: str, + name: Optional[str] = None, + density: Optional[float] = None, + density_unit: Optional[str] = None, + color: Optional[Tuple[float, float, float]] = None, +) -> Material: + """Create a material definition for later Part assignment. + + Material is deliberately separate from `make_part_rpart(...)`; the only + correct workflow is to create a material and then assign it to a Part with + `assign_material_rpart(...)`. + """ + + try: + material = Material( + material_id, + name=name, + density=density, + density_unit=density_unit, + color=color, + ) + _reserve_semantic_id("material", material.material_id) + record_operation_if_active( + _OP_MAKE_MATERIAL_RMATERIAL, + _material_params(material), + outputs=material, + semantic_delta=_semantic_created( + "Material", material.material_id, material.to_dict() + ), + context=_current_context_metadata(), + ) + return material + except Exception as e: + _wrap_public_api_error( + operation="make_material_rmaterial", + what_happened="Failed to create the material definition.", + possible_causes=[ + "The material_id is empty or uses unsupported characters.", + "The density is non-finite, non-positive, or missing a density_unit.", + "The color is not a 3-tuple in the [0.0, 1.0] range.", + ], + how_to_fix=[ + "Use a stable identifier such as 'aluminum_6061'.", + "Provide density and density_unit together, or omit both.", + "Pass RGB color components as floats between 0.0 and 1.0.", + ], + error=e, + ) + +def make_placement_rplacement( + origin: Tuple[float, float, float], + x_axis: Tuple[float, float, float] = (1.0, 0.0, 0.0), + y_axis: Tuple[float, float, float] = (0.0, 1.0, 0.0), +) -> Placement: + """Create a canonical right-handed placement in the active workplane.""" + + try: + cs = get_current_cs() + origin_global = cs.transform_point(np.asarray(origin, dtype=float)) + x_axis_global = cs.transform_vector(np.asarray(x_axis, dtype=float)) + y_axis_global = cs.transform_vector(np.asarray(y_axis, dtype=float)) + placement = Placement( + tuple(float(value) for value in origin_global), + x_axis=tuple(float(value) for value in x_axis_global), + y_axis=tuple(float(value) for value in y_axis_global), + ) + record_operation_if_active( + _OP_MAKE_PLACEMENT_RPLACEMENT, + {"origin": origin, "x_axis": x_axis, "y_axis": y_axis}, + outputs=placement, + context=_current_context_metadata(), + ) + return placement + except Exception as e: + _wrap_public_api_error( + operation="make_placement_rplacement", + what_happened="Failed to create the placement.", + possible_causes=[ + "The origin is not a finite 3D point.", + "One of the axes is zero-length or non-finite.", + "x_axis and y_axis are not orthogonal.", + ], + how_to_fix=[ + "Pass origin, x_axis, and y_axis as finite 3-element tuples.", + "Use one canonical representation; do not mix Euler, quaternion, or axis-angle payloads.", + "Make sure x_axis and y_axis form a right-handed frame.", + ], + error=e, + ) + +def identity_placement_rplacement() -> Placement: + """Create the identity placement of the active workplane.""" + + try: + cs = get_current_cs() + placement = Placement( + tuple(float(value) for value in cs.origin), + x_axis=tuple(float(value) for value in cs.x_axis), + y_axis=tuple(float(value) for value in cs.y_axis), + ) + record_operation_if_active( + _OP_MAKE_IDENTITY_PLACEMENT_RPLACEMENT, + {}, + outputs=placement, + context=_current_context_metadata(), + ) + return placement + except Exception as e: + _wrap_public_api_error( + operation="identity_placement_rplacement", + what_happened="Failed to create the identity placement.", + possible_causes=["Internal placement validation failed."], + how_to_fix=["Report this as a SimpleCADAPI bug if it reproduces."], + error=e, + ) + +def make_part_rpart( + part_id: str, + body: Solid, + name: Optional[str] = None, +) -> Part: + """Wrap exactly one Solid as a semantic single-body Part.""" + + try: + part = Part(part_id, body, name=name) + _reserve_semantic_id("part", part.part_id) + record_operation_if_active( + _OP_MAKE_PART_RPART, + _part_params(part), + outputs=part, + input_shapes=[body], + semantic_delta=_semantic_created("Part", part.part_id, part.to_dict()), + context=_current_context_metadata(), + ) + return part + except Exception as e: + _wrap_public_api_error( + operation="make_part_rpart", + what_happened="Failed to create the single-body Part.", + possible_causes=[ + "The part_id is empty or uses unsupported characters.", + "The body is not a Solid.", + "A Part with the same part_id already exists in the active GraphSession.", + ], + how_to_fix=[ + "Pass a stable part_id such as 'base_plate'.", + "Union intended multiple bodies into one Solid before creating the Part.", + "Do not pass material to make_part_rpart; use assign_material_rpart instead.", + ], + error=e, + ) + +def assign_material_rpart(part: Part, material: Material) -> Part: + """Assign a Material to a Part and return the updated Part.""" + + try: + if not isinstance(part, Part): + raise TypeError("part must be a Part") + if not isinstance(material, Material): + raise TypeError("material must be a Material") + result = part.with_material(material) + record_operation_if_active( + _OP_MAKE_ASSIGN_MATERIAL_RPART, + { + "part_id": part.part_id, + "material_id": material.material_id, + "material": _material_params(material), + }, + outputs=result, + input_shapes=[part, material], + semantic_delta=_semantic_modified( + "Part", + part.part_id, + {"material_id": material.material_id}, + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="assign_material_rpart", + what_happened="Failed to assign the material to the Part.", + possible_causes=[ + "The part input is not a Part.", + "The material input is not a Material.", + ], + how_to_fix=[ + "Create parts with make_part_rpart(...).", + "Create materials with make_material_rmaterial(...).", + ], + error=e, + ) + +def make_assembly_rassembly( + assembly_id: str, + name: Optional[str] = None, +) -> Assembly: + """Create an empty assembly product structure.""" + + try: + assembly = Assembly(assembly_id, name=name) + _reserve_semantic_id("assembly", assembly.assembly_id) + record_operation_if_active( + _OP_MAKE_ASSEMBLY_RASSEMBLY, + _assembly_params(assembly), + outputs=assembly, + semantic_delta=_semantic_created( + "Assembly", assembly.assembly_id, assembly.to_dict() + ), + context=_current_context_metadata(), + ) + return assembly + except Exception as e: + _wrap_public_api_error( + operation="make_assembly_rassembly", + what_happened="Failed to create the assembly.", + possible_causes=[ + "The assembly_id is empty or uses unsupported characters.", + "An Assembly with the same assembly_id already exists in the active GraphSession.", + ], + how_to_fix=["Pass a stable assembly_id such as 'fixture_assembly'."], + error=e, + ) + +def add_component_rassembly( + assembly: Assembly, + item: Union[Part, Assembly], + component_id: str, + placement: Placement, + name: Optional[str] = None, +) -> Assembly: + """Add a placed Part or subassembly component instance to an Assembly.""" + + try: + if not isinstance(assembly, Assembly): + raise TypeError("assembly must be an Assembly") + if not isinstance(item, (Part, Assembly)): + raise TypeError("item must be a Part or Assembly") + if not isinstance(placement, Placement): + raise TypeError("placement must be a Placement") + component = Component(component_id, item, placement, name=name) + result = assembly.with_component(component) + item_kind = "assembly" if isinstance(item, Assembly) else "part" + item_id = item.assembly_id if isinstance(item, Assembly) else item.part_id + record_operation_if_active( + _OP_MAKE_ADD_COMPONENT_RASSEMBLY, + { + "assembly_id": assembly.assembly_id, + "component_id": component.component_id, + "name": component.name, + "item_kind": item_kind, + "item_id": item_id, + "placement": placement.to_dict(), + }, + outputs=result, + input_shapes=[assembly, item, placement], + semantic_delta=SemanticDelta( + created=( + SemanticRef( + graph_id="pending", + node_id="pending", + entity_type="Component", + entity_id=f"{assembly.assembly_id}:{component.component_id}", + ), + ), + modified=( + SemanticRef( + graph_id="pending", + node_id="pending", + entity_type="Assembly", + entity_id=assembly.assembly_id, + ), + ), + metadata={"component": component.to_dict()}, + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="add_component_rassembly", + what_happened="Failed to add the component to the assembly.", + possible_causes=[ + "The assembly input is not an Assembly.", + "The item input is not a Part or Assembly.", + "The component_id is empty, malformed, or duplicated in the assembly.", + "The placement is invalid or missing.", + "Adding this subassembly would create an assembly cycle.", + ], + how_to_fix=[ + "Wrap solids explicitly with make_part_rpart before adding them to assemblies.", + "Use a unique component_id within the parent assembly.", + "Create placements with make_placement_rplacement or identity_placement_rplacement.", + ], + error=e, + ) + +def place_component_rassembly( + assembly: Assembly, + component_id: str, + placement: Placement, +) -> Assembly: + """Move an existing assembly component by replacing its placement.""" + + try: + if not isinstance(assembly, Assembly): + raise TypeError("assembly must be an Assembly") + if not isinstance(placement, Placement): + raise TypeError("placement must be a Placement") + result = assembly.with_component_placement(component_id, placement) + record_operation_if_active( + _OP_MAKE_PLACE_COMPONENT_RASSEMBLY, + { + "assembly_id": assembly.assembly_id, + "component_id": component_id, + "placement": placement.to_dict(), + }, + outputs=result, + input_shapes=[assembly, placement], + semantic_delta=_semantic_modified( + "Component", + f"{assembly.assembly_id}:{component_id}", + {"placement": placement.to_dict()}, + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="place_component_rassembly", + what_happened="Failed to place the assembly component.", + possible_causes=[ + "The assembly input is not an Assembly.", + "The component_id does not exist in the assembly.", + "The placement is invalid or missing.", + ], + how_to_fix=[ + "Use add_component_rassembly before placing a component.", + "Use a component_id returned in assembly.component_ids().", + "Create placements with make_placement_rplacement.", + ], + error=e, + ) + +def _make_geometry_backed_connector( + connector_id: str, + shape: AnyShape, + *, + op: str, + operation_name: str, + name: Optional[str] = None, + flip: bool = False, +) -> Connector: + source_shape = _selection_source_for_shape(shape) or shape + node_ids = _ensure_geo_selection_node_ids(source_shape, [shape]) + source_node_id = node_ids[0] if node_ids else None + geo_selector = _make_geo_selector(shape, source_shape=source_shape) + kind = _shape_kind_token(shape) + geometry_ref = GeometryRef( + kind=kind, + source_node_id=source_node_id, + geo_selector=geo_selector, + flip=bool(flip), + ) + connector = Connector(connector_id, geometry_ref, name=name) + record_operation_if_active( + op, + _connector_params(connector), + outputs=connector, + input_shapes=[shape], + context=_current_context_metadata(), + ) + return connector + +def make_face_connector_rconnector( + connector_id: str, + face: Face, + name: Optional[str] = None, + flip: bool = False, +) -> Connector: + """Create a connector anchored to a Face. + + Z axis follows the face normal; origin is the face center. + Set flip=True to negate the Z axis (point it opposite to the normal). + """ + try: + if not isinstance(face, Face): + raise TypeError("face must be a Face") + return _make_geometry_backed_connector( + connector_id, + face, + op=_OP_MAKE_FACE_CONNECTOR_RCONNECTOR, + operation_name="make_face_connector_rconnector", + name=name, + flip=flip, + ) + except Exception as e: + _wrap_public_api_error( + operation="make_face_connector_rconnector", + what_happened="Failed to create the face connector.", + possible_causes=[ + "The connector_id is empty or malformed.", + "The face is not a valid Face object.", + ], + how_to_fix=[ + "Use a stable connector_id such as 'mount_face'.", + "Select a face via ql.faces().resolve(solid) or solid.get_faces()[i].", + ], + error=e, + ) + +def make_edge_connector_rconnector( + connector_id: str, + edge: Edge, + name: Optional[str] = None, + flip: bool = False, +) -> Connector: + """Create a connector anchored to an Edge. + + Z axis follows the edge direction (start->end); origin is the edge midpoint. + Set flip=True to negate the Z axis. + """ + try: + if not isinstance(edge, Edge): + raise TypeError("edge must be an Edge") + return _make_geometry_backed_connector( + connector_id, + edge, + op=_OP_MAKE_EDGE_CONNECTOR_RCONNECTOR, + operation_name="make_edge_connector_rconnector", + name=name, + flip=flip, + ) + except Exception as e: + _wrap_public_api_error( + operation="make_edge_connector_rconnector", + what_happened="Failed to create the edge connector.", + possible_causes=[ + "The connector_id is empty or malformed.", + "The edge is not a valid Edge object.", + ], + how_to_fix=[ + "Use a stable connector_id such as 'hinge_axis'.", + "Select an edge via ql.edges().resolve(solid) or solid.get_edges()[i].", + ], + error=e, + ) + +def make_vertex_connector_rconnector( + connector_id: str, + vertex: Vertex, + name: Optional[str] = None, + flip: bool = False, +) -> Connector: + """Create a connector anchored to a Vertex. + + Origin is the vertex point; axes are identity. + flip has no effect on vertex connectors (no direction). + """ + try: + if not isinstance(vertex, Vertex): + raise TypeError("vertex must be a Vertex") + return _make_geometry_backed_connector( + connector_id, + vertex, + op=_OP_MAKE_VERTEX_CONNECTOR_RCONNECTOR, + operation_name="make_vertex_connector_rconnector", + name=name, + flip=flip, + ) + except Exception as e: + _wrap_public_api_error( + operation="make_vertex_connector_rconnector", + what_happened="Failed to create the vertex connector.", + possible_causes=[ + "The connector_id is empty or malformed.", + "The vertex is not a valid Vertex object.", + ], + how_to_fix=[ + "Use a stable connector_id such as 'pivot_point'.", + "Select a vertex via ql.vertices().resolve(solid) or solid.get_vertices()[i].", + ], + error=e, + ) + +def make_placement_connector_rconnector( + connector_id: str, + placement: Placement, + name: Optional[str] = None, +) -> Connector: + """Create a connector anchored to an explicit local placement frame. + + Use this when a datum should be defined by a stable coordinate frame + instead of a selected BREP face, edge, or vertex. + """ + + try: + if not isinstance(placement, Placement): + raise TypeError("placement must be a Placement") + anchor = ConnectorAnchor("placement", placement=placement) + connector = Connector(connector_id, None, name=name, anchor=anchor) + record_operation_if_active( + _OP_MAKE_PLACEMENT_CONNECTOR_RCONNECTOR, + { + "connector_id": connector.connector_id, + "placement": placement.to_dict(), + "name": connector.name, + }, + outputs=connector, + input_shapes=[placement], + context=_current_context_metadata(), + ) + return connector + except Exception as e: + _wrap_public_api_error( + operation="make_placement_connector_rconnector", + what_happened="Failed to create the placement connector.", + possible_causes=[ + "The connector_id is empty or malformed.", + "The placement input is not a Placement.", + ], + how_to_fix=[ + "Create placements with make_placement_rplacement.", + "Use a stable connector_id such as 'bearing_axis'.", + ], + error=e, + ) + +def add_connector_rpart(part: Part, connector: Connector) -> Part: + """Attach a connector datum frame to a Part definition.""" + + try: + if not isinstance(part, Part): + raise TypeError("part must be a Part") + result = part.with_connector(connector) + record_operation_if_active( + _OP_MAKE_ADD_CONNECTOR_RPART, + {"part_id": part.part_id, "connector_id": connector.connector_id}, + outputs=result, + input_shapes=[part, connector], + semantic_delta=_semantic_modified( + "Part", part.part_id, {"connector": connector.to_dict()} + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="add_connector_rpart", + what_happened="Failed to add the connector to the Part.", + possible_causes=[ + "The part input is not a Part.", + "The connector input is not a Connector.", + "The connector_id is duplicated in the Part.", + ], + how_to_fix=[ + "Create a connector with make_face_connector_rconnector, make_edge_connector_rconnector, or make_vertex_connector_rconnector.", + "Use unique connector ids within one Part.", + ], + error=e, + ) + +def set_public_connector_rassembly( + assembly: Assembly, + public_connector_id: str, + source_component_id: str, + source_connector_id: str, + name: Optional[str] = None, +) -> Assembly: + """Expose an existing connector on a direct child component.""" + + try: + if not isinstance(assembly, Assembly): + raise TypeError("assembly must be an Assembly") + public = PublicConnectorRef( + public_connector_id=public_connector_id, + component_id=source_component_id, + connector_id=source_connector_id, + name=name, + ) + try: + result = assembly.with_public_connector(public) + except KeyError as error: + raise ValueError(f"missing component or connector for public connector: {error}") from error + record_operation_if_active( + _OP_MAKE_SET_PUBLIC_CONNECTOR_RASSEMBLY, + { + "assembly_id": assembly.assembly_id, + "public_connector_id": public.public_connector_id, + "source_component_id": public.component_id, + "source_connector_id": public.connector_id, + "name": public.name, + }, + outputs=result, + input_shapes=[assembly], + semantic_delta=_semantic_modified( + "Assembly", + assembly.assembly_id, + {"public_connector": public.to_dict()}, + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="set_public_connector_rassembly", + what_happened="Failed to expose the component connector publicly.", + possible_causes=[ + "The assembly input is not an Assembly.", + "The component is not a direct child of the Assembly.", + "The connector does not exist on the child component.", + "The public connector ID is already used in the Assembly.", + ], + how_to_fix=[ + "Add the direct child component before exposing its connector.", + "Create the connector on the child Part or expose it on the child Assembly first.", + "Expose each public connector ID at most once per Assembly.", + ], + error=e, + ) + +def make_connector_ref_rconnectorref( + component_id: str, connector_id: str +) -> ConnectorRef: + """Reference a connector through a component instance.""" + + try: + connector_ref = ConnectorRef(component_id, connector_id) + record_operation_if_active( + _OP_MAKE_CONNECTOR_REF_RCONNECTORREF, + _connector_ref_params(connector_ref), + outputs=connector_ref, + context=_current_context_metadata(), + ) + return connector_ref + except Exception as e: + _wrap_public_api_error( + operation="make_connector_ref_rconnectorref", + what_happened="Failed to create the connector reference.", + possible_causes=["The component_id or connector_id is empty or malformed."], + how_to_fix=["Use stable ids from the owning Assembly and component item."], + error=e, + ) + +def make_scalar_limit_rscalarlimit( + lower_value: float, upper_value: float +) -> ScalarLimit: + """Create a closed scalar limit for driven constraint coordinates.""" + + try: + limit = ScalarLimit(lower_value, upper_value) + record_operation_if_active( + _OP_MAKE_SCALAR_LIMIT_RSCALARLIMIT, + _scalar_limit_params(limit), + outputs=limit, + context=_current_context_metadata(), + ) + return limit + except Exception as e: + _wrap_public_api_error( + operation="make_scalar_limit_rscalarlimit", + what_happened="Failed to create the scalar limit.", + possible_causes=[ + "One of the limit values is non-finite.", + "lower_value is greater than upper_value.", + ], + how_to_fix=["Pass finite lower and upper values in increasing order."], + error=e, + ) + +def ground_component_rassembly(assembly: Assembly, component_id: str) -> Assembly: + """Ground a component at its current authored placement.""" + + try: + if not isinstance(assembly, Assembly): + raise TypeError("assembly must be an Assembly") + result = assembly.with_grounded_component(component_id) + record_operation_if_active( + _OP_MAKE_GROUND_COMPONENT_RASSEMBLY, + {"assembly_id": assembly.assembly_id, "component_id": component_id}, + outputs=result, + input_shapes=[assembly], + semantic_delta=_semantic_modified( + "Assembly", + assembly.assembly_id, + {"grounded_component_id": component_id}, + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="ground_component_rassembly", + what_happened="Failed to ground the assembly component.", + possible_causes=[ + "The assembly input is not an Assembly.", + "The component_id does not exist in the Assembly.", + ], + how_to_fix=["Use a component_id already added to the Assembly."], + error=e, + ) + +def unground_component_rassembly(assembly: Assembly, component_id: str) -> Assembly: + """Remove a component grounding marker.""" + + try: + if not isinstance(assembly, Assembly): + raise TypeError("assembly must be an Assembly") + result = assembly.without_grounded_component(component_id) + record_operation_if_active( + _OP_MAKE_UNGROUND_COMPONENT_RASSEMBLY, + {"assembly_id": assembly.assembly_id, "component_id": component_id}, + outputs=result, + input_shapes=[assembly], + semantic_delta=_semantic_modified( + "Assembly", + assembly.assembly_id, + {"ungrounded_component_id": component_id}, + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="unground_component_rassembly", + what_happened="Failed to unground the assembly component.", + possible_causes=[ + "The assembly input is not an Assembly.", + "The component_id does not exist in the Assembly.", + ], + how_to_fix=["Use a component_id already added to the Assembly."], + error=e, + ) + +def add_fixed_constraint_rassembly( + assembly: Assembly, + constraint_id: str, + connector_a: ConnectorRef, + connector_b: ConnectorRef, + name: Optional[str] = None, +) -> Assembly: + """Constrain two component connectors to the same frame.""" + + return _add_constraint_rassembly( + assembly, + Constraint( + constraint_id, + "fixed", + connector_a, + connector_b, + name=name, + ), + _OP_MAKE_FIXED_CONSTRAINT_RASSEMBLY, + "add_fixed_constraint_rassembly", + ) + +def add_revolute_constraint_rassembly( + assembly: Assembly, + constraint_id: str, + connector_a: ConnectorRef, + connector_b: ConnectorRef, + drive_angle_degrees: Optional[float] = None, + angle_limit: Optional[ScalarLimit] = None, + name: Optional[str] = None, +) -> Assembly: + """Constrain two connectors as a revolute axis pair.""" + + return _add_constraint_rassembly( + assembly, + Constraint( + constraint_id, + "revolute", + connector_a, + connector_b, + drive_angle_degrees=drive_angle_degrees, + angle_limit=angle_limit, + name=name, + ), + _OP_MAKE_REVOLUTE_CONSTRAINT_RASSEMBLY, + "add_revolute_constraint_rassembly", + ) + +def add_prismatic_constraint_rassembly( + assembly: Assembly, + constraint_id: str, + connector_a: ConnectorRef, + connector_b: ConnectorRef, + drive_distance: Optional[float] = None, + distance_limit: Optional[ScalarLimit] = None, + name: Optional[str] = None, +) -> Assembly: + """Constrain two connectors as a prismatic slider pair.""" + + return _add_constraint_rassembly( + assembly, + Constraint( + constraint_id, + "prismatic", + connector_a, + connector_b, + drive_distance=drive_distance, + distance_limit=distance_limit, + name=name, + ), + _OP_MAKE_PRISMATIC_CONSTRAINT_RASSEMBLY, + "add_prismatic_constraint_rassembly", + ) + +def add_gear_constraint_rassembly( + assembly: Assembly, + constraint_id: str, + connector_a: ConnectorRef, + connector_b: ConnectorRef, + pitch_radius_a: float, + pitch_radius_b: float, + phase_offset: Optional[float] = None, + name: Optional[str] = None, +) -> Assembly: + """Couple two revolute axes as meshing gears with inverse rotation.""" + + constraint = Constraint( + constraint_id, + "gear", + connector_a, + connector_b, + pitch_radius_a=pitch_radius_a, + pitch_radius_b=pitch_radius_b, + phase_offset=phase_offset, + name=name, + ) + if phase_offset is None: + constraint = Constraint( + constraint_id, + "gear", + connector_a, + connector_b, + pitch_radius_a=pitch_radius_a, + pitch_radius_b=pitch_radius_b, + phase_offset=coupling_phase_offset(assembly, constraint), + name=name, + ) + return _add_constraint_rassembly( + assembly, + constraint, + _OP_MAKE_GEAR_CONSTRAINT_RASSEMBLY, + "add_gear_constraint_rassembly", + ) + +def add_belt_constraint_rassembly( + assembly: Assembly, + constraint_id: str, + connector_a: ConnectorRef, + connector_b: ConnectorRef, + pulley_radius_a: float, + pulley_radius_b: float, + phase_offset: Optional[float] = None, + name: Optional[str] = None, +) -> Assembly: + """Couple two revolute axes as belt-linked pulleys with same-direction rotation.""" + + constraint = Constraint( + constraint_id, + "belt", + connector_a, + connector_b, + pulley_radius_a=pulley_radius_a, + pulley_radius_b=pulley_radius_b, + phase_offset=phase_offset, + name=name, + ) + if phase_offset is None: + constraint = Constraint( + constraint_id, + "belt", + connector_a, + connector_b, + pulley_radius_a=pulley_radius_a, + pulley_radius_b=pulley_radius_b, + phase_offset=coupling_phase_offset(assembly, constraint), + name=name, + ) + return _add_constraint_rassembly( + assembly, + constraint, + _OP_MAKE_BELT_CONSTRAINT_RASSEMBLY, + "add_belt_constraint_rassembly", + ) + +def add_rack_pinion_constraint_rassembly( + assembly: Assembly, + constraint_id: str, + rack_connector: ConnectorRef, + pinion_connector: ConnectorRef, + pitch_radius: float, + phase_offset: Optional[float] = None, + name: Optional[str] = None, +) -> Assembly: + """Couple a prismatic rack axis to a revolute pinion axis.""" + + constraint = Constraint( + constraint_id, + "rack_pinion", + rack_connector, + pinion_connector, + pitch_radius=pitch_radius, + phase_offset=phase_offset, + name=name, + ) + if phase_offset is None: + constraint = Constraint( + constraint_id, + "rack_pinion", + rack_connector, + pinion_connector, + pitch_radius=pitch_radius, + phase_offset=coupling_phase_offset(assembly, constraint), + name=name, + ) + return _add_constraint_rassembly( + assembly, + constraint, + _OP_MAKE_RACK_PINION_CONSTRAINT_RASSEMBLY, + "add_rack_pinion_constraint_rassembly", + ) + +def _add_constraint_rassembly( + assembly: Assembly, + constraint: Constraint, + op_name: str, + public_name: str, +) -> Assembly: + try: + if not isinstance(assembly, Assembly): + raise TypeError("assembly must be an Assembly") + result = assembly.with_constraint(constraint) + inputs: List[object] = [ + assembly, + constraint.connector_a, + constraint.connector_b, + ] + if constraint.distance_limit is not None: + inputs.append(constraint.distance_limit) + if constraint.angle_limit is not None: + inputs.append(constraint.angle_limit) + record_operation_if_active( + op_name, + _constraint_params(constraint), + outputs=result, + input_shapes=inputs, + semantic_delta=_semantic_modified( + "Assembly", assembly.assembly_id, {"constraint": constraint.to_dict()} + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation=public_name, + what_happened="Failed to add the assembly constraint.", + possible_causes=[ + "The assembly input is not an Assembly.", + "A connector ref references a missing component or connector.", + "The constraint_id is duplicated in the Assembly.", + "A drive value violates its scalar limit.", + ], + how_to_fix=[ + "Create connector refs with make_connector_ref_rconnectorref.", + "Add connectors to Parts or Assemblies before adding constrained components.", + "Use unique constraint ids within one Assembly.", + ], + error=e, + ) + +def solve_assembly_constraints_rassembly( + assembly: Assembly, strict: bool = True +) -> Assembly: + """Solve fixed, revolute, and prismatic assembly constraints. + + Solving is limit-aware: when a constraint carries a ``ScalarLimit`` + (``angle_limit`` or ``distance_limit``), the drive scalar is clamped + into the closed range before placement propagation. When no drive + scalar is present but a limit exists, the current relative-frame + scalar is projected into the bounds. Unresolvable closed kinematic + loops fall back to a golden-section search over the limit bounds. + + A ``ConstraintReport`` is recorded on the returned assembly under the + ``constraint_report`` runtime key for later inspection via + ``inspect_assembly_constraints_rassembly``. + """ + + try: + result = solve_assembly_constraints(assembly, strict=bool(strict)) + solved_component_placements = { + component.component_id: component.placement.to_dict() + for component in result.components + } + record_operation_if_active( + _OP_MAKE_SOLVE_ASSEMBLY_CONSTRAINTS_RASSEMBLY, + { + "assembly_id": assembly.assembly_id, + "strict": bool(strict), + "component_placements": solved_component_placements, + }, + outputs=result, + input_shapes=[assembly], + semantic_delta=_semantic_modified( + "Assembly", assembly.assembly_id, {"constraints_solved": True} + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="solve_assembly_constraints_rassembly", + what_happened="Failed to solve the assembly constraints.", + possible_causes=[ + "No component is grounded.", + "A constraint graph references missing connectors.", + "A connected component cannot be reached from a grounded component.", + "A closed-loop residual exceeds tolerance.", + ], + how_to_fix=[ + "Ground at least one component with ground_component_rassembly.", + "Ensure every constrained component has the required connectors.", + "Inspect constraint residuals before strict solving.", + ], + error=e, + ) + +def measure_constraint_residual_rconstraintresidual( + assembly: Assembly, constraint_id: str +) -> ConstraintResidual: + """Measure residual for one assembly constraint without mutating the assembly.""" + + return measure_constraint_residual(assembly, constraint_id) + +def inspect_assembly_constraints_rconstraintreport( + assembly: Assembly, +) -> ConstraintReport: + """Inspect all assembly constraint residuals without mutating the assembly.""" + + return inspect_assembly_constraints(assembly) + +def _placed_solids_from_item( + item: Union[Part, Assembly], placement: Placement +) -> List[Solid]: + if isinstance(item, Part): + placed = place_shape_ocp( + item.body, + placement.origin, + placement.x_axis, + placement.y_axis, + placement.z_axis, + ) + return [cast(Solid, placed)] + if isinstance(item, Assembly): + solids: List[Solid] = [] + for component in item.components: + solids.extend( + _placed_solids_from_item( + component.item, + compose_placements(placement, component.placement), + ) + ) + return solids + raise TypeError("item must be a Part or Assembly") + +def make_compound_from_assembly_rcompound(assembly: Assembly) -> Compound: + """Project an Assembly into an explicit flattened Compound geometry value.""" + + try: + if not isinstance(assembly, Assembly): + raise TypeError("assembly must be an Assembly") + if not assembly.components: + raise ValueError("assembly must contain at least one component to project") + solids = _placed_solids_from_item(assembly, identity_placement()) + if not solids: + raise ValueError("assembly projection produced no solids") + compound = Compound(make_compound_always([solid.wrapped for solid in solids])) + compound.set_metadata( + "assembly_projection", + { + "assembly_id": assembly.assembly_id, + "component_count": len(assembly.components), + "solid_count": len(solids), + }, + ) + record_operation_if_active( + _OP_MAKE_COMPOUND_FROM_ASSEMBLY_RCOMPOUND, + { + "assembly_id": assembly.assembly_id, + "component_count": len(assembly.components), + }, + outputs=compound, + input_shapes=[assembly], + semantic_delta=_semantic_modified( + "Assembly", + assembly.assembly_id, + {"projection": "compound", "solid_count": len(solids)}, + ), + context=_current_context_metadata(), + ) + return compound + except Exception as e: + _wrap_public_api_error( + operation="make_compound_from_assembly_rcompound", + what_happened="Failed to project the assembly into a Compound.", + possible_causes=[ + "The input is not an Assembly.", + "The assembly has no components.", + "A component placement is invalid.", + "The kernel could not transform or combine the component bodies.", + ], + how_to_fix=[ + "Create an assembly with make_assembly_rassembly and add at least one component.", + "Ensure every component references a valid Part or subassembly.", + "Validate placements before projection.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/_operators_selection.py b/src/simplecadapi/_operators_selection.py new file mode 100644 index 00000000..ea43369a --- /dev/null +++ b/src/simplecadapi/_operators_selection.py @@ -0,0 +1,177 @@ +"""Selection operator implementations.""" + +from __future__ import annotations + +from ._operation_support import * + +def apply_tag_rselection( + scope: AnyShape, + targets: Union[ShapeSelector, Sequence[AnyShape]], + tag: str, + topology_propagation: str | TopologyPropagation = TopologyPropagation.LOCAL, + lineage_policy: str | LineagePolicy = LineagePolicy.CONTINUATION_FRAGMENT, +) -> AnyShape: + """Return a semantic shape view with a canonical tag assignment.""" + + try: + return _apply_tag_rselection( + scope, + targets, + tag, + topology_propagation, + lineage_policy, + ) + except Exception as e: + _wrap_public_api_error( + operation="apply_tag_rselection", + what_happened="Failed to attach the tag to the selected shapes.", + possible_causes=[ + "The assignment scope or target selection is invalid.", + "The tag value is empty or malformed.", + "The selector resolved no targets or references foreign topology.", + ], + how_to_fix=[ + "Pass a valid scope and a non-empty ShapeSelector or shape sequence.", + "Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'.", + "Ensure every explicit target belongs to the assignment scope.", + ], + error=e, + ) + +def apply_tag(shape: AnyShape, tag: str) -> AnyShape: + """Attach a local user tag with continuation/fragment lineage policy.""" + + try: + _ensure_source_shape_has_own_selection_node(shape) + selector = ShapeSelector(_shape_kind_token(shape)).exactly(1) + return _apply_tag_rselection( + shape, + selector, + tag, + TopologyPropagation.LOCAL, + LineagePolicy.CONTINUATION_FRAGMENT, + clone_scope=False, + ) + except Exception as e: + _wrap_public_api_error( + operation="apply_tag", + what_happened="Failed to attach the tag to the shape.", + possible_causes=[ + "The shape is invalid.", + "The tag value is empty or malformed.", + ], + how_to_fix=[ + "Pass a valid shape object.", + "Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'.", + ], + error=e, + ) + +def list_tags( + shape: AnyShape, + scope: str | TagScope = TagScope.EFFECTIVE, +) -> List[str]: + """Return shape tags in deterministic sorted order for one scope.""" + try: + return shape._list_tags(normalize_tag_scope(scope)) + except Exception as e: + _wrap_public_api_error( + operation="list_tags", + what_happened="Failed to list tags on the shape.", + possible_causes=[ + "The shape is invalid.", + "The object is not a SimpleCAD shape.", + ], + how_to_fix=[ + "Pass a valid Vertex, Edge, Wire, Face, or Solid object.", + ], + error=e, + ) + +def explain_tag( + shape: AnyShape, + tag: str, + scope: str | TagScope = TagScope.EFFECTIVE, +) -> List[Dict[str, Any]]: + """Explain every visible binding that produces a tag token.""" + + try: + return shape._explain_tag( + normalize_tag(tag, strict=True), normalize_tag_scope(scope) + ) + except Exception as e: + _wrap_public_api_error( + operation="explain_tag", + what_happened="Failed to explain the tag on the shape.", + possible_causes=[ + "The shape or tag is invalid.", + "The requested scope requires unavailable semantic evidence.", + ], + how_to_fix=[ + "Pass a valid shape and normalized tag token.", + "Request a supported scope or provide complete topology history.", + ], + error=e, + ) + +def select_faces_by_tag( + solid: Solid, + tag: str, + scope: str | TagScope = TagScope.EFFECTIVE, +) -> List[Face]: + """Select faces by tag.""" + try: + normalized = normalize_tag(tag, strict=True) + resolved_scope = normalize_tag_scope(scope) + faces = solid.get_faces() + return [face for face in faces if face._has_tag(normalized, resolved_scope)] + except Exception as e: + _wrap_public_api_error( + operation="select_faces_by_tag", + what_happened="Failed to select faces by tag.", + possible_causes=[ + "The solid is invalid.", + "The tag string is invalid.", + ], + how_to_fix=[ + "Pass a valid Solid object.", + "Use the exact face tag that was previously assigned.", + ], + error=e, + ) + +def select_edges_by_tag( + shape: Union[Face, Solid], + tag: str, + scope: str | TagScope = TagScope.EFFECTIVE, +) -> List[Edge]: + """Select edges by tag.""" + try: + normalized = normalize_tag(tag, strict=True) + resolved_scope = normalize_tag_scope(scope) + if isinstance(shape, Face): + edges = shape.get_edges() + elif isinstance(shape, Solid): + edges = shape.get_edges() + else: + raise ValueError("只能从面或实体中选择边") + + return [edge for edge in edges if edge._has_tag(normalized, resolved_scope)] + except Exception as e: + _wrap_public_api_error( + operation="select_edges_by_tag", + what_happened="Failed to select edges by tag.", + possible_causes=[ + "The input shape is neither a Face nor a Solid.", + "The shape is invalid.", + "The tag string is invalid.", + ], + how_to_fix=[ + "Pass a Face or Solid object.", + "Use the exact edge tag that was previously assigned.", + "If selection is empty unexpectedly, inspect the available edge tags first.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/_operators_sketch.py b/src/simplecadapi/_operators_sketch.py new file mode 100644 index 00000000..f17f9dee --- /dev/null +++ b/src/simplecadapi/_operators_sketch.py @@ -0,0 +1,1612 @@ +"""Sketch operator implementations.""" + +from __future__ import annotations + +from ._operation_support import * + +def make_sketch_rsketch( + name: Optional[str] = None, + *, + plane: Any = "XY", + sketch_id: Optional[str] = None, +) -> Sketch: + """Create an empty declarative sketch document. + + Use this API, not concrete edge/wire constructors, when the intent is to + build a sketch profile with constraints. + """ + try: + session = get_active_session() + resolved_sketch_id = ( + sketch_id + if sketch_id is not None or session is None + else session.allocate_object_id("sketch") + ) + sketch = Sketch( + name=name, + plane=_sketch_plane_in_current_coordinates(plane), + sketch_id=resolved_sketch_id, + ) + return cast( + Sketch, + _finalize_runtime_object( + sketch, + op=_OP_MAKE_SKETCH_RSKETCH, + params={"name": name, "plane": plane, "sketch_id": sketch.sketch_id}, + tags={"sketch"}, + entity_type="Sketch", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_sketch_rsketch", + what_happened="Failed to create a sketch document.", + possible_causes=["The sketch name or plane payload is invalid."], + how_to_fix=["Use plane='XY', 'XZ', 'YZ', or a valid plane mapping."], + error=e, + ) + +def _safe_semantic_tag(prefix: str, value: object) -> str: + raw = str(value or "unnamed").strip().lower() + raw = re.sub(r"[^a-z0-9_-]+", ".", raw).strip(".") + raw = re.sub(r"\.+", ".", raw) + segments: List[str] = [] + for segment in raw.split("."): + if not segment: + continue + if not segment[0].isalpha(): + segment = f"id_{segment}" + segments.append(segment) + if not segments: + segments = ["unnamed"] + return normalize_tag(f"{prefix}.{'.'.join(segments)}", strict=True) + +def _sketch_target_to_path(target: SketchRef) -> str: + if target.kind == "point" and target.subentity != "geometry": + return f"{target.entity_id}.{target.subentity}" + return target.entity_id + +def _resolve_sketch_target( + sketch: Sketch, + target: Union[SketchRef, str], + *, + expected: Optional[Union[str, Sequence[str]]] = None, +) -> SketchRef: + return sketch.resolve_target(target, expected=expected) + +def _resolve_sketch_targets( + sketch: Sketch, + targets: Sequence[Union[SketchRef, str]], + *, + expected: Optional[Sequence[Optional[Union[str, Sequence[str]]]]] = None, +) -> List[SketchRef]: + refs: List[SketchRef] = [] + for index, target in enumerate(targets): + target_expected = expected[index] if expected is not None else None + refs.append(_resolve_sketch_target(sketch, target, expected=target_expected)) + return refs + +def _begin_linear_sketch_edits(sketch: Sketch) -> Sketch: + """Enable in-place edits for one private, linear sketch construction chain.""" + sketch._set_runtime("sketch.linear_edit", True) + return sketch + +def _end_linear_sketch_edits(sketch: Sketch) -> Sketch: + sketch._set_runtime("sketch.linear_edit", False) + return sketch + +def _sketch_update_target(sketch: Sketch) -> Sketch: + if sketch._get_runtime("sketch.linear_edit", False): + sketch._last_solve_result = None + return sketch + return sketch.clone(include_solve=False) + +def add_point_rsketch( + sketch: Sketch, + point_id: str, + x: ScalarLike, + y: ScalarLike, +) -> Sketch: + """Add a named point entity and return an updated sketch document.""" + try: + updated = _sketch_update_target(sketch) + updated.add_point(point_id, x, y) + return cast( + Sketch, + _finalize_runtime_object( + updated, + op=_OP_ADD_POINT_RSKETCH, + params={ + "sketch_id": updated.sketch_id, + "point_id": point_id, + "x": x, + "y": y, + }, + input_objects=[sketch], + tags={"sketch", "point"}, + entity_type="Sketch", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="add_point_rsketch", + what_happened="Failed to add a point to the sketch.", + possible_causes=[ + "The sketch is invalid.", + "The point id is duplicated.", + "The x or y value is not a valid scalar or expression.", + ], + how_to_fix=[ + "Use a unique point id within the sketch.", + "Pass numeric x/y values or valid scalar expressions.", + ], + error=e, + ) + +def get_sketch_entity_rsketchref( + sketch: Sketch, + entity_id: str, +) -> SketchRef: + """Return a stable ref for a named sketch entity.""" + return sketch.ref(entity_id) + +def get_sketch_point_rsketchref( + sketch: Sketch, + point_path: str, +) -> SketchRef: + """Return a stable ref for a sketch point or endpoint path.""" + return sketch.point_ref(point_path) + +def add_line_rsketch( + sketch: Sketch, + entity_id: str, + start: Union[SketchRef, str], + end: Union[SketchRef, str], + *, + construction: bool = False, +) -> Sketch: + """Add a named line entity and return an updated sketch document.""" + try: + start_ref = _resolve_sketch_target(sketch, start, expected="point") + end_ref = _resolve_sketch_target(sketch, end, expected="point") + updated = _sketch_update_target(sketch) + updated.add_line(entity_id, start_ref, end_ref, construction=construction) + return cast( + Sketch, + _finalize_runtime_object( + updated, + op=_OP_ADD_LINE_RSKETCH, + params={ + "sketch_id": updated.sketch_id, + "entity_id": entity_id, + "start": _sketch_target_to_path(start_ref), + "end": _sketch_target_to_path(end_ref), + "construction": construction, + }, + input_objects=[sketch], + tags={"sketch", "line"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="add_line_rsketch", + what_happened="Failed to add a line to the sketch.", + possible_causes=[ + "The line id is duplicated.", + "One of the endpoint refs does not belong to this sketch.", + "Both endpoints resolve to the same point.", + ], + how_to_fix=[ + "Use a unique line id.", + "Create endpoints with add_point_rsketch(...) and refer to them by id.", + ], + error=e, + ) + +def add_circle_rsketch( + sketch: Sketch, + entity_id: str, + center: Union[SketchRef, str], + radius: ScalarLike, + *, + construction: bool = False, +) -> Sketch: + """Add a named circle entity and return an updated sketch document.""" + try: + center_ref = _resolve_sketch_target(sketch, center, expected="point") + updated = _sketch_update_target(sketch) + updated.add_circle(entity_id, center_ref, radius, construction=construction) + return cast( + Sketch, + _finalize_runtime_object( + updated, + op=_OP_ADD_CIRCLE_RSKETCH, + params={ + "sketch_id": updated.sketch_id, + "entity_id": entity_id, + "center": _sketch_target_to_path(center_ref), + "radius": radius, + "construction": construction, + }, + input_objects=[sketch], + tags={"sketch", "circle"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="add_circle_rsketch", + what_happened="Failed to add a circle to the sketch.", + possible_causes=[ + "The circle id is duplicated.", + "The center ref does not belong to this sketch.", + "The radius is not positive.", + ], + how_to_fix=[ + "Use a unique circle id and a positive radius.", + "Create the center with add_point_rsketch(...) and refer to it by id.", + ], + error=e, + ) + +def add_bspline_rsketch( + sketch: Sketch, + entity_id: str, + start: Union[SketchRef, str], + end: Union[SketchRef, str], + control_points: Sequence[Any], + degree: int = 3, + knots: Optional[Sequence[float]] = None, + multiplicities: Optional[Sequence[int]] = None, + weights: Optional[Sequence[float]] = None, + periodic: bool = False, + *, + construction: bool = False, +) -> Sketch: + """Add a B-spline curve entity to a sketch. + + The start/end point refs link the B-spline into a closed profile + loop. Control points may be literal 2-D coordinates or point refs. + """ + try: + start_ref = _resolve_sketch_target(sketch, start, expected="point") + end_ref = _resolve_sketch_target(sketch, end, expected="point") + updated = _sketch_update_target(sketch) + updated.add_bspline( + entity_id, + start_ref, + end_ref, + control_points=control_points, + degree=degree, + knots=knots, + multiplicities=multiplicities, + weights=weights, + periodic=periodic, + construction=construction, + ) + bspline_data = updated.entities[str(entity_id)].data + return cast( + Sketch, + _finalize_runtime_object( + updated, + op=_OP_ADD_BSPLINE_RSKETCH, + params={ + "sketch_id": updated.sketch_id, + "entity_id": entity_id, + "start": _sketch_target_to_path(start_ref), + "end": _sketch_target_to_path(end_ref), + "control_points": bspline_data["control_points"], + "degree": bspline_data["degree"], + "knots": bspline_data["knots"], + "multiplicities": bspline_data["multiplicities"], + "weights": bspline_data["weights"], + "periodic": bspline_data["periodic"], + "construction": construction, + }, + input_objects=[sketch], + tags={"sketch", "bspline"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="add_bspline_rsketch", + what_happened="Failed to add a B-spline to the sketch.", + possible_causes=[ + "The entity id is duplicated.", + "The start or end ref does not belong to this sketch.", + "Too few control points for the requested degree.", + ], + how_to_fix=[ + "Use a unique entity id.", + "Create start and end points with add_point_rsketch(...) first.", + "Pass at least degree+1 control points.", + ], + error=e, + ) + +def add_arc_rsketch( + sketch: Sketch, + entity_id: str, + start: Union[SketchRef, str], + end: Union[SketchRef, str], + center: Union[SketchRef, str], + *, + construction: bool = False, +) -> Sketch: + """Add an arc entity to a sketch.""" + try: + start_ref = _resolve_sketch_target(sketch, start, expected="point") + end_ref = _resolve_sketch_target(sketch, end, expected="point") + center_ref = _resolve_sketch_target(sketch, center, expected="point") + updated = _sketch_update_target(sketch) + updated.add_arc( + entity_id, + start_ref, + end_ref, + center_ref, + construction=construction, + ) + return cast( + Sketch, + _finalize_runtime_object( + updated, + op=_OP_ADD_ARC_RSKETCH, + params={ + "sketch_id": updated.sketch_id, + "entity_id": entity_id, + "start": _sketch_target_to_path(start_ref), + "end": _sketch_target_to_path(end_ref), + "center": _sketch_target_to_path(center_ref), + "construction": construction, + }, + input_objects=[sketch], + tags={"sketch", "arc"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="add_arc_rsketch", + what_happened="Failed to add an arc to the sketch.", + possible_causes=[ + "The entity id is duplicated.", + "The start, end, or center ref does not belong to this sketch.", + "The start and end points are the same.", + ], + how_to_fix=[ + "Use a unique entity id.", + "Create start, end, and center points with add_point_rsketch(...) first.", + ], + error=e, + ) + +def _constrain_rsketch( + sketch: Sketch, + kind: str, + targets: Sequence[Union[SketchRef, str]], + *, + value: Any = None, + constraint_id: Optional[str] = None, + driving: bool = True, + metadata: Optional[Dict[str, Any]] = None, + expected: Optional[Sequence[Optional[Union[str, Sequence[str]]]]] = None, +) -> Sketch: + target_refs = _resolve_sketch_targets(sketch, targets, expected=expected) + updated = _sketch_update_target(sketch) + updated.add_constraint( + kind, + target_refs, + value=value, + constraint_id=constraint_id, + driving=driving, + metadata=metadata, + ) + op = _SKETCH_CONSTRAINT_OPS[kind] + return cast( + Sketch, + _finalize_runtime_object( + updated, + op=op, + params={ + "sketch_id": updated.sketch_id, + "kind": kind, + "targets": [_sketch_target_to_path(target) for target in target_refs], + "value": value, + "constraint_id": constraint_id, + "driving": driving, + "metadata": metadata or {}, + }, + input_objects=[sketch], + tags={"sketch", "constraint"}, + ), + ) + +def constrain_coincident_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain two sketch points to be coincident.""" + return _constrain_rsketch( + sketch, + "coincident", + [a, b], + constraint_id=constraint_id, + expected=["point", "point"], + ) + +def constrain_connect_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Alias for `constrain_coincident_rsketch` using connection wording.""" + return _constrain_rsketch( + sketch, + "coincident", + [a, b], + constraint_id=constraint_id, + expected=["point", "point"], + ) + +def constrain_point_on_rsketch( + sketch: Sketch, + point: Union[SketchRef, str], + entity: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain a sketch point to lie on a line, circle, or circular arc.""" + return _constrain_rsketch( + sketch, + "point_on", + [point, entity], + constraint_id=constraint_id, + expected=["point", ("line", "circle", "arc")], + ) + +def constrain_horizontal_rsketch( + sketch: Sketch, line: Union[SketchRef, str], *, constraint_id: Optional[str] = None +) -> Sketch: + """Constrain a sketch line to be horizontal.""" + return _constrain_rsketch( + sketch, "horizontal", [line], constraint_id=constraint_id, expected=["line"] + ) + +def constrain_vertical_rsketch( + sketch: Sketch, line: Union[SketchRef, str], *, constraint_id: Optional[str] = None +) -> Sketch: + """Constrain a sketch line to be vertical.""" + return _constrain_rsketch( + sketch, "vertical", [line], constraint_id=constraint_id, expected=["line"] + ) + +def constrain_parallel_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain two sketch lines to be parallel.""" + return _constrain_rsketch( + sketch, + "parallel", + [a, b], + constraint_id=constraint_id, + expected=["line", "line"], + ) + +def constrain_perpendicular_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain two sketch lines to be perpendicular.""" + return _constrain_rsketch( + sketch, + "perpendicular", + [a, b], + constraint_id=constraint_id, + expected=["line", "line"], + ) + +def constrain_collinear_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain two sketch lines to lie on the same infinite line.""" + return _constrain_rsketch( + sketch, + "collinear", + [a, b], + constraint_id=constraint_id, + expected=["line", "line"], + ) + +def constrain_tangent_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + at_a: Optional[str] = None, + at_b: Optional[str] = None, + mode: str = "external", + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain supported curves to be tangent on an explicit branch. + + ``at_a``/``at_b`` select ``"start"`` or ``"end"`` for arc and + B-spline endpoint tangency. Circle-circle tangency accepts + ``mode="external"`` or ``mode="internal"``. + """ + if at_a not in {None, "start", "end"} or at_b not in {None, "start", "end"}: + raise ValueError("Tangent endpoint selectors must be 'start' or 'end'") + if mode not in {"external", "internal"}: + raise ValueError("Tangent mode must be 'external' or 'internal'") + return _constrain_rsketch( + sketch, + "tangent", + [a, b], + constraint_id=constraint_id, + metadata={"at_a": at_a, "at_b": at_b, "mode": mode}, + expected=[ + ("line", "circle", "arc", "bspline"), + ("line", "circle", "arc", "bspline"), + ], + ) + +def constrain_concentric_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain two sketch circles to share a center.""" + return _constrain_rsketch( + sketch, + "concentric", + [a, b], + constraint_id=constraint_id, + expected=[("circle", "arc"), ("circle", "arc")], + ) + +def constrain_midpoint_rsketch( + sketch: Sketch, + point: Union[SketchRef, str], + line: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain a sketch point to the midpoint of a line.""" + return _constrain_rsketch( + sketch, + "midpoint", + [point, line], + constraint_id=constraint_id, + expected=["point", "line"], + ) + +def constrain_symmetric_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + axis: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain two sketch points to be symmetric about a line axis.""" + return _constrain_rsketch( + sketch, + "symmetric", + [a, b, axis], + constraint_id=constraint_id, + expected=["point", "point", "line"], + ) + +def constrain_equal_length_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain two sketch lines to have equal length.""" + return _constrain_rsketch( + sketch, + "equal_length", + [a, b], + constraint_id=constraint_id, + expected=["line", "line"], + ) + +def constrain_equal_radius_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Constrain two circles/arcs to have equal radius.""" + return _constrain_rsketch( + sketch, + "equal_radius", + [a, b], + constraint_id=constraint_id, + expected=[("circle", "arc"), ("circle", "arc")], + ) + +def constrain_distance_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + value: ScalarLike, + *, + constraint_id: Optional[str] = None, + driving: bool = True, +) -> Sketch: + """Add a driving point-to-point distance constraint.""" + return _constrain_rsketch( + sketch, + "distance", + [a, b], + value=value, + constraint_id=constraint_id, + driving=driving, + expected=["point", "point"], + ) + +def constrain_distance_x_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + value: ScalarLike, + *, + constraint_id: Optional[str] = None, + driving: bool = True, +) -> Sketch: + """Add a driving horizontal distance constraint.""" + return _constrain_rsketch( + sketch, + "distance_x", + [a, b], + value=value, + constraint_id=constraint_id, + driving=driving, + expected=["point", "point"], + ) + +def constrain_distance_y_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + value: ScalarLike, + *, + constraint_id: Optional[str] = None, + driving: bool = True, +) -> Sketch: + """Add a driving vertical distance constraint.""" + return _constrain_rsketch( + sketch, + "distance_y", + [a, b], + value=value, + constraint_id=constraint_id, + driving=driving, + expected=["point", "point"], + ) + +def constrain_length_rsketch( + sketch: Sketch, + line: Union[SketchRef, str], + value: ScalarLike, + *, + constraint_id: Optional[str] = None, + driving: bool = True, +) -> Sketch: + """Add a driving length constraint to a line, arc, or B-spline.""" + return _constrain_rsketch( + sketch, + "length", + [line], + value=value, + constraint_id=constraint_id, + driving=driving, + expected=[("line", "arc", "bspline")], + ) + +def constrain_angle_rsketch( + sketch: Sketch, + a: Union[SketchRef, str], + b: Union[SketchRef, str], + value: ScalarLike, + *, + constraint_id: Optional[str] = None, + driving: bool = True, +) -> Sketch: + """Add a driving angle constraint between two sketch lines.""" + return _constrain_rsketch( + sketch, + "angle", + [a, b], + value=value, + constraint_id=constraint_id, + driving=driving, + expected=["line", "line"], + ) + +def constrain_radius_rsketch( + sketch: Sketch, + circle: Union[SketchRef, str], + value: ScalarLike, + *, + constraint_id: Optional[str] = None, + driving: bool = True, +) -> Sketch: + """Add a driving circle or arc radius constraint.""" + return _constrain_rsketch( + sketch, + "radius", + [circle], + value=value, + constraint_id=constraint_id, + driving=driving, + expected=[("circle", "arc")], + ) + +def constrain_diameter_rsketch( + sketch: Sketch, + circle: Union[SketchRef, str], + value: ScalarLike, + *, + constraint_id: Optional[str] = None, + driving: bool = True, +) -> Sketch: + """Add a driving circle or arc diameter constraint.""" + return _constrain_rsketch( + sketch, + "diameter", + [circle], + value=value, + constraint_id=constraint_id, + driving=driving, + expected=[("circle", "arc")], + ) + +def constrain_fix_rsketch( + sketch: Sketch, + target: Union[SketchRef, str], + *, + constraint_id: Optional[str] = None, +) -> Sketch: + """Fix a sketch point or entity to its initial coordinates.""" + return _constrain_rsketch(sketch, "fix", [target], constraint_id=constraint_id) + +def inspect_sketch_rsketchresult( + sketch: Sketch, + *, + require_fully_constrained: bool = False, + strict: bool = True, + tolerance: float = 1e-7, + max_iterations: int = 80, +) -> SketchSolveResult: + """Inspect sketch constraints by running the solver without recording graph nodes.""" + try: + result = sketch.clone(include_solve=False).solve( + require_fully_constrained=require_fully_constrained, + strict=strict, + tolerance=tolerance, + max_iterations=max_iterations, + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="inspect_sketch_rsketchresult", + what_happened="Failed to inspect the sketch constraints.", + possible_causes=[ + "The sketch has invalid, conflicting, or underconstrained constraints.", + "A constraint references a missing or wrong-kind entity.", + ], + how_to_fix=[ + "Inspect diagnostics with strict=False if needed.", + "Add fix/dimension constraints until the intended profile is fully constrained.", + ], + error=e, + ) + +def _sketch_solve_snapshot(result: SketchSolveResult) -> Dict[str, Any]: + return result.to_dict() + +def _sketch_source_metadata( + sketch: Sketch, + profile: int | str, + profile_payload: Dict[str, Any], + inner_profile_payloads: Sequence[Tuple[int | str, Dict[str, Any]]] = (), +) -> Dict[str, Any]: + return { + "sketch_id": sketch.sketch_id, + "name": sketch.name, + "plane": sketch.plane, + "profile": profile, + "profile_id": profile_payload.get("id"), + "profile_kind": profile_payload.get("kind"), + "inner_profiles": [ + { + "profile": inner_profile, + "profile_id": inner_payload.get("id"), + "profile_kind": inner_payload.get("kind"), + } + for inner_profile, inner_payload in inner_profile_payloads + ], + } + +def _sketch_edge_metadata( + sketch: Sketch, + entity_id: str, + profile: int | str, + profile_payload: Dict[str, Any], + *, + loop_role: str = "outer", +) -> Dict[str, Any]: + entity = sketch.entities[str(entity_id)] + return { + "sketch_id": sketch.sketch_id, + "sketch_name": sketch.name, + "entity_id": str(entity_id), + "kind": entity.kind, + "profile": profile, + "profile_id": profile_payload.get("id"), + "loop_role": loop_role, + } + +def _sketch_promotion_tags( + sketch: Sketch, + profile_payload: Dict[str, Any], +) -> Tuple[str, str]: + sketch_tag = _safe_semantic_tag("sketch", sketch.name or sketch.sketch_id) + profile_tag = _safe_semantic_tag( + "sketch_profile", profile_payload.get("id", "profile") + ) + return sketch_tag, profile_tag + +def _sketch_promotion_map( + sketch: Sketch, + profile: int | str, + profile_payload: Dict[str, Any], + *, + inner_profile_payloads: Sequence[Tuple[int | str, Dict[str, Any]]] = (), + target_kind: Optional[str] = None, +) -> Dict[str, Any]: + sketch_tag, profile_tag = _sketch_promotion_tags(sketch, profile_payload) + profile_local_name = _sketch_topology_tag_local_name( + profile_payload.get("id", "profile") + ) + profile_identity_tag = f"{sketch_tag}.profile.{profile_local_name}" + edges: List[Dict[str, Any]] = [] + loops: List[Dict[str, Any]] = [] + loop_specs = [ + (profile, profile_payload, "outer"), + *[ + (inner_profile, inner_payload, "inner") + for inner_profile, inner_payload in inner_profile_payloads + ], + ] + for loop_profile, loop_payload, loop_role in loop_specs: + loop_sketch_tag, loop_profile_tag = _sketch_promotion_tags(sketch, loop_payload) + loop_edges: List[Dict[str, Any]] = [] + for entity_id in loop_payload.get("entity_ids", []): + entity_tag = _safe_semantic_tag("sketch_entity", entity_id) + entity_local_name = _sketch_topology_tag_local_name(entity_id) + edge_payload = { + "entity_id": str(entity_id), + "profile": loop_profile, + "profile_id": loop_payload.get("id"), + "loop_role": loop_role, + "target_kind": "edge", + "tags": [loop_sketch_tag, loop_profile_tag, entity_tag], + "topology_name": { + "kind": "edge", + "name": f"{loop_sketch_tag}.entity.{entity_local_name}", + "local_name": entity_local_name, + }, + "metadata": { + "sketch_ref": _sketch_edge_metadata( + sketch, + str(entity_id), + loop_profile, + loop_payload, + loop_role=loop_role, + ) + }, + } + loop_edges.append(edge_payload) + edges.append(edge_payload) + loop_local_name = _sketch_topology_tag_local_name( + loop_payload.get("id", "profile") + ) + loops.append( + { + "role": loop_role, + "profile": loop_profile, + "profile_id": loop_payload.get("id"), + "profile_kind": loop_payload.get("kind"), + "topology_name": { + "kind": "wire", + "name": f"{loop_sketch_tag}.profile.{loop_local_name}", + "local_name": loop_local_name, + }, + "edges": loop_edges, + } + ) + return { + "schema_version": "2.0", + "profile": profile, + "profile_id": profile_payload.get("id"), + "profile_kind": profile_payload.get("kind"), + "tags": [sketch_tag, profile_tag], + "topology_name": { + "kind": target_kind or "profile", + "name": profile_identity_tag, + "local_name": profile_local_name, + }, + "loops": loops, + "edges": edges, + } + +def _apply_sketch_promotion_metadata( + shape: Union[Wire, Face], + *, + sketch: Sketch, + profile: int | str, + profile_payload: Dict[str, Any], + inner_profile_payloads: Sequence[Tuple[int | str, Dict[str, Any]]], + source_wires: Sequence[Tuple[int | str, Dict[str, Any], str, Wire]], + solve_snapshot: Dict[str, Any], +) -> None: + source_sketch = _sketch_source_metadata( + sketch, + profile, + profile_payload, + inner_profile_payloads, + ) + promotion_map = _sketch_promotion_map( + sketch, + profile, + profile_payload, + inner_profile_payloads=inner_profile_payloads, + target_kind="wire" if isinstance(shape, Wire) else "face", + ) + sketch_tag, profile_tag = _sketch_promotion_tags(sketch, profile_payload) + + shape.set_metadata("source_sketch", source_sketch) + shape.set_metadata("sketch_solve", solve_snapshot) + shape.set_metadata("sketch_promotion", promotion_map) + shape._apply_tag(sketch_tag, propagate=False) + shape._apply_tag(profile_tag, propagate=False) + + wires: List[Wire] = [] + if isinstance(shape, Wire): + wires = [shape] + elif isinstance(shape, Face): + wires = cast(List[Wire], shape.get_wires()) + + for wire in wires: + matches = [ + source for source in source_wires if source[3].wrapped.IsSame(wire.wrapped) + ] + if len(matches) != 1: + raise ValueError( + "Sketch promotion cannot establish exact profile-to-wire correspondence" + ) + loop_profile, loop_payload, _loop_role, _source_wire = matches[0] + loop_sketch_tag, loop_profile_tag = _sketch_promotion_tags(sketch, loop_payload) + wire.set_metadata("source_sketch", source_sketch) + wire.set_metadata("sketch_solve", solve_snapshot) + wire.set_metadata("sketch_promotion", promotion_map) + wire.set_metadata( + "sketch_profile", + _sketch_source_metadata(sketch, loop_profile, loop_payload), + ) + wire._apply_tag(loop_sketch_tag, propagate=False) + wire._apply_tag(loop_profile_tag, propagate=False) + + source_edges = [ + (loop_profile, loop_payload, loop_role, str(entity_id), source_edge) + for loop_profile, loop_payload, loop_role, source_wire in source_wires + for entity_id, source_edge in source_wire._get_runtime( + "sketch.entity_edges", [] + ) + ] + for edge in cast(List[Edge], shape.get_edges()): + matches = [source for source in source_edges if source[4].IsSame(edge.wrapped)] + if len(matches) != 1: + raise ValueError( + "Sketch promotion cannot establish exact entity-to-edge correspondence" + ) + loop_profile, loop_payload, loop_role, entity_id, _source_edge = matches[0] + loop_sketch_tag, loop_profile_tag = _sketch_promotion_tags(sketch, loop_payload) + entity_tag = _safe_semantic_tag("sketch_entity", entity_id) + edge.set_metadata( + "sketch_ref", + _sketch_edge_metadata( + sketch, + entity_id, + loop_profile, + loop_payload, + loop_role=loop_role, + ), + ) + edge.set_metadata("source_sketch", source_sketch) + edge._apply_tag(loop_sketch_tag, propagate=False) + edge._apply_tag(loop_profile_tag, propagate=False) + edge._apply_tag(entity_tag, propagate=False) + +def _sketch_topology_tag_local_name(value: object) -> str: + """Return the normalized local segment for a sketch topology tag.""" + + return _safe_semantic_tag("name", value).split(".", 1)[1] + +def _sketch_topology_identity_binding( + tag: str, + *, + kind: str, + local_name: str, + operation: str, + sketch: Sketch, + profile_id: str, + target_topo_id: str, + entity_id: Optional[str] = None, +) -> TagBinding: + rule_id = "simplecad.sketch_promotion_topology_name" + binding_key = "|".join( + ( + rule_id, + operation, + sketch.sketch_id, + profile_id, + entity_id or "", + target_topo_id, + tag, + ) + ) + return TagBinding( + tag=tag, + producer=TagProducer( + "auto_rule", + rule_id=rule_id, + rule_version="1.0", + ), + target=TagTarget("scope_root"), + propagation=TagPropagation( + topology=( + TopologyPropagation.DOWNWARD + if kind == "face" + else TopologyPropagation.LOCAL + ), + lineage=LineagePolicy.CONTINUATION_FRAGMENT, + ), + evidence=TagEvidence( + "topology_change", + { + "operation": operation, + "target_topo_id": target_topo_id, + "evidence_method": "SketchPromotionMap", + "sketch_promotion": { + "sketch_id": sketch.sketch_id, + "profile_id": profile_id, + **({"entity_id": entity_id} if entity_id is not None else {}), + }, + "topology_name": { + "kind": kind, + "name": tag, + "local_name": local_name, + }, + }, + ), + certainty=TagCertainty.PROVEN, + lifecycle=TagLifecycle.RECOMPUTE, + binding_id=f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, binding_key).hex}", + ) + +def _apply_sketch_promotion_identity_tags( + shape: Union[Wire, Face], + *, + sketch: Sketch, + profile_payload: Dict[str, Any], + source_wires: Sequence[Tuple[int | str, Dict[str, Any], str, Wire]], + operation: str, +) -> Union[Wire, Face]: + """Attach topology-identity tags from an exact sketch promotion map.""" + + sketch_prefix = _safe_semantic_tag("sketch", sketch.name or sketch.sketch_id) + profile_local_name = _sketch_topology_tag_local_name( + profile_payload.get("id", "profile") + ) + profile_kind = "wire" if isinstance(shape, Wire) else "face" + profile_tag = f"{sketch_prefix}.profile.{profile_local_name}" + shape._add_tag_binding( + _sketch_topology_identity_binding( + profile_tag, + kind=profile_kind, + local_name=profile_local_name, + operation=operation, + sketch=sketch, + profile_id=str(profile_payload.get("id", "profile")), + target_topo_id=shape.topo_id, + ) + ) + + if isinstance(shape, Face): + for wire in cast(List[Wire], shape.get_wires()): + matches = [ + source + for source in source_wires + if source[3].wrapped.IsSame(wire.wrapped) + ] + if len(matches) != 1: + raise ValueError( + "Sketch promotion cannot establish exact profile-to-wire correspondence" + ) + _loop_profile, loop_payload, _loop_role, _source_wire = matches[0] + loop_local_name = _sketch_topology_tag_local_name( + loop_payload.get("id", "profile") + ) + wire._add_tag_binding( + _sketch_topology_identity_binding( + f"{sketch_prefix}.profile.{loop_local_name}", + kind="wire", + local_name=loop_local_name, + operation=operation, + sketch=sketch, + profile_id=str(loop_payload.get("id", "profile")), + target_topo_id=wire.topo_id, + ) + ) + + source_edges = [ + (loop_payload, str(entity_id), source_edge) + for _loop_profile, loop_payload, _loop_role, source_wire in source_wires + for entity_id, source_edge in source_wire._get_runtime( + "sketch.entity_edges", [] + ) + ] + for edge in cast(List[Edge], shape.get_edges()): + matches = [source for source in source_edges if source[2].IsSame(edge.wrapped)] + if len(matches) != 1: + raise ValueError( + "Sketch promotion cannot establish exact entity-to-edge correspondence" + ) + loop_payload, entity_id, _source_edge = matches[0] + entity_local_name = _sketch_topology_tag_local_name(entity_id) + edge._add_tag_binding( + _sketch_topology_identity_binding( + f"{sketch_prefix}.entity.{entity_local_name}", + kind="edge", + local_name=entity_local_name, + operation=operation, + sketch=sketch, + profile_id=str(loop_payload.get("id", "profile")), + entity_id=entity_id, + target_topo_id=edge.topo_id, + ) + ) + return shape + +def _promote_sketch_profile( + sketch: Sketch, + profile: int | str, + *, + target_kind: str, + inner_profiles: Sequence[int | str] = (), + require_fully_constrained: bool, + strict: bool, + tolerance: float, + max_iterations: int, +) -> Tuple[ + Union[Wire, Face], + SketchSolveResult, + Dict[str, Any], + List[Tuple[int | str, Dict[str, Any]]], + List[Tuple[int | str, Dict[str, Any], str, Wire]], +]: + working = sketch.clone(include_solve=False) + solve_result = working.solve( + require_fully_constrained=require_fully_constrained, + strict=strict, + tolerance=tolerance, + max_iterations=max_iterations, + ) + profile_payload = sketch._profile_payload(profile, solve_result=solve_result) + inner_profile_payloads: List[Tuple[int | str, Dict[str, Any]]] = [] + seen_profile_ids = {str(profile_payload.get("id"))} + for inner_profile in inner_profiles: + inner_payload = sketch._profile_payload( + inner_profile, + solve_result=solve_result, + ) + inner_profile_id = str(inner_payload.get("id")) + if inner_profile_id in seen_profile_ids: + raise ValueError( + f"Sketch profile '{inner_profile_id}' was selected more than once" + ) + seen_profile_ids.add(inner_profile_id) + inner_profile_payloads.append((inner_profile, inner_payload)) + solve_snapshot = _sketch_solve_snapshot(solve_result) + with suspend_graph_recording(), use_coordinate_system(WORLD_CS): + outer_wire = sketch._wire_from_profile_payload(profile_payload) + source_wires: List[Tuple[int | str, Dict[str, Any], str, Wire]] = [ + (profile, profile_payload, "outer", outer_wire) + ] + if target_kind == "wire": + if inner_profile_payloads: + raise ValueError("A Wire promotion accepts exactly one sketch profile") + shape = outer_wire + elif target_kind == "face": + inner_wires: List[Wire] = [] + for inner_profile, inner_payload in inner_profile_payloads: + inner_wire = sketch._wire_from_profile_payload(inner_payload) + inner_wires.append(inner_wire) + source_wires.append((inner_profile, inner_payload, "inner", inner_wire)) + expected_normal = np.array(sketch._plane_normal_tuple(), dtype=float) + expected_normal = expected_normal / np.linalg.norm(expected_normal) + + def aligned_wire(wire: Wire): + loop_face = Face(make_face_from_wire_ocp(wire.wrapped)) + loop_normal = loop_face.get_normal_at() + loop_normal_vec = np.array( + [loop_normal.x, loop_normal.y, loop_normal.z], + dtype=float, + ) + return ( + wire.wrapped + if np.dot(expected_normal, loop_normal_vec) >= 0.0 + else TopoDS.Wire_s(wire.wrapped.Reversed()) + ) + + raw_face = ( + make_face_from_wires_ocp( + aligned_wire(outer_wire), + [aligned_wire(wire) for wire in inner_wires], + ) + if inner_wires + else make_face_from_wire_ocp(aligned_wire(outer_wire)) + ) + if inner_wires and not BRepCheck_Analyzer(raw_face).IsValid(): + raise ValueError( + "Sketch hole profiles must lie strictly inside the outer profile and must not touch or intersect another loop" + ) + face = Face(raw_face) + actual_normal = face.get_normal_at() + if ( + np.dot( + expected_normal, + np.array( + [actual_normal.x, actual_normal.y, actual_normal.z], + dtype=float, + ), + ) + < 0.0 + ): + face = Face(TopoDS.Face_s(raw_face.Reversed())) + shape = face + else: + raise ValueError( + f"Unsupported sketch promotion target kind '{target_kind}'" + ) + _apply_sketch_promotion_metadata( + cast(Union[Wire, Face], shape), + sketch=sketch, + profile=profile, + profile_payload=profile_payload, + inner_profile_payloads=inner_profile_payloads, + source_wires=source_wires, + solve_snapshot=solve_snapshot, + ) + return ( + cast(Union[Wire, Face], shape), + solve_result, + profile_payload, + inner_profile_payloads, + source_wires, + ) + +def _assert_sketch_solve_snapshot_matches( + result: SketchSolveResult, + snapshot: Dict[str, Any], + *, + tolerance: float = 1e-7, +) -> None: + _assert_sketch_solve_snapshot_dict_matches( + result.to_dict(), snapshot, tolerance=tolerance + ) + +def _assert_sketch_solve_snapshot_dict_matches( + actual: Dict[str, Any], + snapshot: Dict[str, Any], + *, + tolerance: float = 1e-7, +) -> None: + if str(actual.get("status")) != str(snapshot.get("status")): + raise ValueError( + f"Sketch solve status changed from {snapshot.get('status')!r} to {actual.get('status')!r}" + ) + if int(actual.get("dof", -1)) != int(snapshot.get("dof", -1)): + raise ValueError( + f"Sketch solve DOF changed from {snapshot.get('dof')!r} to {actual.get('dof')!r}" + ) + if ( + abs( + float(actual.get("residual_norm", 0.0)) + - float(snapshot.get("residual_norm", 0.0)) + ) + > tolerance + ): + raise ValueError("Sketch solve residual changed beyond recorded tolerance") + + actual_points = cast(Dict[str, Any], actual.get("solved_points", {})) + expected_points = cast(Dict[str, Any], snapshot.get("solved_points", {})) + if set(actual_points) != set(expected_points): + raise ValueError("Sketch solve point set changed") + for point_id, point in actual_points.items(): + expected = expected_points[point_id] + if ( + math.dist( + (float(point[0]), float(point[1])), + (float(expected[0]), float(expected[1])), + ) + > tolerance + ): + raise ValueError( + f"Sketch solve point '{point_id}' changed beyond recorded tolerance" + ) + + actual_scalars = cast(Dict[str, Any], actual.get("solved_scalars", {})) + expected_scalars = cast(Dict[str, Any], snapshot.get("solved_scalars", {})) + if set(actual_scalars) != set(expected_scalars): + raise ValueError("Sketch solve scalar set changed") + for scalar_id, value in actual_scalars.items(): + if abs(float(value) - float(expected_scalars[scalar_id])) > tolerance: + raise ValueError( + f"Sketch solve scalar '{scalar_id}' changed beyond recorded tolerance" + ) + + actual_entities = cast(Dict[str, Any], actual.get("solved_entities", {})) + expected_entities = cast(Dict[str, Any], snapshot.get("solved_entities", {})) + _assert_sketch_solved_entities_match( + actual_entities, + expected_entities, + tolerance=tolerance, + ) + +def _assert_sketch_solved_entities_match( + actual: Dict[str, Any], + expected: Dict[str, Any], + *, + tolerance: float, +) -> None: + if set(actual) != set(expected): + raise ValueError("Sketch solve entity set changed") + for entity_id, entity in actual.items(): + _assert_sketch_solved_value_matches( + entity, + expected[entity_id], + tolerance=tolerance, + path=f"Sketch solve entity '{entity_id}'", + ) + +def _assert_sketch_solved_value_matches( + actual: Any, + expected: Any, + *, + tolerance: float, + path: str, +) -> None: + if isinstance(actual, Mapping) and isinstance(expected, Mapping): + if set(actual) != set(expected): + raise ValueError(f"{path} field set changed") + for key, value in actual.items(): + _assert_sketch_solved_value_matches( + value, + expected[key], + tolerance=tolerance, + path=f"{path}.{key}", + ) + return + if isinstance(actual, (list, tuple)) and isinstance(expected, (list, tuple)): + if len(actual) != len(expected): + raise ValueError(f"{path} sequence length changed") + for index, value in enumerate(actual): + _assert_sketch_solved_value_matches( + value, + expected[index], + tolerance=tolerance, + path=f"{path}[{index}]", + ) + return + if ( + isinstance(actual, (int, float)) + and not isinstance(actual, bool) + and isinstance(expected, (int, float)) + and not isinstance(expected, bool) + ): + if abs(float(actual) - float(expected)) > tolerance: + raise ValueError(f"{path} changed beyond recorded tolerance") + return + if actual != expected: + raise ValueError(f"{path} changed") + +def make_wire_from_sketch_rwire( + sketch: Sketch, + profile: int | str = 0, + *, + require_fully_constrained: bool = False, + strict: bool = True, + tolerance: float = 1e-7, + max_iterations: int = 80, +) -> Wire: + """Promote a sketch profile to a concrete wire, solving internally.""" + try: + if not isinstance(sketch, Sketch): + raise ValueError("Input must be a Sketch") + ( + wire, + solve_result, + profile_payload, + inner_profile_payloads, + source_wires, + ) = _promote_sketch_profile( + sketch, + profile, + target_kind="wire", + require_fully_constrained=require_fully_constrained, + strict=strict, + tolerance=tolerance, + max_iterations=max_iterations, + ) + solve_snapshot = _sketch_solve_snapshot(solve_result) + finalized = cast( + Wire, + _finalize_derived_shape( + cast(Wire, wire), + op=_OP_MAKE_WIRE_FROM_SKETCH_RWIRE, + params={ + "profile": profile, + "sketch": sketch.to_dict(), + "require_fully_constrained": require_fully_constrained, + "strict": strict, + "tolerance": tolerance, + "max_iterations": max_iterations, + "solve_snapshot": solve_snapshot, + "promotion_map": _sketch_promotion_map( + sketch, + profile, + profile_payload, + inner_profile_payloads=inner_profile_payloads, + target_kind="wire", + ), + }, + input_shapes=cast(Sequence[AnyShape], [sketch]), + tags={"derived", "wire", "sketch"}, + ), + ) + return cast( + Wire, + _apply_sketch_promotion_identity_tags( + finalized, + sketch=sketch, + profile_payload=profile_payload, + source_wires=source_wires, + operation=_OP_MAKE_WIRE_FROM_SKETCH_RWIRE, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_wire_from_sketch_rwire", + what_happened="Failed to create a wire from the sketch.", + possible_causes=[ + "The sketch has no closed non-construction profile.", + "The sketch constraints are conflicting or invalid.", + "The requested profile index or id does not exist.", + ], + how_to_fix=[ + "Build sketch profiles only through sketch APIs and close all profile loops.", + "Call inspect_sketch_rsketchresult(..., strict=False) to inspect diagnostics.", + ], + error=e, + ) + +def make_face_from_sketch_rface( + sketch: Sketch, + profile: int | str = 0, + *, + inner_profiles: Sequence[int | str] = (), + require_fully_constrained: bool = False, + strict: bool = True, + tolerance: float = 1e-7, + max_iterations: int = 80, +) -> Face: + """Promote one outer and optional inner sketch profiles to a face.""" + try: + if not isinstance(sketch, Sketch): + raise ValueError("Input must be a Sketch") + normalized_inner_profiles = tuple(inner_profiles) + ( + face, + solve_result, + profile_payload, + inner_profile_payloads, + source_wires, + ) = _promote_sketch_profile( + sketch, + profile, + target_kind="face", + inner_profiles=normalized_inner_profiles, + require_fully_constrained=require_fully_constrained, + strict=strict, + tolerance=tolerance, + max_iterations=max_iterations, + ) + solve_snapshot = _sketch_solve_snapshot(solve_result) + finalized = cast( + Face, + _finalize_derived_shape( + cast(Face, face), + op=_OP_MAKE_FACE_FROM_SKETCH_RFACE, + params={ + "profile": profile, + "inner_profiles": normalized_inner_profiles, + "sketch": sketch.to_dict(), + "require_fully_constrained": require_fully_constrained, + "strict": strict, + "tolerance": tolerance, + "max_iterations": max_iterations, + "solve_snapshot": solve_snapshot, + "promotion_map": _sketch_promotion_map( + sketch, + profile, + profile_payload, + inner_profile_payloads=inner_profile_payloads, + target_kind="face", + ), + }, + input_shapes=cast(Sequence[AnyShape], [sketch]), + tags={"derived", "face", "sketch"}, + ), + ) + return cast( + Face, + _apply_sketch_promotion_identity_tags( + finalized, + sketch=sketch, + profile_payload=profile_payload, + source_wires=source_wires, + operation=_OP_MAKE_FACE_FROM_SKETCH_RFACE, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_face_from_sketch_rface", + what_happened="Failed to create a face from the sketch.", + possible_causes=[ + "The sketch has no closed non-construction profile.", + "The sketch constraints are conflicting or invalid.", + "The requested profile index or id does not exist.", + "An inner profile is outside, intersects, or duplicates the outer profile.", + ], + how_to_fix=[ + "Build a closed profile with add_line_rsketch(...) or add_circle_rsketch(...).", + "Add constraints until the profile can solve cleanly.", + "Pass hole loops explicitly with inner_profiles=[...].", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/_operators_transform.py b/src/simplecadapi/_operators_transform.py new file mode 100644 index 00000000..3e2712ff --- /dev/null +++ b/src/simplecadapi/_operators_transform.py @@ -0,0 +1,432 @@ +"""Transform operator implementations.""" + +from __future__ import annotations + +from ._operation_support import * + +def translate_shape(shape: AnyShape, vector: Tuple[float, float, float]) -> AnyShape: + """Translate a shape by an offset vector.""" + try: + cs = get_current_cs() + vector_value = cast(Tuple[float, float, float], evaluate_value(vector)) + global_vector = cs.transform_vector(np.array(vector_value)) + resolved_vector = tuple(float(value) for value in global_vector) + if isinstance(shape, Solid): + tracked = cast( + TrackedResult, + tracked_translate(shape, resolved_vector), + ) + translated = cast(Solid, tracked.shape) + translated._metadata = shape._metadata.copy() + _attach_lineage_from_source( + shape, + translated, + derivation="continuation", + op=_OP_MAKE_TRANSLATE_RSHAPE, + ) + return _finalize_tracked_solid( + translated, + op=_OP_MAKE_TRANSLATE_RSHAPE, + params={"vector": vector}, + source_solid=shape, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[shape], + ) + + new_shape = translate_shape_ocp(shape, resolved_vector) + + new_shape._metadata = shape._metadata.copy() + _copy_runtime_state(shape, new_shape) + _attach_lineage_from_source( + shape, + new_shape, + derivation="continuation", + op=_OP_MAKE_TRANSLATE_RSHAPE, + ) + record_operation_if_active( + op=_OP_MAKE_TRANSLATE_RSHAPE, + params={"vector": vector}, + outputs=new_shape, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return new_shape + except Exception as e: + _wrap_public_api_error( + operation="translate_shape", + what_happened="Failed to translate the shape.", + possible_causes=[ + "The shape is invalid or has been corrupted by an earlier operation.", + "The translation vector is not a valid finite 3D vector.", + "The kernel rejected the transform.", + ], + how_to_fix=[ + "Pass a valid SimpleCAD shape object.", + "Pass vector as a finite 3-element tuple or expression-backed vector.", + "Inspect the shape and vector values before retrying.", + ], + error=e, + ) + +def rotate_shape( + shape: AnyShape, + angle: ScalarLike, + axis: Tuple[float, float, float] = (0, 0, 1), + origin: Tuple[float, float, float] = (0, 0, 0), +) -> AnyShape: + """Rotate a shape around an axis.""" + angle_value = evaluate_scalar(angle) + if angle_value == 0: + return shape + else: + try: + cs = get_current_cs() + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) + global_axis = cs.transform_vector(np.array(axis_value)) + global_origin = cs.transform_point(np.array(origin_value)) + resolved_axis = tuple(float(value) for value in global_axis) + resolved_origin = tuple(float(value) for value in global_origin) + if isinstance(shape, Solid): + tracked = cast( + TrackedResult, + tracked_rotate( + shape, + angle_value, + axis=resolved_axis, + origin=resolved_origin, + ), + ) + rotated = cast(Solid, tracked.shape) + rotated._metadata = shape._metadata.copy() + _attach_lineage_from_source( + shape, + rotated, + derivation="continuation", + op=_OP_MAKE_ROTATE_RSHAPE, + ) + return _finalize_tracked_solid( + rotated, + op=_OP_MAKE_ROTATE_RSHAPE, + params={"angle": angle, "axis": axis, "origin": origin}, + source_solid=shape, + delta=tracked.delta, + delta_entries=cast( + Dict[str, Dict[str, object]], tracked.delta_entries + ), + input_shapes=[shape], + ) + + new_shape = rotate_shape_ocp( + shape, + angle_value, + resolved_axis, + resolved_origin, + ) + + new_shape._metadata = shape._metadata.copy() + _copy_runtime_state(shape, new_shape) + _attach_lineage_from_source( + shape, + new_shape, + derivation="continuation", + op=_OP_MAKE_ROTATE_RSHAPE, + ) + record_operation_if_active( + op=_OP_MAKE_ROTATE_RSHAPE, + params={"angle": angle, "axis": axis, "origin": origin}, + outputs=new_shape, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return new_shape + except Exception as e: + _wrap_public_api_error( + operation="rotate_shape", + what_happened="Failed to rotate the shape.", + possible_causes=[ + "The shape is invalid.", + "The rotation angle is invalid or non-finite.", + "The axis or origin is not a valid finite 3D vector.", + ], + how_to_fix=[ + "Pass a valid shape and a finite rotation angle.", + "Use a non-zero axis vector and a valid origin point.", + "Log the evaluated angle, axis, and origin before retrying.", + ], + error=e, + ) + +def linear_pattern_rsolidlist( + shape: AnyShape, direction: Tuple[float, float, float], count: int, spacing: float +) -> List[Solid]: + """Create a linear pattern of solids.""" + try: + if count <= 0: + raise ValueError("阵列数量必须大于0") + if spacing <= 0: + raise ValueError("阵列间距必须大于0") + + direction_value = cast(Tuple[float, float, float], evaluate_value(direction)) + direction_array = np.asarray(direction_value, dtype=float) + direction_norm = float(np.linalg.norm(direction_array)) + if direction_norm <= 1e-15 or not np.isfinite(direction_norm): + raise ValueError("阵列方向不能是零向量") + local_direction = direction_array / direction_norm + + if get_active_session() is not None: + rv: List[Solid] = [] + for i in range(count): + offset = local_direction * (spacing * i) + translated_shape = translate_shape( + shape, (float(offset[0]), float(offset[1]), float(offset[2])) + ) + translated_shape._apply_tag("solid.pattern.linear", propagate=False) + geo = dict(translated_shape.get_metadata("geo", {})) + geo["pattern"] = {"type": "linear", "index": i + 1} + translated_shape.set_metadata("geo", geo) + _attach_track_summary(translated_shape, op="linear_pattern") + rv.append(cast(Solid, translated_shape)) + return rv + + shapes = [] + with suspend_graph_recording(): + for i in range(count): + offset = local_direction * (spacing * i) + translated_shape = translate_shape( + shape, (float(offset[0]), float(offset[1]), float(offset[2])) + ) + shapes.append(translated_shape) + + rv = [] + for i, s in enumerate(shapes): + s._apply_tag("solid.pattern.linear", propagate=False) + geo = dict(s.get_metadata("geo", {})) + geo["pattern"] = {"type": "linear", "index": i + 1} + s.set_metadata("geo", geo) + _attach_track_summary(s, op="linear_pattern") + rv.append(s) + + record_operation_if_active( + op="linear_pattern", + params={ + "direction": direction, + "count": count, + "spacing": spacing, + }, + outputs=rv, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return rv + + except Exception as e: + _wrap_public_api_error( + operation="linear_pattern_rsolidlist", + what_happened="Failed to create the linear pattern.", + possible_causes=[ + "The count is not a positive integer.", + "The spacing is not positive.", + "The direction vector is invalid.", + ], + how_to_fix=[ + "Use count >= 1.", + "Use spacing > 0.", + "Pass a valid finite direction vector.", + ], + error=e, + ) + +def radial_pattern_rsolidlist( + shape: AnyShape, + center: Tuple[float, float, float], + axis: Tuple[float, float, float], + count: int, + total_rotation_angle: float, +) -> List[Solid]: + """Create a radial pattern of solids.""" + try: + if count <= 0: + raise ValueError("阵列数量必须大于0") + if total_rotation_angle <= 0: + raise ValueError("角度必须大于0") + + shapes = [] + angle_step = total_rotation_angle / count # 修正角度计算,均匀分布 + + if get_active_session() is not None: + rv: List[Solid] = [] + for i in range(count): + rotation_angle = angle_step * i + rotated_shape = ( + cast(Solid, translate_shape(shape, (0.0, 0.0, 0.0))) + if i == 0 + else cast(Solid, rotate_shape(shape, rotation_angle, axis, center)) + ) + rotated_shape._apply_tag("solid.pattern.radial", propagate=False) + geo = dict(rotated_shape.get_metadata("geo", {})) + geo["pattern"] = {"type": "radial", "index": i + 1} + rotated_shape.set_metadata("geo", geo) + _attach_track_summary(rotated_shape, op="radial_pattern") + rv.append(cast(Solid, rotated_shape)) + return rv + + with suspend_graph_recording(): + for i in range(count): + rotation_angle = angle_step * i + rotated_shape = rotate_shape(shape, rotation_angle, axis, center) + shapes.append(rotated_shape) + + rv = [] + for i, s in enumerate(shapes): + s._apply_tag("solid.pattern.radial", propagate=False) + geo = dict(s.get_metadata("geo", {})) + geo["pattern"] = {"type": "radial", "index": i + 1} + s.set_metadata("geo", geo) + _attach_track_summary(s, op="radial_pattern") + rv.append(s) + + record_operation_if_active( + op="radial_pattern", + params={ + "center": center, + "axis": axis, + "count": count, + "total_rotation_angle": total_rotation_angle, + }, + outputs=rv, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return rv + except Exception as e: + _wrap_public_api_error( + operation="radial_pattern_rsolidlist", + what_happened="Failed to create the radial pattern.", + possible_causes=[ + "The count is not a positive integer.", + "The total rotation angle is not positive.", + "The center or axis is invalid.", + ], + how_to_fix=[ + "Use count >= 1.", + "Use a total rotation angle greater than zero.", + "Pass a valid center point and a non-zero axis vector.", + ], + error=e, + ) + +def mirror_shape( + shape: AnyShape, + plane_origin: Tuple[float, float, float], + plane_normal: Tuple[float, float, float], +) -> AnyShape: + """Mirror a shape across a plane.""" + try: + cs = get_current_cs() + plane_origin_value = cast( + Tuple[float, float, float], evaluate_value(plane_origin) + ) + plane_normal_value = cast( + Tuple[float, float, float], evaluate_value(plane_normal) + ) + global_origin = cs.transform_point(np.array(plane_origin_value)) + global_normal = cs.transform_vector(np.array(plane_normal_value)) + + # 确保法向量不是零向量 + if np.linalg.norm(global_normal) < 1e-10: + raise ValueError("镜像平面法向量不能是零向量") + + if isinstance(shape, Solid): + resolved_origin = tuple(float(value) for value in global_origin) + resolved_normal = tuple(float(value) for value in global_normal) + tracked = cast( + TrackedResult, + tracked_mirror( + shape, + resolved_origin, + resolved_normal, + ), + ) + new_shape = cast(Solid, tracked.shape) + new_shape._metadata = shape._metadata.copy() + _attach_lineage_from_source( + shape, + new_shape, + derivation="continuation", + op=_OP_MAKE_MIRROR_RSHAPE, + ) + new_shape._apply_tag("solid.transform.mirrored", propagate=False) + return _finalize_tracked_solid( + new_shape, + op=_OP_MAKE_MIRROR_RSHAPE, + params={ + "plane_origin": plane_origin, + "plane_normal": plane_normal, + }, + source_solid=shape, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[shape], + ) + + else: + new_shape = mirror_shape_ocp( + shape, + ( + float(global_origin[0]), + float(global_origin[1]), + float(global_origin[2]), + ), + ( + float(global_normal[0]), + float(global_normal[1]), + float(global_normal[2]), + ), + ) + + new_shape._metadata = shape._metadata.copy() + _attach_lineage_from_source( + shape, + new_shape, + derivation="continuation", + op=_OP_MAKE_MIRROR_RSHAPE, + ) + new_shape._apply_tag("solid.transform.mirrored", propagate=False) + + _attach_track_summary(new_shape, op=_OP_MAKE_MIRROR_RSHAPE) + record_operation_if_active( + op=_OP_MAKE_MIRROR_RSHAPE, + params={ + "plane_origin": plane_origin, + "plane_normal": plane_normal, + }, + outputs=new_shape, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return new_shape + except Exception as e: + _wrap_public_api_error( + operation="mirror_shape", + what_happened="Failed to mirror the shape across the plane.", + possible_causes=[ + "The plane origin or plane normal is invalid.", + "The plane normal is zero-length.", + "The kernel rejected the mirror transform.", + ], + how_to_fix=[ + "Pass a valid plane origin and a non-zero plane normal.", + "Validate the shape before mirroring.", + "If the plane is computed dynamically, inspect the evaluated values first.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/artifacts/assembly_definition.py b/src/simplecadapi/artifacts/assembly_definition.py index a6e3060c..22eef98e 100644 --- a/src/simplecadapi/artifacts/assembly_definition.py +++ b/src/simplecadapi/artifacts/assembly_definition.py @@ -174,11 +174,11 @@ class AssemblyDefinition: "/public_connectors", "connector IDs must be unique", ) - if any(item.anchor_kind != "forwarded" for item in connectors): + if any(item.anchor_kind != "public" for item in connectors): raise ArtifactValidationError( "connector_invalid", "/public_connectors", - "assembly connectors must be forwarded", + "assembly connectors must be public declarations", ) object.__setattr__(self, "public_connectors", connectors) if not isinstance(self.interface_hashes, InterfaceHashes): diff --git a/src/simplecadapi/artifacts/assembly_io.py b/src/simplecadapi/artifacts/assembly_io.py index 0f9294f6..b2b0f955 100644 --- a/src/simplecadapi/artifacts/assembly_io.py +++ b/src/simplecadapi/artifacts/assembly_io.py @@ -9,6 +9,7 @@ from typing import Any, Mapping from ..assembly import ( Assembly, Component, + PublicConnectorRef, _restore_component_occurrence_placements, ) from ..assembly_solver import ( @@ -21,12 +22,11 @@ from ..connector import ( ConnectorAnchor, ConnectorRef, GeometryRef, - resolve_connector_placement, ) from ..constraint import Constraint, ScalarLimit from ..material import Material from ..part import Part -from ..placement import Placement, inverse_placement +from ..placement import Placement from ..scene.archive import canonical_zip_bytes, preflight_zip_bytes from .assembly_definition import ( AssemblyDefinition, @@ -346,21 +346,20 @@ def validate_assembly_definition_graph( ) for connector_index, connector in enumerate(node.public_connectors): - source = dict(connector.forwarded_from or {}) - component_id = str(source.get("component_id", "")) - source_connector_id = str(source.get("connector_id", "")) + component_id = str(connector.source_component_id) + source_connector_id = str(connector.source_connector_id) instance = instance_by_id.get(component_id) if instance is None: raise ArtifactValidationError( "reference_missing", - f"/public_connectors/{connector_index}/forwarded_from/component_id", - f"forwarded connector references missing instance {component_id!r}", + f"/public_connectors/{connector_index}/source_component_id", + f"public connector references missing instance {component_id!r}", ) if source_connector_id not in connector_sets[instance.definition_id]: rendered = "/".join((*trace, instance.instance_id)) raise ArtifactValidationError( "reference_missing", - f"/public_connectors/{connector_index}/forwarded_from/connector_id", + f"/public_connectors/{connector_index}/source_connector_id", f"connector {source_connector_id!r} is missing along instance path {rendered}", ) @@ -606,7 +605,7 @@ def _runtime_connector(interface: ConnectorInterface) -> Connector: raise ArtifactValidationError( "connector_invalid", "/connectors", - "part connector cannot use a forwarded anchor", + "part connector must use a geometry or placement anchor", ) @@ -771,47 +770,18 @@ def materialize_definition( ) for item in node.instances ), + public_connectors=tuple( + PublicConnectorRef( + public_connector_id=interface.connector_id, + component_id=str(interface.source_component_id), + connector_id=str(interface.source_connector_id), + name=interface.name, + ) + for interface in node.public_connectors + ), constraints=tuple(_constraint_from_record(item) for item in node.relations), grounded_component_ids=node.grounded_instance_ids, ) - connectors: list[Connector] = [] - for interface in node.public_connectors: - source = dict(interface.forwarded_from or {}) - component_id = str(source["component_id"]) - connector_id = str(source["connector_id"]) - component = authored.get_component(component_id) - source_connector = component.item.get_connector(connector_id) - source_owner = ( - component.item if isinstance(component.item, Assembly) else None - ) - source_frame = component.placement.compose( - resolve_connector_placement( - source_connector, - owner_assembly=source_owner, - ) - ) - target_frame = Placement(**dict(interface.local_frame)) - offset = inverse_placement(source_frame).compose(target_frame) - connectors.append( - Connector( - interface.connector_id, - name=interface.name, - anchor=ConnectorAnchor( - "forwarded", - source_component_id=component_id, - source_connector_id=connector_id, - offset=offset, - ), - ) - ) - authored = Assembly( - assembly_id=authored.assembly_id, - name=authored.name, - components=authored.components, - connectors=tuple(connectors), - constraints=authored.constraints, - grounded_component_ids=authored.grounded_component_ids, - ) restored = _apply_verified_snapshot(authored, node.solved_snapshot) if restored is None: restored = ( diff --git a/src/simplecadapi/artifacts/references.py b/src/simplecadapi/artifacts/references.py index 84f2a9c8..b19c167a 100644 --- a/src/simplecadapi/artifacts/references.py +++ b/src/simplecadapi/artifacts/references.py @@ -126,7 +126,8 @@ class ConnectorInterface: anchor_kind: str local_frame: Mapping[str, Any] binding: Mapping[str, Any] | None - forwarded_from: Mapping[str, Any] | None + source_component_id: str | None = None + source_connector_id: str | None = None interface_hash: str = "" binding_hash: str = "" @@ -134,7 +135,7 @@ class ConnectorInterface: object.__setattr__(self, "connector_id", validate_logical_id(self.connector_id, "/connector/connector_id")) if self.name is not None and (not isinstance(self.name, str) or not self.name.strip()): raise ArtifactValidationError("name_invalid", "/connector/name", "name must be null or non-empty") - if self.anchor_kind not in {"geometry", "placement", "forwarded"}: + if self.anchor_kind not in {"geometry", "placement", "public"}: raise ArtifactValidationError("connector_invalid", "/connector/anchor_kind", "unsupported anchor kind") try: frame = Placement(**dict(self.local_frame)).to_dict() @@ -145,15 +146,20 @@ class ConnectorInterface: raise ArtifactValidationError("connector_invalid", "/connector/binding", "geometry connector requires binding") if self.anchor_kind != "geometry" and self.binding is not None: raise ArtifactValidationError("connector_invalid", "/connector/binding", "only geometry connector accepts binding") - if self.anchor_kind == "forwarded" and self.forwarded_from is None: - raise ArtifactValidationError("connector_invalid", "/connector/forwarded_from", "forwarded connector requires source") - if self.anchor_kind != "forwarded" and self.forwarded_from is not None: - raise ArtifactValidationError("connector_invalid", "/connector/forwarded_from", "source is only valid for forwarded connector") + if self.anchor_kind == "public": + if self.source_component_id is None or self.source_connector_id is None: + raise ArtifactValidationError("connector_invalid", "/connector/source_component_id", "public connector requires a source") + object.__setattr__(self, "source_component_id", validate_logical_id(self.source_component_id, "/connector/source_component_id")) + object.__setattr__(self, "source_connector_id", validate_logical_id(self.source_connector_id, "/connector/source_connector_id")) + elif self.source_component_id is not None or self.source_connector_id is not None: + raise ArtifactValidationError("connector_invalid", "/connector/source_component_id", "source is only valid for public connectors") interface_payload = { "connector_id": self.connector_id, + "name": self.name, "anchor_kind": self.anchor_kind, "local_frame": frame, - "forwarded_from": dict(self.forwarded_from) if self.forwarded_from is not None else None, + "source_component_id": self.source_component_id, + "source_connector_id": self.source_connector_id, "units": "mm", } binding_payload = dict(self.binding) if self.binding is not None else None @@ -167,31 +173,47 @@ class ConnectorInterface: object.__setattr__(self, "binding_hash", expected_binding) def to_dict(self) -> dict[str, Any]: - return { + payload = { "connector_id": self.connector_id, "name": self.name, "anchor_kind": self.anchor_kind, "local_frame": dict(self.local_frame), "binding": dict(self.binding) if self.binding is not None else None, - "forwarded_from": dict(self.forwarded_from) if self.forwarded_from is not None else None, "interface_hash": self.interface_hash, "binding_hash": self.binding_hash, } + if self.anchor_kind == "public": + payload["source_component_id"] = self.source_component_id + payload["source_connector_id"] = self.source_connector_id + return payload @classmethod def from_dict(cls, data: Mapping[str, Any], path: str = "/connector") -> "ConnectorInterface": - _closed( - data, - {"connector_id", "name", "anchor_kind", "local_frame", "binding", "forwarded_from", "interface_hash", "binding_hash"}, - path, - ) + base = { + "connector_id", "name", "anchor_kind", "local_frame", "binding", + "interface_hash", "binding_hash", + } + actual = set(data) + missing = sorted(base - actual) + if missing: + raise ArtifactValidationError("fields_invalid", path, f"missing={missing}") + extra = actual - base + allowed_source = {"source_component_id", "source_connector_id"} + if extra and extra != allowed_source: + raise ArtifactValidationError("fields_invalid", path, f"unknown={sorted(extra)}") + anchor_kind = str(data["anchor_kind"]) + if anchor_kind == "public" and extra != allowed_source: + raise ArtifactValidationError("fields_invalid", path, "public connector source fields are required") + if anchor_kind != "public" and extra: + raise ArtifactValidationError("fields_invalid", path, "source fields are only valid for public connectors") return cls( connector_id=str(data["connector_id"]), name=data["name"], - anchor_kind=str(data["anchor_kind"]), + anchor_kind=anchor_kind, local_frame=dict(data["local_frame"]), binding=dict(data["binding"]) if data["binding"] is not None else None, - forwarded_from=dict(data["forwarded_from"]) if data["forwarded_from"] is not None else None, + source_component_id=(str(data["source_component_id"]) if "source_component_id" in data else None), + source_connector_id=(str(data["source_connector_id"]) if "source_connector_id" in data else None), interface_hash=str(data["interface_hash"]), binding_hash=str(data["binding_hash"]), ) diff --git a/src/simplecadapi/assembly.py b/src/simplecadapi/assembly.py index 78c6c559..9a90967e 100644 --- a/src/simplecadapi/assembly.py +++ b/src/simplecadapi/assembly.py @@ -6,13 +6,7 @@ from dataclasses import dataclass, field from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union from ._semantic import SemanticValueMixin, _validate_identifier -from .connector import ( - Connector, - ConnectorRef, - _validate_assembly_connector_anchors, - _validate_connectors, - resolve_connector, -) +from .connector import ConnectorRef, resolve_connector, resolve_item_connector from .constraint import Constraint, _validate_constraints from .part import Part from .placement import Placement @@ -28,6 +22,49 @@ def _assembly_authored_runtime(value: SemanticValueMixin) -> Dict[str, Any]: AssemblyItem = Union[Part, "Assembly"] +@dataclass(frozen=True) +class PublicConnectorRef: + """Public alias for an existing connector on a direct child component.""" + + public_connector_id: str + component_id: str + connector_id: str + name: Optional[str] = None + + def __post_init__(self) -> None: + object.__setattr__( + self, + "public_connector_id", + _validate_identifier( + self.public_connector_id, + field_name="public_connector_id", + ), + ) + object.__setattr__( + self, + "component_id", + _validate_identifier(self.component_id, field_name="component_id"), + ) + object.__setattr__( + self, + "connector_id", + _validate_identifier(self.connector_id, field_name="connector_id"), + ) + if self.name is not None: + name = str(self.name).strip() + if not name: + raise ValueError("name must not be empty when provided") + object.__setattr__(self, "name", name) + + def to_dict(self) -> Dict[str, Any]: + return { + "public_connector_id": self.public_connector_id, + "component_id": self.component_id, + "connector_id": self.connector_id, + "name": self.name, + } + + @dataclass(frozen=True) @@ -78,7 +115,7 @@ class Assembly(SemanticValueMixin): assembly_id: str name: Optional[str] = None components: Tuple[Component, ...] = () - connectors: Tuple[Connector, ...] = () + public_connectors: Tuple[PublicConnectorRef, ...] = () constraints: Tuple[Constraint, ...] = () grounded_component_ids: Tuple[str, ...] = () _metadata: Dict[str, Any] = field(default_factory=dict, compare=False, repr=False) @@ -108,11 +145,29 @@ class Assembly(SemanticValueMixin): raise ValueError( "duplicate component_id in assembly: " + ", ".join(duplicates) ) - connectors = _validate_connectors(self.connectors) - object.__setattr__(self, "connectors", connectors) - for connector in connectors: - connector._set_runtime("owner_assembly", self) - _validate_assembly_connector_anchors(self) + public_connectors = tuple(self.public_connectors or ()) + for public in public_connectors: + if not isinstance(public, PublicConnectorRef): + raise TypeError( + "public_connectors must contain PublicConnectorRef values" + ) + public_ids = [public.public_connector_id for public in public_connectors] + duplicates = sorted( + { + public_id + for public_id in public_ids + if public_ids.count(public_id) > 1 + } + ) + if duplicates: + raise ValueError( + "duplicate public_connector_id in assembly: " + + ", ".join(duplicates) + ) + object.__setattr__(self, "public_connectors", public_connectors) + for public in public_connectors: + component = self.get_component(public.component_id) + resolve_item_connector(component.item, public.connector_id) constraints = _validate_constraints(self.constraints) object.__setattr__(self, "constraints", constraints) for constraint in constraints: @@ -154,7 +209,7 @@ class Assembly(SemanticValueMixin): self.assembly_id, name=self.name, components=(*self.components, component), - connectors=self.connectors, + public_connectors=self.public_connectors, constraints=self.constraints, grounded_component_ids=self.grounded_component_ids, _metadata=dict(self._metadata), @@ -188,36 +243,43 @@ class Assembly(SemanticValueMixin): self.assembly_id, name=self.name, components=tuple(components), - connectors=self.connectors, + public_connectors=self.public_connectors, constraints=self.constraints, grounded_component_ids=self.grounded_component_ids, _metadata=dict(self._metadata), _runtime={}, ) - def connector_ids(self) -> Tuple[str, ...]: - return tuple(connector.connector_id for connector in self.connectors) + def public_connector_ids(self) -> Tuple[str, ...]: + return tuple( + public.public_connector_id for public in self.public_connectors + ) - def get_connector(self, connector_id: str) -> Connector: - target = _validate_identifier(connector_id, field_name="connector_id") - for connector in self.connectors: - if connector.connector_id == target: - connector._set_runtime("owner_assembly", self) - return connector - raise KeyError(f"assembly has no connector_id '{target}'") + def get_public_connector(self, public_connector_id: str) -> PublicConnectorRef: + target = _validate_identifier( + public_connector_id, + field_name="public_connector_id", + ) + for public in self.public_connectors: + if public.public_connector_id == target: + return public + raise KeyError(f"assembly has no public_connector_id '{target}'") - def with_connector(self, connector: Connector) -> "Assembly": - if not isinstance(connector, Connector): - raise TypeError("connector must be a Connector") - if connector.connector_id in self.connector_ids(): + def with_public_connector(self, public: PublicConnectorRef) -> "Assembly": + if not isinstance(public, PublicConnectorRef): + raise TypeError("public must be a PublicConnectorRef") + if public.public_connector_id in self.public_connector_ids(): raise ValueError( - f"duplicate connector_id in assembly: {connector.connector_id}" + "duplicate public_connector_id in assembly: " + f"{public.public_connector_id}" ) + component = self.get_component(public.component_id) + resolve_item_connector(component.item, public.connector_id) return Assembly( self.assembly_id, name=self.name, components=self.components, - connectors=(*self.connectors, connector), + public_connectors=(*self.public_connectors, public), constraints=self.constraints, grounded_component_ids=self.grounded_component_ids, _metadata=dict(self._metadata), @@ -246,7 +308,7 @@ class Assembly(SemanticValueMixin): self.assembly_id, name=self.name, components=self.components, - connectors=self.connectors, + public_connectors=self.public_connectors, constraints=(*self.constraints, constraint), grounded_component_ids=self.grounded_component_ids, _metadata=dict(self._metadata), @@ -262,7 +324,7 @@ class Assembly(SemanticValueMixin): self.assembly_id, name=self.name, components=self.components, - connectors=self.connectors, + public_connectors=self.public_connectors, constraints=self.constraints, grounded_component_ids=(*self.grounded_component_ids, target), _metadata=dict(self._metadata), @@ -279,7 +341,7 @@ class Assembly(SemanticValueMixin): self.assembly_id, name=self.name, components=self.components, - connectors=self.connectors, + public_connectors=self.public_connectors, constraints=self.constraints, grounded_component_ids=grounded, _metadata=dict(self._metadata), @@ -291,7 +353,9 @@ class Assembly(SemanticValueMixin): "assembly_id": self.assembly_id, "name": self.name, "components": [component.to_dict() for component in self.components], - "connectors": [connector.to_dict() for connector in self.connectors], + "public_connectors": [ + public.to_dict() for public in self.public_connectors + ], "constraints": [constraint.to_dict() for constraint in self.constraints], "grounded_component_ids": list(self.grounded_component_ids), } @@ -359,7 +423,7 @@ def _with_component_path_placement( assembly.assembly_id, name=assembly.name, components=components, - connectors=assembly.connectors, + public_connectors=assembly.public_connectors, constraints=assembly.constraints, grounded_component_ids=assembly.grounded_component_ids, _metadata=dict(assembly._metadata), @@ -454,7 +518,7 @@ def _restore_component_occurrence_placements( owner.assembly_id, name=owner.name, components=tuple(components), - connectors=owner.connectors, + public_connectors=owner.public_connectors, constraints=owner.constraints, grounded_component_ids=owner.grounded_component_ids, _metadata=dict(owner._metadata), @@ -502,4 +566,4 @@ def _assert_no_assembly_cycle(parent: Assembly, child: Assembly) -> None: _assert_no_assembly_cycle(parent, component.item) -__all__ = ["Assembly", "Component"] +__all__ = ["Assembly", "Component", "PublicConnectorRef"] diff --git a/src/simplecadapi/assembly_solver.py b/src/simplecadapi/assembly_solver.py index 2cb059fd..1c3ed5a5 100644 --- a/src/simplecadapi/assembly_solver.py +++ b/src/simplecadapi/assembly_solver.py @@ -12,11 +12,8 @@ from .assembly import ( _with_component_path_placement, ) from .connector import ( - Connector, - ConnectorAnchor, ConnectorRef, - resolve_connector, - resolve_connector_placement, + resolve_item_connector_placement, ) from .constraint import ( Constraint, @@ -221,14 +218,10 @@ def solve_assembly_constraints(assembly: Assembly, strict: bool = True) -> Assem candidate, constraint.constraint_id, ) - if not residual.within_tolerance: - adjusted = _try_close_forwarded_constraint(candidate, constraint) - if adjusted is not None: - assembly = adjusted - elif strict: - raise ValueError( - f"constraint '{constraint.constraint_id}' residual exceeds tolerance" - ) + if not residual.within_tolerance and strict: + raise ValueError( + f"constraint '{constraint.constraint_id}' residual exceeds tolerance" + ) else: remaining.append(constraint) pending = remaining @@ -384,9 +377,10 @@ def _connector_local_frame_for_ref( assembly: Assembly, connector_ref: ConnectorRef ) -> Placement: component = assembly.get_component(connector_ref.component_id) - connector = resolve_connector(assembly, connector_ref) - owner = component.item if isinstance(component.item, Assembly) else None - return resolve_connector_placement(connector, owner_assembly=owner) + return resolve_item_connector_placement( + component.item, + connector_ref.connector_id, + ) def _connector_world_frame( @@ -396,161 +390,6 @@ def _connector_world_frame( return component.placement.compose( _connector_local_frame_for_ref(assembly, connector_ref) ) - - -@dataclass(frozen=True) -class _ForwardedSolveTarget: - component_path: Tuple[str, ...] - parent_world: Placement - connector_tail: Placement - - -def _forwarded_solve_target( - assembly: Assembly, connector_ref: ConnectorRef -) -> Optional[_ForwardedSolveTarget]: - component = assembly.get_component(connector_ref.component_id) - if not isinstance(component.item, Assembly): - return None - connector = component.item.get_connector(connector_ref.connector_id) - return _descend_forwarded_solve_target( - owner=component.item, - connector=connector, - owner_world=component.placement, - component_path=(component.component_id,), - ) - - -def _descend_forwarded_solve_target( - *, - owner: Assembly, - connector: Connector, - owner_world: Placement, - component_path: Tuple[str, ...], -) -> Optional[_ForwardedSolveTarget]: - anchor = cast(ConnectorAnchor, connector.anchor) - if anchor.anchor_kind != "forwarded": - return None - source_component_id = cast(str, anchor.source_component_id) - source_connector_id = cast(str, anchor.source_connector_id) - source_component = owner.get_component(source_component_id) - source_connector = source_component.item.get_connector(source_connector_id) - source_path = (*component_path, source_component_id) - if ( - isinstance(source_component.item, Assembly) - and source_connector.anchor_kind == "forwarded" - ): - nested = _descend_forwarded_solve_target( - owner=source_component.item, - connector=source_connector, - owner_world=owner_world.compose(source_component.placement), - component_path=source_path, - ) - if nested is None: - return None - tail = nested.connector_tail - if anchor.offset is not None: - tail = tail.compose(anchor.offset) - return _ForwardedSolveTarget( - component_path=nested.component_path, - parent_world=nested.parent_world, - connector_tail=tail, - ) - source_owner = ( - source_component.item if isinstance(source_component.item, Assembly) else None - ) - tail = resolve_connector_placement( - source_connector, - owner_assembly=source_owner, - ) - if anchor.offset is not None: - tail = tail.compose(anchor.offset) - return _ForwardedSolveTarget( - component_path=source_path, - parent_world=owner_world, - connector_tail=tail, - ) - - -def _assemblies_for_component_path( - assembly: Assembly, component_path: Tuple[str, ...] -) -> Tuple[Assembly, ...]: - component = assembly.get_component(component_path[0]) - if not isinstance(component.item, Assembly): - return () - owner = component.item - owners = [owner] - for component_id in component_path[1:-1]: - component = owner.get_component(component_id) - if not isinstance(component.item, Assembly): - return () - owner = component.item - owners.append(owner) - return tuple(owners) - - -def _preserves_satisfied_constraints(before: Assembly, after: Assembly) -> bool: - for constraint in before.constraints: - previous = measure_constraint_residual(before, constraint.constraint_id) - if ( - previous.within_tolerance - and not measure_constraint_residual( - after, constraint.constraint_id - ).within_tolerance - ): - return False - return True - - -def _try_close_forwarded_constraint( - assembly: Assembly, constraint: Constraint -) -> Optional[Assembly]: - motion = _constraint_motion_from_current(assembly, constraint) - for moving_side in ("a", "b"): - moving_ref = ( - constraint.connector_a if moving_side == "a" else constraint.connector_b - ) - target = _forwarded_solve_target(assembly, moving_ref) - if target is None: - continue - owners = _assemblies_for_component_path(assembly, target.component_path) - if not owners: - continue - parent = owners[-1] - if target.component_path[-1] in parent.grounded_component_ids: - continue - if moving_side == "b": - fixed_frame = _connector_world_frame(assembly, constraint.connector_a) - target_frame = fixed_frame.compose(motion) - else: - fixed_frame = _connector_world_frame(assembly, constraint.connector_b) - target_frame = fixed_frame.compose(inverse_placement(motion)) - placement = ( - inverse_placement(target.parent_world) - .compose(target_frame) - .compose(inverse_placement(target.connector_tail)) - ) - candidate = _with_component_path_placement( - assembly, - target.component_path, - placement, - ) - if not measure_constraint_residual( - candidate, constraint.constraint_id - ).within_tolerance: - continue - if not _preserves_satisfied_constraints(assembly, candidate): - continue - updated_owners = _assemblies_for_component_path( - candidate, target.component_path - ) - if not all( - inspect_assembly_constraints(owner).solved for owner in updated_owners - ): - continue - return candidate - return None - - def _constraint_current_scalar(assembly: Assembly, constraint: Constraint) -> float: frame_a = _connector_world_frame(assembly, constraint.connector_a) frame_b = _connector_world_frame(assembly, constraint.connector_b) diff --git a/src/simplecadapi/auto_tools/auto_docs_gen.py b/src/simplecadapi/auto_tools/auto_docs_gen.py index 7514d260..e55b8df5 100644 --- a/src/simplecadapi/auto_tools/auto_docs_gen.py +++ b/src/simplecadapi/auto_tools/auto_docs_gen.py @@ -16,6 +16,13 @@ from typing import Dict, Iterable, List, Sequence DEFAULT_SOURCE_FILENAMES: tuple[str, ...] = ( "operations.py", + "_operators_geometry.py", + "_operators_transform.py", + "_operators_boolean.py", + "_operators_product.py", + "_operators_sketch.py", + "_operators_selection.py", + "_operators_features.py", "evolve.py", "ql.py", "serializer.py", @@ -73,6 +80,13 @@ DEFAULT_STDLIB_SOURCE_FILENAMES: tuple[str, ...] = ( FULL_PUBLIC_FUNCTION_MODULES = frozenset( { "operations.py", + "_operators_geometry.py", + "_operators_transform.py", + "_operators_boolean.py", + "_operators_product.py", + "_operators_sketch.py", + "_operators_selection.py", + "_operators_features.py", "evolve.py", "ql.py", "math.py", diff --git a/src/simplecadapi/auto_tools/make_export.py b/src/simplecadapi/auto_tools/make_export.py index da0537a9..3e629434 100644 --- a/src/simplecadapi/auto_tools/make_export.py +++ b/src/simplecadapi/auto_tools/make_export.py @@ -37,6 +37,15 @@ CORE_EXPORTS = [ ] MODULE_ORDER = ("operations", "evolve", "ql") +OPERATOR_MODULES = ( + "_operators_geometry", + "_operators_transform", + "_operators_boolean", + "_operators_product", + "_operators_sketch", + "_operators_selection", + "_operators_features", +) MODULE_LABELS = { "operations": "Operations", "evolve": "Evolve", @@ -126,6 +135,17 @@ def _module_file(module_name: str, package_root: Path | None = None) -> Path: return root / f"{module_name}.py" +def _operator_function_names(package_root: Path) -> List[str]: + names: List[str] = [] + seen: set[str] = set() + for module_name in OPERATOR_MODULES: + for name in extract_public_functions(_module_file(module_name, package_root)): + if name not in seen: + seen.add(name) + names.append(name) + return names + + def _parse_module(file_path: Path) -> ast.Module | None: if not file_path.exists(): print(f"警告: {file_path} 文件不存在") @@ -171,10 +191,15 @@ def collect_api_inventory( for module_name in MODULE_ORDER: file_path = _module_file(module_name, root) + functions = ( + _operator_function_names(root) + if module_name == "operations" + else extract_public_functions(file_path) + ) inventory[module_name] = ModuleInventory( name=module_name, display_name=MODULE_LABELS[module_name], - functions=extract_public_functions(file_path), + functions=functions, classes=[], ) diff --git a/src/simplecadapi/boolean.py b/src/simplecadapi/boolean.py new file mode 100644 index 00000000..f230a0bf --- /dev/null +++ b/src/simplecadapi/boolean.py @@ -0,0 +1,603 @@ +"""Boolean operators for the SimpleCAD public API.""" + +from __future__ import annotations + +from ._operation_support import * + +def union_rsolid( + *solids: Union[Solid, Sequence[Solid]], + clean: bool = True, + glue: bool = _DEFAULT_UNION_GLUE, + tol: Optional[float] = None, + tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, +) -> Solid: + """Compute the boolean union and return one manifold solid. + + Face-area contact and positive-volume overlap can produce one solid without + artificial embedding. Edge-only, vertex-only, and point/curve tangencies + are non-manifold connections and cannot satisfy the one-Solid contract. + + ``glue`` is an OCC optimization for compatible touching or coincident + topology, not a geometry repair switch. If the optimized pass does not + return one solid, SimpleCAD automatically retries the normal fuse algorithm. + + Args: + solids: One or more Solid objects or sequences of Solid. Nested sequences are + flattened before processing. + clean: Unify same-domain faces and remove splitter edges when possible. + glue: Try OCC glue optimization first, then fall back to normal fuse if + necessary. Defaults to False. + tol: Optional finite non-negative fuzzy-boolean tolerance used by OCC. It + may intentionally bridge a small gap but cannot make a non-manifold + point or edge contact into a valid solid. + tracking_policy: FULL computes topology history and lineage. GRAPH keeps + the replayable operation node without computing a TopoDelta. + + Returns: + Solid: The merged union result. + + Usage: + Accepts standalone `Solid` objects, lists of `Solid`, and nested sequences, + but always returns exactly one `Solid`. If the kernel cannot produce + exactly one solid result, the API raises a clear error instead of + returning multiple pieces. + + Examples: + body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) + rib = make_box_rsolid(2, 4, 4, bottom_face_center=(4, 0, 0)) + merged = union_rsolid(body, rib) + print(merged.get_volume()) + """ + + try: + policy = ( + TrackingPolicy.GRAPH + if current_tracking_policy() == TrackingPolicy.GRAPH + else TrackingPolicy(tracking_policy) + ) + remaining = _flatten_boolean_solids(solids, "union_rsolid") + + if not remaining: + raise ValueError("union_rsolid 至少需要一个Solid输入") + + for solid in remaining: + if solid.wrapped.IsNull(): + raise ValueError("输入实体无效,无法进行并集运算。") + + if len(remaining) == 1 and not clean: + return remaining[0] + + effective_tol = _resolve_union_tol(remaining, tol) + tracked_union_result: Optional[TrackedBooleanResult] = None + if policy == TrackingPolicy.FULL and len(remaining) >= 2: + tracked_union_result = cast( + TrackedBooleanResult, + _evaluate_tracked_union( + remaining, + glue=glue, + tol=effective_tol, + clean=clean, + ), + ) + if tracked_union_result.solid is None: + raise ValueError("union did not produce a valid solid") + fused_solid = tracked_union_result.solid + else: + fused_solid = cast( + Solid, + _require_union_solid( + fuse_shapes( + [solid.wrapped for solid in remaining], + glue=glue, + tol=effective_tol, + clean=clean, + ), + effective_tol, + ), + ) + + all_metadata = {} + for solid in remaining: + all_metadata.update(solid._metadata) + + fused_solid._metadata = all_metadata.copy() + + params: Dict[str, object] = { + "input_count": len(remaining), + "clean": clean, + "glue": glue, + "tol": effective_tol, + "tracking_policy": policy.value, + } + if tracked_union_result is not None: + fused_solid = _finalize_tracked_solid( + fused_solid, + op=_OP_MAKE_UNION_RSOLID, + params=params, + source_solids=remaining, + delta=tracked_union_result.delta, + delta_entries=cast( + Dict[str, Dict[str, object]], + tracked_union_result.delta_entries, + ), + input_shapes=remaining, + ) + elif policy == TrackingPolicy.GRAPH: + fused_solid = cast( + Solid, + _finalize_derived_shape( + fused_solid, + op=_OP_MAKE_UNION_RSOLID, + params=params, + input_shapes=remaining, + ), + ) + else: + _attach_track_summary(fused_solid, op=_OP_MAKE_UNION_RSOLID) + record_operation_if_active( + op=_OP_MAKE_UNION_RSOLID, + params=params, + outputs=fused_solid, + input_shapes=remaining, + context=_current_context_metadata(), + ) + + return fused_solid + except Exception as e: + _wrap_public_api_error( + operation="union_rsolid", + what_happened=( + str(e) + if isinstance(e, ValueError) and str(e).startswith("union produced ") + else "Failed to compute the boolean union." + ), + possible_causes=[ + "One or more inputs are not Solid objects.", + "At least one input solid is null or invalid.", + "The inputs are separated beyond tol, so the kernel cannot produce exactly one solid.", + "The inputs meet only along an edge, vertex, tangent point, or tangent curve, so their union is not one manifold solid.", + ], + how_to_fix=[ + "Pass only valid Solid objects or sequences of Solid objects.", + "For intended face contact, make the solids share a finite-area face and retry; no artificial overlap is required.", + "For a real small gap, pass an explicit tol only when approximating that gap is acceptable.", + "Do not expect glue or tol to turn point-, edge-, or tangent-only contact into a valid single solid.", + ], + error=e, + ) + +def cut_rsolid( + *solids: Union[Solid, Sequence[Solid]], + skip_non_intersecting: bool = True, + tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, +) -> Solid: + """Compute the boolean difference of solids. + + Args: + solids: One or more Solid objects or sequences of Solid. Nested sequences are + flattened before processing; the first solid is the base, the rest are + subtracted in order. + skip_non_intersecting: When True, tools with no meaningful intersection are + ignored for interactive convenience. Graph replay records this flag and + should use False for strict diagnostic workflows. + tracking_policy: FULL computes topology history and lineage. GRAPH keeps + the replayable operation node without computing a TopoDelta. + + Returns: + Solid: The cut result solid. + + Usage: + Accepts a base solid followed by one or more tool solids, including nested + sequences, and returns a single `Solid`. + """ + try: + policy = ( + TrackingPolicy.GRAPH + if current_tracking_policy() == TrackingPolicy.GRAPH + else TrackingPolicy(tracking_policy) + ) + remaining = _flatten_boolean_solids(solids, "cut_rsolid") + + if not remaining: + raise ValueError("cut_rsolid 至少需要一个Solid输入") + + if len(remaining) == 1: + return remaining[0] + + # 从第一个实体开始,依次减去其他实体 + result_solid = remaining[0] + deltas: List[TopoDelta] = [] + merged_delta_entries: Dict[str, Dict[str, object]] = {} + cut_performed = False + + for i in range(1, len(remaining)): + candidate = remaining[i] + + s1 = result_solid.wrapped + s2 = candidate.wrapped + + if s1.IsNull() or s2.IsNull(): + raise ValueError("输入实体无效,无法进行差集运算。") + + # 检查是否有交集 + intersection = common_shapes([s1, s2]) + intersection_solids = solids_of(intersection) + if not intersection_solids: + if skip_non_intersecting: + continue + raise ValueError("差集工具实体与当前实体没有交集。") + intersection_obj = Solid(intersection_solids[0]) + + if intersection_obj.get_volume() < 1e-12: + # 没有有效的交集,跳过此次切割 + if skip_non_intersecting: + continue + raise ValueError("差集工具实体与当前实体交集体积过小。") + + tracked = ( + cast( + TrackedBooleanResult, + tracked_cut(result_solid, candidate), + ) + if policy == TrackingPolicy.FULL and len(remaining) == 2 + else ( + tracked_cut(result_solid, candidate) + if policy == TrackingPolicy.FULL + else None + ) + ) + if tracked is not None: + if tracked.solid is None: + raise ValueError("差集运算失败: OCC 未返回有效实体") + new_result = tracked.solid + else: + new_result = _require_single_boolean_solid( + solids_of(cut_shapes(s1, [s2])), + operation="cut_rsolid", + failure_reason="差集运算失败: OCC 未返回有效实体", + ) + new_result._metadata = result_solid._metadata.copy() + result_solid = new_result + if tracked is not None: + deltas.append(tracked.delta) + merged_delta_entries.update( + cast(Dict[str, Dict[str, object]], tracked.delta_entries) + ) + cut_performed = True + + result_solid._metadata = remaining[0]._metadata.copy() + result_solid._apply_tag("solid.boolean.cut", propagate=False) + + merged_delta = _merge_topo_deltas(deltas) + params: Dict[str, object] = { + "tool_count": len(remaining) - 1, + "skip_non_intersecting": bool(skip_non_intersecting), + "tracking_policy": policy.value, + } + if cut_performed and merged_delta is not None: + result_solid = _finalize_tracked_solid( + result_solid, + op=_OP_MAKE_CUT_RSOLID, + params=params, + source_solids=remaining, + delta=merged_delta, + delta_entries=merged_delta_entries or None, + input_shapes=remaining, + ) + elif policy == TrackingPolicy.GRAPH: + result_solid = cast( + Solid, + _finalize_derived_shape( + result_solid, + op=_OP_MAKE_CUT_RSOLID, + params=params, + input_shapes=remaining, + ), + ) + else: + _attach_track_summary(result_solid, op=_OP_MAKE_CUT_RSOLID) + record_operation_if_active( + op=_OP_MAKE_CUT_RSOLID, + params=params, + outputs=result_solid, + input_shapes=remaining, + context=_current_context_metadata(), + ) + + return result_solid + except Exception as e: + _wrap_public_api_error( + operation="cut_rsolid", + what_happened="Failed to compute the boolean cut.", + possible_causes=[ + "One or more inputs are not Solid objects.", + "The base solid or tool solids are invalid.", + "The kernel could not compute a valid cut result for the current geometry.", + ], + how_to_fix=[ + "Pass a valid base solid followed by valid tool solids.", + "Check whether the tool geometry actually intersects the base solid.", + "If the cut depends on earlier union results, verify those results first.", + ], + error=e, + ) + +def intersect_rsolid(*solids: Union[Solid, Sequence[Solid]]) -> Solid: + """Compute the boolean intersection of solids. + + Args: + solids: One or more Solid objects or sequences of Solid. Nested sequences are + flattened before processing. + + Returns: + Solid: The overlap region as a single solid. + + Usage: + Accepts one or more solids, including nested sequences, and returns a single + `Solid`. If the inputs do not overlap meaningfully, the API raises a clear + error instead of returning an empty list. + """ + try: + remaining = _flatten_boolean_solids(solids, "intersect_rsolid") + + if not remaining: + raise ValueError("intersect_rsolid 至少需要一个Solid输入") + + if len(remaining) == 1: + return remaining[0] + + # 从第一个实体开始,依次与后续实体进行交集运算 + result_solid = remaining[0] + deltas: List[TopoDelta] = [] + merged_delta_entries: Dict[str, Dict[str, object]] = {} + intersect_performed = False + + for i in range(1, len(remaining)): + candidate = remaining[i] + + s1 = result_solid.wrapped + s2 = candidate.wrapped + + if s1.IsNull() or s2.IsNull(): + raise ValueError("输入实体无效,无法进行交集运算。") + + tracked = ( + cast( + TrackedBooleanResult, + tracked_intersect(result_solid, candidate), + ) + if len(remaining) == 2 + else tracked_intersect(result_solid, candidate) + ) + if tracked.solid is None: + raise ValueError("交集结果为空或 OCC 未返回有效实体") + + result_solid = tracked.solid + deltas.append(tracked.delta) + merged_delta_entries.update( + cast(Dict[str, Dict[str, object]], tracked.delta_entries) + ) + intersect_performed = True + + # 检查交集是否为空 + if result_solid.get_volume() < 1e-12: + raise ValueError("交集结果为空或体积过小") + + all_metadata: dict = {} + for solid in remaining: + all_metadata.update(solid._metadata) + + result_solid._metadata = all_metadata + result_solid._apply_tag("solid.boolean.intersect", propagate=False) + + merged_delta = _merge_topo_deltas(deltas) + if intersect_performed and merged_delta is not None: + result_solid = _finalize_tracked_solid( + result_solid, + op=_OP_MAKE_INTERSECT_RSOLID, + params={"input_count": len(remaining)}, + source_solids=remaining, + delta=merged_delta, + delta_entries=merged_delta_entries or None, + input_shapes=remaining, + ) + else: + _attach_track_summary(result_solid, op=_OP_MAKE_INTERSECT_RSOLID) + record_operation_if_active( + op=_OP_MAKE_INTERSECT_RSOLID, + params={"input_count": len(remaining)}, + outputs=result_solid, + input_shapes=remaining, + context=_current_context_metadata(), + ) + + return result_solid + except Exception as e: + _wrap_public_api_error( + operation="intersect_rsolid", + what_happened="Failed to compute the boolean intersection.", + possible_causes=[ + "One or more inputs are not Solid objects.", + "At least one input solid is invalid.", + "The solids do not overlap enough to produce a non-empty single solid.", + "The kernel could not compute a stable overlap region.", + ], + how_to_fix=[ + "Pass only valid Solid objects.", + "Verify that the solids truly overlap in space.", + "Move the solids so they share a meaningful overlap volume before intersecting.", + ], + error=e, + ) + +def _extract_single_face(shape_ocp, operation: str) -> Face: + """Extract exactly one Face from an OCP shape result.""" + result_faces = faces_of_ocp(shape_ocp) + if len(result_faces) != 1: + raise ValueError( + f"{operation} expected exactly 1 face in the result, got {len(result_faces)}" + ) + return Face(result_faces[0]) + +def make_2d_cut_rface(body: Face, tool: Face) -> Face: + """Subtract one 2D face from another (2D boolean difference). + + Parameters + ---------- + body : Face + The face to subtract from. + tool : Face + The face to subtract (the cutter). + + Returns + ------- + Face + The resulting face after subtraction. The result may contain + inner wires (holes) if the tool was fully inside the body. + """ + try: + if not isinstance(body, Face): + raise ValueError("body must be a Face") + if not isinstance(tool, Face): + raise ValueError("tool must be a Face") + + result_shape = cut_shapes(body.wrapped, [tool.wrapped]) + result_face = _extract_single_face(result_shape, "make_2d_cut_rface") + + result_face._metadata = body._metadata.copy() + + return cast( + Face, + _finalize_derived_shape( + result_face, + op=_OP_MAKE_CUT_RFACE, + params={}, + input_shapes=[body, tool], + tags={"derived", "face"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_2d_cut_rface", + what_happened="Failed to subtract one face from another.", + possible_causes=[ + "The body or tool is not a Face.", + "The faces do not overlap or are not coplanar.", + "The kernel could not compute a stable 2D difference.", + ], + how_to_fix=[ + "Pass two valid Face objects.", + "Ensure both faces lie on the same plane.", + "Verify the tool face overlaps the body face.", + ], + error=e, + ) + +def make_2d_union_rface(face_a: Face, face_b: Face) -> Face: + """Compute the boolean union of two 2D faces. + + Parameters + ---------- + face_a : Face + First face. + face_b : Face + Second face. + + Returns + ------- + Face + The merged face. Both inputs must overlap or touch so that the + result is a single connected face. + """ + try: + if not isinstance(face_a, Face): + raise ValueError("face_a must be a Face") + if not isinstance(face_b, Face): + raise ValueError("face_b must be a Face") + + result_shape = fuse_shapes([face_a.wrapped, face_b.wrapped], clean=True) + result_face = _extract_single_face(result_shape, "make_2d_union_rface") + + result_face._metadata = {**face_a._metadata, **face_b._metadata} + + return cast( + Face, + _finalize_derived_shape( + result_face, + op=_OP_MAKE_UNION_RFACE, + params={}, + input_shapes=[face_a, face_b], + tags={"derived", "face"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_2d_union_rface", + what_happened="Failed to union two faces.", + possible_causes=[ + "One or both inputs are not Face objects.", + "The faces do not overlap or touch.", + "The faces are not coplanar.", + ], + how_to_fix=[ + "Pass two valid Face objects.", + "Ensure the faces overlap or share a boundary.", + "Ensure both faces lie on the same plane.", + ], + error=e, + ) + +def make_2d_intersect_rface(face_a: Face, face_b: Face) -> Face: + """Compute the boolean intersection of two 2D faces. + + Parameters + ---------- + face_a : Face + First face. + face_b : Face + Second face. + + Returns + ------- + Face + The overlapping region of the two faces. + """ + try: + if not isinstance(face_a, Face): + raise ValueError("face_a must be a Face") + if not isinstance(face_b, Face): + raise ValueError("face_b must be a Face") + + result_shape = common_shapes([face_a.wrapped, face_b.wrapped]) + result_face = _extract_single_face(result_shape, "make_2d_intersect_rface") + + result_face._metadata = {**face_a._metadata, **face_b._metadata} + + return cast( + Face, + _finalize_derived_shape( + result_face, + op=_OP_MAKE_INTERSECT_RFACE, + params={}, + input_shapes=[face_a, face_b], + tags={"derived", "face"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_2d_intersect_rface", + what_happened="Failed to intersect two faces.", + possible_causes=[ + "One or both inputs are not Face objects.", + "The faces do not overlap.", + "The faces are not coplanar.", + ], + how_to_fix=[ + "Pass two valid Face objects.", + "Ensure the faces have a non-empty overlap region.", + "Ensure both faces lie on the same plane.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/build/assembly_builder.py b/src/simplecadapi/build/assembly_builder.py index 17df1979..0891eb9f 100644 --- a/src/simplecadapi/build/assembly_builder.py +++ b/src/simplecadapi/build/assembly_builder.py @@ -40,7 +40,7 @@ from ..cache.policy import CachePolicy, resolve_cache_policy from ..graph import GraphSession, get_active_session, record_operation_if_active from ..assembly import Assembly, _component_occurrence_placements from ..assembly_solver import inspect_assembly_constraints -from ..connector import resolve_connector_placement +from ..connector import ConnectorRef, resolve_connector_ref_placement from ..part import Part from ..placement import Placement from .assembly_state import ( @@ -138,28 +138,19 @@ def _part_ref(definition: Definition) -> PartRef: def _public_connector_interface( assembly: Assembly, - connector: Any, + public: Any, ) -> ConnectorInterface: - anchor = connector.anchor - if anchor.anchor_kind != "forwarded": - raise ArtifactValidationError( - "connector_invalid", - "/public_connectors", - "assembly connectors must be forwarded", - ) return ConnectorInterface( - connector_id=connector.connector_id, - name=connector.name, - anchor_kind="forwarded", - local_frame=resolve_connector_placement( - connector, - owner_assembly=assembly, + connector_id=public.public_connector_id, + name=public.name, + anchor_kind="public", + local_frame=resolve_connector_ref_placement( + assembly, + ConnectorRef(public.component_id, public.connector_id), ).to_dict(), binding=None, - forwarded_from={ - "component_id": anchor.source_component_id, - "connector_id": anchor.source_connector_id, - }, + source_component_id=public.component_id, + source_connector_id=public.connector_id, ) @@ -309,8 +300,8 @@ def _assembly_definition( connectors = tuple( sorted( ( - _public_connector_interface(assembly, connector) - for connector in assembly.connectors + _public_connector_interface(assembly, public) + for public in assembly.public_connectors ), key=lambda item: item.connector_id.encode("utf-8"), ) diff --git a/src/simplecadapi/build/dependency_graph.py b/src/simplecadapi/build/dependency_graph.py index 67f7fe5b..753c1a03 100644 --- a/src/simplecadapi/build/dependency_graph.py +++ b/src/simplecadapi/build/dependency_graph.py @@ -154,15 +154,13 @@ def build_assembly_dependency_graph(assembly: Assembly) -> AssemblyDependencyGra for relation_id in relation_ids: relation_to_component[relation_id] = component_id - public_sources: dict[str, Endpoint] = {} - for connector in assembly.connectors: - anchor = connector.anchor - if anchor.anchor_kind != "forwarded": - continue - public_sources[connector.connector_id] = ( - str(anchor.source_component_id), - str(anchor.source_connector_id), + public_sources: dict[str, Endpoint] = { + public.public_connector_id: ( + public.component_id, + public.connector_id, ) + for public in assembly.public_connectors + } return AssemblyDependencyGraph( assembly_id=assembly.assembly_id, diff --git a/src/simplecadapi/build/part_builder.py b/src/simplecadapi/build/part_builder.py index 9bee0251..672d8daf 100644 --- a/src/simplecadapi/build/part_builder.py +++ b/src/simplecadapi/build/part_builder.py @@ -174,26 +174,18 @@ def _connector_interface(connector: Connector, body: Solid) -> ConnectorInterfac anchor = cast(Any, connector.anchor) frame = resolve_connector_placement(connector).to_dict() binding: Mapping[str, Any] | None = None - forwarded: Mapping[str, Any] | None = None if anchor.anchor_kind == "geometry": geometry_ref = cast(Any, anchor.geometry_ref) binding = { **geometry_ref.to_dict(), "resolved_entities": [resolve_geometry_entity_ref(body, geometry_ref)], } - elif anchor.anchor_kind == "forwarded": - forwarded = { - "source_component_id": anchor.source_component_id, - "source_connector_id": anchor.source_connector_id, - "offset": anchor.offset.to_dict() if anchor.offset is not None else None, - } return ConnectorInterface( connector_id=connector.connector_id, name=connector.name, anchor_kind=anchor.anchor_kind, local_frame=frame, binding=binding, - forwarded_from=forwarded, ) diff --git a/src/simplecadapi/connector.py b/src/simplecadapi/connector.py index 11a92236..5ff05aa9 100644 --- a/src/simplecadapi/connector.py +++ b/src/simplecadapi/connector.py @@ -60,85 +60,47 @@ class GeometryRef(SemanticValueMixin): class ConnectorAnchor(SemanticValueMixin): """Serializable source for a connector datum frame. - Supported `anchor_kind` values are `geometry`, `placement`, and `forwarded`. + Supported ``anchor_kind`` values are ``geometry`` and ``placement``. + Assembly public exposure is modeled separately by ``PublicConnectorRef``. """ anchor_kind: str geometry_ref: Optional[GeometryRef] = None placement: Optional[Placement] = None - source_component_id: Optional[str] = None - source_connector_id: Optional[str] = None - offset: Optional[Placement] = None _metadata: Dict[str, Any] = field(default_factory=dict, compare=False, repr=False) _runtime: Dict[str, Any] = field(default_factory=dict, compare=False, repr=False) def __post_init__(self) -> None: kind = str(self.anchor_kind).strip().lower() - if kind not in {"geometry", "placement", "forwarded"}: - raise ValueError("anchor_kind must be geometry, placement, or forwarded") + if kind not in {"geometry", "placement"}: + raise ValueError("anchor_kind must be geometry or placement") object.__setattr__(self, "anchor_kind", kind) if kind == "geometry": if not isinstance(self.geometry_ref, GeometryRef): raise TypeError("geometry anchors require geometry_ref") if self.placement is not None: raise ValueError("geometry anchors do not accept placement") - if self.source_component_id is not None or self.source_connector_id is not None: - raise ValueError("geometry anchors do not accept forwarded source ids") - if self.offset is not None: - raise ValueError("geometry anchors do not accept offset") return - if kind == "placement": - if not isinstance(self.placement, Placement): - raise TypeError("placement anchors require placement") - if self.geometry_ref is not None: - raise ValueError("placement anchors do not accept geometry_ref") - if self.source_component_id is not None or self.source_connector_id is not None: - raise ValueError("placement anchors do not accept forwarded source ids") - if self.offset is not None: - raise ValueError("placement anchors do not accept offset") - return - if self.geometry_ref is not None or self.placement is not None: - raise ValueError("forwarded anchors do not accept geometry_ref or placement") - object.__setattr__( - self, - "source_component_id", - _validate_identifier( - self.source_component_id or "", - field_name="source_component_id", - ), - ) - object.__setattr__( - self, - "source_connector_id", - _validate_identifier( - self.source_connector_id or "", - field_name="source_connector_id", - ), - ) - if self.offset is not None and not isinstance(self.offset, Placement): - raise TypeError("offset must be a Placement") + if not isinstance(self.placement, Placement): + raise TypeError("placement anchors require placement") + if self.geometry_ref is not None: + raise ValueError("placement anchors do not accept geometry_ref") def to_dict(self) -> Dict[str, Any]: payload: Dict[str, Any] = {"anchor_kind": self.anchor_kind} if self.anchor_kind == "geometry": payload["geometry_ref"] = cast(GeometryRef, self.geometry_ref).to_dict() - elif self.anchor_kind == "placement": - payload["placement"] = cast(Placement, self.placement).to_dict() else: - payload["source_component_id"] = self.source_component_id - payload["source_connector_id"] = self.source_connector_id - payload["offset"] = self.offset.to_dict() if self.offset is not None else None + payload["placement"] = cast(Placement, self.placement).to_dict() return payload @dataclass(frozen=True) class Connector(SemanticValueMixin): - """Semantic datum frame anchored by geometry, placement, or forwarding. + """Semantic datum frame anchored by geometry or an explicit placement. - Geometry connectors derive placement from a selected BREP sub-shape. - Placement connectors store an explicit local datum frame. Forwarded - connectors expose a component connector as an assembly-level public - interface. + Assembly public interfaces reference existing component connectors instead + of cloning connectors into the Assembly. """ connector_id: str @@ -178,9 +140,8 @@ class Connector(SemanticValueMixin): @property def placement(self) -> Placement: - """Lazily-computed local Placement derived from the connector anchor.""" - owner = self._get_runtime("owner_assembly") - return resolve_connector_placement(self, owner_assembly=owner) + """Return the connector frame in its owning Part coordinate system.""" + return resolve_connector_placement(self) def to_dict(self) -> Dict[str, Any]: payload: Dict[str, Any] = { @@ -232,91 +193,102 @@ def _validate_connectors(connectors: Iterable[Connector]) -> Tuple[Connector, .. raise ValueError("duplicate connector_id: " + ", ".join(duplicates)) return result - def _validate_part_connector_anchors(connectors: Iterable[Connector]) -> None: for connector in connectors: - if connector.anchor_kind == "forwarded": - raise ValueError("forwarded connectors can only be added to assemblies") + if connector.anchor_kind not in {"geometry", "placement"}: + raise ValueError( + "Part connectors must use geometry or placement anchors" + ) -def _validate_assembly_connector_anchors(assembly: Assembly) -> None: - for connector in assembly.connectors: - if connector.anchor_kind != "forwarded": - continue - anchor = cast(ConnectorAnchor, connector.anchor) - try: - source_component = assembly.get_component(cast(str, anchor.source_component_id)) - except KeyError as exc: - raise ValueError( - f"forwarded connector '{connector.connector_id}' references missing " - f"component '{anchor.source_component_id}'" - ) from exc - try: - source_component.item.get_connector(cast(str, anchor.source_connector_id)) - except KeyError as exc: - raise ValueError( - f"forwarded connector '{connector.connector_id}' references missing " - f"connector '{anchor.source_connector_id}' on component " - f"'{anchor.source_component_id}'" - ) from exc - resolve_connector_placement(connector, owner_assembly=assembly) def resolve_connector(assembly: "Assembly", connector_ref: ConnectorRef) -> Connector: component = assembly.get_component(connector_ref.component_id) - return component.item.get_connector(connector_ref.connector_id) + return resolve_item_connector(component.item, connector_ref.connector_id) -def resolve_connector_placement( - connector: Connector, - owner_assembly: Optional[Assembly] = None, - _seen: Optional[set] = None, -) -> Placement: +def resolve_connector_placement(connector: Connector) -> Placement: + """Resolve a real connector in its owning Part coordinate system.""" + if not isinstance(connector, Connector): raise TypeError("connector must be a Connector") anchor = cast(ConnectorAnchor, connector.anchor) if anchor.anchor_kind == "geometry": return _placement_from_geometry_ref(cast(GeometryRef, anchor.geometry_ref)) - if anchor.anchor_kind == "placement": - return cast(Placement, anchor.placement) - if owner_assembly is None: - raise ValueError( - f"forwarded connector '{connector.connector_id}' requires an owner assembly" - ) - seen = set(_seen or set()) - key = (id(owner_assembly), connector.connector_id) - if key in seen: - raise ValueError(f"forwarded connector cycle detected at '{connector.connector_id}'") - seen.add(key) - source_component_id = cast(str, anchor.source_component_id) - source_connector_id = cast(str, anchor.source_connector_id) - try: - source_component = owner_assembly.get_component(source_component_id) - except KeyError as exc: - raise ValueError( - f"forwarded connector '{connector.connector_id}' references missing " - f"component '{source_component_id}'" - ) from exc - try: - source_connector = source_component.item.get_connector(source_connector_id) - except KeyError as exc: - raise ValueError( - f"forwarded connector '{connector.connector_id}' references missing " - f"connector '{source_connector_id}' on component '{source_component_id}'" - ) from exc - from .assembly import Assembly + return cast(Placement, anchor.placement) - source_owner = source_component.item if isinstance(source_component.item, Assembly) else None - source_frame = source_component.placement.compose( - resolve_connector_placement( - source_connector, - owner_assembly=source_owner, + +def resolve_item_connector( + item: Any, + connector_id: str, + *, + _seen: Optional[set[tuple[int, str]]] = None, +) -> Connector: + """Resolve a Part connector through nested Assembly public declarations.""" + + from .assembly import Assembly + from .part import Part + + if isinstance(item, Part): + return item.get_connector(connector_id) + if not isinstance(item, Assembly): + raise TypeError("item must be a Part or Assembly") + seen = set(_seen or set()) + key = (id(item), str(connector_id)) + if key in seen: + raise ValueError(f"public connector cycle detected at {connector_id!r}") + seen.add(key) + public = item.get_public_connector(connector_id) + component = item.get_component(public.component_id) + return resolve_item_connector( + component.item, + public.connector_id, + _seen=seen, + ) + + +def resolve_item_connector_placement( + item: Any, + connector_id: str, + *, + _seen: Optional[set[tuple[int, str]]] = None, +) -> Placement: + """Resolve a connector frame in the coordinate system of ``item``.""" + + from .assembly import Assembly + from .part import Part + + if isinstance(item, Part): + return resolve_connector_placement(item.get_connector(connector_id)) + if not isinstance(item, Assembly): + raise TypeError("item must be a Part or Assembly") + seen = set(_seen or set()) + key = (id(item), str(connector_id)) + if key in seen: + raise ValueError(f"public connector cycle detected at {connector_id!r}") + seen.add(key) + public = item.get_public_connector(connector_id) + component = item.get_component(public.component_id) + return component.placement.compose( + resolve_item_connector_placement( + component.item, + public.connector_id, _seen=seen, ) ) - if anchor.offset is not None: - source_frame = source_frame.compose(anchor.offset) - return source_frame + + +def resolve_connector_ref_placement( + assembly: "Assembly", + connector_ref: ConnectorRef, +) -> Placement: + """Resolve a direct component connector in the Assembly coordinate system.""" + + component = assembly.get_component(connector_ref.component_id) + return component.placement.compose( + resolve_item_connector_placement(component.item, connector_ref.connector_id) + ) def _placement_from_geometry_ref(geo_ref: GeometryRef) -> Placement: diff --git a/src/simplecadapi/contracts/assembly-definition-2.schema.json b/src/simplecadapi/contracts/assembly-definition-2.schema.json index 2fbc0944..31ba92d0 100644 --- a/src/simplecadapi/contracts/assembly-definition-2.schema.json +++ b/src/simplecadapi/contracts/assembly-definition-2.schema.json @@ -40,7 +40,7 @@ "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"]}, "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"}}}, + "connector": {"type": "object", "additionalProperties": false, "required": ["connector_id", "name", "anchor_kind", "local_frame", "binding", "source_component_id", "source_connector_id", "interface_hash", "binding_hash"], "properties": {"connector_id": {"$ref": "#/$defs/id"}, "name": {"type": ["string", "null"], "minLength": 1}, "anchor_kind": {"const": "public"}, "local_frame": {"$ref": "#/$defs/frame"}, "binding": {"type": "null"}, "source_component_id": {"$ref": "#/$defs/id"}, "source_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"}}, "interfaceHashes": {"type": "object", "additionalProperties": false, "required": ["geometry", "connectors", "bindings", "material"], "properties": {"geometry": {"$ref": "#/$defs/hash"}, "connectors": {"$ref": "#/$defs/hashMap"}, "bindings": {"$ref": "#/$defs/hashMap"}, "material": {"type": "null"}}} } diff --git a/src/simplecadapi/contracts/part-definition-2.schema.json b/src/simplecadapi/contracts/part-definition-2.schema.json index 50a0dd19..0e2b0a9a 100644 --- a/src/simplecadapi/contracts/part-definition-2.schema.json +++ b/src/simplecadapi/contracts/part-definition-2.schema.json @@ -91,14 +91,13 @@ "connector": { "type": "object", "additionalProperties": false, - "required": ["connector_id", "name", "anchor_kind", "local_frame", "binding", "forwarded_from", "interface_hash", "binding_hash"], + "required": ["connector_id", "name", "anchor_kind", "local_frame", "binding", "interface_hash", "binding_hash"], "properties": { "connector_id": {"$ref": "#/$defs/id"}, "name": {"type": ["string", "null"], "minLength": 1}, - "anchor_kind": {"enum": ["geometry", "placement", "forwarded"]}, + "anchor_kind": {"enum": ["geometry", "placement"]}, "local_frame": {"$ref": "#/$defs/frame"}, "binding": {"type": ["object", "null"]}, - "forwarded_from": {"type": ["object", "null"]}, "interface_hash": {"$ref": "#/$defs/hash"}, "binding_hash": {"$ref": "#/$defs/hash"} } diff --git a/src/simplecadapi/core.py b/src/simplecadapi/core.py index bcc0dc10..50c30002 100644 --- a/src/simplecadapi/core.py +++ b/src/simplecadapi/core.py @@ -951,7 +951,7 @@ def _record_indexed_topology_selection(source: Any, selected_shapes: Iterable[An if not shapes: return try: - from .operations import _ensure_geo_selection_node_ids + from ._operation_support import _ensure_geo_selection_node_ids _ensure_geo_selection_node_ids(cast(AnyShape, source), cast(List[AnyShape], shapes)) except Exception: diff --git a/src/simplecadapi/evolve.py b/src/simplecadapi/evolve.py index 5badc53b..dc719a5e 100644 --- a/src/simplecadapi/evolve.py +++ b/src/simplecadapi/evolve.py @@ -4,20 +4,20 @@ from . import ql from .core import Solid from .errors import raise_harness_error from .math import fit_cubic_bspline_control_points -from .operations import ( +from ._operators_features import ( chamfer_rsolid, - cut_rsolid, extrude_rsolid, helical_sweep_rsolid, loft_rsolid, +) +from ._operators_geometry import ( make_circle_rface, make_cylinder_rsolid, make_polyline_rwire, make_spline_rwire, - rotate_shape, - translate_shape, - union_rsolid, ) +from ._operators_transform import rotate_shape, translate_shape +from ._operators_boolean import cut_rsolid, union_rsolid def make_n_hole_flange_rsolid( diff --git a/src/simplecadapi/geometry.py b/src/simplecadapi/geometry.py new file mode 100644 index 00000000..d36c3f32 --- /dev/null +++ b/src/simplecadapi/geometry.py @@ -0,0 +1,4394 @@ +"""Geometry operators for the SimpleCAD public API.""" + +from __future__ import annotations + +from ._operation_support import * + +@dataclass(frozen=True) +class SurfaceBoundary: + """One edge constraint used by ``make_surface_patch_rface``.""" + + edge: Edge + continuity: str = "C0" + support: Optional[Face] = None + + def __post_init__(self) -> None: + if not isinstance(self.edge, Edge): + raise TypeError("SurfaceBoundary.edge must be an Edge") + if self.support is not None and not isinstance(self.support, Face): + raise TypeError("SurfaceBoundary.support must be a Face or None") + if str(self.continuity).upper() not in {"C0", "G1", "G2"}: + raise ValueError("SurfaceBoundary.continuity must be C0, G1, or G2") + + def as_dict(self) -> Dict[str, object]: + return { + "continuity": str(self.continuity).upper(), + "has_support": self.support is not None, + } + +@dataclass(frozen=True) +class SurfaceFillingSettings: + """Explicit OCCT filling controls; units are model units and radians.""" + + degree: int = 3 + points_per_curve: int = 15 + iterations: int = 2 + anisotropic: bool = False + tolerance_2d: float = 1e-5 + tolerance_3d: float = 1e-4 + angular_tolerance: float = 0.01 + curvature_tolerance: float = 0.1 + max_degree: int = 8 + max_segments: int = 9 + + def __post_init__(self) -> None: + if self.degree < 1 or self.points_per_curve < 2 or self.iterations < 1: + raise ValueError( + "filling degree, points_per_curve, and iterations must be positive" + ) + if self.max_degree < self.degree or self.max_segments < 1: + raise ValueError( + "max_degree must cover degree and max_segments must be positive" + ) + for name in ( + "tolerance_2d", + "tolerance_3d", + "angular_tolerance", + "curvature_tolerance", + ): + value = float(getattr(self, name)) + if not np.isfinite(value) or value <= 0: + raise ValueError(f"{name} must be a positive finite value") + + def as_dict(self) -> Dict[str, object]: + return cast(Dict[str, object], asdict(self)) + +def _surface_tag_output(shape: AnyShape, tag_prefix: Optional[str]) -> AnyShape: + if tag_prefix is None: + return shape + normalized = normalize_tag(tag_prefix, strict=True) + shape._apply_tag(f"{normalized}.{_shape_kind_token(shape)}", propagate=False) + return shape + +def _surface_point_grid( + points: Sequence[Sequence[Sequence[float]]], +) -> List[List[Tuple[float, float, float]]]: + rows = [ + [tuple(float(component) for component in point) for point in row] + for row in points + ] + if len(rows) < 2 or any(len(row) < 2 for row in rows): + raise ValueError("surface point grids require at least 2 rows and 2 columns") + width = len(rows[0]) + if any(len(row) != width for row in rows): + raise ValueError("surface point grids must be rectangular") + if any(len(point) != 3 for row in rows for point in row): + raise ValueError("surface points must contain exactly three coordinates") + if not all(np.isfinite(value) for row in rows for point in row for value in point): + raise ValueError("surface points must be finite") + return rows + +def _surface_global_point_grid( + points: Sequence[Sequence[Sequence[float]]], +) -> List[List[Tuple[float, float, float]]]: + cs = get_current_cs() + grid = _surface_point_grid(points) + return [ + [ + tuple(float(value) for value in cs.transform_point(np.asarray(point))) + for point in row + ] + for row in grid + ] + +def _surface_global_points( + points: Sequence[Sequence[float]], +) -> List[Tuple[float, float, float]]: + cs = get_current_cs() + result = [] + for point in points: + values = tuple(float(value) for value in point) + if len(values) != 3 or not all(np.isfinite(value) for value in values): + raise ValueError("surface constraint points must be finite 3D points") + result.append( + tuple(float(value) for value in cs.transform_point(np.asarray(values))) + ) + return result + +def _surface_local_point_grid( + points: Sequence[Sequence[Sequence[float]]], +) -> List[List[Tuple[float, float, float]]]: + return _surface_point_grid(points) + +def make_bezier_surface_rface( + control_points: Sequence[Sequence[Sequence[float]]], + weights: Optional[Sequence[Sequence[float]]] = None, + *, + tag_prefix: Optional[str] = None, +) -> Face: + """Create a trimmed Face carrying a tensor-product Bezier surface.""" + try: + local_points = _surface_local_point_grid(control_points) + global_points = _surface_global_point_grid(local_points) + global_weights = ( + None if weights is None else [list(map(float, row)) for row in weights] + ) + if global_weights is not None: + if len(global_weights) != len(local_points) or any( + len(row) != len(local_points[0]) for row in global_weights + ): + raise ValueError("Bezier weights must match the control-point grid") + if any( + weight <= 0 or not np.isfinite(weight) + for row in global_weights + for weight in row + ): + raise ValueError("Bezier weights must be positive finite values") + result = Face(make_bezier_surface(global_points, global_weights)) + result = cast( + Face, + _finalize_primitive_shape( + result, + op="make_bezier_surface_rface", + params={ + "control_points": local_points, + "weights": global_weights, + "tag_prefix": tag_prefix, + }, + tags={"primitive", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_bezier_surface_rface", + what_happened="Failed to create the Bezier surface face.", + possible_causes=[ + "The control-point grid is invalid or degenerate.", + "The kernel rejected the Bezier surface.", + ], + how_to_fix=[ + "Pass a rectangular finite grid with at least two rows and columns.", + "Use positive finite weights with the same dimensions as the grid.", + ], + error=e, + ) + +def make_cylindrical_surface_rface( + radius: ScalarLike, + u_range: Tuple[ScalarLike, ScalarLike], + v_range: Tuple[ScalarLike, ScalarLike], + origin: Tuple[float, float, float] = (0, 0, 0), + axis: Tuple[float, float, float] = (0, 0, 1), + x_direction: Optional[Tuple[float, float, float]] = None, + *, + tolerance: ScalarLike = 1e-7, + tag_prefix: Optional[str] = None, +) -> Face: + """Create a finite cylindrical carrier Face over explicit U/V ranges. + + ``radius``, V values, and ``tolerance`` use model length units. U values + are unitless raw radians, must increase, and may span at most one + revolution. Unit-aware angle expressions are not accepted for U because + the existing expression evaluator returns canonical angles in degrees. + """ + + try: + if expression_uses_units(radius) and infer_dimension(radius) != LENGTH: + raise ValueError("radius must use model length units") + if any( + expression_uses_units(value) and infer_dimension(value) != DIMENSIONLESS + for value in u_range + ): + raise ValueError( + "u_range must use unitless raw radians; unit-aware angle values " + "evaluate in degrees" + ) + if any( + expression_uses_units(value) and infer_dimension(value) != LENGTH + for value in v_range + ): + raise ValueError("v_range must use model length units") + if expression_uses_units(tolerance) and infer_dimension(tolerance) != LENGTH: + raise ValueError("tolerance must use model length units") + radius_value = evaluate_scalar(radius) + u_values = tuple(evaluate_scalar(value) for value in u_range) + v_values = tuple(evaluate_scalar(value) for value in v_range) + tolerance_value = float(evaluate_scalar(tolerance)) + if not np.isfinite(radius_value) or radius_value <= 0.0: + raise ValueError("radius must be a positive finite value") + if len(u_values) != 2 or not all(np.isfinite(value) for value in u_values): + raise ValueError("u_range must contain two finite values") + if len(v_values) != 2 or not all(np.isfinite(value) for value in v_values): + raise ValueError("v_range must contain two finite values") + u_span = u_values[1] - u_values[0] + v_span = v_values[1] - v_values[0] + if ( + u_span <= Precision.PConfusion_s() + or u_span > 2.0 * math.pi + Precision.Angular_s() + ): + raise ValueError( + "u_range must be increasing and span at most one revolution" + ) + if v_span <= Precision.Confusion_s(): + raise ValueError("v_range must be increasing beyond kernel confusion") + if not np.isfinite(tolerance_value) or tolerance_value <= 0.0: + raise ValueError("tolerance must be a positive finite value") + + origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + x_value = ( + tuple(float(value) for value in _default_plane_x_direction(axis_value)) + if x_direction is None + else cast(Tuple[float, float, float], evaluate_value(x_direction)) + ) + vectors = [ + tuple(float(value) for value in item) + for item in (origin_value, axis_value, x_value) + ] + if any( + len(item) != 3 or not all(np.isfinite(value) for value in item) + for item in vectors + ): + raise ValueError("origin, axis, and x_direction must be finite 3D values") + axis_norm = float(np.linalg.norm(vectors[1])) + x_norm = float(np.linalg.norm(vectors[2])) + if axis_norm <= 1e-12 or x_norm <= 1e-12: + raise ValueError("axis and x_direction must be non-zero") + parallel = abs(float(np.dot(vectors[1], vectors[2])) / (axis_norm * x_norm)) + if parallel >= 1.0 - 1e-12: + raise ValueError("axis and x_direction must not be parallel") + + cs = get_current_cs() + global_origin = cs.transform_point(np.asarray(vectors[0], dtype=float)) + global_axis = cs.transform_vector(np.asarray(vectors[1], dtype=float)) + global_x_direction = cs.transform_vector(np.asarray(vectors[2], dtype=float)) + result = cast( + Face, + _finalize_primitive_shape( + Face( + make_cylindrical_surface( + radius_value, + cast(Tuple[float, float], u_values), + cast(Tuple[float, float], v_values), + origin=global_origin, + axis=global_axis, + x_direction=global_x_direction, + tolerance=tolerance_value, + ) + ), + op="make_cylindrical_surface_rface", + params={ + "radius": radius, + "u_range": u_range, + "v_range": v_range, + "origin": origin, + "axis": axis, + "x_direction": x_direction, + "tolerance": tolerance, + "tag_prefix": tag_prefix, + }, + tags={"primitive", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_cylindrical_surface_rface", + what_happened="Failed to create the cylindrical surface face.", + possible_causes=[ + "The radius, U/V ranges, or tolerance is invalid.", + "The axis frame is degenerate or parallel.", + "The kernel rejected the bounded cylindrical surface.", + ], + how_to_fix=[ + "Use model length units for radius, V, and tolerance.", + "Pass increasing finite U bounds as unitless raw radians.", + "Keep the U span at or below one revolution and provide non-parallel axis directions.", + ], + error=e, + ) + +def fit_point_grid_rface( + points: Sequence[Sequence[Sequence[float]]], + *, + tolerance: float = 1e-3, + degree_min: int = 3, + degree_max: int = 8, + smoothing: Optional[Tuple[float, float, float]] = None, + tag_prefix: Optional[str] = None, +) -> Face: + """Fit a B-spline Face through a rectangular 3D point grid.""" + try: + tolerance_value = float(tolerance) + if not np.isfinite(tolerance_value) or tolerance_value <= 0: + raise ValueError("tolerance must be a positive finite value") + degree_min_value, degree_max_value = int(degree_min), int(degree_max) + if degree_min_value < 1 or degree_max_value < degree_min_value: + raise ValueError("degree_max must be greater than or equal to degree_min") + smoothing_values = ( + None if smoothing is None else tuple(float(v) for v in smoothing) + ) + if smoothing_values is not None and ( + len(smoothing_values) != 3 + or any(not np.isfinite(v) or v < 0 for v in smoothing_values) + ): + raise ValueError("smoothing must contain three finite non-negative weights") + local_points = _surface_local_point_grid(points) + global_points = _surface_global_point_grid(local_points) + result = Face( + fit_point_grid_surface( + global_points, + tolerance=tolerance_value, + degree_min=degree_min_value, + degree_max=degree_max_value, + smoothing=smoothing_values, + ) + ) + result = cast( + Face, + _finalize_primitive_shape( + result, + op="fit_point_grid_rface", + params={ + "points": local_points, + "tolerance": tolerance_value, + "degree_min": degree_min_value, + "degree_max": degree_max_value, + "smoothing": smoothing_values, + "tag_prefix": tag_prefix, + }, + tags={"primitive", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="fit_point_grid_rface", + what_happened="Failed to fit a B-spline surface face.", + possible_causes=[ + "The point grid or fitting controls are invalid.", + "The kernel fitting algorithm did not converge.", + ], + how_to_fix=[ + "Pass a rectangular finite point grid and positive tolerance.", + "Keep degree_min <= degree_max and use non-negative smoothing weights.", + ], + error=e, + ) + +def make_ruled_surface_rface( + edge_a: Edge, edge_b: Edge, *, tag_prefix: Optional[str] = None +) -> Face: + """Create a ruled Face spanning two compatible edges.""" + try: + if not isinstance(edge_a, Edge) or not isinstance(edge_b, Edge): + raise TypeError("make_ruled_surface_rface requires two Edge objects") + result = cast( + Face, + _finalize_derived_shape( + Face(make_ruled_face(edge_a.wrapped, edge_b.wrapped)), + op="make_ruled_surface_rface", + params={"tag_prefix": tag_prefix}, + input_shapes=[edge_a, edge_b], + tags={"derived", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_ruled_surface_rface", + what_happened="Failed to create the ruled surface face.", + possible_causes=[ + "The inputs are not edges.", + "The two edges cannot define a ruled surface.", + ], + how_to_fix=[ + "Pass two valid Edge objects with compatible parameterization." + ], + error=e, + ) + +def make_gordon_surface_rface( + profiles: Sequence[Edge], + guides: Sequence[Edge], + *, + tolerance: float = 1e-3, + tag_prefix: Optional[str] = None, +) -> Face: + """Create a Gordon Face from intersecting profile and guide edge networks.""" + try: + profile_list, guide_list = list(profiles), list(guides) + if len(profile_list) < 2 or len(guide_list) < 2: + raise ValueError( + "Gordon surfaces require at least two profiles and two guides" + ) + if not all(isinstance(edge, Edge) for edge in [*profile_list, *guide_list]): + raise TypeError("Gordon profiles and guides must contain only Edge objects") + if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: + raise ValueError("tolerance must be a positive finite value") + result = cast( + Face, + _finalize_derived_shape( + Face( + make_gordon_surface( + [edge.wrapped for edge in profile_list], + [edge.wrapped for edge in guide_list], + tolerance=float(tolerance), + ) + ), + op="make_gordon_surface_rface", + params={ + "profile_count": len(profile_list), + "guide_count": len(guide_list), + "tolerance": float(tolerance), + "tag_prefix": tag_prefix, + }, + input_shapes=[*profile_list, *guide_list], + tags={"derived", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_gordon_surface_rface", + what_happened="Failed to create the Gordon surface face.", + possible_causes=[ + "The curve network is too small, non-intersecting, or inconsistent.", + "The kernel Gordon interpolation failed.", + ], + how_to_fix=[ + "Pass at least two profiles and two guides whose endpoints form a compatible network.", + "Increase tolerance only when the source curves are numerically noisy.", + ], + error=e, + ) + +def make_surface_patch_rface( + boundaries: Sequence[SurfaceBoundary], + *, + points: Sequence[Sequence[float]] = (), + settings: Optional[SurfaceFillingSettings] = None, + holes: Sequence[Wire] = (), + tag_prefix: Optional[str] = None, +) -> Face: + """Fill a constrained boundary network into one Face, optionally with holes.""" + try: + boundary_list = list(boundaries) + if not boundary_list or not all( + isinstance(item, SurfaceBoundary) for item in boundary_list + ): + raise ValueError("boundaries must be a non-empty SurfaceBoundary sequence") + settings_value = settings or SurfaceFillingSettings() + if not isinstance(settings_value, SurfaceFillingSettings): + raise TypeError("settings must be SurfaceFillingSettings") + hole_list = list(holes) + if not all(isinstance(wire, Wire) for wire in hole_list): + raise TypeError("holes must contain only Wire objects") + support_shapes = [ + item.support for item in boundary_list if item.support is not None + ] + interleaved_inputs: List[AnyShape] = [] + for item in boundary_list: + interleaved_inputs.append(item.edge) + if item.support is not None: + interleaved_inputs.append(item.support) + input_shapes: List[AnyShape] = [*interleaved_inputs, *hole_list] + local_points = [tuple(float(v) for v in point) for point in points] + global_points = _surface_global_points(local_points) + result = cast( + Face, + _finalize_derived_shape( + Face( + make_filling_face( + [ + ( + item.edge.wrapped, + item.support.wrapped if item.support else None, + str(item.continuity).upper(), + ) + for item in boundary_list + ], + global_points, + settings=settings_value.as_dict(), + holes=[wire.wrapped for wire in hole_list], + ) + ), + op="make_surface_patch_rface", + params={ + "boundary_count": len(boundary_list), + "support_count": len(support_shapes), + "hole_count": len(hole_list), + "boundaries": [item.as_dict() for item in boundary_list], + "points": local_points, + "settings": settings_value.as_dict(), + "tag_prefix": tag_prefix, + }, + input_shapes=input_shapes, + tags={"derived", "surface", "face"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_surface_patch_rface", + what_happened="Failed to fill the constrained surface patch.", + possible_causes=[ + "A boundary is invalid, open, or incompatible with its support face.", + "The filling controls are invalid or the kernel did not converge.", + ], + how_to_fix=[ + "Pass non-empty SurfaceBoundary values with valid Edge objects.", + "Use C0/G1/G2 continuity and explicit positive filling tolerances.", + ], + error=e, + ) + +def _validated_loft_sections( + sections: Sequence[Union[Wire, Vertex]], *, operation: str +) -> List[Union[Wire, Vertex]]: + section_list = list(sections) + if len(section_list) < 2: + raise ValueError(f"{operation} requires at least two sections") + if not all(isinstance(section, (Wire, Vertex)) for section in section_list): + raise TypeError( + f"{operation} sections must contain only Wire or Vertex objects" + ) + if not any(isinstance(section, Wire) for section in section_list): + raise ValueError(f"{operation} requires at least one Wire section") + if any(isinstance(section, Vertex) for section in section_list[1:-1]): + raise ValueError(f"{operation} allows Vertex sections only at the start or end") + return section_list + +def _pending_loft_role(shape: AnyShape, role: str, method: str) -> TopoRoleEntry: + return TopoRoleEntry( + ref=TopoRef( + "pending", + "pending", + 0, + { + "wire": TopoKind.WIRE, + "face": TopoKind.FACE, + }[_shape_kind_token(shape)], + _topo_id(shape.wrapped), + ), + role=role, + metadata={ + "coverage": "complete", + "status": "proven", + "evidence_kind": "kernel_operation_role", + "evidence_method": method, + }, + ) + +def _matching_shell_boundary(shell: Shell, profile: Wire) -> Wire: + profile_edges = list(profile.get_edges()) + matches = [ + boundary + for boundary in shell.get_wires() + if len(boundary.get_edges()) == len(profile_edges) + and all( + any( + edge.wrapped.IsSame(profile_edge.wrapped) + for edge in boundary.get_edges() + ) + for profile_edge in profile_edges + ) + ] + if len(matches) != 1: + raise ValueError( + f"loft endpoint profile must match exactly one result boundary, got {len(matches)}" + ) + return matches[0] + +def _apply_loft_role_metadata( + shape: AnyShape, delta: TopoDelta, *, op: str +) -> AnyShape: + candidates: Dict[Tuple[TopoKind, str], AnyShape] = {} + for kind, members in ( + (TopoKind.FACE, shape.get_faces() if hasattr(shape, "get_faces") else []), + (TopoKind.WIRE, shape.get_wires() if hasattr(shape, "get_wires") else []), + ): + for member in members: + candidates[(kind, _topo_id(member.wrapped))] = member + for entry in delta.roles: + member = candidates.get((entry.ref.kind, entry.ref.topo_id)) + if member is None: + continue + track = dict(member.get_metadata("track", {})) + roles = sorted({*track.get("result_roles", ()), entry.role}) + track.update( + { + "op": op, + "topo_id": entry.ref.topo_id, + "kind": entry.ref.kind.name, + "coverage": "complete", + "status": "proven", + "result_roles": roles, + } + ) + member.set_metadata("track", track) + return shape + +def _apply_shell_loft_tag_prefix( + shell: Shell, *, tag_prefix: Optional[str], has_start: bool, has_end: bool +) -> Shell: + if tag_prefix is None: + return shell + prefix = normalize_tag(tag_prefix, strict=True) + result: AnyShape = _apply_topology_identity_tag( + shell, + ShapeSelector("shell").exactly(1), + f"{prefix}.shell", + kind="shell", + local_name="shell", + authoring_source="simplecadapi.loft_rshell.tag_prefix", + ) + for present, role, local_name in ( + (has_start, "loft.start_wire", "start"), + (has_end, "loft.end_wire", "end"), + ): + if not present: + continue + result = _apply_topology_identity_tag( + cast(Shell, result), + ShapeSelector("wire").where(output_role(role)).exactly(1), + f"{prefix}.wire.{local_name}", + kind="wire", + local_name=local_name, + authoring_source="simplecadapi.loft_rshell.tag_prefix", + ) + result = _apply_topology_identity_tag( + cast(Shell, result), + ShapeSelector("face").where(output_role("loft.side")).at_least(1), + f"{prefix}.face.side", + kind="face", + local_name="side", + authoring_source="simplecadapi.loft_rshell.tag_prefix", + ) + return cast(Shell, result) + +def trim_surface_rface( + carrier: Face, + outer: Wire, + holes: Sequence[Wire] = (), + *, + tolerance: float = 1e-7, + tag_prefix: Optional[str] = None, +) -> Face: + """Trim a carrier Face to exactly one connected Face. + + Existing carrier bounds and holes are preserved by intersecting them with + the requested closed, simple outer loop and optional closed, simple holes. + Empty or disconnected intersections are rejected. Every trim curve must + lie on the carrier within ``tolerance``. Periodic carriers do not support + holes; their outer loop must fit within one seam period without crossing + the seam. + """ + + try: + if not isinstance(carrier, Face): + raise TypeError("carrier must be a Face") + if not isinstance(outer, Wire): + raise TypeError("outer must be a Wire") + hole_list = list(holes) + if not all(isinstance(wire, Wire) for wire in hole_list): + raise TypeError("holes must contain only Wire objects") + tolerance_value = float(tolerance) + if not np.isfinite(tolerance_value) or tolerance_value <= 0.0: + raise ValueError("tolerance must be a positive finite value") + result = Face( + trim_surface_face( + carrier.wrapped, + outer.wrapped, + [wire.wrapped for wire in hole_list], + tolerance=tolerance_value, + ) + ) + for source in (carrier, outer, *hole_list): + _attach_lineage_from_source( + source, + result, + derivation="fragment", + op="trim_surface_rface", + coverage="partial", + ) + result = cast( + Face, + _finalize_derived_shape( + result, + op="trim_surface_rface", + params={ + "hole_count": len(hole_list), + "tolerance": tolerance_value, + "tag_prefix": tag_prefix, + }, + input_shapes=[carrier, outer, *hole_list], + tags={"derived", "surface", "face", "trimmed"}, + ), + ) + return cast(Face, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="trim_surface_rface", + what_happened="Failed to trim the carrier surface face.", + possible_causes=[ + "A trim wire is open, invalid, or does not lie on the carrier.", + "A periodic trim crosses the carrier seam.", + "A hole intersects the outer boundary or another hole.", + "The bounded intersection is empty or has multiple connected regions.", + ], + how_to_fix=[ + "Pass one closed, simple outer Wire and optional closed, simple hole Wires.", + "Keep every trim curve on the carrier within tolerance and inside one periodic seam.", + "Choose boundaries whose carrier intersection is exactly one connected Face.", + ], + error=e, + ) + +def loft_rshell( + sections: Sequence[Union[Wire, Vertex]], + *, + ruled: bool = False, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_wire_tag: Optional[str] = None, + end_wire_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Shell: + """Create an open loft Shell with endpoint-Wire and side-Face naming.""" + try: + section_list = _validated_loft_sections(sections, operation="loft_rshell") + start_is_wire = isinstance(section_list[0], Wire) + end_is_wire = isinstance(section_list[-1], Wire) + if start_wire_tag is not None and not start_is_wire: + raise ValueError("start_wire_tag requires a Wire start section") + if end_wire_tag is not None and not end_is_wire: + raise ValueError("end_wire_tag requires a Wire end section") + assignments = _normalize_operation_role_tags( + "make_loft_rshell", + ( + ("loft.start_wire", start_wire_tag), + ("loft.end_wire", end_wire_tag), + ("loft.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + result = Shell( + make_loft_shell( + [section.wrapped for section in section_list], ruled=bool(ruled) + ) + ) + roles = [ + _pending_loft_role(face, "loft.side", "ResultSideFace") + for face in result.get_faces() + ] + if start_is_wire: + roles.append( + _pending_loft_role( + _matching_shell_boundary(result, cast(Wire, section_list[0])), + "loft.start_wire", + "EndpointBoundary", + ) + ) + if end_is_wire: + roles.append( + _pending_loft_role( + _matching_shell_boundary(result, cast(Wire, section_list[-1])), + "loft.end_wire", + "EndpointBoundary", + ) + ) + delta = TopoDelta(roles=tuple(roles)) + _apply_loft_role_metadata(result, delta, op="make_loft_rshell") + finalized = cast( + Shell, + _finalize_derived_shape( + result, + op="make_loft_rshell", + params={ + "section_count": len(section_list), + "ruled": bool(ruled), + "tag_prefix": tag_prefix, + }, + input_shapes=section_list, + tags={"derived", "surface", "shell"}, + topo_delta=delta, + ), + ) + target_kinds = _validate_operation_output_roles(delta, assignments) + tagged = cast( + Shell, + _apply_operation_role_tags( + finalized, + op="make_loft_rshell", + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ), + ) + return _apply_shell_loft_tag_prefix( + tagged, + tag_prefix=tag_prefix, + has_start=start_is_wire, + has_end=end_is_wire, + ) + except Exception as e: + _wrap_public_api_error( + operation="loft_rshell", + what_happened="Failed to create the surface loft shell.", + possible_causes=[ + "Sections are incompatible or a Vertex was used away from an endpoint.", + "The kernel loft algorithm failed.", + ], + how_to_fix=[ + "Pass at least two Wire or endpoint Vertex sections in loft order." + ], + error=e, + ) + +def sew_faces_rshell( + faces: Sequence[Face], *, tolerance: float = 1e-6, tag_prefix: Optional[str] = None +) -> Shell: + """Sew faces into exactly one connected Shell.""" + try: + face_list = list(faces) + if not face_list or not all(isinstance(face, Face) for face in face_list): + raise ValueError("sew_faces_rshell requires a non-empty Face sequence") + if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: + raise ValueError("tolerance must be a positive finite value") + sewn, result_face_indices = sew_faces_with_history_ocp( + [face.wrapped for face in face_list], tolerance=float(tolerance) + ) + result = cast( + Shell, + _finalize_derived_shape( + Shell(sewn), + op="sew_faces_rshell", + params={ + "face_count": len(face_list), + "tolerance": float(tolerance), + "tag_prefix": tag_prefix, + }, + input_shapes=face_list, + tags={"derived", "surface", "shell"}, + ), + ) + _carry_face_provenance( + result, face_list, result_face_indices=result_face_indices + ) + return cast(Shell, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="sew_faces_rshell", + what_happened="Failed to sew faces into one shell.", + possible_causes=[ + "Faces are disconnected or their gaps exceed tolerance.", + "The sewing result contains multiple shell components.", + ], + how_to_fix=["Pass connected Face objects and a positive sewing tolerance."], + error=e, + ) + +def make_solid_from_shell_rsolid( + shell: Shell, *, tag_prefix: Optional[str] = None +) -> Solid: + """Create an oriented Solid from one valid closed Shell.""" + + try: + if not isinstance(shell, Shell): + raise TypeError("make_solid_from_shell_rsolid requires a Shell") + solid = Solid(solid_from_shell(shell.wrapped)) + source_entities = shell._topology_cache.entities() + for target_entity in solid._topology_cache.entities(): + matches = [ + source_entity + for source_entity in source_entities + if source_entity.kind == target_entity.kind + and _same_semantic_topology( + source_entity.kind, + source_entity.representative, + target_entity.representative, + ) + ] + if len(matches) == 1 and matches[0].wrappers and target_entity.wrappers: + target_entity.wrappers[0]._copy_semantic_state_from( + matches[0].wrappers[0] + ) + _attach_lineage_from_source( + shell, + solid, + derivation="continuation", + op="make_solid_from_shell_rsolid", + coverage="partial", + ) + result = cast( + Solid, + _finalize_derived_shape( + solid, + op="make_solid_from_shell_rsolid", + params={"tag_prefix": tag_prefix}, + input_shapes=[shell], + tags={"derived", "surface", "solid"}, + ), + ) + _carry_face_provenance( + result, + shell.get_faces(), + allow_orientation_change=True, + replace_local_bindings=False, + ) + return cast(Solid, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="make_solid_from_shell_rsolid", + what_happened="Failed to create a solid from the shell.", + possible_causes=[ + "The input is not a Shell.", + "The shell is open, invalid, or cannot be oriented as one material boundary.", + ], + how_to_fix=[ + "Sew a valid closed shell before converting it to a solid.", + "Inspect free boundaries and face orientation when conversion fails.", + ], + error=e, + ) + +def free_boundaries_rwirelist(shell: Shell, *, tolerance: float = 1e-6) -> List[Wire]: + """Return unique closed and open free boundary wires of a Shell.""" + try: + if not isinstance(shell, Shell): + raise TypeError("free_boundaries_rwirelist requires a Shell") + if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: + raise ValueError("tolerance must be a positive finite value") + result = [ + Wire(wire) + for wire in free_boundaries_ocp(shell.wrapped, tolerance=float(tolerance)) + ] + record_operation_if_active( + op="free_boundaries_rwirelist", + params={"tolerance": float(tolerance)}, + outputs=result, + input_shapes=[shell], + semantic_delta=_semantic_delta_for_output( + "free_boundaries_rwirelist", + output_count=len(result), + entity_type="Profile", + ), + context=_current_context_metadata(), + ) + return result + except Exception as e: + _wrap_public_api_error( + operation="free_boundaries_rwirelist", + what_happened="Failed to extract free boundary wires.", + possible_causes=[ + "The input is not a valid Shell.", + "The boundary analysis tolerance is invalid.", + ], + how_to_fix=["Pass a Shell and a positive finite tolerance."], + error=e, + ) + +def fill_holes_rshell( + shell: Shell, + hole_indices: Optional[Sequence[int]] = None, + *, + tolerance: float = 1e-6, + settings: Optional[SurfaceFillingSettings] = None, + tag_prefix: Optional[str] = None, +) -> Shell: + """Fill selected closed free boundaries and return a sewn Shell.""" + try: + if not isinstance(shell, Shell): + raise TypeError("fill_holes_rshell requires a Shell") + if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: + raise ValueError("tolerance must be a positive finite value") + settings_value = settings or SurfaceFillingSettings() + if not isinstance(settings_value, SurfaceFillingSettings): + raise TypeError("settings must be SurfaceFillingSettings") + indices = ( + None if hole_indices is None else [int(index) for index in hole_indices] + ) + result = cast( + Shell, + _finalize_derived_shape( + Shell( + fill_shell_holes_ocp( + shell.wrapped, + hole_indices=indices, + tolerance=float(tolerance), + settings=settings_value.as_dict(), + ) + ), + op="fill_holes_rshell", + params={ + "hole_indices": indices, + "tolerance": float(tolerance), + "settings": settings_value.as_dict(), + "tag_prefix": tag_prefix, + }, + input_shapes=[shell], + tags={"derived", "surface", "shell"}, + ), + ) + return cast(Shell, _surface_tag_output(result, tag_prefix)) + except Exception as e: + _wrap_public_api_error( + operation="fill_holes_rshell", + what_happened="Failed to fill selected shell holes.", + possible_causes=[ + "A selected boundary is not a closed hole or the index is out of range.", + "The filling or sewing operation failed.", + ], + how_to_fix=[ + "Use free_boundaries_rwirelist() to inspect valid boundary indices before filling." + ], + error=e, + ) + +def make_point_rvertex(x: ScalarLike, y: ScalarLike, z: ScalarLike) -> Vertex: + """Create a point in 3D space and return it as a vertex.""" + try: + cs = get_current_cs() + point_value = cast(Tuple[float, float, float], evaluate_value((x, y, z))) + global_point = cs.transform_point(np.array(point_value)) + vertex_shape = BRepBuilderAPI_MakeVertex( + gp_Pnt( + float(global_point[0]), float(global_point[1]), float(global_point[2]) + ) + ).Vertex() + return cast( + Vertex, + _finalize_primitive_shape( + Vertex(vertex_shape), + op=_OP_MAKE_POINT_RVERTEX, + params={"x": x, "y": y, "z": z}, + tags={"primitive", "vertex"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_point_rvertex", + what_happened="Failed to create a point vertex.", + possible_causes=[ + "One or more coordinate values are not valid finite scalars.", + "The current coordinate system rejected the transformed point.", + ], + how_to_fix=[ + "Pass numeric x, y, and z values or valid scalar expressions.", + "Inspect the coordinate values and the active workplane before retrying.", + ], + error=e, + ) + +def make_line_redge( + start: Tuple[ScalarLike, ScalarLike, ScalarLike], + end: Tuple[ScalarLike, ScalarLike, ScalarLike], + *, + tag_prefix: Optional[str] = None, +) -> Edge: + """Create a straight edge between two points.""" + try: + cs = get_current_cs() + start_value = cast(Tuple[float, float, float], evaluate_value(start)) + end_value = cast(Tuple[float, float, float], evaluate_value(end)) + start_global = cs.transform_point(np.array(start_value)) + end_global = cs.transform_point(np.array(end_value)) + + edge_shape = make_line_edge(start_global, end_global) + edge = cast( + Edge, + _finalize_primitive_shape( + Edge(edge_shape), + op=_OP_MAKE_LINE_REDGE, + params={"start": start, "end": end}, + tags={"primitive", "edge"}, + ), + ) + return cast( + Edge, + _apply_shape_tag_prefix( + edge, + tag_prefix, + kind="edge", + authoring_source="simplecadapi.make_line_redge.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_line_redge", + what_happened="Failed to create a line edge.", + possible_causes=[ + "The start or end point is not a valid finite 3D point.", + "The transformed points are degenerate or rejected by the kernel.", + ], + how_to_fix=[ + "Pass start and end as 3-element numeric tuples or valid expressions.", + "Ensure the two points are distinct and finite.", + ], + error=e, + ) + +def make_segment_redge( + start: Tuple[float, float, float], end: Tuple[float, float, float] +) -> Edge: + """Alias of `make_line_redge` that returns a straight edge.""" + return make_line_redge(start, end) + +def make_segment_rwire( + start: Tuple[float, float, float], end: Tuple[float, float, float] +) -> Wire: + """Create a wire containing a single straight segment.""" + try: + if get_active_session() is not None: + edge = make_line_redge(start, end) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_line_redge(start, end) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_segment_wire", + params={"start": start, "end": end}, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_segment_rwire", + what_happened="Failed to create a single-segment wire.", + possible_causes=[ + "The segment endpoints are invalid.", + "The kernel could not assemble the segment into a wire.", + ], + how_to_fix=[ + "Pass two valid 3D endpoints.", + "If the segment is computed dynamically, log the two endpoints before retrying.", + ], + error=e, + ) + +def make_circle_redge( + center: Tuple[float, float, float], + radius: ScalarLike, + normal: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, +) -> Edge: + """Create a circular edge.""" + try: + radius_value = evaluate_scalar(radius) + if radius_value <= 0: + raise ValueError("半径必须大于0") + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) + center_global = cs.transform_point(np.array(center_value)) + normal_global = cs.transform_vector(np.array(normal_value)) + x_direction_global = cs.transform_vector( + _default_plane_x_direction(normal_value) + ) + + edge_shape = make_circle_edge( + center_global, + radius_value, + normal_global, + x_direction=x_direction_global, + ) + edge = cast( + Edge, + _finalize_primitive_shape( + Edge(edge_shape), + op=_OP_MAKE_CIRCLE_REDGE, + params={"center": center, "radius": radius, "normal": normal}, + tags={"primitive", "edge"}, + ), + ) + return cast( + Edge, + _apply_shape_tag_prefix( + edge, + tag_prefix, + kind="edge", + authoring_source="simplecadapi.make_circle_redge.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_circle_redge", + what_happened="Failed to create a circular edge.", + possible_causes=[ + "The radius is not a positive finite scalar.", + "The center or normal is not a valid finite 3D vector.", + "The kernel rejected the circle definition.", + ], + how_to_fix=[ + "Use a radius greater than zero.", + "Pass finite center and normal vectors.", + "If the normal is computed dynamically, verify it is not zero-length.", + ], + error=e, + ) + +def make_circle_rwire( + center: Tuple[float, float, float], + radius: ScalarLike, + normal: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + edge_tag: Optional[str] = None, +) -> Wire: + """Create a circular wire.""" + try: + if get_active_session() is not None: + edge = make_circle_redge(center, radius, normal) + wire = make_wire_from_edges_rwire([edge]) + local_edge_tag = edge_tag or "circle" + return cast( + Wire, + _apply_profile_tag_prefix( + wire, + tag_prefix, + ( + [local_edge_tag] + if tag_prefix is not None or edge_tag is not None + else None + ), + authoring_source="simplecadapi.make_circle_rwire.tag_prefix", + ), + ) + + with suspend_graph_recording(): + edge = make_circle_redge(center, radius, normal) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + wire = cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_circle_wire", + params={"center": center, "radius": radius, "normal": normal}, + tags={"primitive", "wire"}, + ), + ) + local_edge_tag = edge_tag or "circle" + return cast( + Wire, + _apply_profile_tag_prefix( + wire, + tag_prefix, + ( + [local_edge_tag] + if tag_prefix is not None or edge_tag is not None + else None + ), + authoring_source="simplecadapi.make_circle_rwire.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_circle_rwire", + what_happened="Failed to create a circular wire.", + possible_causes=[ + "The circle edge could not be created.", + "The wire assembly step rejected the generated edge.", + ], + how_to_fix=[ + "Check the center, radius, and normal inputs.", + "Retry with a positive radius and a valid normal vector.", + ], + error=e, + ) + +def make_circle_rface( + center: Tuple[float, float, float], + radius: ScalarLike, + normal: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + edge_tag: Optional[str] = None, +) -> Face: + """Create a circular face.""" + try: + if get_active_session() is not None: + wire = make_circle_rwire( + center, + radius, + normal, + tag_prefix=tag_prefix, + edge_tag=edge_tag, + ) + return make_face_from_wire_rface(wire, normal=normal, tag_prefix=tag_prefix) + + with suspend_graph_recording(): + wire = make_circle_rwire( + center, + radius, + normal, + tag_prefix=tag_prefix, + edge_tag=edge_tag, + ) + face_shape = make_face_from_wire_ocp(wire.wrapped) + face = Face(face_shape) + face._metadata = wire._metadata.copy() + result = cast( + Face, + _finalize_primitive_shape( + face, + op="make_circle_face", + params={"center": center, "radius": radius, "normal": normal}, + tags={"primitive", "face"}, + ), + ) + result = cast( + Face, + _copy_exact_topology_identity_tags( + result, [wire], operation="make_circle_rface" + ), + ) + return cast( + Face, + _apply_shape_tag_prefix( + result, + tag_prefix, + kind="face", + authoring_source="simplecadapi.make_circle_rface.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_circle_rface", + what_happened="Failed to create a circular face.", + possible_causes=[ + "The underlying circular wire could not be created.", + "The kernel could not create a face from the wire.", + ], + how_to_fix=[ + "Verify the center, radius, and normal values.", + "Use a positive radius and a valid non-zero normal vector.", + ], + error=e, + ) + +def make_rectangle_rwire( + width: ScalarLike, + height: ScalarLike, + center: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 0), + normal: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + edge_tags: Optional[Sequence[str]] = None, +) -> Wire: + """Create a rectangular wire.""" + try: + width_value = evaluate_scalar(width) + height_value = evaluate_scalar(height) + if width_value <= 0 or height_value <= 0: + raise ValueError("宽度和高度必须大于0") + + if get_active_session() is not None: + normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) + _, x_axis, y_axis = _orthonormal_plane_axes(normal_value) + half_w = width / 2 + half_h = height / 2 + corners = [ + _offset_point_expr(center, x_axis, y_axis, -half_w, -half_h), + _offset_point_expr(center, x_axis, y_axis, half_w, -half_h), + _offset_point_expr(center, x_axis, y_axis, half_w, half_h), + _offset_point_expr(center, x_axis, y_axis, -half_w, half_h), + ] + wire = _make_closed_profile_rwire(corners) + return cast( + Wire, + _apply_profile_tag_prefix( + wire, + tag_prefix, + edge_tags, + authoring_source="simplecadapi.make_rectangle_rwire.tag_prefix", + ), + ) + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) + center_global = cs.transform_point(np.array(center_value)) + normal_global = cs.transform_vector(np.array(normal_value)) + + normal_norm = float(np.linalg.norm(normal_global)) + if normal_norm <= 1e-15 or not np.isfinite(normal_norm): + raise ValueError("法向量不能是零向量") + + _, local_x, local_y = _orthonormal_plane_axes(normal_value) + plane_x = cs.transform_vector(local_x) + plane_y = cs.transform_vector(local_y) + + # 创建矩形的四个顶点(在本地坐标系中) + half_w, half_h = width_value / 2, height_value / 2 + local_points = [ + (-half_w, -half_h), + (half_w, -half_h), + (half_w, half_h), + (-half_w, half_h), + ] + + # 转换到全局坐标系 + global_points = [] + for local_point in local_points: + # 在本地坐标系中的点 + point_3d = ( + center_global + local_point[0] * plane_x + local_point[1] * plane_y + ) + global_points.append(tuple(float(v) for v in point_3d)) + + # 创建边 + wire_points = [ + (float(point[0]), float(point[1]), float(point[2])) + for point in global_points + ] + wire_shape = make_polyline_wire(wire_points, closed=True) + wire = cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_rectangle_wire", + params={ + "width": width, + "height": height, + "center": center, + "normal": normal, + }, + tags={"primitive", "wire"}, + ), + ) + return cast( + Wire, + _apply_profile_tag_prefix( + wire, + tag_prefix, + edge_tags, + authoring_source="simplecadapi.make_rectangle_rwire.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_rectangle_rwire", + what_happened="Failed to create a rectangular wire.", + possible_causes=[ + "Width or height is not a positive finite scalar.", + "The center or normal is not a valid finite 3D vector.", + "The local rectangle basis became degenerate.", + ], + how_to_fix=[ + "Use width and height values greater than zero.", + "Pass a valid center and a non-zero normal vector.", + "If the normal is near zero, normalize or replace it before retrying.", + ], + error=e, + ) + +def make_rectangle_rface( + width: ScalarLike, + height: ScalarLike, + center: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 0), + normal: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + edge_tags: Optional[Sequence[str]] = None, +) -> Face: + """Create a rectangular face.""" + try: + if get_active_session() is not None: + wire = make_rectangle_rwire( + width, + height, + center, + normal, + tag_prefix=tag_prefix, + edge_tags=edge_tags, + ) + return make_face_from_wire_rface( + wire, normal=cast(Any, normal), tag_prefix=tag_prefix + ) + + with suspend_graph_recording(): + wire = make_rectangle_rwire( + width, + height, + center, + normal, + tag_prefix=tag_prefix, + edge_tags=edge_tags, + ) + face_shape = make_face_from_wire_ocp(wire.wrapped) + face = Face(face_shape) + face._metadata = wire._metadata.copy() + result = cast( + Face, + _finalize_primitive_shape( + face, + op="make_rectangle_face", + params={ + "width": width, + "height": height, + "center": center, + "normal": normal, + }, + tags={"primitive", "face"}, + ), + ) + result = cast( + Face, + _copy_exact_topology_identity_tags( + result, [wire], operation="make_rectangle_rface" + ), + ) + return cast( + Face, + _apply_shape_tag_prefix( + result, + tag_prefix, + kind="face", + authoring_source="simplecadapi.make_rectangle_rface.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_rectangle_rface", + what_happened="Failed to create a rectangular face.", + possible_causes=[ + "The rectangular wire could not be created.", + "The face construction step rejected the generated wire.", + ], + how_to_fix=[ + "Verify width, height, center, and normal.", + "Retry with positive dimensions and a valid non-zero normal vector.", + ], + error=e, + ) + +def make_face_from_wire_rface( + wire: Wire, + normal: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, +) -> Face: + """Create a face from a closed wire.""" + try: + if not isinstance(wire, Wire): + raise ValueError("输入必须是Wire类型") + + # 检查Wire是否封闭 + if not wire.is_closed(): + raise ValueError("Wire必须是封闭的才能创建面") + + # The wire is already global geometry; only the requested local normal + # is resolved through the active workplane chain. + cs = get_current_cs() + global_normal = cs.transform_vector(np.array(normal)) + + # 标准化法向量 + normal_vec = global_normal / np.linalg.norm(global_normal) + + # 创建面 + face_shape = make_face_from_wire_ocp(wire.wrapped) + face = Face(face_shape) + + # 检查面的法向量是否与期望方向一致 + face_normal = face.get_normal_at() + face_normal_vec = np.array([face_normal.x, face_normal.y, face_normal.z]) + + # 计算法向量的点积,如果小于0则需要反向 + dot_product = np.dot(normal_vec, face_normal_vec) + + if dot_product < 0: + # 反向面(通过反向Wire的方向) + # OCP Wire 没有直接的 reverse 包装方法,这里重新构建 + # 简单的方法是使用makeFromWires的orientation参数 + # 或者我们接受当前面的方向,添加一个警告 + print(f"警告: 创建的面的法向量与期望方向相反 (点积: {dot_product:.3f})") + + face._metadata = wire._metadata.copy() + + result = cast( + Face, + _finalize_derived_shape( + face, + op=_OP_MAKE_FACE_FROM_WIRE_RFACE, + params={"normal": normal}, + input_shapes=[wire], + tags={"derived", "face"}, + ), + ) + result = cast( + Face, + _copy_exact_topology_identity_tags( + result, [wire], operation="make_face_from_wire_rface" + ), + ) + return cast( + Face, + _apply_shape_tag_prefix( + result, + tag_prefix, + kind="face", + authoring_source="simplecadapi.make_face_from_wire_rface.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_face_from_wire_rface", + what_happened="Failed to create a face from the input wire.", + possible_causes=[ + "The input is not a Wire instance.", + "The wire is open or geometrically invalid.", + "The kernel rejected the closed wire when building a face.", + ], + how_to_fix=[ + "Pass a Wire object, not an Edge or a list of points.", + "Ensure the wire is closed before calling this API.", + "If the wire was assembled from edges, verify the edges connect end-to-end.", + ], + error=e, + ) + +def make_face_from_wires_rface( + outer_wire: Wire, + inner_wires: Sequence[Wire], + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Face: + """Create a face from one outer closed wire and optional inner closed wires.""" + try: + if not isinstance(outer_wire, Wire): + raise ValueError("outer_wire must be a Wire") + if not outer_wire.is_closed(): + raise ValueError("outer_wire must be closed") + + inner_list = list(inner_wires or []) + for inner_wire in inner_list: + if not isinstance(inner_wire, Wire): + raise ValueError("inner_wires must contain only Wire objects") + if not inner_wire.is_closed(): + raise ValueError("inner wires must be closed") + + cs = get_current_cs() + global_normal = cs.transform_vector(np.array(normal)) + normal_norm = float(np.linalg.norm(global_normal)) + if normal_norm <= 1e-15 or not np.isfinite(normal_norm): + raise ValueError("normal must be a non-zero finite vector") + normal_vec = global_normal / normal_norm + + face_shape = make_face_from_wires_ocp( + outer_wire.wrapped, + [inner_wire.wrapped for inner_wire in inner_list], + ) + face = Face(face_shape) + + face_normal = face.get_normal_at() + face_normal_vec = np.array([face_normal.x, face_normal.y, face_normal.z]) + dot_product = float(np.dot(normal_vec, face_normal_vec)) + if dot_product < 0: + print(f"警告: 创建的面的法向量与期望方向相反 (点积: {dot_product:.3f})") + + face._metadata = outer_wire._metadata.copy() + + return cast( + Face, + _finalize_derived_shape( + face, + op=_OP_MAKE_FACE_FROM_WIRES_RFACE, + params={"normal": normal, "inner_wire_count": len(inner_list)}, + input_shapes=[outer_wire, *inner_list], + tags={"derived", "face"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_face_from_wires_rface", + what_happened="Failed to create a face from the input outer and inner wires.", + possible_causes=[ + "The outer wire is not a Wire instance or is not closed.", + "One or more inner wires are not Wire instances or are not closed.", + "The inner wires are not contained by the outer wire or are geometrically invalid.", + "The kernel rejected the multi-loop face definition.", + ], + how_to_fix=[ + "Pass one closed outer Wire and zero or more closed inner Wire objects.", + "Ensure every inner wire lies inside the outer wire and does not intersect other loops.", + "Use a valid non-zero normal vector.", + ], + error=e, + ) + +def make_wire_from_edges_rwire( + edges: List[Edge], *, tag_prefix: Optional[str] = None +) -> Wire: + """Create a wire from a list of connected edges.""" + try: + if not edges: + raise ValueError("边列表不能为空") + + wire_shape = make_wire_from_edges_ocp([edge.wrapped for edge in edges]) + result = cast( + Wire, + _finalize_derived_shape( + Wire(wire_shape), + op=_OP_MAKE_WIRE_FROM_EDGES_RWIRE, + params={"edge_count": len(edges)}, + input_shapes=edges, + tags={"derived", "wire"}, + ), + ) + result = cast( + Wire, + _copy_exact_topology_identity_tags( + result, edges, operation="make_wire_from_edges_rwire" + ), + ) + return cast( + Wire, + _apply_shape_tag_prefix( + result, + tag_prefix, + kind="wire", + authoring_source="simplecadapi.make_wire_from_edges_rwire.tag_prefix", + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_wire_from_edges_rwire", + what_happened="Failed to assemble a wire from the input edges.", + possible_causes=[ + "The edge list is empty.", + "One or more items are invalid edges.", + "The edges do not connect into a valid wire chain.", + ], + how_to_fix=[ + "Pass a non-empty list of Edge objects.", + "Ensure consecutive edges share matching endpoints.", + "Inspect the edge order if the wire should form a closed loop.", + ], + error=e, + ) + +def make_wire_from_sketch_rwire( + sketch: Sketch, + profile: int | str = 0, + *, + require_fully_constrained: bool = False, + strict: bool = True, + tolerance: float = 1e-7, + max_iterations: int = 80, +) -> Wire: + """Promote a sketch profile to a concrete wire, solving internally.""" + try: + if not isinstance(sketch, Sketch): + raise ValueError("Input must be a Sketch") + ( + wire, + solve_result, + profile_payload, + inner_profile_payloads, + source_wires, + ) = _promote_sketch_profile( + sketch, + profile, + target_kind="wire", + require_fully_constrained=require_fully_constrained, + strict=strict, + tolerance=tolerance, + max_iterations=max_iterations, + ) + solve_snapshot = _sketch_solve_snapshot(solve_result) + finalized = cast( + Wire, + _finalize_derived_shape( + cast(Wire, wire), + op=_OP_MAKE_WIRE_FROM_SKETCH_RWIRE, + params={ + "profile": profile, + "sketch": sketch.to_dict(), + "require_fully_constrained": require_fully_constrained, + "strict": strict, + "tolerance": tolerance, + "max_iterations": max_iterations, + "solve_snapshot": solve_snapshot, + "promotion_map": _sketch_promotion_map( + sketch, + profile, + profile_payload, + inner_profile_payloads=inner_profile_payloads, + target_kind="wire", + ), + }, + input_shapes=cast(Sequence[AnyShape], [sketch]), + tags={"derived", "wire", "sketch"}, + ), + ) + return cast( + Wire, + _apply_sketch_promotion_identity_tags( + finalized, + sketch=sketch, + profile_payload=profile_payload, + source_wires=source_wires, + operation=_OP_MAKE_WIRE_FROM_SKETCH_RWIRE, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_wire_from_sketch_rwire", + what_happened="Failed to create a wire from the sketch.", + possible_causes=[ + "The sketch has no closed non-construction profile.", + "The sketch constraints are conflicting or invalid.", + "The requested profile index or id does not exist.", + ], + how_to_fix=[ + "Build sketch profiles only through sketch APIs and close all profile loops.", + "Call inspect_sketch_rsketchresult(..., strict=False) to inspect diagnostics.", + ], + error=e, + ) + +def make_face_from_sketch_rface( + sketch: Sketch, + profile: int | str = 0, + *, + inner_profiles: Sequence[int | str] = (), + require_fully_constrained: bool = False, + strict: bool = True, + tolerance: float = 1e-7, + max_iterations: int = 80, +) -> Face: + """Promote one outer and optional inner sketch profiles to a face.""" + try: + if not isinstance(sketch, Sketch): + raise ValueError("Input must be a Sketch") + normalized_inner_profiles = tuple(inner_profiles) + ( + face, + solve_result, + profile_payload, + inner_profile_payloads, + source_wires, + ) = _promote_sketch_profile( + sketch, + profile, + target_kind="face", + inner_profiles=normalized_inner_profiles, + require_fully_constrained=require_fully_constrained, + strict=strict, + tolerance=tolerance, + max_iterations=max_iterations, + ) + solve_snapshot = _sketch_solve_snapshot(solve_result) + finalized = cast( + Face, + _finalize_derived_shape( + cast(Face, face), + op=_OP_MAKE_FACE_FROM_SKETCH_RFACE, + params={ + "profile": profile, + "inner_profiles": normalized_inner_profiles, + "sketch": sketch.to_dict(), + "require_fully_constrained": require_fully_constrained, + "strict": strict, + "tolerance": tolerance, + "max_iterations": max_iterations, + "solve_snapshot": solve_snapshot, + "promotion_map": _sketch_promotion_map( + sketch, + profile, + profile_payload, + inner_profile_payloads=inner_profile_payloads, + target_kind="face", + ), + }, + input_shapes=cast(Sequence[AnyShape], [sketch]), + tags={"derived", "face", "sketch"}, + ), + ) + return cast( + Face, + _apply_sketch_promotion_identity_tags( + finalized, + sketch=sketch, + profile_payload=profile_payload, + source_wires=source_wires, + operation=_OP_MAKE_FACE_FROM_SKETCH_RFACE, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_face_from_sketch_rface", + what_happened="Failed to create a face from the sketch.", + possible_causes=[ + "The sketch has no closed non-construction profile.", + "The sketch constraints are conflicting or invalid.", + "The requested profile index or id does not exist.", + "An inner profile is outside, intersects, or duplicates the outer profile.", + ], + how_to_fix=[ + "Build a closed profile with add_line_rsketch(...) or add_circle_rsketch(...).", + "Add constraints until the profile can solve cleanly.", + "Pass hole loops explicitly with inner_profiles=[...].", + ], + error=e, + ) + +def load_brep_region_rsolid( + path: str | Path, + sha256: str, + *, + tag_prefix: Optional[str] = None, +) -> Solid: + """Load a hash-pinned, target-derived BREP region snapshot as one Solid. + + The complete artifact SHA-256 is verified before native BREP decoding. In a + GraphSession, ``path`` must be relative and is replayed relative to the replay + process working directory. Model JSON records the locator and digest, not the + sidecar bytes. + """ + + try: + return cast( + Solid, + _load_brep_region_rshape( + path, + sha256, + root_kind="solid", + tag_prefix=tag_prefix, + replay_root=(Path.cwd() if get_active_session() is not None else None), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="load_brep_region_rsolid", + what_happened="Failed to load the BREP region snapshot.", + possible_causes=[ + "The snapshot path does not exist or is not readable.", + "The supplied SHA-256 does not match the snapshot bytes.", + "The snapshot is corrupt, unsupported, invalid, or not one solid.", + ], + how_to_fix=[ + "Create the snapshot with copy_step_region_rpath(...).", + "Pass the SHA-256 of the complete .scadbrep file.", + "Keep the sidecar at the same path when replaying model JSON.", + ], + error=e, + ) + +def _carry_face_provenance( + shape: Shell | Solid, + source_faces: Sequence[Face], + *, + result_face_indices: Optional[Sequence[int]] = None, + allow_orientation_change: bool = False, + replace_local_bindings: bool = True, +) -> None: + result_faces = list(shape.get_faces()) + if result_face_indices is None: + mapped_indices = [] + for source in source_faces: + matches = [ + index + for index, result in enumerate(result_faces) + if result.wrapped.IsSame(source.wrapped) + ] + if len(matches) != 1: + raise ValueError("face continuation mapping is incomplete or ambiguous") + mapped_indices.append(matches[0]) + else: + mapped_indices = [int(index) for index in result_face_indices] + if len(mapped_indices) != len(source_faces) or len(set(mapped_indices)) != len( + result_faces + ): + raise ValueError("face continuation mapping is not one-to-one") + for source, result_index in zip(source_faces, mapped_indices): + if result_index < 0 or result_index >= len(result_faces): + raise ValueError( + "face continuation mapping contains an invalid result index" + ) + face = result_faces[result_index] + provenance = source.get_metadata("provenance") + if ( + isinstance(provenance, dict) + and provenance.get("construction") == "exact_transcription" + and not allow_orientation_change + and not face.wrapped.IsEqual(source.wrapped) + ): + raise ValueError("sewing modified an exact-transcription input face") + projected_bindings = [ + binding + for binding in source._local_tag_bindings() + if lineage_policy_allows(binding.propagation, "continuation") + ] + if replace_local_bindings: + face._replace_local_tag_bindings(projected_bindings) + _attach_lineage_from_source( + source, + face, + derivation="continuation", + op="face_continuation", + coverage="complete", + ) + if isinstance(provenance, dict): + face.set_metadata("provenance", dict(provenance)) + face._set_runtime("semantic.lineage.coverage", "complete") + +def load_brep_region_rshell( + path: str | Path, + sha256: str, + *, + tag_prefix: Optional[str] = None, +) -> Shell: + """Load a hash-pinned, target-derived BREP face region as one Shell. + + The Shell keeps target-derived topology and is tagged with imported-sidecar + provenance. Use ordinary replayable surface operations to join it to fitted + or analytic feature faces. GraphSession requires a relative sidecar path. + """ + + try: + return cast( + Shell, + _load_brep_region_rshape( + path, + sha256, + root_kind="shell", + tag_prefix=tag_prefix, + replay_root=(Path.cwd() if get_active_session() is not None else None), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="load_brep_region_rshell", + what_happened="Failed to load the BREP face-region snapshot.", + possible_causes=[ + "The snapshot path or SHA-256 is incorrect.", + "The snapshot is corrupt, unsupported, invalid, or not one Shell.", + ], + how_to_fix=[ + "Create a face-region snapshot with copy_step_region_rpath(..., face_ids=[...]).", + "Pass the SHA-256 of the complete .scadbrep file.", + ], + error=e, + ) + +def _load_brep_region_rshape( + path: str | Path, + sha256: str, + *, + root_kind: str, + tag_prefix: Optional[str], + replay_root: Path | None, +) -> Shell | Solid: + source_path = _brep_region_path(path, for_graph=replay_root is not None) + wrapped, manifest, canonical_hash = read_artifact( + source_path, + sha256, + expected_root_kind=cast(Any, root_kind), + replay_root=replay_root, + ) + shape: Shell | Solid = Solid(wrapped) if root_kind == "solid" else Shell(wrapped) + shape._add_tag("imported") + shape._add_tag("sidecar") + shape._add_tag(root_kind) + normalized_prefix = ( + normalize_tag(tag_prefix, strict=True) if tag_prefix is not None else None + ) + if normalized_prefix is not None: + shape._apply_tag(f"{normalized_prefix}.{root_kind}", propagate=False) + shape.set_metadata( + "brep_region", + { + "artifact_sha256": canonical_hash, + "profile": manifest["profile"], + "provenance": manifest["provenance"], + "source_face_ids": manifest["region"].get("source_face_ids"), + }, + ) + _attach_brep_region_provenance(shape, manifest, canonical_hash) + op = ( + _OP_LOAD_BREP_REGION_RSOLID + if root_kind == "solid" + else _OP_LOAD_BREP_REGION_RSHELL + ) + return cast( + Shell | Solid, + _finalize_primitive_shape( + shape, + op=op, + params={ + "path": source_path, + "sha256": canonical_hash, + "tag_prefix": normalized_prefix, + }, + tags={"imported", "sidecar", root_kind}, + ), + ) + +def _attach_brep_region_provenance( + shape: Shell | Solid, + manifest: Mapping[str, Any], + artifact_sha256: str, +) -> None: + source = manifest["source"] + region = manifest["region"] + evidence = { + "artifact_sha256": artifact_sha256, + "profile": manifest["profile"], + "source_sha256": source["content_hash"], + "source_name": source["name"], + "source_face_ids": region.get("source_face_ids"), + "construction": "exact_transcription", + "topology_origin": "retained", + "runtime_dependency": "embedded_target_derived", + } + root_binding = TagBinding( + tag="provenance.exact_transcription", + producer=TagProducer(TagProducerKind.IMPORTED_SIDECAR), + target=TagTarget(TagTargetKind.SCOPE_ROOT), + propagation=TagPropagation( + topology=TopologyPropagation.DOWNWARD, + lineage=LineagePolicy.CONTINUATION_FRAGMENT, + ), + evidence=TagEvidence(TagEvidenceKind.IMPORTED_SIDECAR, evidence), + certainty=TagCertainty.ASSERTED, + lifecycle=TagLifecycle.SNAPSHOT, + binding_id=f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, '|'.join(('simplecad.brep_region.root', artifact_sha256, str(region['kind'])))).hex}", + ) + shape._add_tag_binding(root_binding) + source_face_ids = tuple(region.get("source_face_ids") or ()) + for index, face in enumerate(shape.get_faces()): + face_evidence = { + **evidence, + "source_face_id": ( + source_face_ids[index] if index < len(source_face_ids) else None + ), + } + face.set_metadata("provenance", face_evidence) + face._add_tag_binding( + TagBinding( + tag="provenance.exact_transcription", + producer=TagProducer(TagProducerKind.IMPORTED_SIDECAR), + target=TagTarget(TagTargetKind.SCOPE_ROOT), + propagation=TagPropagation( + topology=TopologyPropagation.LOCAL, + lineage=LineagePolicy.CONTINUATION_FRAGMENT, + ), + evidence=TagEvidence(TagEvidenceKind.IMPORTED_SIDECAR, face_evidence), + certainty=TagCertainty.ASSERTED, + lifecycle=TagLifecycle.SNAPSHOT, + binding_id=f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, '|'.join(('simplecad.brep_region.face', artifact_sha256, str(face_evidence['source_face_id'])))).hex}", + ) + ) + face._set_runtime("semantic.lineage.coverage", "complete") + +def _brep_region_path(path: str | Path, *, for_graph: bool) -> str: + source = Path(path) + if ":" in source.name: + raise ValueError(".scadbrep filenames must not contain ':'") + if for_graph and source.is_absolute(): + raise ValueError( + "GraphSession requires a relative .scadbrep path so model JSON does " + "not record machine-specific absolute paths" + ) + if for_graph and source.drive: + raise ValueError("GraphSession .scadbrep paths must not contain a drive") + if for_graph and ".." in source.parts: + raise ValueError(".scadbrep paths must not traverse parent directories") + if for_graph and "\\" in str(path): + raise ValueError("GraphSession .scadbrep paths must use '/' separators") + if source.suffix.lower() != ".scadbrep": + raise ValueError("path must end in .scadbrep") + return source.as_posix() if for_graph else str(source) + +def make_box_rsolid( + width: ScalarLike, + height: ScalarLike, + depth: ScalarLike, + bottom_face_center: Tuple[float, float, float] = (0, 0, 0), + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + bottom_face_tag: Optional[str] = None, + top_face_tag: Optional[str] = None, + front_face_tag: Optional[str] = None, + back_face_tag: Optional[str] = None, + left_face_tag: Optional[str] = None, + right_face_tag: Optional[str] = None, +) -> Solid: + """Create a box with native kernel-backed Face topology tags.""" + try: + assignments = _normalize_operation_role_tags( + "make_box_rsolid", + ( + ("box.bottom", bottom_face_tag), + ("box.top", top_face_tag), + ("box.front", front_face_tag), + ("box.back", back_face_tag), + ("box.left", left_face_tag), + ("box.right", right_face_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + width_value = evaluate_scalar(width) + height_value = evaluate_scalar(height) + depth_value = evaluate_scalar(depth) + + if width_value <= 0 or height_value <= 0 or depth_value <= 0: + raise ValueError("宽度、高度和深度必须大于0") + + cs = get_current_cs() + center_value = cast( + Tuple[float, float, float], evaluate_value(bottom_face_center) + ) + center_global = cs.transform_point(np.array(center_value)) + corner_global = ( + center_global + - np.asarray(cs.x_axis, dtype=float) * (width_value / 2.0) + - np.asarray(cs.y_axis, dtype=float) * (height_value / 2.0) + ) + tracked = cast( + TrackedResult, + tracked_box( + tuple(float(value) for value in corner_global), + width_value, + height_value, + depth_value, + x_axis=tuple(float(value) for value in cs.x_axis), + y_axis=tuple(float(value) for value in cs.y_axis), + z_axis=tuple(float(value) for value in cs.z_axis), + ), + ) + solid = cast(Solid, tracked.shape) + + # 自动标记面 + solid.auto_tag_faces("box") + solid._apply_tag("geom.primitive.box", propagate=False) + solid._add_tag("box") + solid.set_metadata( + "geo", + { + "type": "box", + "size": {"x": width_value, "y": height_value, "z": depth_value}, + "bottom_face_center": bottom_face_center, + }, + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op="make_box_rsolid", + params={ + "width": width, + "height": height, + "depth": depth, + "bottom_face_center": bottom_face_center, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + ) + tagged = _apply_operation_role_tags( + finalized, + op="make_box_rsolid", + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op="make_box_rsolid", + delta=tracked.delta, + face_roles=( + ("box.bottom", "bottom"), + ("box.top", "top"), + ("box.front", "front"), + ("box.back", "back"), + ("box.left", "left"), + ("box.right", "right"), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_box_rsolid", + what_happened="Failed to create a box solid.", + possible_causes=[ + "Width, height, or depth is not a positive finite scalar.", + "The bottom face center is not a valid finite 3D point.", + "The kernel rejected the box dimensions or placement.", + ], + how_to_fix=[ + "Use width, height, and depth values greater than zero.", + "Pass bottom_face_center as a finite 3D tuple.", + "If dimensions come from expressions, inspect the evaluated numeric values.", + ], + error=e, + ) + +def make_cylinder_rsolid( + radius: ScalarLike, + height: ScalarLike, + bottom_face_center: Tuple[float, float, float] = (0, 0, 0), + axis: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_face_tag: Optional[str] = None, + start_edge_tag: Optional[str] = None, + end_edge_tag: Optional[str] = None, + seam_edge_tag: Optional[str] = None, +) -> Solid: + """Create a cylinder with native kernel-backed Face and Edge topology tags.""" + try: + assignments = _normalize_operation_role_tags( + "make_cylinder_rsolid", + ( + ("cylinder.start", start_face_tag), + ("cylinder.end", end_face_tag), + ("cylinder.side", side_face_tag), + ("cylinder.start_boundary", start_edge_tag), + ("cylinder.end_boundary", end_edge_tag), + ("cylinder.seam", seam_edge_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + radius_value = evaluate_scalar(radius) + height_value = evaluate_scalar(height) + if radius_value <= 0 or height_value <= 0: + raise ValueError("半径和高度必须大于0") + + cs = get_current_cs() + center_value = cast( + Tuple[float, float, float], evaluate_value(bottom_face_center) + ) + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + center_global = cs.transform_point(np.array(center_value)) + axis_global = cs.transform_vector(np.array(axis_value)) + + resolved_center = tuple(float(value) for value in center_global) + resolved_axis = tuple(float(value) for value in axis_global) + tracked = cast( + TrackedResult, + tracked_cylinder( + resolved_center, + resolved_axis, + radius_value, + height_value, + ), + ) + solid = cast(Solid, tracked.shape) + + # 自动标记面 + solid.auto_tag_faces("cylinder") + solid._apply_tag("geom.primitive.cylinder", propagate=False) + solid._add_tag("cylinder") + solid.set_metadata( + "geo", + { + "type": "cylinder", + "radius": radius_value, + "height": height_value, + "bottom_face_center": bottom_face_center, + "axis": axis, + }, + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op="make_cylinder_rsolid", + params={ + "radius": radius, + "height": height, + "bottom_face_center": bottom_face_center, + "axis": axis, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + ) + tagged = _apply_operation_role_tags( + finalized, + op="make_cylinder_rsolid", + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op="make_cylinder_rsolid", + delta=tracked.delta, + start_role="cylinder.start", + end_role="cylinder.end", + side_role="cylinder.side", + edge_roles=( + ("cylinder.start_boundary", "start"), + ("cylinder.end_boundary", "end"), + ("cylinder.seam", "seam"), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_cylinder_rsolid", + what_happened="Failed to create a cylinder solid.", + possible_causes=[ + "Radius or height is not a positive finite scalar.", + "The bottom face center or axis is not a valid finite 3D vector.", + "The axis is degenerate or rejected by the kernel.", + ], + how_to_fix=[ + "Use radius and height values greater than zero.", + "Pass a valid bottom_face_center and a non-zero axis vector.", + "If the axis is computed dynamically, inspect its evaluated numeric value.", + ], + error=e, + ) + +def make_cone_rsolid( + bottom_radius: ScalarLike, + height: ScalarLike, + top_radius: ScalarLike = 0.0, + bottom_face_center: Tuple[float, float, float] = (0, 0, 0), + axis: Tuple[float, float, float] = (0, 0, 1), + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_face_tag: Optional[str] = None, + start_edge_tag: Optional[str] = None, + end_edge_tag: Optional[str] = None, + seam_edge_tag: Optional[str] = None, +) -> Solid: + """Create a cone or frustum with native kernel-backed topology tags.""" + try: + assignments = _normalize_operation_role_tags( + "make_cone_rsolid", + ( + ("cone.start", start_face_tag), + ("cone.end", end_face_tag), + ("cone.side", side_face_tag), + ("cone.start_boundary", start_edge_tag), + ("cone.end_boundary", end_edge_tag), + ("cone.seam", seam_edge_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + bottom_radius_value = evaluate_scalar(bottom_radius) + height_value = evaluate_scalar(height) + top_radius_value = evaluate_scalar(top_radius) + if bottom_radius_value <= 0 or height_value <= 0: + raise ValueError("底面半径和高度必须大于0") + + cs = get_current_cs() + center_value = cast( + Tuple[float, float, float], evaluate_value(bottom_face_center) + ) + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + center_global = cs.transform_point(np.array(center_value)) + axis_global = cs.transform_vector(np.array(axis_value)) + + resolved_center = tuple(float(value) for value in center_global) + resolved_axis = tuple(float(value) for value in axis_global) + tracked = cast( + TrackedResult, + tracked_cone( + resolved_center, + resolved_axis, + bottom_radius_value, + top_radius_value, + height_value, + ), + ) + solid = cast(Solid, tracked.shape) + + # 自动标记面 + solid._apply_tag("geom.primitive.cone", propagate=False) + solid._add_tag("cone") + solid.set_metadata( + "geo", + { + "type": "cone", + "bottom_radius": bottom_radius_value, + "top_radius": top_radius_value, + "height": height_value, + "bottom_face_center": bottom_face_center, + "axis": axis, + }, + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op="make_cone_rsolid", + params={ + "bottom_radius": bottom_radius, + "top_radius": top_radius, + "height": height, + "bottom_face_center": bottom_face_center, + "axis": axis, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + ) + tagged = _apply_operation_role_tags( + finalized, + op="make_cone_rsolid", + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op="make_cone_rsolid", + delta=tracked.delta, + start_role="cone.start", + end_role="cone.end" if top_radius_value > 0.0 else None, + side_role="cone.side", + edge_roles=( + ("cone.start_boundary", "start"), + ("cone.end_boundary", "end"), + ("cone.seam", "seam"), + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_cone_rsolid", + what_happened="Failed to create a cone or truncated cone solid.", + possible_causes=[ + "Bottom radius or height is not a positive finite scalar.", + "The bottom face center or axis is not a valid finite 3D vector.", + "The kernel rejected the cone dimensions or orientation.", + ], + how_to_fix=[ + "Use a positive bottom radius and a positive height.", + "Pass a valid center point and non-zero axis vector.", + "If top_radius is used, make sure it is a finite scalar.", + ], + error=e, + ) + +def make_sphere_rsolid( + radius: ScalarLike, center: Tuple[float, float, float] = (0, 0, 0) +) -> Solid: + """Create a sphere solid.""" + try: + radius_value = evaluate_scalar(radius) + if radius_value <= 0: + raise ValueError("半径必须大于0") + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + center_global = cs.transform_point(np.array(center_value)) + + resolved_center = tuple(float(value) for value in center_global) + solid = cast( + Solid, + Solid(make_sphere_solid(resolved_center, radius_value)), + ) + + # 自动标记面 + solid.auto_tag_faces("sphere") + solid._apply_tag("geom.primitive.sphere", propagate=False) + solid._add_tag("sphere") + solid.set_metadata( + "geo", + { + "type": "sphere", + "radius": radius_value, + "center": center, + }, + ) + + return _finalize_primitive_solid( + solid, + op="make_sphere_rsolid", + params={ + "radius": radius, + "center": center, + }, + tags={"primitive", "solid"}, + ) + except Exception as e: + _wrap_public_api_error( + operation="make_sphere_rsolid", + what_happened="Failed to create a sphere solid.", + possible_causes=[ + "The radius is not a positive finite scalar.", + "The center is not a valid finite 3D point.", + "The kernel rejected the sphere definition.", + ], + how_to_fix=[ + "Use a radius greater than zero.", + "Pass center as a finite 3D tuple.", + "If the center is expression-driven, inspect the evaluated coordinates.", + ], + error=e, + ) + +def make_three_point_arc_redge( + start: Tuple[float, float, float], + middle: Tuple[float, float, float], + end: Tuple[float, float, float], +) -> Edge: + """Create an arc edge from three points.""" + try: + cs = get_current_cs() + start_value = cast(Tuple[float, float, float], evaluate_value(start)) + middle_value = cast(Tuple[float, float, float], evaluate_value(middle)) + end_value = cast(Tuple[float, float, float], evaluate_value(end)) + start_global = cs.transform_point(np.array(start_value)) + middle_global = cs.transform_point(np.array(middle_value)) + end_global = cs.transform_point(np.array(end_value)) + + edge_shape = make_arc_three_point_edge(start_global, middle_global, end_global) + return cast( + Edge, + _finalize_primitive_shape( + Edge(edge_shape), + op=_OP_MAKE_THREE_POINT_ARC_REDGE, + params={"start": start, "middle": middle, "end": end}, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_three_point_arc_redge", + what_happened="Failed to create a three-point arc edge.", + possible_causes=[ + "One or more points are invalid.", + "The three points are collinear or nearly collinear.", + "The kernel rejected the derived arc geometry.", + ], + how_to_fix=[ + "Pass three finite 3D points.", + "Make sure the three points do not lie on the same straight line.", + "If points are computed dynamically, log them before retrying.", + ], + error=e, + ) + +def make_three_point_arc_rwire( + start: Tuple[float, float, float], + middle: Tuple[float, float, float], + end: Tuple[float, float, float], +) -> Wire: + """Create a wire containing an arc defined by three points.""" + try: + if get_active_session() is not None: + edge = make_three_point_arc_redge(start, middle, end) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_three_point_arc_redge(start, middle, end) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_three_point_arc_wire", + params={"start": start, "middle": middle, "end": end}, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_three_point_arc_rwire", + what_happened="Failed to create a wire from the three-point arc.", + possible_causes=[ + "The arc edge could not be created.", + "The wire assembly step rejected the generated edge.", + ], + how_to_fix=[ + "Verify the three arc points first.", + "If the edge is valid but the wire still fails, inspect the generated arc geometry.", + ], + error=e, + ) + +def make_angle_arc_redge( + center: Tuple[float, float, float], + radius: ScalarLike, + start_angle: ScalarLike, + end_angle: ScalarLike, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Edge: + """Create an arc edge from a center, radius, and angle range.""" + try: + radius_value = evaluate_scalar(radius) + start_angle_value = evaluate_scalar(start_angle) + end_angle_value = evaluate_scalar(end_angle) + if radius_value <= 0: + raise ValueError("半径必须大于0") + if start_angle_value == end_angle_value: + raise ValueError("起始角度和结束角度不能相同") + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) + center_global = cs.transform_point(np.array(center_value)) + normal_global = cs.transform_vector(np.array(normal_value)) + x_direction_global = cs.transform_vector( + _default_plane_x_direction(normal_value) + ) + + edge_shape = make_arc_angle_edge( + center_global, + radius_value, + start_angle_value, + end_angle_value, + normal_global, + x_direction=x_direction_global, + ) + return cast( + Edge, + _finalize_primitive_shape( + Edge(edge_shape), + op=_OP_MAKE_ANGLE_ARC_REDGE, + params={ + "center": center, + "radius": radius, + "start_angle": start_angle, + "end_angle": end_angle, + "normal": normal, + }, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_angle_arc_redge", + what_happened="Failed to create an angle-defined arc edge.", + possible_causes=[ + "The radius is not positive.", + "The start and end angles collapse to the same value.", + "The center or normal is invalid, or the kernel rejected the arc.", + ], + how_to_fix=[ + "Use a positive radius.", + "Make sure start_angle and end_angle are different.", + "Pass a valid finite center and a non-zero normal vector.", + ], + error=e, + ) + +def make_angle_arc_rwire( + center: Tuple[float, float, float], + radius: float, + start_angle: float, + end_angle: float, + normal: Tuple[float, float, float] = (0, 0, 1), +) -> Wire: + """Create a wire containing an arc defined by a center, radius, and angle range.""" + + try: + if get_active_session() is not None: + edge = make_angle_arc_redge(center, radius, start_angle, end_angle, normal) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_angle_arc_redge(center, radius, start_angle, end_angle, normal) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_angle_arc_wire", + params={ + "center": center, + "radius": radius, + "start_angle": start_angle, + "end_angle": end_angle, + "normal": normal, + }, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_angle_arc_rwire", + what_happened="Failed to create a wire from the angle-defined arc.", + possible_causes=[ + "The underlying arc edge could not be created.", + "The wire assembly step rejected the generated edge.", + ], + how_to_fix=[ + "Check the center, radius, angle range, and normal.", + "Retry after validating the arc edge input values.", + ], + error=e, + ) + +def _normalize_bspline_control_points( + control_points: Sequence[Sequence[ScalarLike]], +) -> Tuple[Tuple[float, float, float], ...]: + points = list(control_points) + if not points: + raise ValueError("control_points must contain at least one point") + normalized: List[Tuple[float, float, float]] = [] + for index, point in enumerate(points): + value = cast(Sequence[float], evaluate_value(point)) + if len(value) == 2: + coords = (float(value[0]), float(value[1]), 0.0) + elif len(value) == 3: + coords = (float(value[0]), float(value[1]), float(value[2])) + else: + raise ValueError(f"control point {index} must be 2D or 3D") + if not all(math.isfinite(component) for component in coords): + raise ValueError(f"control point {index} contains a non-finite coordinate") + normalized.append(coords) + return tuple(normalized) + +def _collapse_knot_vector( + knots: Sequence[ScalarLike], +) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: + values = [float(evaluate_scalar(knot)) for knot in knots] + if not values: + raise ValueError("knots must not be empty") + if any(not math.isfinite(value) for value in values): + raise ValueError("knots must contain only finite values") + for previous, current in zip(values, values[1:]): + if current < previous: + raise ValueError( + "knots must be non-decreasing when passed as a full knot vector" + ) + unique: List[float] = [] + multiplicities: List[int] = [] + for value in values: + if unique and abs(value - unique[-1]) <= 1e-12: + multiplicities[-1] += 1 + else: + unique.append(value) + multiplicities.append(1) + return tuple(unique), tuple(multiplicities) + +def _default_bspline_knots( + control_count: int, degree: int, periodic: bool +) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: + if periodic: + knot_count = control_count + 1 + return ( + tuple(index / (knot_count - 1) for index in range(knot_count)), + tuple(1 for _ in range(knot_count)), + ) + knot_count = control_count - degree + 1 + if knot_count < 2: + raise ValueError("control point count must be at least degree + 1") + knots = tuple(index / (knot_count - 1) for index in range(knot_count)) + multiplicities = [degree + 1] + multiplicities.extend(1 for _ in range(max(0, knot_count - 2))) + multiplicities.append(degree + 1) + return knots, tuple(multiplicities) + +def _normalize_bspline_knots( + *, + control_count: int, + degree: int, + periodic: bool, + knots: Optional[Sequence[ScalarLike]], + multiplicities: Optional[Sequence[int]], +) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: + if knots is None: + if multiplicities is not None: + raise ValueError("multiplicities require explicit knots") + unique_knots, mults = _default_bspline_knots(control_count, degree, periodic) + elif multiplicities is None: + unique_knots, mults = _collapse_knot_vector(knots) + else: + unique_knots = tuple(float(evaluate_scalar(knot)) for knot in knots) + mults = tuple(int(value) for value in multiplicities) + + if len(unique_knots) != len(mults): + raise ValueError("knots and multiplicities must have the same length") + if len(unique_knots) < 2: + raise ValueError("at least two unique knots are required") + if any(not math.isfinite(knot) for knot in unique_knots): + raise ValueError("knots must contain only finite values") + for previous, current in zip(unique_knots, unique_knots[1:]): + if current <= previous: + raise ValueError("unique knots must be strictly increasing") + if any(multiplicity <= 0 for multiplicity in mults): + raise ValueError("multiplicities must be positive integers") + if any(multiplicity > degree + 1 for multiplicity in mults): + raise ValueError("multiplicities must not exceed degree + 1") + + expected_sum = control_count + (1 if periodic else degree + 1) + actual_sum = sum(mults) + if actual_sum != expected_sum: + raise ValueError( + "sum(multiplicities) must equal " + f"{expected_sum} for this {'periodic' if periodic else 'non-periodic'} B-spline" + ) + return tuple(unique_knots), tuple(mults) + +def _normalize_bspline_weights( + weights: Optional[Sequence[ScalarLike]], control_count: int +) -> Optional[Tuple[float, ...]]: + if weights is None: + return None + values = tuple(float(evaluate_scalar(weight)) for weight in weights) + if len(values) != control_count: + raise ValueError("weights must contain exactly one value per control point") + if any(not math.isfinite(value) or value <= 0.0 for value in values): + raise ValueError("weights must be finite positive values") + return values + +def make_spline_redge( + *, + control_points: Sequence[Sequence[ScalarLike]], + degree: int = 3, + knots: Optional[Sequence[ScalarLike]] = None, + multiplicities: Optional[Sequence[int]] = None, + weights: Optional[Sequence[ScalarLike]] = None, + periodic: bool = False, +) -> Edge: + """Create an exact B-spline edge from named control-point parameters. + + Pass sampled curve points through `fit_cubic_bspline_control_points(...)` first, + then pass the result fields explicitly as `control_points=...`, `knots=...`, + and `multiplicities=...`. `control_points` are poles, not interpolation + points; the curve generally does not pass through interior poles. + """ + try: + if isinstance(degree, bool) or int(degree) != degree: + raise ValueError("degree must be an integer") + degree_value = int(degree) + if degree_value < 1: + raise ValueError("degree must be at least 1") + if degree_value > 25: + raise ValueError("degree must be 25 or lower") + periodic_value = bool(periodic) + + local_control_points = _normalize_bspline_control_points(control_points) + if len(local_control_points) < degree_value + 1: + raise ValueError("control point count must be at least degree + 1") + resolved_knots, resolved_multiplicities = _normalize_bspline_knots( + control_count=len(local_control_points), + degree=degree_value, + periodic=periodic_value, + knots=knots, + multiplicities=multiplicities, + ) + resolved_weights = _normalize_bspline_weights( + weights, len(local_control_points) + ) + + cs = get_current_cs() + global_control_points = tuple( + tuple(float(component) for component in cs.transform_point(np.array(point))) + for point in local_control_points + ) + edge_shape = make_bspline_edge( + control_points=global_control_points, + degree=degree_value, + knots=resolved_knots, + multiplicities=resolved_multiplicities, + weights=resolved_weights, + periodic=periodic_value, + ) + edge = Edge(edge_shape) + edge.set_metadata( + "geo", + { + "type": "bspline", + "degree": degree_value, + "control_points": [list(point) for point in global_control_points], + "knots": list(resolved_knots), + "multiplicities": list(resolved_multiplicities), + "weights": ( + list(resolved_weights) if resolved_weights is not None else None + ), + "periodic": periodic_value, + }, + ) + + return cast( + Edge, + _finalize_primitive_shape( + edge, + op=_OP_MAKE_SPLINE_REDGE, + params={ + "control_points": control_points, + "degree": degree_value, + "knots": resolved_knots, + "multiplicities": resolved_multiplicities, + "weights": weights, + "periodic": periodic_value, + }, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_spline_redge", + what_happened="Failed to create a spline edge.", + possible_causes=[ + "The exact B-spline definition is inconsistent.", + "Control points, knots, multiplicities, or weights are invalid.", + "A sampled-point list was passed directly instead of fitted control points.", + ], + how_to_fix=[ + "Pass keyword arguments such as control_points=..., degree=3, knots=..., multiplicities=....", + "Use fit_cubic_bspline_control_points(sample_points) for sampled curves, then pass its result fields explicitly.", + "Ensure sum(multiplicities) matches the exact B-spline degree/control-count rule.", + ], + error=e, + ) + +def _normalize_interpolation_points( + points: Sequence[Sequence[ScalarLike]], + *, + periodic: bool, + tolerance: float, +) -> Tuple[Tuple[float, float, float], ...]: + normalized = list(_normalize_bspline_control_points(points)) + if periodic and len(normalized) >= 2: + if ( + np.linalg.norm(np.asarray(normalized[0]) - np.asarray(normalized[-1])) + <= tolerance + ): + normalized.pop() + minimum = 3 if periodic else 2 + if len(normalized) < minimum: + qualifier = "distinct" if periodic else "" + raise ValueError( + f"interpolation requires at least {minimum} {qualifier} points".replace( + " ", " " + ) + ) + adjacent_pairs = list(zip(normalized, normalized[1:])) + if periodic: + adjacent_pairs.append((normalized[-1], normalized[0])) + for index, (first, second) in enumerate(adjacent_pairs): + if np.linalg.norm(np.asarray(first) - np.asarray(second)) <= tolerance: + second_index = (index + 1) % len(normalized) + raise ValueError( + f"interpolation points {index} and {second_index} are within " + f"the interpolation tolerance" + ) + return tuple(normalized) + +def make_interpolated_spline_redge( + *, + points: Sequence[Sequence[ScalarLike]], + periodic: bool = False, + tolerance: ScalarLike = 1.0e-6, +) -> Edge: + """Interpolate an exact B-spline edge through the supplied points.""" + try: + periodic_value = bool(periodic) + tolerance_value = float(evaluate_scalar(tolerance)) + if not math.isfinite(tolerance_value) or tolerance_value <= 0.0: + raise ValueError("tolerance must be a finite positive value") + local_points = _normalize_interpolation_points( + points, + periodic=periodic_value, + tolerance=tolerance_value, + ) + cs = get_current_cs() + global_points = tuple( + tuple(float(component) for component in cs.transform_point(np.array(point))) + for point in local_points + ) + edge = Edge( + make_interpolated_bspline_edge( + global_points, + periodic=periodic_value, + tolerance=tolerance_value, + ) + ) + edge.set_metadata( + "geo", + { + "type": "bspline", + "construction": "interpolated", + "interpolation_points": [list(point) for point in global_points], + "periodic": periodic_value, + "tolerance": tolerance_value, + }, + ) + return cast( + Edge, + _finalize_primitive_shape( + edge, + op=_OP_MAKE_INTERPOLATED_SPLINE_REDGE, + params={ + "points": points, + "periodic": periodic_value, + "tolerance": tolerance, + }, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_interpolated_spline_redge", + what_happened="Failed to interpolate a B-spline edge through the input points.", + possible_causes=[ + "Too few distinct interpolation points were provided.", + "Consecutive points are duplicated or contain invalid coordinates.", + "The requested periodic interpolation is geometrically inconsistent.", + ], + how_to_fix=[ + "Provide at least two open-curve points or three periodic-curve points.", + "Remove consecutive duplicate points; a repeated periodic endpoint is optional.", + "Use a smaller positive tolerance when nearby points must remain distinct.", + ], + error=e, + ) + +def make_interpolated_spline_rwire( + *, + points: Sequence[Sequence[ScalarLike]], + periodic: bool = False, + tolerance: ScalarLike = 1.0e-6, +) -> Wire: + """Create a one-edge wire that interpolates the supplied points.""" + try: + edge_kwargs = { + "points": points, + "periodic": periodic, + "tolerance": tolerance, + } + if get_active_session() is not None: + edge = make_interpolated_spline_redge(**edge_kwargs) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_interpolated_spline_redge(**edge_kwargs) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_interpolated_spline_wire", + params=edge_kwargs, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_interpolated_spline_rwire", + what_happened="Failed to create an interpolated spline wire.", + possible_causes=[ + "The interpolated spline edge could not be created.", + "The kernel rejected the resulting one-edge wire.", + ], + how_to_fix=[ + "Validate the interpolation points and tolerance.", + "Use periodic=True for a closed profile and omit a duplicated final point.", + ], + error=e, + ) + +def make_periodic_spline_rwire( + *, + points: Sequence[Sequence[ScalarLike]], + tolerance: ScalarLike = 1.0e-6, +) -> Wire: + """Create a closed periodic spline wire interpolating the supplied points.""" + return make_interpolated_spline_rwire( + points=points, + periodic=True, + tolerance=tolerance, + ) + +def make_spline_rwire( + *, + control_points: Sequence[Sequence[ScalarLike]], + degree: int = 3, + knots: Optional[Sequence[ScalarLike]] = None, + multiplicities: Optional[Sequence[int]] = None, + weights: Optional[Sequence[ScalarLike]] = None, + periodic: bool = False, +) -> Wire: + """Create a wire containing one exact B-spline edge.""" + try: + edge_kwargs = { + "control_points": control_points, + "degree": degree, + "knots": knots, + "multiplicities": multiplicities, + "weights": weights, + "periodic": periodic, + } + if get_active_session() is not None: + edge = make_spline_redge(**edge_kwargs) + return make_wire_from_edges_rwire([edge]) + + with suspend_graph_recording(): + edge = make_spline_redge(**edge_kwargs) + wire_shape = make_wire_from_edges_ocp([edge.wrapped]) + rv = Wire(wire_shape) + return cast( + Wire, + _finalize_primitive_shape( + rv, + op="make_spline_wire", + params=edge_kwargs, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_spline_rwire", + what_happened="Failed to create a spline wire.", + possible_causes=[ + "The spline edge could not be created.", + "The exact B-spline definition is inconsistent.", + "The kernel rejected the resulting wire geometry.", + ], + how_to_fix=[ + "Validate the B-spline control points, degree, knots, multiplicities, and weights first.", + "For sampled curves, call fit_cubic_bspline_control_points(...) and pass the result fields explicitly.", + "Retry after inspecting the evaluated spline inputs.", + ], + error=e, + ) + +def make_polyline_rwire( + points: List[Tuple[ScalarLike, ScalarLike, ScalarLike]], closed: bool = False +) -> Wire: + """Create a polyline wire from a point list.""" + try: + if len(points) < 2: + raise ValueError("至少需要2个点") + + if get_active_session() is not None: + edges = [ + make_line_redge(points[idx], points[idx + 1]) + for idx in range(len(points) - 1) + ] + if closed and len(points) > 2: + edges.append(make_line_redge(points[-1], points[0])) + return make_wire_from_edges_rwire(edges) + + cs = get_current_cs() + + # 转换所有点到全局坐标系 + global_points = [] + for point in points: + point_value = cast(Tuple[float, float, float], evaluate_value(point)) + global_point = cs.transform_point(np.array(point_value)) + global_points.append(tuple(float(v) for v in global_point)) + + wire_shape = make_polyline_wire( + [ + (float(point[0]), float(point[1]), float(point[2])) + for point in global_points + ], + closed=closed, + ) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_polyline_wire", + params={"points": points, "closed": closed}, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_polyline_rwire", + what_happened="Failed to create a polyline wire.", + possible_causes=[ + "Fewer than two points were provided.", + "One or more points are invalid or non-finite.", + "The kernel rejected the resulting polyline geometry.", + ], + how_to_fix=[ + "Pass at least two finite 3D points.", + "If closed=True, ensure the sequence describes a valid loop.", + "Inspect the evaluated points before retrying.", + ], + error=e, + ) + +def make_helix_redge( + pitch: ScalarLike, + height: ScalarLike, + radius: ScalarLike, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Edge: + """Create a helix edge.""" + try: + pitch_value = evaluate_scalar(pitch) + height_value = evaluate_scalar(height) + radius_value = evaluate_scalar(radius) + if pitch_value <= 0: + raise ValueError("螺距必须大于0") + if height_value <= 0: + raise ValueError("高度必须大于0") + if radius_value <= 0: + raise ValueError("半径必须大于0") + + cs = get_current_cs() + center_value = cast(Tuple[float, float, float], evaluate_value(center)) + dir_value = cast(Tuple[float, float, float], evaluate_value(dir)) + global_center = cs.transform_point(np.array(center_value)) + global_dir = cs.transform_vector(np.array(dir_value)) + global_x_direction = cs.transform_vector(_default_plane_x_direction(dir_value)) + + wire_shape = make_helix_wire( + pitch_value, + height_value, + radius_value, + global_center, + global_dir, + x_direction=global_x_direction, + ) + wire = Wire(wire_shape) + edges = wire.get_edges() + if not edges: + raise ValueError("无法从螺旋线中提取边") + helix_edge = edges[0] + return cast( + Edge, + _finalize_primitive_shape( + helix_edge, + op=_OP_MAKE_HELIX_REDGE, + params={ + "pitch": pitch, + "height": height, + "radius": radius, + "center": center, + "dir": dir, + }, + tags={"primitive", "edge"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_helix_redge", + what_happened="Failed to create a helix edge.", + possible_causes=[ + "Pitch, height, or radius is not positive.", + "The center or direction vector is invalid.", + "The kernel rejected the helix definition.", + ], + how_to_fix=[ + "Use positive pitch, height, and radius values.", + "Pass a valid center and a non-zero direction vector.", + "Inspect the evaluated helix parameters before retrying.", + ], + error=e, + ) + +def make_helix_rwire( + pitch: float, + height: float, + radius: float, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Wire: + """Create a helix wire.""" + try: + if get_active_session() is not None: + edge = make_helix_redge(pitch, height, radius, center=center, dir=dir) + return make_wire_from_edges_rwire([edge]) + + cs = get_current_cs() + global_center = cs.transform_point(np.array(center)) + global_dir = cs.transform_vector(np.array(dir)) + global_x_direction = cs.transform_vector(_default_plane_x_direction(dir)) + + wire_shape = make_helix_wire( + pitch, + height, + radius, + global_center, + global_dir, + x_direction=global_x_direction, + ) + return cast( + Wire, + _finalize_primitive_shape( + Wire(wire_shape), + op="make_helix_wire", + params={ + "pitch": pitch, + "height": height, + "radius": radius, + "center": center, + "dir": dir, + }, + tags={"primitive", "wire"}, + ), + ) + except Exception as e: + _wrap_public_api_error( + operation="make_helix_rwire", + what_happened="Failed to create a helix wire.", + possible_causes=[ + "The helix parameters are invalid.", + "The direction vector is zero or malformed.", + "The kernel rejected the wire geometry.", + ], + how_to_fix=[ + "Use positive pitch, height, and radius values.", + "Pass a valid center and a non-zero direction vector.", + "Retry after logging the evaluated helix parameters.", + ], + error=e, + ) + +def extrude_rsolid( + profile: Union[Wire, Face], + direction: Tuple[float, float, float], + distance: ScalarLike, + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Create a solid by extruding a profile, with optional role-based tags.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_EXTRUDE_RSOLID, + ( + ("extrusion.start", start_face_tag), + ("extrusion.end", end_face_tag), + ("extrusion.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + distance_value = evaluate_scalar(distance) + if distance_value <= 0: + raise ValueError("拉伸距离必须大于0") + + cs = get_current_cs() + direction_value = cast(Tuple[float, float, float], evaluate_value(direction)) + global_direction = cs.transform_vector(np.array(direction_value)) + + direction_norm = float(np.linalg.norm(global_direction)) + if direction_norm <= 1e-15: + raise ValueError("拉伸方向不能是零向量") + direction_vec = tuple( + (global_direction / direction_norm * distance_value).tolist() + ) + + if isinstance(profile, Wire): + # 如果是线,先转换为面 + if profile.is_closed(): + face = Face(make_face_from_wire_ocp(profile.wrapped)) + else: + raise ValueError( + "如果传入线框作为拉伸对象,那么线框必须是闭合的, 而你的线框没有闭合,请检查构成线框的点是否正确" + ) + elif isinstance(profile, Face): + face = profile + else: + raise ValueError("只能拉伸线或面") # type: ignore[unreachable] + + resolved_direction = tuple(float(value) for value in global_direction) + tracked = cast( + TrackedResult, + tracked_extrude( + face, + resolved_direction, + distance_value, + ), + ) + solid = cast(Solid, tracked.shape) + + solid._apply_tag("solid.extrusion", propagate=False) + solid._metadata = profile._metadata.copy() + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op=_OP_MAKE_EXTRUDE_RSOLID, + params={ + "direction": direction, + "distance": distance, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[profile], + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_EXTRUDE_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_EXTRUDE_RSOLID, + delta=tracked.delta, + start_role="extrusion.start", + end_role="extrusion.end", + side_role="extrusion.side", + source_shapes=[profile], + ) + except Exception as e: + _wrap_public_api_error( + operation="extrude_rsolid", + what_happened="Failed to extrude the profile into a solid.", + possible_causes=[ + "The distance is not a positive finite scalar.", + "The direction vector is invalid.", + "A wire profile was provided but it is not closed.", + "The kernel rejected the profile or the extrusion direction.", + ], + how_to_fix=[ + "Use a distance greater than zero.", + "Pass a valid finite direction vector.", + "If you extrude a wire, make sure the wire is closed or convert it to a face first.", + "Inspect the evaluated profile and direction before retrying.", + ], + error=e, + ) + +def revolve_rsolid( + profile: Union[Wire, Face], + axis: Tuple[float, float, float] = (0, 0, 1), + angle: ScalarLike = 360, + origin: Tuple[float, float, float] = (0, 0, 0), + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Create a revolved solid, with optional kernel-role-based tags.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_REVOLVE_RSOLID, + ( + ("revolution.start", start_face_tag), + ("revolution.end", end_face_tag), + ("revolution.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + angle_value = evaluate_scalar(angle) + if angle_value <= 0: + raise ValueError("旋转角度必须大于0") + + cs = get_current_cs() + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) + global_axis = cs.transform_vector(np.array(axis_value)) + global_origin = cs.transform_point(np.array(origin_value)) + + # 获取轮廓对应的面 + if isinstance(profile, Wire): + # 如果是线,先转换为面 + if profile.is_closed(): + face = Face(make_face_from_wire_ocp(profile.wrapped)) + else: + raise ValueError("旋转的线必须是闭合的") + elif isinstance(profile, Face): + face = profile + else: + raise ValueError("只能旋转线或面") + + resolved_axis = tuple(float(value) for value in global_axis) + resolved_origin = tuple(float(value) for value in global_origin) + tracked = cast( + TrackedResult, + tracked_revolve( + face, + resolved_axis, + resolved_origin, + angle_value, + ), + ) + solid = cast(Solid, tracked.shape) + + solid._metadata = profile._metadata.copy() + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + solid, + op=_OP_MAKE_REVOLVE_RSOLID, + params={ + "axis": axis, + "angle": angle, + "origin": origin, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[profile], + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_REVOLVE_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_REVOLVE_RSOLID, + delta=tracked.delta, + start_role="revolution.start" if angle_value < 360.0 else None, + end_role="revolution.end" if angle_value < 360.0 else None, + side_role="revolution.side", + source_shapes=[profile], + ) + except Exception as e: + _wrap_public_api_error( + operation="revolve_rsolid", + what_happened="Failed to revolve the profile into a solid.", + possible_causes=[ + "The angle is not a positive finite scalar.", + "The axis or origin is invalid.", + "A wire profile was provided but it is not closed.", + "The kernel rejected the revolve definition.", + ], + how_to_fix=[ + "Use an angle greater than zero.", + "Pass a valid non-zero axis vector and a valid origin point.", + "If you revolve a wire, ensure it is closed or convert it to a face first.", + "Inspect the evaluated axis, origin, and profile before retrying.", + ], + error=e, + ) + +def _normalize_shape_input( + shapes: Union[AnyShape, Sequence[AnyShape]], +) -> List[AnyShape]: + """Normalize rendering input into a flat list of shapes.""" + + if isinstance(shapes, _EXPORTABLE_TYPES): + return [shapes] + + if isinstance(shapes, Sequence) and not isinstance(shapes, (str, bytes)): + normalized: List[AnyShape] = [] + for item in shapes: + normalized.extend(_normalize_shape_input(cast(AnyShape, item))) + return normalized + + raise ValueError( + "rendering accepts Compound, Solid, Shell, Face, Wire, Edge, Vertex, or nested sequences of those types" + ) + +def render_screenshot_rpath( + shapes: Union[Solid, Sequence[Solid]], + output_path: str, + highlight_tags: Optional[Sequence[str]] = None, + tag_labels: Optional[Dict[str, str]] = None, + image_size: Tuple[int, int] = (1400, 900), + view: Union[Tuple[float, float], str] = "auto", + show_axes: bool = True, + show_legend: bool = True, + zoom: float = 4.0, + show_callouts: bool = True, +) -> str: + """Render SDK solids through the shared OCCT/VTK BREP renderer.""" + try: + from .inspect.brep.render import _render_sdk_screenshot_rpath + + shape_list = _normalize_shape_input(shapes) + solids = [shape for shape in shape_list if isinstance(shape, Solid)] + if len(solids) != len(shape_list) or not solids: + raise ValueError("render_screenshot_rpath only supports Solid inputs") + return str( + _render_sdk_screenshot_rpath( + solids, + output_path, + highlight_tags=tuple(highlight_tags or ()), + tag_labels=tag_labels, + image_size=image_size, + view=view, + show_axes=show_axes, + show_legend=show_legend, + zoom=zoom, + show_callouts=show_callouts, + ) + ) + except Exception as e: + _wrap_public_api_error( + operation="render_screenshot_rpath", + what_happened="Failed to render the screenshot.", + possible_causes=[ + "The input does not contain any valid Solid objects.", + "The rendering view or zoom configuration is invalid.", + "The output path is invalid or not writable.", + ], + how_to_fix=[ + "Pass a Solid or a sequence of Solid objects.", + "Use a supported view preset or a valid (elev, azim) tuple.", + "Check that the output path is writable.", + ], + error=e, + ) + +def fillet_rsolid( + solid: Solid, + edges: Union[Sequence[Edge], ShapeSelector], + radius: ScalarLike, + *, + result_tag: Optional[str] = None, + generated_faces_tag: Optional[str] = None, +) -> Solid: + """Apply fillets, with optional tagging of kernel-proven patch faces.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_FILLET_RSOLID, + (("fillet.patch", generated_faces_tag),), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + radius_value = evaluate_scalar(radius) + if radius_value <= 0: + raise ValueError("圆角半径必须大于0") + + selected_edges = cast(List[Edge], _resolve_selector_or_shapes(solid, edges)) + if not selected_edges: + raise ValueError("圆角操作至少需要一条边") + + tracked = cast( + TrackedResult, + tracked_fillet(solid, selected_edges, radius_value), + ) + result = cast(Solid, tracked.shape) + + result._metadata = solid._metadata.copy() + + selected_edge_refs = _serialize_shape_refs(selected_edges) + selected_edge_node_ids = _ensure_geo_selection_node_ids(solid, selected_edges) + + selection_params: Dict[str, object] = { + "radius": radius, + "edge_count": len(selected_edges), + "selected_edges": selected_edge_refs, + } + if selected_edge_node_ids: + selection_params["selected_edge_node_ids"] = selected_edge_node_ids + else: + selection_params["selected_edge_indices"] = _serialize_selection_indices( + selected_edges, solid.get_edges() + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_FILLET_RSOLID, + params=selection_params, + source_solid=solid, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[solid, *selected_edges], + ) + return _apply_operation_role_tags( + finalized, + op=_OP_MAKE_FILLET_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + except Exception as e: + _wrap_public_api_error( + operation="fillet_rsolid", + what_happened="Failed to apply the fillet operation.", + possible_causes=[ + "The radius is not a positive finite scalar.", + "No valid edges were selected.", + "The selected edges are incompatible with the requested fillet radius.", + ], + how_to_fix=[ + "Use a positive fillet radius.", + "Select at least one valid edge or use a selector that resolves to edges.", + "If the kernel rejects the fillet, try a smaller radius or a simpler edge set.", + ], + error=e, + ) + +def chamfer_rsolid( + solid: Solid, + edges: Union[Sequence[Edge], ShapeSelector], + distance: ScalarLike, + *, + result_tag: Optional[str] = None, + generated_faces_tag: Optional[str] = None, +) -> Solid: + """Apply chamfers, with optional tagging of kernel-proven patch faces.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_CHAMFER_RSOLID, + (("chamfer.patch", generated_faces_tag),), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + distance_value = evaluate_scalar(distance) + if distance_value <= 0: + raise ValueError("倒角距离必须大于0") + + selected_edges = cast(List[Edge], _resolve_selector_or_shapes(solid, edges)) + if not selected_edges: + raise ValueError("倒角操作至少需要一条边") + + tracked = cast( + TrackedResult, + tracked_chamfer(solid, selected_edges, distance_value), + ) + result = cast(Solid, tracked.shape) + + result._metadata = solid._metadata.copy() + + selected_edge_refs = _serialize_shape_refs(selected_edges) + selected_edge_node_ids = _ensure_geo_selection_node_ids(solid, selected_edges) + + selection_params: Dict[str, object] = { + "distance": distance, + "edge_count": len(selected_edges), + "selected_edges": selected_edge_refs, + } + if selected_edge_node_ids: + selection_params["selected_edge_node_ids"] = selected_edge_node_ids + else: + selection_params["selected_edge_indices"] = _serialize_selection_indices( + selected_edges, solid.get_edges() + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_CHAMFER_RSOLID, + params=selection_params, + source_solid=solid, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[solid, *selected_edges], + ) + return _apply_operation_role_tags( + finalized, + op=_OP_MAKE_CHAMFER_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + except Exception as e: + _wrap_public_api_error( + operation="chamfer_rsolid", + what_happened="Failed to apply the chamfer operation.", + possible_causes=[ + "The distance is not a positive finite scalar.", + "No valid edges were selected.", + "The selected edges are incompatible with the requested chamfer size.", + ], + how_to_fix=[ + "Use a positive chamfer distance.", + "Select at least one valid edge or use a selector that resolves to edges.", + "If the kernel rejects the chamfer, try a smaller distance or fewer edges.", + ], + error=e, + ) + +def shell_rsolid( + solid: Solid, + faces_to_remove: Union[Sequence[Face], ShapeSelector], + thickness: ScalarLike, + *, + result_tag: Optional[str] = None, + body_faces_tag: Optional[str] = None, + offset_faces_tag: Optional[str] = None, + closing_faces_tag: Optional[str] = None, + wall_edges_tag: Optional[str] = None, +) -> Solid: + """Shell a solid, with optional kernel-role-based face tags.""" + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_SHELL_RSOLID, + ( + ("shell.body_face", body_faces_tag), + ("shell.offset_face", offset_faces_tag), + ("shell.closing_descendant", closing_faces_tag), + ("shell.wall", wall_edges_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + thickness_value = evaluate_scalar(thickness) + if thickness_value <= 0: + raise ValueError("壁厚必须大于0") + + selected_faces = cast( + List[Face], _resolve_selector_or_shapes(solid, faces_to_remove) + ) + if not selected_faces: + raise ValueError("抽壳操作至少需要一个待移除面") + + tracked = cast( + TrackedResult, + tracked_shell(solid, selected_faces, thickness_value), + ) + result = cast(Solid, tracked.shape) + + result._metadata = solid._metadata.copy() + + selected_face_refs = _serialize_shape_refs(selected_faces) + selected_face_node_ids = _ensure_geo_selection_node_ids(solid, selected_faces) + + selection_params: Dict[str, object] = { + "thickness": thickness, + "removed_face_count": len(selected_faces), + "selected_faces": selected_face_refs, + } + if selected_face_node_ids: + selection_params["selected_face_node_ids"] = selected_face_node_ids + else: + selection_params["selected_face_indices"] = _serialize_selection_indices( + selected_faces, solid.get_faces() + ) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_SHELL_RSOLID, + params=selection_params, + source_solid=solid, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[solid, *selected_faces], + ) + return _apply_operation_role_tags( + finalized, + op=_OP_MAKE_SHELL_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + except Exception as e: + _wrap_public_api_error( + operation="shell_rsolid", + what_happened="Failed to apply the shell operation.", + possible_causes=[ + "The thickness is not a positive finite scalar.", + "No valid faces were selected for removal.", + "The requested shell thickness is incompatible with the current solid.", + ], + how_to_fix=[ + "Use a positive shell thickness.", + "Select at least one valid face to remove.", + "If the shell fails, try a smaller thickness or a different face selection.", + ], + error=e, + ) + +def loft_rsolid( + profiles: Sequence[Union[Wire, Vertex]], + ruled: bool = False, + *, + tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Create a lofted solid, with optional kernel-role-based tags.""" + try: + profile_list = _validated_loft_sections(profiles, operation="loft_rsolid") + if start_face_tag is not None and isinstance(profile_list[0], Vertex): + raise ValueError("start_face_tag requires a Wire start section") + if end_face_tag is not None and isinstance(profile_list[-1], Vertex): + raise ValueError("end_face_tag requires a Wire end section") + policy = ( + TrackingPolicy.GRAPH + if current_tracking_policy() == TrackingPolicy.GRAPH + else TrackingPolicy(tracking_policy) + ) + assignments = _normalize_operation_role_tags( + _OP_MAKE_LOFT_RSOLID, + ( + ("loft.start", start_face_tag), + ("loft.end", end_face_tag), + ("loft.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + profiles = profile_list + + if policy == TrackingPolicy.GRAPH and (assignments or tag_prefix is not None): + raise ValueError( + "GRAPH tracking does not provide loft face-role evidence; " + "use FULL tracking for tag_prefix, start_face_tag, end_face_tag, " + "or side_faces_tag" + ) + + tracked = ( + cast( + TrackedResult, + tracked_loft(profiles, ruled=ruled), + ) + if policy == TrackingPolicy.FULL + else None + ) + result = ( + cast(Solid, tracked.shape) + if tracked is not None + else Solid( + make_loft_solid((profile.wrapped for profile in profiles), ruled=ruled) + ) + ) + + all_metadata = {} + for profile in profiles: + all_metadata.update(profile._metadata) + + result._metadata = all_metadata + + params: Dict[str, object] = { + "profile_count": len(profiles), + "ruled": ruled, + "tracking_policy": policy.value, + } + if tracked is not None: + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_LOFT_RSOLID, + params=params, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=profiles, + ) + else: + target_kinds = {} + finalized = cast( + Solid, + _finalize_derived_shape( + result, + op=_OP_MAKE_LOFT_RSOLID, + params=params, + input_shapes=profiles, + ), + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_LOFT_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + if tracked is None: + return tagged + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_LOFT_RSOLID, + delta=tracked.delta, + start_role=("loft.start" if isinstance(profiles[0], Wire) else None), + end_role=("loft.end" if isinstance(profiles[-1], Wire) else None), + side_role="loft.side", + source_shapes=profiles, + ) + except Exception as e: + _wrap_public_api_error( + operation="loft_rsolid", + what_happened="Failed to loft the input profiles into a solid.", + possible_causes=[ + "Fewer than two sections were provided.", + "A Vertex section was used away from the start or end.", + "One or more Wire/Vertex sections are invalid or incompatible.", + "The kernel rejected the loft because the section geometry is inconsistent.", + ], + how_to_fix=[ + "Pass at least two Wire or endpoint Vertex sections.", + "Keep Wire topology compatible across sections.", + "If loft fails, inspect each section individually and simplify its geometry.", + ], + error=e, + ) + +def sweep_rsolid( + profile: Face, + path: Wire, + is_frenet: bool = False, + *, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Create a swept solid, with optional kernel-role-based tags.""" + make_solid = True # 默认创建实体 + try: + assignments = _normalize_operation_role_tags( + _OP_MAKE_SWEEP_RSOLID, + ( + ("sweep.start", start_face_tag), + ("sweep.end", end_face_tag), + ("sweep.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + tracked = cast( + TrackedResult, + tracked_sweep(profile, path, is_frenet=is_frenet), + ) + result = cast(Solid, tracked.shape) + + result._metadata = {**profile._metadata, **path._metadata} + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_SWEEP_RSOLID, + params={"is_frenet": bool(is_frenet)}, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[profile, path], + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_SWEEP_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_SWEEP_RSOLID, + delta=tracked.delta, + start_role="sweep.start", + end_role="sweep.end", + side_role="sweep.side", + source_shapes=[profile], + ) + except Exception as e: + _wrap_public_api_error( + operation="sweep_rsolid", + what_happened="Failed to sweep the profile along the path.", + possible_causes=[ + "The profile face is invalid.", + "The path wire is invalid or unsuitable for sweep.", + "The kernel rejected the sweep orientation or geometry.", + ], + how_to_fix=[ + "Pass a valid Face profile and a valid Wire path.", + "Check that the path wire is continuous and geometrically reasonable.", + "If sweep fails, simplify the profile or path before retrying.", + ], + error=e, + ) + +def twisted_sweep_rsolid( + profile: Face, + distance: ScalarLike, + twist_angle: ScalarLike, + axis: Tuple[float, float, float] = (0.0, 0.0, 1.0), + origin: Tuple[float, float, float] = (0.0, 0.0, 0.0), + *, + guide_radius: ScalarLike = 1.0, + tag_prefix: Optional[str] = None, + result_tag: Optional[str] = None, + start_face_tag: Optional[str] = None, + end_face_tag: Optional[str] = None, + side_faces_tag: Optional[str] = None, +) -> Solid: + """Sweep a planar profile along a straight axis with linear rotation. + + ``twist_angle`` is the signed total rotation in degrees. The operation uses + a cylindrical auxiliary spine to define a continuous rotation law, yielding + one continuous side face per profile edge instead of a segmented ruled loft. + """ + try: + if not isinstance(profile, Face): + raise TypeError("profile must be a Face") + distance_value = float(evaluate_scalar(distance)) + twist_value = float(evaluate_scalar(twist_angle)) + guide_radius_value = float(evaluate_scalar(guide_radius)) + if not math.isfinite(distance_value) or distance_value <= 0.0: + raise ValueError("distance must be a finite positive number") + if not math.isfinite(twist_value): + raise ValueError("twist_angle must be finite") + if not math.isfinite(guide_radius_value) or guide_radius_value <= 0.0: + raise ValueError("guide_radius must be a finite positive number") + + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) + if len(axis_value) != 3 or len(origin_value) != 3: + raise ValueError("axis and origin must each contain three values") + cs = get_current_cs() + global_axis = cs.transform_vector(np.asarray(axis_value, dtype=float)) + global_origin = cs.transform_point(np.asarray(origin_value, dtype=float)) + axis_norm = float(np.linalg.norm(global_axis)) + if not math.isfinite(axis_norm) or axis_norm <= 1.0e-15: + raise ValueError("axis must be a finite non-zero vector") + global_axis /= axis_norm + resolved_axis = tuple(float(value) for value in global_axis) + resolved_origin = tuple(float(value) for value in global_origin) + + assignments = _normalize_operation_role_tags( + _OP_MAKE_TWISTED_SWEEP_RSOLID, + ( + ("twisted_sweep.start", start_face_tag), + ("twisted_sweep.end", end_face_tag), + ("twisted_sweep.side", side_faces_tag), + ), + ) + normalized_result_tag = ( + normalize_tag(result_tag, strict=True) if result_tag is not None else None + ) + tracked = cast( + TrackedResult, + tracked_twisted_sweep( + profile, + axis=resolved_axis, + origin=resolved_origin, + distance=distance_value, + twist_angle=twist_value, + guide_radius=guide_radius_value, + ), + ) + result = cast(Solid, tracked.shape) + kernel_metadata = result.get_metadata("twisted_sweep.kernel", {}) + result._metadata = profile._metadata.copy() + result.set_metadata("twisted_sweep.kernel", kernel_metadata) + + target_kinds = _validate_operation_output_roles(tracked.delta, assignments) + finalized = _finalize_tracked_solid( + result, + op=_OP_MAKE_TWISTED_SWEEP_RSOLID, + params={ + "axis": axis, + "origin": origin, + "distance": distance, + "twist_angle": twist_angle, + "guide_radius": guide_radius, + }, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[profile], + ) + tagged = _apply_operation_role_tags( + finalized, + op=_OP_MAKE_TWISTED_SWEEP_RSOLID, + assignments=assignments, + target_kinds=target_kinds, + result_tag=normalized_result_tag, + ) + return _apply_feature_tag_prefix( + tagged, + tag_prefix=tag_prefix, + op=_OP_MAKE_TWISTED_SWEEP_RSOLID, + delta=tracked.delta, + start_role="twisted_sweep.start", + end_role="twisted_sweep.end", + side_role="twisted_sweep.side", + source_shapes=[profile], + ) + except Exception as e: + _wrap_public_api_error( + operation="twisted_sweep_rsolid", + what_happened="Failed to sweep the profile with a linear axial rotation.", + possible_causes=[ + "The profile is invalid or contains inner wires.", + "The distance, twist angle, axis, or guide radius is invalid.", + "The requested twist causes self-intersection or kernel failure.", + ], + how_to_fix=[ + "Pass a valid planar Face without inner wires.", + "Use a positive distance and guide radius with a non-zero axis.", + "Reduce the twist angle or simplify the profile.", + ], + error=e, + ) + +def helical_sweep_rsolid( + profile: Wire, + pitch: float, + height: float, + radius: float, + center: Tuple[float, float, float] = (0, 0, 0), + dir: Tuple[float, float, float] = (0, 0, 1), +) -> Solid: + """Create a solid by sweeping a profile along a helical path.""" + try: + if get_active_session() is not None: + helix = make_helix_rwire(pitch, height, radius, center=center, dir=dir) + return sweep_rsolid( + make_face_from_wire_rface(profile), helix, is_frenet=True + ) + + if pitch <= 0: + raise ValueError("螺距必须大于0") + if height <= 0: + raise ValueError("高度必须大于0") + if radius <= 0: + raise ValueError("半径必须大于0") + + cs = get_current_cs() + global_center = cs.transform_point(np.array(center)) + global_dir = cs.transform_vector(np.array(dir)) + global_x_direction = cs.transform_vector(_default_plane_x_direction(dir)) + + result_shape = make_helical_sweep_solid( + profile.wrapped, + pitch, + height, + radius, + global_center, + global_dir, + x_direction=global_x_direction, + ) + result = Solid(result_shape) + + result._metadata = profile._metadata.copy() + result._apply_tag("solid.feature.helical_sweep", propagate=False) + + return result + except Exception as e: + _wrap_public_api_error( + operation="helical_sweep_rsolid", + what_happened="Failed to create the helical sweep solid.", + possible_causes=[ + "Pitch, height, or radius is not positive.", + "The input profile wire is invalid or cannot form a face.", + "The center or direction vector is invalid.", + "The underlying helix or sweep construction failed.", + ], + how_to_fix=[ + "Use positive pitch, height, and radius values.", + "Pass a valid profile wire that can be turned into a face.", + "Validate the center and direction inputs before retrying.", + "If the sweep still fails, try the explicit macro path: helix wire -> face from profile -> sweep.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/operations.py b/src/simplecadapi/operations.py index 562f1a12..125a29b4 100644 --- a/src/simplecadapi/operations.py +++ b/src/simplecadapi/operations.py @@ -1,10636 +1,62 @@ -"""SimpleCAD API operation implementations based on the README design.""" +"""Compatibility facade for the SimpleCAD operator implementation modules. -from __future__ import annotations +Public callers should continue importing through ``simplecadapi`` or this module. +Assignments to facade symbols are mirrored into implementation modules so +existing monkeypatch-based integrations keep observing the executed binding. +""" -import re -import uuid -from pathlib import Path -from typing import ( - Any, - Callable, - Dict, - List, - Mapping, - Optional, - Sequence, - Set, - Tuple, - Union, - cast, +import sys as _sys +from types import ModuleType as _ModuleType + +from . import _operation_support as _support +from . import _operators_boolean as _boolean +from . import _operators_features as _features +from . import _operators_geometry as _geometry +from . import _operators_product as _product +from . import _operators_selection as _selection +from . import _operators_sketch as _sketch +from . import _operators_transform as _transform +from ._operation_support import * +from ._operators_geometry import * +from ._operators_transform import * +from ._operators_boolean import * +from ._operators_product import * +from ._operators_sketch import * +from ._operators_selection import * +from ._operators_features import * + +_IMPLEMENTATION_MODULES = ( + _support, + _geometry, + _transform, + _boolean, + _product, + _sketch, + _selection, + _features, ) -from dataclasses import dataclass, asdict -import math -import numpy as np -from ._vendor_warning_filters import suppress_vendor_deprecation_warnings -from .errors import SimpleCADError, raise_harness_error - -suppress_vendor_deprecation_warnings() - -from OCP.BRepCheck import BRepCheck_Analyzer -from OCP.BRepBuilderAPI import BRepBuilderAPI_MakeVertex -from OCP.Precision import Precision -from OCP.gp import gp_Ax2, gp_Dir, gp_Pnt -from OCP.TopoDS import TopoDS - -from .core import ( - Vertex, - Edge, - Wire, - Face, - Shell, - Solid, - Compound, - AnyShape, - WORLD_CS, - clone_semantic_shape_view, - _same_semantic_topology, - get_current_cs, - use_coordinate_system, -) -from .autotag import apply_tracking_tags_to_delta -from .expr import ScalarLike, evaluate_scalar, evaluate_value -from .units import DIMENSIONLESS, LENGTH, expression_uses_units, infer_dimension -from .graph import ( - attach_graph_node, - attach_semantic_graph_node, - get_active_session, - record_operation, - record_operation_if_active, - suspend_graph_recording, -) -from .ql import ShapeSelector, output_role -from .assembly import Assembly, Component -from .assembly_solver import ( - coupling_phase_offset, - inspect_assembly_constraints, - measure_constraint_residual, - solve_assembly_constraints, -) -from .connector import Connector, ConnectorAnchor, ConnectorRef, GeometryRef -from .constraint import Constraint, ConstraintReport, ConstraintResidual, ScalarLimit -from .material import Material -from .part import Part -from .placement import Placement, compose_placements, identity_placement -from .sketch import Sketch, SketchRef, SketchSolveResult -from .tagging import ( - LineagePolicy, - SemanticCapabilityError, - TagBinding, - TagBindingScope, - TagCertainty, - TagEvidence, - TagLifecycle, - TagProducer, - TagProducerKind, - TagPropagation, - TagScope, - TagTarget, - TagTargetKind, - TagEvidenceKind, - TopologyPropagation, - lineage_policy_allows, - normalize_tag, - normalize_tag_scope, -) -from .topology import ( - SemanticDelta, - SemanticRef, - TopoDelta, - TopoRoleEntry, - TopoEntry, - TopoKind, - TopoRef, - topo_ref_to_dict, -) -from .tracking import ( - TrackingPolicy, - TrackedBooleanResult, - TrackedResult, - _topo_id, - current_tracking_policy, - tracked_box, - tracked_chamfer, - tracked_cone, - tracked_cylinder, - tracked_cut, - tracked_extrude, - tracked_fillet, - tracked_intersect, - tracked_mirror, - tracked_loft, - tracked_revolve, - tracked_rotate, - tracked_shell, - tracked_sweep, - tracked_twisted_sweep, - tracked_translate, - track_union_history, -) -from .kernel.ocp_builders import ( - make_sphere_solid, -) -from ._brep_region import read_artifact -from .kernel.ocp_curves import ( - make_arc_angle_edge, - make_arc_three_point_edge, - make_bspline_edge, - make_circle_edge, - make_helix_wire, - make_interpolated_bspline_edge, - make_line_edge, - make_polyline_wire, - make_wire_from_edges as make_wire_from_edges_ocp, -) -from .kernel.ocp_features import ( - make_face_from_wire as make_face_from_wire_ocp, - make_face_from_wires as make_face_from_wires_ocp, - make_helical_sweep_solid, - make_loft_solid, - make_sweep_solid, -) -from .kernel.ocp_transforms import ( - mirror_shape_ocp, - rotate_shape_ocp, - place_shape_ocp, - translate_shape_ocp, -) -from .kernel.ocp_booleans import ( - common_shapes, - cut_shapes, - fuse_shapes, - fuse_shapes_with_history, - solids_of, -) -from .kernel.ocp_topology import faces_of as faces_of_ocp -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, - free_boundaries as free_boundaries_ocp, - make_bezier_surface, - make_cylindrical_surface, - make_filling_face, - make_gordon_surface, - make_loft_shell, - make_ruled_face, - sew_faces_with_history as sew_faces_with_history_ocp, - shell_from_face, - trim_surface_face, -) -from .kernel.ocp_mesh import solid_from_shell - - -@dataclass(frozen=True) -class SurfaceBoundary: - """One edge constraint used by ``make_surface_patch_rface``.""" - - edge: Edge - continuity: str = "C0" - support: Optional[Face] = None - - def __post_init__(self) -> None: - if not isinstance(self.edge, Edge): - raise TypeError("SurfaceBoundary.edge must be an Edge") - if self.support is not None and not isinstance(self.support, Face): - raise TypeError("SurfaceBoundary.support must be a Face or None") - if str(self.continuity).upper() not in {"C0", "G1", "G2"}: - raise ValueError("SurfaceBoundary.continuity must be C0, G1, or G2") - - def as_dict(self) -> Dict[str, object]: - return { - "continuity": str(self.continuity).upper(), - "has_support": self.support is not None, - } - - -@dataclass(frozen=True) -class SurfaceFillingSettings: - """Explicit OCCT filling controls; units are model units and radians.""" - - degree: int = 3 - points_per_curve: int = 15 - iterations: int = 2 - anisotropic: bool = False - tolerance_2d: float = 1e-5 - tolerance_3d: float = 1e-4 - angular_tolerance: float = 0.01 - curvature_tolerance: float = 0.1 - max_degree: int = 8 - max_segments: int = 9 - - def __post_init__(self) -> None: - if self.degree < 1 or self.points_per_curve < 2 or self.iterations < 1: - raise ValueError( - "filling degree, points_per_curve, and iterations must be positive" - ) - if self.max_degree < self.degree or self.max_segments < 1: - raise ValueError( - "max_degree must cover degree and max_segments must be positive" - ) - for name in ( - "tolerance_2d", - "tolerance_3d", - "angular_tolerance", - "curvature_tolerance", - ): - value = float(getattr(self, name)) - if not np.isfinite(value) or value <= 0: - raise ValueError(f"{name} must be a positive finite value") - - def as_dict(self) -> Dict[str, object]: - return cast(Dict[str, object], asdict(self)) - - -def _surface_tag_output(shape: AnyShape, tag_prefix: Optional[str]) -> AnyShape: - if tag_prefix is None: - return shape - normalized = normalize_tag(tag_prefix, strict=True) - shape._apply_tag(f"{normalized}.{_shape_kind_token(shape)}", propagate=False) - return shape - - -def _surface_point_grid( - points: Sequence[Sequence[Sequence[float]]], -) -> List[List[Tuple[float, float, float]]]: - rows = [ - [tuple(float(component) for component in point) for point in row] - for row in points - ] - if len(rows) < 2 or any(len(row) < 2 for row in rows): - raise ValueError("surface point grids require at least 2 rows and 2 columns") - width = len(rows[0]) - if any(len(row) != width for row in rows): - raise ValueError("surface point grids must be rectangular") - if any(len(point) != 3 for row in rows for point in row): - raise ValueError("surface points must contain exactly three coordinates") - if not all(np.isfinite(value) for row in rows for point in row for value in point): - raise ValueError("surface points must be finite") - return rows - - -def _surface_global_point_grid( - points: Sequence[Sequence[Sequence[float]]], -) -> List[List[Tuple[float, float, float]]]: - cs = get_current_cs() - grid = _surface_point_grid(points) - return [ - [ - tuple(float(value) for value in cs.transform_point(np.asarray(point))) - for point in row - ] - for row in grid - ] - - -def _surface_global_points( - points: Sequence[Sequence[float]], -) -> List[Tuple[float, float, float]]: - cs = get_current_cs() - result = [] - for point in points: - values = tuple(float(value) for value in point) - if len(values) != 3 or not all(np.isfinite(value) for value in values): - raise ValueError("surface constraint points must be finite 3D points") - result.append( - tuple(float(value) for value in cs.transform_point(np.asarray(values))) - ) - return result - - -def _surface_local_point_grid( - points: Sequence[Sequence[Sequence[float]]], -) -> List[List[Tuple[float, float, float]]]: - return _surface_point_grid(points) - - -def make_bezier_surface_rface( - control_points: Sequence[Sequence[Sequence[float]]], - weights: Optional[Sequence[Sequence[float]]] = None, - *, - tag_prefix: Optional[str] = None, -) -> Face: - """Create a trimmed Face carrying a tensor-product Bezier surface.""" - try: - local_points = _surface_local_point_grid(control_points) - global_points = _surface_global_point_grid(local_points) - global_weights = ( - None if weights is None else [list(map(float, row)) for row in weights] - ) - if global_weights is not None: - if len(global_weights) != len(local_points) or any( - len(row) != len(local_points[0]) for row in global_weights - ): - raise ValueError("Bezier weights must match the control-point grid") - if any( - weight <= 0 or not np.isfinite(weight) - for row in global_weights - for weight in row - ): - raise ValueError("Bezier weights must be positive finite values") - result = Face(make_bezier_surface(global_points, global_weights)) - result = cast( - Face, - _finalize_primitive_shape( - result, - op="make_bezier_surface_rface", - params={ - "control_points": local_points, - "weights": global_weights, - "tag_prefix": tag_prefix, - }, - tags={"primitive", "surface", "face"}, - ), - ) - return cast(Face, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="make_bezier_surface_rface", - what_happened="Failed to create the Bezier surface face.", - possible_causes=[ - "The control-point grid is invalid or degenerate.", - "The kernel rejected the Bezier surface.", - ], - how_to_fix=[ - "Pass a rectangular finite grid with at least two rows and columns.", - "Use positive finite weights with the same dimensions as the grid.", - ], - error=e, - ) - - -def make_cylindrical_surface_rface( - radius: ScalarLike, - u_range: Tuple[ScalarLike, ScalarLike], - v_range: Tuple[ScalarLike, ScalarLike], - origin: Tuple[float, float, float] = (0, 0, 0), - axis: Tuple[float, float, float] = (0, 0, 1), - x_direction: Optional[Tuple[float, float, float]] = None, - *, - tolerance: ScalarLike = 1e-7, - tag_prefix: Optional[str] = None, -) -> Face: - """Create a finite cylindrical carrier Face over explicit U/V ranges. - - ``radius``, V values, and ``tolerance`` use model length units. U values - are unitless raw radians, must increase, and may span at most one - revolution. Unit-aware angle expressions are not accepted for U because - the existing expression evaluator returns canonical angles in degrees. - """ - - try: - if expression_uses_units(radius) and infer_dimension(radius) != LENGTH: - raise ValueError("radius must use model length units") - if any( - expression_uses_units(value) and infer_dimension(value) != DIMENSIONLESS - for value in u_range - ): - raise ValueError( - "u_range must use unitless raw radians; unit-aware angle values " - "evaluate in degrees" - ) - if any( - expression_uses_units(value) and infer_dimension(value) != LENGTH - for value in v_range - ): - raise ValueError("v_range must use model length units") - if expression_uses_units(tolerance) and infer_dimension(tolerance) != LENGTH: - raise ValueError("tolerance must use model length units") - radius_value = evaluate_scalar(radius) - u_values = tuple(evaluate_scalar(value) for value in u_range) - v_values = tuple(evaluate_scalar(value) for value in v_range) - tolerance_value = float(evaluate_scalar(tolerance)) - if not np.isfinite(radius_value) or radius_value <= 0.0: - raise ValueError("radius must be a positive finite value") - if len(u_values) != 2 or not all(np.isfinite(value) for value in u_values): - raise ValueError("u_range must contain two finite values") - if len(v_values) != 2 or not all(np.isfinite(value) for value in v_values): - raise ValueError("v_range must contain two finite values") - u_span = u_values[1] - u_values[0] - v_span = v_values[1] - v_values[0] - if ( - u_span <= Precision.PConfusion_s() - or u_span > 2.0 * math.pi + Precision.Angular_s() - ): - raise ValueError( - "u_range must be increasing and span at most one revolution" - ) - if v_span <= Precision.Confusion_s(): - raise ValueError("v_range must be increasing beyond kernel confusion") - if not np.isfinite(tolerance_value) or tolerance_value <= 0.0: - raise ValueError("tolerance must be a positive finite value") - - origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) - axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) - x_value = ( - tuple(float(value) for value in _default_plane_x_direction(axis_value)) - if x_direction is None - else cast(Tuple[float, float, float], evaluate_value(x_direction)) - ) - vectors = [ - tuple(float(value) for value in item) - for item in (origin_value, axis_value, x_value) - ] - if any( - len(item) != 3 or not all(np.isfinite(value) for value in item) - for item in vectors - ): - raise ValueError("origin, axis, and x_direction must be finite 3D values") - axis_norm = float(np.linalg.norm(vectors[1])) - x_norm = float(np.linalg.norm(vectors[2])) - if axis_norm <= 1e-12 or x_norm <= 1e-12: - raise ValueError("axis and x_direction must be non-zero") - parallel = abs(float(np.dot(vectors[1], vectors[2])) / (axis_norm * x_norm)) - if parallel >= 1.0 - 1e-12: - raise ValueError("axis and x_direction must not be parallel") - - cs = get_current_cs() - global_origin = cs.transform_point(np.asarray(vectors[0], dtype=float)) - global_axis = cs.transform_vector(np.asarray(vectors[1], dtype=float)) - global_x_direction = cs.transform_vector(np.asarray(vectors[2], dtype=float)) - result = cast( - Face, - _finalize_primitive_shape( - Face( - make_cylindrical_surface( - radius_value, - cast(Tuple[float, float], u_values), - cast(Tuple[float, float], v_values), - origin=global_origin, - axis=global_axis, - x_direction=global_x_direction, - tolerance=tolerance_value, - ) - ), - op="make_cylindrical_surface_rface", - params={ - "radius": radius, - "u_range": u_range, - "v_range": v_range, - "origin": origin, - "axis": axis, - "x_direction": x_direction, - "tolerance": tolerance, - "tag_prefix": tag_prefix, - }, - tags={"primitive", "surface", "face"}, - ), - ) - return cast(Face, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="make_cylindrical_surface_rface", - what_happened="Failed to create the cylindrical surface face.", - possible_causes=[ - "The radius, U/V ranges, or tolerance is invalid.", - "The axis frame is degenerate or parallel.", - "The kernel rejected the bounded cylindrical surface.", - ], - how_to_fix=[ - "Use model length units for radius, V, and tolerance.", - "Pass increasing finite U bounds as unitless raw radians.", - "Keep the U span at or below one revolution and provide non-parallel axis directions.", - ], - error=e, - ) - - -def fit_point_grid_rface( - points: Sequence[Sequence[Sequence[float]]], - *, - tolerance: float = 1e-3, - degree_min: int = 3, - degree_max: int = 8, - smoothing: Optional[Tuple[float, float, float]] = None, - tag_prefix: Optional[str] = None, -) -> Face: - """Fit a B-spline Face through a rectangular 3D point grid.""" - try: - tolerance_value = float(tolerance) - if not np.isfinite(tolerance_value) or tolerance_value <= 0: - raise ValueError("tolerance must be a positive finite value") - degree_min_value, degree_max_value = int(degree_min), int(degree_max) - if degree_min_value < 1 or degree_max_value < degree_min_value: - raise ValueError("degree_max must be greater than or equal to degree_min") - smoothing_values = ( - None if smoothing is None else tuple(float(v) for v in smoothing) - ) - if smoothing_values is not None and ( - len(smoothing_values) != 3 - or any(not np.isfinite(v) or v < 0 for v in smoothing_values) - ): - raise ValueError("smoothing must contain three finite non-negative weights") - local_points = _surface_local_point_grid(points) - global_points = _surface_global_point_grid(local_points) - result = Face( - fit_point_grid_surface( - global_points, - tolerance=tolerance_value, - degree_min=degree_min_value, - degree_max=degree_max_value, - smoothing=smoothing_values, - ) - ) - result = cast( - Face, - _finalize_primitive_shape( - result, - op="fit_point_grid_rface", - params={ - "points": local_points, - "tolerance": tolerance_value, - "degree_min": degree_min_value, - "degree_max": degree_max_value, - "smoothing": smoothing_values, - "tag_prefix": tag_prefix, - }, - tags={"primitive", "surface", "face"}, - ), - ) - return cast(Face, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="fit_point_grid_rface", - what_happened="Failed to fit a B-spline surface face.", - possible_causes=[ - "The point grid or fitting controls are invalid.", - "The kernel fitting algorithm did not converge.", - ], - how_to_fix=[ - "Pass a rectangular finite point grid and positive tolerance.", - "Keep degree_min <= degree_max and use non-negative smoothing weights.", - ], - error=e, - ) - - -def make_ruled_surface_rface( - edge_a: Edge, edge_b: Edge, *, tag_prefix: Optional[str] = None -) -> Face: - """Create a ruled Face spanning two compatible edges.""" - try: - if not isinstance(edge_a, Edge) or not isinstance(edge_b, Edge): - raise TypeError("make_ruled_surface_rface requires two Edge objects") - result = cast( - Face, - _finalize_derived_shape( - Face(make_ruled_face(edge_a.wrapped, edge_b.wrapped)), - op="make_ruled_surface_rface", - params={"tag_prefix": tag_prefix}, - input_shapes=[edge_a, edge_b], - tags={"derived", "surface", "face"}, - ), - ) - return cast(Face, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="make_ruled_surface_rface", - what_happened="Failed to create the ruled surface face.", - possible_causes=[ - "The inputs are not edges.", - "The two edges cannot define a ruled surface.", - ], - how_to_fix=[ - "Pass two valid Edge objects with compatible parameterization." - ], - error=e, - ) - - -def make_gordon_surface_rface( - profiles: Sequence[Edge], - guides: Sequence[Edge], - *, - tolerance: float = 1e-3, - tag_prefix: Optional[str] = None, -) -> Face: - """Create a Gordon Face from intersecting profile and guide edge networks.""" - try: - profile_list, guide_list = list(profiles), list(guides) - if len(profile_list) < 2 or len(guide_list) < 2: - raise ValueError( - "Gordon surfaces require at least two profiles and two guides" - ) - if not all(isinstance(edge, Edge) for edge in [*profile_list, *guide_list]): - raise TypeError("Gordon profiles and guides must contain only Edge objects") - if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: - raise ValueError("tolerance must be a positive finite value") - result = cast( - Face, - _finalize_derived_shape( - Face( - make_gordon_surface( - [edge.wrapped for edge in profile_list], - [edge.wrapped for edge in guide_list], - tolerance=float(tolerance), - ) - ), - op="make_gordon_surface_rface", - params={ - "profile_count": len(profile_list), - "guide_count": len(guide_list), - "tolerance": float(tolerance), - "tag_prefix": tag_prefix, - }, - input_shapes=[*profile_list, *guide_list], - tags={"derived", "surface", "face"}, - ), - ) - return cast(Face, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="make_gordon_surface_rface", - what_happened="Failed to create the Gordon surface face.", - possible_causes=[ - "The curve network is too small, non-intersecting, or inconsistent.", - "The kernel Gordon interpolation failed.", - ], - how_to_fix=[ - "Pass at least two profiles and two guides whose endpoints form a compatible network.", - "Increase tolerance only when the source curves are numerically noisy.", - ], - error=e, - ) - - -def make_surface_patch_rface( - boundaries: Sequence[SurfaceBoundary], - *, - points: Sequence[Sequence[float]] = (), - settings: Optional[SurfaceFillingSettings] = None, - holes: Sequence[Wire] = (), - tag_prefix: Optional[str] = None, -) -> Face: - """Fill a constrained boundary network into one Face, optionally with holes.""" - try: - boundary_list = list(boundaries) - if not boundary_list or not all( - isinstance(item, SurfaceBoundary) for item in boundary_list - ): - raise ValueError("boundaries must be a non-empty SurfaceBoundary sequence") - settings_value = settings or SurfaceFillingSettings() - if not isinstance(settings_value, SurfaceFillingSettings): - raise TypeError("settings must be SurfaceFillingSettings") - hole_list = list(holes) - if not all(isinstance(wire, Wire) for wire in hole_list): - raise TypeError("holes must contain only Wire objects") - support_shapes = [ - item.support for item in boundary_list if item.support is not None - ] - interleaved_inputs: List[AnyShape] = [] - for item in boundary_list: - interleaved_inputs.append(item.edge) - if item.support is not None: - interleaved_inputs.append(item.support) - input_shapes: List[AnyShape] = [*interleaved_inputs, *hole_list] - local_points = [tuple(float(v) for v in point) for point in points] - global_points = _surface_global_points(local_points) - result = cast( - Face, - _finalize_derived_shape( - Face( - make_filling_face( - [ - ( - item.edge.wrapped, - item.support.wrapped if item.support else None, - str(item.continuity).upper(), - ) - for item in boundary_list - ], - global_points, - settings=settings_value.as_dict(), - holes=[wire.wrapped for wire in hole_list], - ) - ), - op="make_surface_patch_rface", - params={ - "boundary_count": len(boundary_list), - "support_count": len(support_shapes), - "hole_count": len(hole_list), - "boundaries": [item.as_dict() for item in boundary_list], - "points": local_points, - "settings": settings_value.as_dict(), - "tag_prefix": tag_prefix, - }, - input_shapes=input_shapes, - tags={"derived", "surface", "face"}, - ), - ) - return cast(Face, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="make_surface_patch_rface", - what_happened="Failed to fill the constrained surface patch.", - possible_causes=[ - "A boundary is invalid, open, or incompatible with its support face.", - "The filling controls are invalid or the kernel did not converge.", - ], - how_to_fix=[ - "Pass non-empty SurfaceBoundary values with valid Edge objects.", - "Use C0/G1/G2 continuity and explicit positive filling tolerances.", - ], - error=e, - ) - - -def _validated_loft_sections( - sections: Sequence[Union[Wire, Vertex]], *, operation: str -) -> List[Union[Wire, Vertex]]: - section_list = list(sections) - if len(section_list) < 2: - raise ValueError(f"{operation} requires at least two sections") - if not all(isinstance(section, (Wire, Vertex)) for section in section_list): - raise TypeError( - f"{operation} sections must contain only Wire or Vertex objects" - ) - if not any(isinstance(section, Wire) for section in section_list): - raise ValueError(f"{operation} requires at least one Wire section") - if any(isinstance(section, Vertex) for section in section_list[1:-1]): - raise ValueError(f"{operation} allows Vertex sections only at the start or end") - return section_list - - -def _pending_loft_role(shape: AnyShape, role: str, method: str) -> TopoRoleEntry: - return TopoRoleEntry( - ref=TopoRef( - "pending", - "pending", - 0, - { - "wire": TopoKind.WIRE, - "face": TopoKind.FACE, - }[_shape_kind_token(shape)], - _topo_id(shape.wrapped), - ), - role=role, - metadata={ - "coverage": "complete", - "status": "proven", - "evidence_kind": "kernel_operation_role", - "evidence_method": method, - }, +__all__ = tuple( + dict.fromkeys( + name + for module in _IMPLEMENTATION_MODULES + for name in module.__all__ ) - - -def _matching_shell_boundary(shell: Shell, profile: Wire) -> Wire: - profile_edges = list(profile.get_edges()) - matches = [ - boundary - for boundary in shell.get_wires() - if len(boundary.get_edges()) == len(profile_edges) - and all( - any( - edge.wrapped.IsSame(profile_edge.wrapped) - for edge in boundary.get_edges() - ) - for profile_edge in profile_edges - ) - ] - if len(matches) != 1: - raise ValueError( - f"loft endpoint profile must match exactly one result boundary, got {len(matches)}" - ) - return matches[0] - - -def _apply_loft_role_metadata( - shape: AnyShape, delta: TopoDelta, *, op: str -) -> AnyShape: - candidates: Dict[Tuple[TopoKind, str], AnyShape] = {} - for kind, members in ( - (TopoKind.FACE, shape.get_faces() if hasattr(shape, "get_faces") else []), - (TopoKind.WIRE, shape.get_wires() if hasattr(shape, "get_wires") else []), - ): - for member in members: - candidates[(kind, _topo_id(member.wrapped))] = member - for entry in delta.roles: - member = candidates.get((entry.ref.kind, entry.ref.topo_id)) - if member is None: - continue - track = dict(member.get_metadata("track", {})) - roles = sorted({*track.get("result_roles", ()), entry.role}) - track.update( - { - "op": op, - "topo_id": entry.ref.topo_id, - "kind": entry.ref.kind.name, - "coverage": "complete", - "status": "proven", - "result_roles": roles, - } - ) - member.set_metadata("track", track) - return shape - - -def _apply_shell_loft_tag_prefix( - shell: Shell, *, tag_prefix: Optional[str], has_start: bool, has_end: bool -) -> Shell: - if tag_prefix is None: - return shell - prefix = normalize_tag(tag_prefix, strict=True) - result: AnyShape = _apply_topology_identity_tag( - shell, - ShapeSelector("shell").exactly(1), - f"{prefix}.shell", - kind="shell", - local_name="shell", - authoring_source="simplecadapi.loft_rshell.tag_prefix", - ) - for present, role, local_name in ( - (has_start, "loft.start_wire", "start"), - (has_end, "loft.end_wire", "end"), - ): - if not present: - continue - result = _apply_topology_identity_tag( - cast(Shell, result), - ShapeSelector("wire").where(output_role(role)).exactly(1), - f"{prefix}.wire.{local_name}", - kind="wire", - local_name=local_name, - authoring_source="simplecadapi.loft_rshell.tag_prefix", - ) - result = _apply_topology_identity_tag( - cast(Shell, result), - ShapeSelector("face").where(output_role("loft.side")).at_least(1), - f"{prefix}.face.side", - kind="face", - local_name="side", - authoring_source="simplecadapi.loft_rshell.tag_prefix", - ) - return cast(Shell, result) - - -def trim_surface_rface( - carrier: Face, - outer: Wire, - holes: Sequence[Wire] = (), - *, - tolerance: float = 1e-7, - tag_prefix: Optional[str] = None, -) -> Face: - """Trim a carrier Face to exactly one connected Face. - - Existing carrier bounds and holes are preserved by intersecting them with - the requested closed, simple outer loop and optional closed, simple holes. - Empty or disconnected intersections are rejected. Every trim curve must - lie on the carrier within ``tolerance``. Periodic carriers do not support - holes; their outer loop must fit within one seam period without crossing - the seam. - """ - - try: - if not isinstance(carrier, Face): - raise TypeError("carrier must be a Face") - if not isinstance(outer, Wire): - raise TypeError("outer must be a Wire") - hole_list = list(holes) - if not all(isinstance(wire, Wire) for wire in hole_list): - raise TypeError("holes must contain only Wire objects") - tolerance_value = float(tolerance) - if not np.isfinite(tolerance_value) or tolerance_value <= 0.0: - raise ValueError("tolerance must be a positive finite value") - result = Face( - trim_surface_face( - carrier.wrapped, - outer.wrapped, - [wire.wrapped for wire in hole_list], - tolerance=tolerance_value, - ) - ) - for source in (carrier, outer, *hole_list): - _attach_lineage_from_source( - source, - result, - derivation="fragment", - op="trim_surface_rface", - coverage="partial", - ) - result = cast( - Face, - _finalize_derived_shape( - result, - op="trim_surface_rface", - params={ - "hole_count": len(hole_list), - "tolerance": tolerance_value, - "tag_prefix": tag_prefix, - }, - input_shapes=[carrier, outer, *hole_list], - tags={"derived", "surface", "face", "trimmed"}, - ), - ) - return cast(Face, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="trim_surface_rface", - what_happened="Failed to trim the carrier surface face.", - possible_causes=[ - "A trim wire is open, invalid, or does not lie on the carrier.", - "A periodic trim crosses the carrier seam.", - "A hole intersects the outer boundary or another hole.", - "The bounded intersection is empty or has multiple connected regions.", - ], - how_to_fix=[ - "Pass one closed, simple outer Wire and optional closed, simple hole Wires.", - "Keep every trim curve on the carrier within tolerance and inside one periodic seam.", - "Choose boundaries whose carrier intersection is exactly one connected Face.", - ], - error=e, - ) - - -def loft_rshell( - sections: Sequence[Union[Wire, Vertex]], - *, - ruled: bool = False, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - start_wire_tag: Optional[str] = None, - end_wire_tag: Optional[str] = None, - side_faces_tag: Optional[str] = None, -) -> Shell: - """Create an open loft Shell with endpoint-Wire and side-Face naming.""" - try: - section_list = _validated_loft_sections(sections, operation="loft_rshell") - start_is_wire = isinstance(section_list[0], Wire) - end_is_wire = isinstance(section_list[-1], Wire) - if start_wire_tag is not None and not start_is_wire: - raise ValueError("start_wire_tag requires a Wire start section") - if end_wire_tag is not None and not end_is_wire: - raise ValueError("end_wire_tag requires a Wire end section") - assignments = _normalize_operation_role_tags( - "make_loft_rshell", - ( - ("loft.start_wire", start_wire_tag), - ("loft.end_wire", end_wire_tag), - ("loft.side", side_faces_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - result = Shell( - make_loft_shell( - [section.wrapped for section in section_list], ruled=bool(ruled) - ) - ) - roles = [ - _pending_loft_role(face, "loft.side", "ResultSideFace") - for face in result.get_faces() - ] - if start_is_wire: - roles.append( - _pending_loft_role( - _matching_shell_boundary(result, cast(Wire, section_list[0])), - "loft.start_wire", - "EndpointBoundary", - ) - ) - if end_is_wire: - roles.append( - _pending_loft_role( - _matching_shell_boundary(result, cast(Wire, section_list[-1])), - "loft.end_wire", - "EndpointBoundary", - ) - ) - delta = TopoDelta(roles=tuple(roles)) - _apply_loft_role_metadata(result, delta, op="make_loft_rshell") - finalized = cast( - Shell, - _finalize_derived_shape( - result, - op="make_loft_rshell", - params={ - "section_count": len(section_list), - "ruled": bool(ruled), - "tag_prefix": tag_prefix, - }, - input_shapes=section_list, - tags={"derived", "surface", "shell"}, - topo_delta=delta, - ), - ) - target_kinds = _validate_operation_output_roles(delta, assignments) - tagged = cast( - Shell, - _apply_operation_role_tags( - finalized, - op="make_loft_rshell", - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ), - ) - return _apply_shell_loft_tag_prefix( - tagged, - tag_prefix=tag_prefix, - has_start=start_is_wire, - has_end=end_is_wire, - ) - except Exception as e: - _wrap_public_api_error( - operation="loft_rshell", - what_happened="Failed to create the surface loft shell.", - possible_causes=[ - "Sections are incompatible or a Vertex was used away from an endpoint.", - "The kernel loft algorithm failed.", - ], - how_to_fix=[ - "Pass at least two Wire or endpoint Vertex sections in loft order." - ], - error=e, - ) - - -def sew_faces_rshell( - faces: Sequence[Face], *, tolerance: float = 1e-6, tag_prefix: Optional[str] = None -) -> Shell: - """Sew faces into exactly one connected Shell.""" - try: - face_list = list(faces) - if not face_list or not all(isinstance(face, Face) for face in face_list): - raise ValueError("sew_faces_rshell requires a non-empty Face sequence") - if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: - raise ValueError("tolerance must be a positive finite value") - sewn, result_face_indices = sew_faces_with_history_ocp( - [face.wrapped for face in face_list], tolerance=float(tolerance) - ) - result = cast( - Shell, - _finalize_derived_shape( - Shell(sewn), - op="sew_faces_rshell", - params={ - "face_count": len(face_list), - "tolerance": float(tolerance), - "tag_prefix": tag_prefix, - }, - input_shapes=face_list, - tags={"derived", "surface", "shell"}, - ), - ) - _carry_face_provenance( - result, face_list, result_face_indices=result_face_indices - ) - return cast(Shell, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="sew_faces_rshell", - what_happened="Failed to sew faces into one shell.", - possible_causes=[ - "Faces are disconnected or their gaps exceed tolerance.", - "The sewing result contains multiple shell components.", - ], - how_to_fix=["Pass connected Face objects and a positive sewing tolerance."], - error=e, - ) - - -def make_solid_from_shell_rsolid( - shell: Shell, *, tag_prefix: Optional[str] = None -) -> Solid: - """Create an oriented Solid from one valid closed Shell.""" - - try: - if not isinstance(shell, Shell): - raise TypeError("make_solid_from_shell_rsolid requires a Shell") - solid = Solid(solid_from_shell(shell.wrapped)) - source_entities = shell._topology_cache.entities() - for target_entity in solid._topology_cache.entities(): - matches = [ - source_entity - for source_entity in source_entities - if source_entity.kind == target_entity.kind - and _same_semantic_topology( - source_entity.kind, - source_entity.representative, - target_entity.representative, - ) - ] - if len(matches) == 1 and matches[0].wrappers and target_entity.wrappers: - target_entity.wrappers[0]._copy_semantic_state_from( - matches[0].wrappers[0] - ) - _attach_lineage_from_source( - shell, - solid, - derivation="continuation", - op="make_solid_from_shell_rsolid", - coverage="partial", - ) - result = cast( - Solid, - _finalize_derived_shape( - solid, - op="make_solid_from_shell_rsolid", - params={"tag_prefix": tag_prefix}, - input_shapes=[shell], - tags={"derived", "surface", "solid"}, - ), - ) - _carry_face_provenance( - result, - shell.get_faces(), - allow_orientation_change=True, - replace_local_bindings=False, - ) - return cast(Solid, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="make_solid_from_shell_rsolid", - what_happened="Failed to create a solid from the shell.", - possible_causes=[ - "The input is not a Shell.", - "The shell is open, invalid, or cannot be oriented as one material boundary.", - ], - how_to_fix=[ - "Sew a valid closed shell before converting it to a solid.", - "Inspect free boundaries and face orientation when conversion fails.", - ], - error=e, - ) - - -def free_boundaries_rwirelist(shell: Shell, *, tolerance: float = 1e-6) -> List[Wire]: - """Return unique closed and open free boundary wires of a Shell.""" - try: - if not isinstance(shell, Shell): - raise TypeError("free_boundaries_rwirelist requires a Shell") - if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: - raise ValueError("tolerance must be a positive finite value") - result = [ - Wire(wire) - for wire in free_boundaries_ocp(shell.wrapped, tolerance=float(tolerance)) - ] - record_operation_if_active( - op="free_boundaries_rwirelist", - params={"tolerance": float(tolerance)}, - outputs=result, - input_shapes=[shell], - semantic_delta=_semantic_delta_for_output( - "free_boundaries_rwirelist", - output_count=len(result), - entity_type="Profile", - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="free_boundaries_rwirelist", - what_happened="Failed to extract free boundary wires.", - possible_causes=[ - "The input is not a valid Shell.", - "The boundary analysis tolerance is invalid.", - ], - how_to_fix=["Pass a Shell and a positive finite tolerance."], - error=e, - ) - - -def fill_holes_rshell( - shell: Shell, - hole_indices: Optional[Sequence[int]] = None, - *, - tolerance: float = 1e-6, - settings: Optional[SurfaceFillingSettings] = None, - tag_prefix: Optional[str] = None, -) -> Shell: - """Fill selected closed free boundaries and return a sewn Shell.""" - try: - if not isinstance(shell, Shell): - raise TypeError("fill_holes_rshell requires a Shell") - if not np.isfinite(float(tolerance)) or float(tolerance) <= 0: - raise ValueError("tolerance must be a positive finite value") - settings_value = settings or SurfaceFillingSettings() - if not isinstance(settings_value, SurfaceFillingSettings): - raise TypeError("settings must be SurfaceFillingSettings") - indices = ( - None if hole_indices is None else [int(index) for index in hole_indices] - ) - result = cast( - Shell, - _finalize_derived_shape( - Shell( - fill_shell_holes_ocp( - shell.wrapped, - hole_indices=indices, - tolerance=float(tolerance), - settings=settings_value.as_dict(), - ) - ), - op="fill_holes_rshell", - params={ - "hole_indices": indices, - "tolerance": float(tolerance), - "settings": settings_value.as_dict(), - "tag_prefix": tag_prefix, - }, - input_shapes=[shell], - tags={"derived", "surface", "shell"}, - ), - ) - return cast(Shell, _surface_tag_output(result, tag_prefix)) - except Exception as e: - _wrap_public_api_error( - operation="fill_holes_rshell", - what_happened="Failed to fill selected shell holes.", - possible_causes=[ - "A selected boundary is not a closed hole or the index is out of range.", - "The filling or sewing operation failed.", - ], - how_to_fix=[ - "Use free_boundaries_rwirelist() to inspect valid boundary indices before filling." - ], - error=e, - ) - - -from .kernel.ocp_mesh import tessellate_face -from .kernel.ocp_properties import bounding_box, distance as ocp_distance - -_DEFAULT_UNION_GLUE = False -_DEFAULT_UNION_TOL_FACTOR = 1e-7 -_DEFAULT_UNION_TOL_MIN = 1e-7 -_DEFAULT_UNION_TOL_MAX = 1e-5 - - -_OP_MAKE_POINT_RVERTEX = "make_point_rvertex" -_OP_LOAD_BREP_REGION_RSOLID = "load_brep_region_rsolid" -_OP_LOAD_BREP_REGION_RSHELL = "load_brep_region_rshell" -_OP_MAKE_LINE_REDGE = "make_line_redge" -_OP_MAKE_CIRCLE_REDGE = "make_circle_redge" -_OP_MAKE_THREE_POINT_ARC_REDGE = "make_three_point_arc_redge" -_OP_MAKE_ANGLE_ARC_REDGE = "make_angle_arc_redge" -_OP_MAKE_SPLINE_REDGE = "make_spline_redge" -_OP_MAKE_INTERPOLATED_SPLINE_REDGE = "make_interpolated_spline_redge" -_OP_MAKE_HELIX_REDGE = "make_helix_redge" -_OP_MAKE_WIRE_FROM_EDGES_RWIRE = "make_wire_from_edges_rwire" -_OP_MAKE_FACE_FROM_WIRE_RFACE = "make_face_from_wire_rface" -_OP_MAKE_FACE_FROM_WIRES_RFACE = "make_face_from_wires_rface" -_OP_MAKE_TRANSLATE_RSHAPE = "make_translate_rshape" -_OP_MAKE_ROTATE_RSHAPE = "make_rotate_rshape" -_OP_MAKE_MIRROR_RSHAPE = "make_mirror_rshape" -_OP_MAKE_EXTRUDE_RSOLID = "make_extrude_rsolid" -_OP_MAKE_REVOLVE_RSOLID = "make_revolve_rsolid" -_OP_MAKE_LOFT_RSOLID = "make_loft_rsolid" -_OP_MAKE_SWEEP_RSOLID = "make_sweep_rsolid" -_OP_MAKE_TWISTED_SWEEP_RSOLID = "make_twisted_sweep_rsolid" -_OP_MAKE_UNION_RSOLID = "make_union_rsolid" -_OP_MAKE_CUT_RSOLID = "make_cut_rsolid" -_OP_MAKE_INTERSECT_RSOLID = "make_intersect_rsolid" -_OP_MAKE_CUT_RFACE = "make_2d_cut_rface" -_OP_MAKE_UNION_RFACE = "make_2d_union_rface" -_OP_MAKE_INTERSECT_RFACE = "make_2d_intersect_rface" -_OP_MAKE_FILLET_RSOLID = "make_fillet_rsolid" -_OP_MAKE_CHAMFER_RSOLID = "make_chamfer_rsolid" -_OP_MAKE_SHELL_RSOLID = "make_shell_rsolid" -_OP_MAKE_SELECT_RVERTEX = "make_select_rvertex" -_OP_MAKE_SELECT_REDGE = "make_select_redge" -_OP_MAKE_SELECT_RWIRE = "make_select_rwire" -_OP_MAKE_SELECT_RFACE = "make_select_rface" -_OP_MAKE_SELECT_RSHELL = "make_select_rshell" -_OP_MAKE_SELECT_RSOLID = "make_select_rsolid" -_OP_APPLY_TAG_RSELECTION = "apply_tag_rselection" -_OP_MAKE_SKETCH_RSKETCH = "make_sketch_rsketch" -_OP_ADD_POINT_RSKETCH = "add_point_rsketch" -_OP_ADD_LINE_RSKETCH = "add_line_rsketch" -_OP_ADD_CIRCLE_RSKETCH = "add_circle_rsketch" -_OP_ADD_ARC_RSKETCH = "add_arc_rsketch" -_OP_ADD_BSPLINE_RSKETCH = "add_bspline_rsketch" -_OP_MAKE_WIRE_FROM_SKETCH_RWIRE = "make_wire_from_sketch_rwire" -_OP_MAKE_FACE_FROM_SKETCH_RFACE = "make_face_from_sketch_rface" -_OP_MAKE_MATERIAL_RMATERIAL = "make_material_rmaterial" -_OP_MAKE_PLACEMENT_RPLACEMENT = "make_placement_rplacement" -_OP_MAKE_IDENTITY_PLACEMENT_RPLACEMENT = "make_identity_placement_rplacement" -_OP_MAKE_PART_RPART = "make_part_rpart" -_OP_MAKE_ASSIGN_MATERIAL_RPART = "make_assign_material_rpart" -_OP_MAKE_ASSEMBLY_RASSEMBLY = "make_assembly_rassembly" -_OP_MAKE_ADD_COMPONENT_RASSEMBLY = "make_add_component_rassembly" -_OP_MAKE_PLACE_COMPONENT_RASSEMBLY = "make_place_component_rassembly" -_OP_MAKE_COMPOUND_FROM_ASSEMBLY_RCOMPOUND = "make_compound_from_assembly_rcompound" -_OP_MAKE_FACE_CONNECTOR_RCONNECTOR = "make_face_connector_rconnector" -_OP_MAKE_EDGE_CONNECTOR_RCONNECTOR = "make_edge_connector_rconnector" -_OP_MAKE_VERTEX_CONNECTOR_RCONNECTOR = "make_vertex_connector_rconnector" -_OP_MAKE_PLACEMENT_CONNECTOR_RCONNECTOR = "make_placement_connector_rconnector" -_OP_MAKE_ADD_CONNECTOR_RPART = "make_add_connector_rpart" -_OP_MAKE_ADD_CONNECTOR_RASSEMBLY = "make_add_connector_rassembly" -_OP_MAKE_FORWARD_CONNECTOR_RASSEMBLY = "make_forward_connector_rassembly" -_OP_MAKE_CONNECTOR_REF_RCONNECTORREF = "make_connector_ref_rconnectorref" -_OP_MAKE_SCALAR_LIMIT_RSCALARLIMIT = "make_scalar_limit_rscalarlimit" -_OP_MAKE_GROUND_COMPONENT_RASSEMBLY = "make_ground_component_rassembly" -_OP_MAKE_UNGROUND_COMPONENT_RASSEMBLY = "make_unground_component_rassembly" -_OP_MAKE_FIXED_CONSTRAINT_RASSEMBLY = "make_fixed_constraint_rassembly" -_OP_MAKE_REVOLUTE_CONSTRAINT_RASSEMBLY = "make_revolute_constraint_rassembly" -_OP_MAKE_PRISMATIC_CONSTRAINT_RASSEMBLY = "make_prismatic_constraint_rassembly" -_OP_MAKE_GEAR_CONSTRAINT_RASSEMBLY = "make_gear_constraint_rassembly" -_OP_MAKE_BELT_CONSTRAINT_RASSEMBLY = "make_belt_constraint_rassembly" -_OP_MAKE_RACK_PINION_CONSTRAINT_RASSEMBLY = "make_rack_pinion_constraint_rassembly" -_OP_MAKE_SOLVE_ASSEMBLY_CONSTRAINTS_RASSEMBLY = ( - "make_solve_assembly_constraints_rassembly" ) - -_OPERATION_OUTPUT_ROLE_CARDINALITY: Dict[str, Tuple[Tuple[str, str], ...]] = { - "make_box_rsolid": ( - ("box.bottom", "one"), - ("box.top", "one"), - ("box.front", "one"), - ("box.back", "one"), - ("box.left", "one"), - ("box.right", "one"), - ), - "make_cylinder_rsolid": ( - ("cylinder.start", "one"), - ("cylinder.end", "one"), - ("cylinder.side", "one"), - ("cylinder.start_boundary", "one"), - ("cylinder.end_boundary", "one"), - ("cylinder.seam", "one"), - ), - "make_cone_rsolid": ( - ("cone.start", "one"), - ("cone.end", "one"), - ("cone.side", "one"), - ("cone.start_boundary", "one"), - ("cone.end_boundary", "one"), - ("cone.seam", "one"), - ), - _OP_MAKE_EXTRUDE_RSOLID: ( - ("extrusion.start", "one"), - ("extrusion.end", "one"), - ("extrusion.side", "many"), - ), - _OP_MAKE_REVOLVE_RSOLID: ( - ("revolution.start", "one"), - ("revolution.end", "one"), - ("revolution.side", "many"), - ), - _OP_MAKE_FILLET_RSOLID: (("fillet.patch", "many"),), - _OP_MAKE_CHAMFER_RSOLID: (("chamfer.patch", "many"),), - _OP_MAKE_SHELL_RSOLID: ( - ("shell.body_face", "many"), - ("shell.offset_face", "many"), - ("shell.closing_descendant", "many"), - ("shell.wall", "many"), - ), - _OP_MAKE_LOFT_RSOLID: ( - ("loft.start", "one"), - ("loft.end", "one"), - ("loft.side", "many"), - ), - _OP_MAKE_SWEEP_RSOLID: ( - ("sweep.start", "one"), - ("sweep.end", "one"), - ("sweep.side", "many"), - ), - "make_loft_rshell": ( - ("loft.start_wire", "one"), - ("loft.end_wire", "one"), - ("loft.side", "many"), - ), - _OP_MAKE_TWISTED_SWEEP_RSOLID: ( - ("twisted_sweep.start", "one"), - ("twisted_sweep.end", "one"), - ("twisted_sweep.side", "many"), - ), +_SYMBOL_MODULES = { + name: tuple( + module for module in _IMPLEMENTATION_MODULES if name in vars(module) + ) + for name in __all__ } -_SKETCH_CONSTRAINT_OPS = { - "coincident": "make_constrain_coincident_rsketch", - "connect": "make_constrain_coincident_rsketch", - "point_on": "make_constrain_point_on_rsketch", - "horizontal": "make_constrain_horizontal_rsketch", - "vertical": "make_constrain_vertical_rsketch", - "parallel": "make_constrain_parallel_rsketch", - "perpendicular": "make_constrain_perpendicular_rsketch", - "collinear": "make_constrain_collinear_rsketch", - "tangent": "make_constrain_tangent_rsketch", - "concentric": "make_constrain_concentric_rsketch", - "midpoint": "make_constrain_midpoint_rsketch", - "symmetric": "make_constrain_symmetric_rsketch", - "equal_length": "make_constrain_equal_length_rsketch", - "equal_radius": "make_constrain_equal_radius_rsketch", - "distance": "make_constrain_distance_rsketch", - "distance_x": "make_constrain_distance_x_rsketch", - "distance_y": "make_constrain_distance_y_rsketch", - "length": "make_constrain_length_rsketch", - "angle": "make_constrain_angle_rsketch", - "radius": "make_constrain_radius_rsketch", - "diameter": "make_constrain_diameter_rsketch", - "fix": "make_constrain_fix_rsketch", -} +class _OperationsFacade(_ModuleType): + def __setattr__(self, name, value): + for module in self.__dict__.get("_SYMBOL_MODULES", {}).get(name, ()): + setattr(module, name, value) + super().__setattr__(name, value) -def _orthonormal_plane_axes( - normal: Tuple[float, float, float], -) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: - normal_vec = np.array(normal, dtype=float) - norm = float(np.linalg.norm(normal_vec)) - if norm <= 1e-12: - raise ValueError("法向量不能是零向量") - z_axis = normal_vec / norm - ref_vec = ( - np.array([1.0, 0.0, 0.0]) if abs(z_axis[2]) > 0.9 else np.array([0.0, 0.0, 1.0]) - ) - x_axis = np.cross(z_axis, ref_vec) - x_norm = float(np.linalg.norm(x_axis)) - if x_norm <= 1e-12: - raise ValueError("无法根据给定法向量构建局部坐标系") - x_axis = x_axis / x_norm - y_axis = np.cross(z_axis, x_axis) - y_axis = y_axis / float(np.linalg.norm(y_axis)) - return z_axis, x_axis, y_axis - - -def _default_plane_x_direction(normal: Sequence[float]) -> np.ndarray: - """Return OCP's canonical in-plane X axis for a local normal.""" - normal_vec = np.asarray(normal, dtype=float) - axis = gp_Ax2( - gp_Pnt(0.0, 0.0, 0.0), - gp_Dir(float(normal_vec[0]), float(normal_vec[1]), float(normal_vec[2])), - ) - direction = axis.XDirection() - return np.asarray(direction.Coord(), dtype=float) - - -def _sketch_plane_in_current_coordinates( - plane: Any, -) -> Dict[str, Tuple[float, float, float]]: - if isinstance(plane, str): - token = plane.upper() - frames = { - "XY": ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), - "XZ": ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 0.0, 1.0)), - "YZ": ((0.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), - } - if token not in frames: - raise ValueError( - "Sketch plane must be 'XY', 'XZ', 'YZ', or a plane mapping" - ) - origin, x_axis, y_axis = frames[token] - elif isinstance(plane, Mapping): - origin = tuple(plane.get("origin", (0.0, 0.0, 0.0))) - x_axis = tuple(plane.get("x_axis", (1.0, 0.0, 0.0))) - y_axis = tuple(plane.get("y_axis", (0.0, 1.0, 0.0))) - else: - raise ValueError("Sketch plane must be 'XY', 'XZ', 'YZ', or a plane mapping") - - cs = get_current_cs() - global_origin = cs.transform_point(np.asarray(origin, dtype=float)) - global_x_axis = cs.transform_vector(np.asarray(x_axis, dtype=float)) - global_y_axis = cs.transform_vector(np.asarray(y_axis, dtype=float)) - return { - "origin": tuple(float(value) for value in global_origin), - "x_axis": tuple(float(value) for value in global_x_axis), - "y_axis": tuple(float(value) for value in global_y_axis), - } - - -def _pick_perpendicular_unit(axis: Tuple[float, float, float]) -> np.ndarray: - axis_vec = np.array(axis, dtype=float) - axis_norm = float(np.linalg.norm(axis_vec)) - if axis_norm <= 1e-12: - raise ValueError("轴向量不能是零向量") - axis_unit = axis_vec / axis_norm - ref_vec = ( - np.array([1.0, 0.0, 0.0]) - if abs(axis_unit[2]) > 0.9 - else np.array([0.0, 0.0, 1.0]) - ) - radial = np.cross(axis_unit, ref_vec) - radial_norm = float(np.linalg.norm(radial)) - if radial_norm <= 1e-12: - raise ValueError("无法根据给定轴向量构建旋转剖面") - return radial / radial_norm - - -def _offset_point_expr( - center: Tuple[ScalarLike, ScalarLike, ScalarLike], - x_axis: Sequence[float], - y_axis: Sequence[float], - dx: ScalarLike, - dy: ScalarLike, -) -> Tuple[ScalarLike, ScalarLike, ScalarLike]: - return ( - center[0] + dx * float(x_axis[0]) + dy * float(y_axis[0]), - center[1] + dx * float(x_axis[1]) + dy * float(y_axis[1]), - center[2] + dx * float(x_axis[2]) + dy * float(y_axis[2]), - ) - - -def _make_closed_profile_rwire( - points: Sequence[Tuple[ScalarLike, ScalarLike, ScalarLike]], -) -> Wire: - edges = [ - make_line_redge(points[index], points[(index + 1) % len(points)]) - for index in range(len(points)) - ] - return make_wire_from_edges_rwire(edges) - - -def _make_closed_profile_rface( - points: Sequence[Tuple[ScalarLike, ScalarLike, ScalarLike]], - *, - normal: Tuple[float, float, float] = (0.0, 0.0, 1.0), -) -> Face: - return make_face_from_wire_rface(_make_closed_profile_rwire(points), normal=normal) - - -def _wrap_public_api_error( - *, - operation: str, - what_happened: str, - possible_causes: Sequence[str], - how_to_fix: Sequence[str], - error: BaseException, -) -> None: - raise_harness_error( - operation=operation, - what_happened=what_happened, - possible_causes=possible_causes, - how_to_fix=how_to_fix, - error=error, - ) - - -def _semantic_id_registry(kind: str) -> Set[str]: - session = get_active_session() - if session is None: - return set() - registry = getattr(session, "_simplecad_semantic_ids", None) - if registry is None: - registry = {} - setattr(session, "_simplecad_semantic_ids", registry) - return cast(Set[str], registry.setdefault(kind, set())) - - -def _reserve_semantic_id(kind: str, value: str) -> None: - session = get_active_session() - if session is None: - return - registry = _semantic_id_registry(kind) - if value in registry: - raise ValueError(f"duplicate {kind} id in active GraphSession: {value}") - registry.add(value) - - -def _semantic_created( - entity_type: str, entity_id: str, metadata: Optional[Dict[str, Any]] = None -) -> SemanticDelta: - return SemanticDelta( - created=( - SemanticRef( - graph_id="pending", - node_id="pending", - entity_type=entity_type, - entity_id=entity_id, - ), - ), - metadata=dict(metadata or {}), - ) - - -def _semantic_modified( - entity_type: str, entity_id: str, metadata: Optional[Dict[str, Any]] = None -) -> SemanticDelta: - return SemanticDelta( - modified=( - SemanticRef( - graph_id="pending", - node_id="pending", - entity_type=entity_type, - entity_id=entity_id, - ), - ), - metadata=dict(metadata or {}), - ) - - -def _material_params(material: Material) -> Dict[str, object]: - return material.to_dict() - - -def _part_params(part: Part) -> Dict[str, object]: - return {"part_id": part.part_id, "name": part.name} - - -def _assembly_params(assembly: Assembly) -> Dict[str, object]: - return {"assembly_id": assembly.assembly_id, "name": assembly.name} - - -def _connector_params(connector: Connector) -> Dict[str, object]: - return connector.to_dict() - - -def _connector_ref_params(connector_ref: ConnectorRef) -> Dict[str, object]: - return connector_ref.to_dict() - - -def _scalar_limit_params(limit: ScalarLimit) -> Dict[str, object]: - return limit.to_dict() - - -def _constraint_params(constraint: Constraint) -> Dict[str, object]: - return constraint.to_dict() - - -def _resolve_union_tol( - solids: Sequence[Solid], tol: Optional[float] -) -> Optional[float]: - """Resolve and validate the fuzzy tolerance for boolean union. - - The default is scale-aware and intentionally conservative. An explicit - tolerance is accepted only when it is finite and non-negative; silently - forwarding NaN or a negative fuzzy value to OCC makes failures difficult - to diagnose and can vary across kernel versions. - """ - - if tol is not None: - resolved = float(tol) - if not math.isfinite(resolved) or resolved < 0.0: - raise ValueError("tol must be a finite non-negative number") - return resolved - - bbox_min = np.array([np.inf, np.inf, np.inf], dtype=float) - bbox_max = np.array([-np.inf, -np.inf, -np.inf], dtype=float) - - for solid in solids: - bb = bounding_box(solid.wrapped) - bbox_min = np.minimum(bbox_min, np.array([bb.xmin, bb.ymin, bb.zmin])) - bbox_max = np.maximum(bbox_max, np.array([bb.xmax, bb.ymax, bb.zmax])) - - span = float(np.linalg.norm(bbox_max - bbox_min)) - if not np.isfinite(span) or span <= 0: - return _DEFAULT_UNION_TOL_MIN - - return min( - max(span * _DEFAULT_UNION_TOL_FACTOR, _DEFAULT_UNION_TOL_MIN), - _DEFAULT_UNION_TOL_MAX, - ) - - -def _union_separation_diagnostic( - results: Sequence[Solid], tol: Optional[float] -) -> Optional[str]: - """Return a short diagnostic for multi-solid union results.""" - - if len(results) < 2: - return None - - effective_tol = float(tol or 0.0) - nearest_gap_above_tol: Optional[float] = None - - for i in range(len(results)): - for j in range(i + 1, len(results)): - gap = float(ocp_distance(results[i].wrapped, results[j].wrapped)) - if gap > effective_tol: - if nearest_gap_above_tol is None or gap < nearest_gap_above_tol: - nearest_gap_above_tol = gap - - if nearest_gap_above_tol is None: - return None - - return ( - f"union produced {len(results)} separated solids; " - f"nearest detected gap is about {nearest_gap_above_tol:.6g}, " - f"which exceeds tol={effective_tol:.6g}" - ) - - -def _require_union_solid(result_shape: Any, effective_tol: Optional[float]) -> Solid: - result_shapes = solids_of(result_shape) - if len(result_shapes) == 1: - return Solid(result_shapes[0]) - - failure_reason = "union did not produce a valid solid" - diagnostic = _union_separation_diagnostic( - [Solid(result) for result in result_shapes], effective_tol - ) - if diagnostic: - failure_reason = diagnostic - elif len(result_shapes) > 1: - failure_reason = ( - f"union produced {len(result_shapes)} solids at zero detected gap; " - "the inputs likely meet only along an edge, vertex, tangent point, " - "or tangent curve, which is not one manifold solid" - ) - raise ValueError(failure_reason) - - -def _evaluate_tracked_union( - solids: Sequence[Solid], - *, - glue: bool, - tol: Optional[float], - clean: bool, -) -> TrackedBooleanResult: - fused = fuse_shapes_with_history( - [solid.wrapped for solid in solids], - glue=glue, - tol=tol, - clean=clean, - ) - result = _require_union_solid(fused.shape, tol) - return track_union_history(solids, result, fused.history, fused.section_edges) - - -def _flatten_boolean_solids( - args: Sequence[Union[Solid, Sequence[Solid]]], operation_name: str -) -> List[Solid]: - """Flatten nested boolean inputs into a validated solid list.""" - - def _flatten(values: Sequence[Union[Solid, Sequence[Solid]]]) -> List[Solid]: - flattened: List[Solid] = [] - for value in values: - if isinstance(value, Solid): - flattened.append(value) - elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)): - flattened.extend( - _flatten(cast(Sequence[Union[Solid, Sequence[Solid]]], value)) - ) - else: - raise ValueError(f"{operation_name}函数只接受Solid类型的对象") - return flattened - - return _flatten(args) - - -def _require_single_boolean_solid( - result_shapes: Sequence[Any], - *, - operation: str, - failure_reason: str, -) -> Solid: - if not result_shapes: - raise ValueError(failure_reason) - if len(result_shapes) != 1: - raise ValueError( - f"{operation} 期望得到单个Solid结果,但内核返回了 {len(result_shapes)} 个实体。" - ) - return Solid(result_shapes[0]) - - -def _merge_topo_deltas(deltas: Sequence[TopoDelta]) -> Optional[TopoDelta]: - if not deltas: - return None - preserved: List[TopoRef] = [] - modified: List[TopoRef] = [] - generated: List[TopoRef] = [] - deleted: List[TopoRef] = [] - section_edges: List[TopoRef] = [] - entries: List[TopoEntry] = [] - raw_event: Dict[str, Any] = {"steps": []} - - for idx, delta in enumerate(deltas): - preserved.extend(delta.preserved) - modified.extend(delta.modified) - generated.extend(delta.generated) - deleted.extend(delta.deleted) - section_edges.extend(delta.section_edges) - entries.extend(delta.entries) - raw_event["steps"].append( - { - "index": idx, - "preserved": len(delta.preserved), - "modified": len(delta.modified), - "generated": len(delta.generated), - "deleted": len(delta.deleted), - "section_edges": len(delta.section_edges), - } - ) - - return TopoDelta( - preserved=tuple(preserved), - modified=tuple(modified), - generated=tuple(generated), - deleted=tuple(deleted), - section_edges=tuple(section_edges), - entries=tuple(entries), - raw_event=raw_event, - ) - - -def _copy_runtime_state(source: AnyShape, target: AnyShape) -> AnyShape: - runtime = getattr(source, "_runtime", None) - if isinstance(runtime, dict): - # A transformed BRep owns a new evaluated geometry. Copy semantic and - # graph provenance, but never carry the source's geometry-dependent - # mesh or mesh error into the new wrapper. - target._runtime = { - key: value - for key, value in runtime.items() - if not key == "mesh.error" - and not key == "mesh.default" - and not key.startswith("mesh:") - } - return target - - -def _attach_lineage_from_source( - source: AnyShape, - target: AnyShape, - *, - derivation: str, - op: str, - coverage: str = "complete", -) -> None: - coverage_rank = {"complete": 0, "partial": 1, "none": 2} - - def aggregate(*values: object) -> str: - normalized = [str(value) for value in values if value in coverage_rank] - return ( - max(normalized, key=coverage_rank.__getitem__) if normalized else "complete" - ) - - effective_coverage = aggregate( - coverage, - source._get_runtime("semantic.lineage.coverage"), - ) - bindings = { - binding.binding_id: (binding, effective_coverage) - for binding in source._local_tag_bindings() - if lineage_policy_allows(binding.propagation, derivation) - } - for witness in source._tag_lineage: - if not lineage_policy_allows( - witness.binding.propagation, witness.derivation - ) or not lineage_policy_allows(witness.binding.propagation, derivation): - continue - existing = bindings.get(witness.binding.binding_id) - witness_coverage = aggregate(effective_coverage, witness.coverage) - bindings[witness.binding.binding_id] = ( - witness.binding, - aggregate(existing[1], witness_coverage) if existing else witness_coverage, - ) - for binding, binding_coverage in bindings.values(): - evidence = TagEvidence( - "topology_change", - { - "op": op, - "derivation": derivation, - "coverage": binding_coverage, - }, - ) - target._add_tag_lineage( - binding, - derivation=derivation, - source_topo_id=source.topo_id, - evidence=evidence, - coverage=binding_coverage, - ) - target._set_runtime( - "semantic.lineage.coverage", - aggregate( - target._get_runtime("semantic.lineage.coverage"), - effective_coverage, - ), - ) - - -def _current_context_metadata() -> Dict[str, Tuple[float, float, float]]: - cs = get_current_cs() - return { - "origin": (float(cs.origin[0]), float(cs.origin[1]), float(cs.origin[2])), - "x_axis": (float(cs.x_axis[0]), float(cs.x_axis[1]), float(cs.x_axis[2])), - "y_axis": (float(cs.y_axis[0]), float(cs.y_axis[1]), float(cs.y_axis[2])), - "z_axis": (float(cs.z_axis[0]), float(cs.z_axis[1]), float(cs.z_axis[2])), - } - - -def _attach_track_summary( - shape: AnyShape, - *, - op: str, - delta: Optional[object] = None, - delta_entries: Optional[Dict[str, Dict[str, object]]] = None, -) -> AnyShape: - track_payload: Dict[str, object] = {"op": op} - if delta is not None: - track_payload["has_delta"] = True - track_payload["preserved"] = len(getattr(delta, "preserved", ())) - track_payload["modified"] = len(getattr(delta, "modified", ())) - track_payload["generated"] = len(getattr(delta, "generated", ())) - track_payload["deleted"] = len(getattr(delta, "deleted", ())) - if delta_entries: - track_payload["entry_count"] = len(delta_entries) - shape.set_metadata("track", track_payload) - return shape - - -def _vector_like_to_tuple(value: Any) -> Optional[Tuple[float, float, float]]: - if value is None: - return None - if hasattr(value, "x") and hasattr(value, "y") and hasattr(value, "z"): - return (float(value.x), float(value.y), float(value.z)) - if isinstance(value, (list, tuple)) and len(value) == 3: - return (float(value[0]), float(value[1]), float(value[2])) - return None - - -def _make_selector_hint(shape: AnyShape) -> Dict[str, object]: - hint: Dict[str, object] = { - "kind": type(shape).__name__.lower(), - "tags": shape._list_tags(), - } - - if isinstance(shape, Edge): - hint["length"] = float(shape.get_length()) - try: - hint["start"] = tuple( - float(v) for v in shape.get_start_vertex().get_coordinates() - ) - hint["end"] = tuple( - float(v) for v in shape.get_end_vertex().get_coordinates() - ) - except Exception: - center = getattr(shape.wrapped, "Center", lambda: None)() - center_tuple = _vector_like_to_tuple(center) - if center_tuple is not None: - hint["center"] = center_tuple - elif isinstance(shape, Face): - hint["area"] = float(shape.get_area()) - center_tuple = _vector_like_to_tuple(shape.get_center()) - normal_tuple = _vector_like_to_tuple(shape.get_normal_at()) - if center_tuple is not None: - hint["center"] = center_tuple - if normal_tuple is not None: - hint["normal"] = normal_tuple - elif isinstance(shape, Wire): - hint["edge_count"] = len(shape.get_edges()) - hint["closed"] = bool(shape.is_closed()) - elif isinstance(shape, Vertex): - hint["coordinates"] = tuple(float(v) for v in shape.get_coordinates()) - elif isinstance(shape, Shell): - hint["face_count"] = len(shape.get_faces()) - bb = bounding_box(shape.wrapped) - hint["bbox"] = { - "min": (float(bb.xmin), float(bb.ymin), float(bb.zmin)), - "max": (float(bb.xmax), float(bb.ymax), float(bb.zmax)), - } - elif isinstance(shape, Solid): - hint["volume"] = float(shape.get_volume()) - bb = bounding_box(shape.wrapped) - hint["bbox"] = { - "min": (float(bb.xmin), float(bb.ymin), float(bb.zmin)), - "max": (float(bb.xmax), float(bb.ymax), float(bb.zmax)), - } - elif isinstance(shape, Compound): - hint["volume"] = float(shape.get_volume()) - hint["solid_count"] = len(shape.get_solids()) - bb = bounding_box(shape.wrapped) - hint["bbox"] = { - "min": (float(bb.xmin), float(bb.ymin), float(bb.zmin)), - "max": (float(bb.xmax), float(bb.ymax), float(bb.zmax)), - } - - return hint - - -def _jsonable_geo_value(value: object) -> object: - if value is None or isinstance(value, (str, bool)): - return value - if isinstance(value, np.integer): - return int(value) - if isinstance(value, np.floating): - return float(value) - if isinstance(value, (int, float)): - return value - if hasattr(value, "to_tuple"): - try: - return [float(v) for v in value.to_tuple()] - except Exception: - pass - if hasattr(value, "x") and hasattr(value, "y") and hasattr(value, "z"): - try: - return [float(value.x), float(value.y), float(value.z)] - except Exception: - pass - if isinstance(value, dict): - return {str(k): _jsonable_geo_value(v) for k, v in value.items()} - if isinstance(value, (list, tuple)): - return [_jsonable_geo_value(v) for v in value] - return str(value) - - -def _bbox_selector_payload(shape: AnyShape) -> Optional[Dict[str, List[float]]]: - try: - bb = bounding_box(shape.wrapped) - return { - "min": [float(bb.xmin), float(bb.ymin), float(bb.zmin)], - "max": [float(bb.xmax), float(bb.ymax), float(bb.zmax)], - } - except Exception: - return None - - -def _shape_geom_type(shape: AnyShape) -> Optional[str]: - try: - from OCP.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Surface - from OCP.GeomAbs import ( - GeomAbs_BSplineCurve, - GeomAbs_BSplineSurface, - GeomAbs_BezierCurve, - GeomAbs_BezierSurface, - GeomAbs_Circle, - GeomAbs_Cone, - GeomAbs_Cylinder, - GeomAbs_Line, - GeomAbs_Plane, - GeomAbs_Sphere, - GeomAbs_Torus, - ) - - if isinstance(shape, Edge): - curve_type = BRepAdaptor_Curve(shape.wrapped).GetType() - mapping = { - GeomAbs_Line: "LINE", - GeomAbs_Circle: "CIRCLE", - GeomAbs_BSplineCurve: "BSPLINE", - GeomAbs_BezierCurve: "BEZIER", - } - return mapping.get( - curve_type, - str(curve_type).replace("GeomAbs_CurveType.GeomAbs_", "").upper(), - ) - if isinstance(shape, Face): - surface_type = BRepAdaptor_Surface(shape.wrapped).GetType() - mapping = { - GeomAbs_Plane: "PLANE", - GeomAbs_Cylinder: "CYLINDER", - GeomAbs_Cone: "CONE", - GeomAbs_Sphere: "SPHERE", - GeomAbs_Torus: "TORUS", - GeomAbs_BSplineSurface: "BSPLINE", - GeomAbs_BezierSurface: "BEZIER", - } - return mapping.get( - surface_type, - str(surface_type).replace("GeomAbs_SurfaceType.GeomAbs_", "").upper(), - ) - except Exception: - return None - return None - - -def _shape_kind_token(shape: AnyShape) -> str: - if isinstance(shape, Vertex): - return "vertex" - if isinstance(shape, Edge): - return "edge" - if isinstance(shape, Wire): - return "wire" - if isinstance(shape, Face): - return "face" - if isinstance(shape, Shell): - return "shell" - if isinstance(shape, Solid): - return "solid" - if isinstance(shape, Compound): - return "compound" - return type(shape).__name__.lower() - - -def _selection_op_for_shape(shape: AnyShape) -> Optional[str]: - if isinstance(shape, Vertex): - return _OP_MAKE_SELECT_RVERTEX - if isinstance(shape, Edge): - return _OP_MAKE_SELECT_REDGE - if isinstance(shape, Wire): - return _OP_MAKE_SELECT_RWIRE - if isinstance(shape, Face): - return _OP_MAKE_SELECT_RFACE - if isinstance(shape, Shell): - return _OP_MAKE_SELECT_RSHELL - if isinstance(shape, Solid): - return _OP_MAKE_SELECT_RSOLID - return None - - -def _candidate_shapes_for_selection(source: AnyShape, kind: str) -> List[AnyShape]: - if kind == "edge": - if hasattr(source, "get_edges"): - return list(source.get_edges()) - return [source] if isinstance(source, Edge) else [] - if kind == "face": - if isinstance(source, (Shell, Solid, Compound)): - return list(source.get_faces()) - return [source] if isinstance(source, Face) else [] - if kind == "wire": - if isinstance(source, Face): - return [source.get_outer_wire(), *source.get_inner_wires()] - if hasattr(source, "get_children"): - return [ - cast(AnyShape, child) - for child in source.get_children() - if isinstance(child, Wire) - ] - return [source] if isinstance(source, Wire) else [] - if kind == "vertex": - if isinstance(source, Edge): - return cast(List[AnyShape], source.get_children()) - if hasattr(source, "get_children"): - return [ - cast(AnyShape, child) - for child in source.get_children() - if isinstance(child, Vertex) - ] - return [source] if isinstance(source, Vertex) else [] - if kind == "shell": - if isinstance(source, Compound): - return [ - cast(AnyShape, child) - for child in source.get_children() - if isinstance(child, Shell) - ] - return [source] if isinstance(source, Shell) else [] - if kind == "solid": - if isinstance(source, Compound): - return cast(List[AnyShape], source.get_solids()) - return [source] if isinstance(source, Solid) else [] - if kind == "compound": - return [source] if isinstance(source, Compound) else [] - return [] - - -def _source_selection_index( - source: AnyShape, selected: AnyShape, *, kind: str -) -> Optional[int]: - for idx, candidate in enumerate(_candidate_shapes_for_selection(source, kind)): - try: - if candidate.same_topology(selected): - return idx - except Exception: - pass - if getattr(candidate, "topo_id", None) == getattr(selected, "topo_id", None): - return idx - return None - - -def _make_geo_selector( - shape: AnyShape, - *, - source_shape: Optional[AnyShape] = None, -) -> Dict[str, object]: - kind = _shape_kind_token(shape) - selector: Dict[str, object] = { - "mode": "geo_exact", - "kind": kind, - "metadata_geo": _jsonable_geo_value(shape.get_metadata("geo", {})), - } - provenance = shape.get_metadata("provenance") - if isinstance(shape, Face) and isinstance(provenance, dict): - artifact_sha256 = provenance.get("artifact_sha256") - source_face_id = provenance.get("source_face_id") - if isinstance(artifact_sha256, str) and isinstance(source_face_id, str): - selector["brep_region_ref"] = { - "artifact_sha256": artifact_sha256, - "source_face_id": source_face_id, - } - # `source_shape` is intentionally not serialized as a source index. The - # canonical selector is geometry-based; source lineage comes from graph inputs. - - bbox_payload = _bbox_selector_payload(shape) - if bbox_payload is not None: - selector["bbox"] = bbox_payload - - geom_type = _shape_geom_type(shape) - if geom_type is not None: - selector["geom_type"] = geom_type - - if isinstance(shape, Vertex): - selector["coordinates"] = [float(v) for v in shape.get_coordinates()] - elif isinstance(shape, Edge): - selector["length"] = float(shape.get_length()) - center = shape.get_center() - selector["center"] = [float(center.x), float(center.y), float(center.z)] - try: - selector["start"] = [ - float(v) for v in shape.get_start_vertex().get_coordinates() - ] - selector["end"] = [ - float(v) for v in shape.get_end_vertex().get_coordinates() - ] - except Exception: - pass - elif isinstance(shape, Wire): - selector["edge_count"] = len(shape.get_edges()) - selector["closed"] = bool(shape.is_closed()) - elif isinstance(shape, Face): - selector["area"] = float(shape.get_area()) - center = shape.get_center() - normal = shape.get_normal_at() - selector["center"] = [float(center.x), float(center.y), float(center.z)] - selector["normal"] = [float(normal.x), float(normal.y), float(normal.z)] - selector["edge_count"] = len(shape.get_edges()) - selector["inner_wire_count"] = len(shape.get_inner_wires()) - elif isinstance(shape, Shell): - selector["face_count"] = len(shape.get_faces()) - elif isinstance(shape, Solid): - selector["volume"] = float(shape.get_volume()) - center = shape.get_center() if hasattr(shape, "get_center") else None - if center is not None: - selector["center"] = [float(center.x), float(center.y), float(center.z)] - elif isinstance(shape, Compound): - selector["volume"] = float(shape.get_volume()) - selector["solid_count"] = len(shape.get_solids()) - return selector - - -def _record_geo_selection_nodes( - source_shape: AnyShape, - selected_shapes: Sequence[AnyShape], -) -> List[str]: - session = get_active_session() - if session is None: - return [] - source_node = source_shape._get_runtime("graph.node") - if source_node is None: - return [] - - node_ids: List[str] = [] - for selected in selected_shapes: - op = _selection_op_for_shape(selected) - if op is None: - continue - kind = _shape_kind_token(selected) - selected_node = _active_graph_node_for_shape(selected) - inputs = [source_node] - if ( - selected_node is not None - and getattr(selected_node, "op", None) == _OP_APPLY_TAG_RSELECTION - and selected_node is not source_node - ): - inputs.append(selected_node) - node = record_operation( - op=op, - params={ - "target_kind": kind, - "geo_selector": _make_geo_selector( - selected, - source_shape=source_shape, - ), - }, - inputs=inputs, - output_count=1, - semantic_delta=_semantic_delta_for_output(op, entity_type="Selection"), - context=_current_context_metadata(), - ) - attach_graph_node( - selected, - node, - output_slot=0, - graph_id=session.graph.graph_id, - ) - node_ids.append(node.node_id) - return node_ids - - -_GEO_SELECT_OPS = { - _OP_MAKE_SELECT_RVERTEX, - _OP_MAKE_SELECT_REDGE, - _OP_MAKE_SELECT_RWIRE, - _OP_MAKE_SELECT_RFACE, - _OP_MAKE_SELECT_RSHELL, - _OP_MAKE_SELECT_RSOLID, -} - - -def _is_geo_select_node(node: object) -> bool: - return getattr(node, "op", None) in _GEO_SELECT_OPS - - -def _ensure_source_shape_has_own_selection_node( - source_shape: AnyShape, -) -> Optional[object]: - source_node = _active_graph_node_for_shape(source_shape) - if ( - source_node is None - or _is_geo_select_node(source_node) - or getattr(source_node, "op", None) == _OP_APPLY_TAG_RSELECTION - ): - return source_node - - parent_source = _selection_source_for_shape(source_shape) - if parent_source is None: - return source_node - - _ensure_geo_selection_node_ids(parent_source, [source_shape]) - return _active_graph_node_for_shape(source_shape) - - -def _ensure_geo_selection_node_ids( - source_shape: AnyShape, - selected_shapes: Sequence[AnyShape], -) -> List[str]: - session = get_active_session() - if session is None: - return [] - source_node = _ensure_source_shape_has_own_selection_node(source_shape) - if source_node is None: - return [] - - node_ids: List[str] = [] - for selected in selected_shapes: - existing_node = _active_graph_node_for_shape(selected) - existing_op = getattr(existing_node, "op", None) - if existing_node is not None and existing_op in _GEO_SELECT_OPS: - node_ids.append(str(existing_node.node_id)) - continue - node_ids.extend(_record_geo_selection_nodes(source_shape, [selected])) - return node_ids - - -def _active_graph_node_for_shape(shape: AnyShape) -> Optional[object]: - session = get_active_session() - if session is None: - return None - node = shape._get_runtime("graph.node") - node_id = getattr(node, "node_id", None) - if node_id is None: - return None - if session.graph.get_node(str(node_id)) is None: - return None - return node - - -def _parent_shapes(shape: AnyShape) -> List[AnyShape]: - parents: List[AnyShape] = [] - get_parent = getattr(shape, "get_parent", None) - if callable(get_parent): - parent = get_parent() - if parent is not None: - parents.append(cast(AnyShape, parent)) - get_parents = getattr(shape, "get_parents", None) - if callable(get_parents): - for parent in get_parents(): - if parent is not None: - parents.append(cast(AnyShape, parent)) - return parents - - -def _selection_source_for_shape(shape: AnyShape) -> Optional[AnyShape]: - kind = _shape_kind_token(shape) - seen: Set[int] = set() - stack = _parent_shapes(shape) - - while stack: - source = stack.pop(0) - marker = id(source) - if marker in seen or source is shape: - continue - seen.add(marker) - - if _source_selection_index(source, shape, kind=kind) is not None: - if _active_graph_node_for_shape(source) is not None: - return source - - stack.extend(_parent_shapes(source)) - - return None - - -def _ensure_geo_selection_input_nodes( - input_shapes: Optional[Sequence[AnyShape]], -) -> Optional[Sequence[AnyShape]]: - if not input_shapes: - return input_shapes - - for shape in input_shapes: - if _active_graph_node_for_shape(shape) is not None: - continue - source = _selection_source_for_shape(shape) - if source is not None: - _ensure_geo_selection_node_ids(source, [shape]) - return input_shapes - - -def _serialize_shape_ref(shape: AnyShape) -> Optional[Dict[str, object]]: - topo_ref = shape._get_runtime("topo.ref") - if isinstance(topo_ref, TopoRef): - data = cast(Dict[str, object], topo_ref_to_dict(topo_ref)) - data["selector_hint"] = _make_selector_hint(shape) - return data - - topo_ref_meta = shape.get_metadata("topo_ref") - if isinstance(topo_ref_meta, dict): - data = cast(Dict[str, object], dict(topo_ref_meta)) - data["selector_hint"] = _make_selector_hint(shape) - return data - - return None - - -def _serialize_shape_refs(shapes: Sequence[AnyShape]) -> List[Dict[str, object]]: - refs: List[Dict[str, object]] = [] - for shape in shapes: - ref = _serialize_shape_ref(shape) - if ref is not None: - refs.append(ref) - return refs - - -def _shape_ref_topo_id(shape: AnyShape) -> Optional[str]: - ref = _serialize_shape_ref(shape) - if ref is None: - return None - topo_id = ref.get("topo_id") - return str(topo_id) if topo_id is not None else None - - -def _serialize_selection_indices( - selected_shapes: Sequence[AnyShape], - candidates: Sequence[AnyShape], -) -> List[int]: - candidate_index_by_topo_id: Dict[str, int] = {} - for idx, candidate in enumerate(candidates): - topo_id = _shape_ref_topo_id(candidate) - if topo_id is not None and topo_id not in candidate_index_by_topo_id: - candidate_index_by_topo_id[topo_id] = idx - - result: List[int] = [] - for selected in selected_shapes: - topo_id = _shape_ref_topo_id(selected) - if topo_id is None: - continue - if topo_id in candidate_index_by_topo_id: - result.append(candidate_index_by_topo_id[topo_id]) - return result - - -def _resolve_selector_or_shapes( - scope: AnyShape, - selection: Union[Sequence[AnyShape], ShapeSelector], -) -> List[AnyShape]: - if isinstance(selection, ShapeSelector): - return cast(List[AnyShape], selection.resolve(scope)) - return list(selection) - - -def _semantic_delta_for_output( - op: str, output_count: int = 1, entity_type: Optional[str] = None -) -> SemanticDelta: - resolved_entity_type = entity_type - if resolved_entity_type is None: - if op in { - "make_point", - _OP_MAKE_POINT_RVERTEX, - }: - resolved_entity_type = "Point" - elif op in { - _OP_MAKE_SKETCH_RSKETCH, - _OP_ADD_POINT_RSKETCH, - _OP_ADD_LINE_RSKETCH, - _OP_ADD_CIRCLE_RSKETCH, - _OP_ADD_ARC_RSKETCH, - _OP_ADD_BSPLINE_RSKETCH, - _OP_MAKE_WIRE_FROM_SKETCH_RWIRE, - _OP_MAKE_FACE_FROM_SKETCH_RFACE, - *_SKETCH_CONSTRAINT_OPS.values(), - }: - resolved_entity_type = "Sketch" - elif op in { - "make_line", - "make_circle_edge", - "make_circle_wire", - "make_circle_face", - "make_rectangle_wire", - "make_rectangle_face", - "make_segment_wire", - "make_three_point_arc", - "make_three_point_arc_wire", - "make_angle_arc", - "make_angle_arc_wire", - "make_spline", - "make_spline_wire", - "make_polyline_wire", - "make_helix", - "make_helix_wire", - "make_face_from_wire", - "make_wire_from_edges", - _OP_MAKE_LINE_REDGE, - _OP_MAKE_CIRCLE_REDGE, - _OP_MAKE_THREE_POINT_ARC_REDGE, - _OP_MAKE_ANGLE_ARC_REDGE, - _OP_MAKE_SPLINE_REDGE, - _OP_MAKE_HELIX_REDGE, - _OP_MAKE_FACE_FROM_WIRE_RFACE, - _OP_MAKE_WIRE_FROM_EDGES_RWIRE, - }: - if op.endswith("_face") or op in { - "make_face_from_wire", - _OP_MAKE_FACE_FROM_WIRE_RFACE, - }: - resolved_entity_type = "Sketch" - else: - resolved_entity_type = "Profile" - elif op in { - "make_box", - "make_cylinder", - "make_cone", - "make_sphere", - "make_box_rsolid", - "make_cylinder_rsolid", - "make_cone_rsolid", - "make_sphere_rsolid", - "extrude", - "revolve", - "loft", - "sweep", - "helical_sweep", - "fillet", - "chamfer", - "shell", - "cut", - "union", - "intersect", - "translate", - "rotate", - "mirror", - _OP_MAKE_EXTRUDE_RSOLID, - _OP_MAKE_REVOLVE_RSOLID, - _OP_MAKE_LOFT_RSOLID, - _OP_MAKE_SWEEP_RSOLID, - _OP_MAKE_TWISTED_SWEEP_RSOLID, - _OP_MAKE_FILLET_RSOLID, - _OP_MAKE_CHAMFER_RSOLID, - _OP_MAKE_SHELL_RSOLID, - _OP_MAKE_CUT_RSOLID, - _OP_MAKE_UNION_RSOLID, - _OP_MAKE_INTERSECT_RSOLID, - _OP_MAKE_TRANSLATE_RSHAPE, - _OP_MAKE_ROTATE_RSHAPE, - _OP_MAKE_MIRROR_RSHAPE, - _OP_LOAD_BREP_REGION_RSOLID, - }: - if op in { - "extrude", - "revolve", - "loft", - "sweep", - "fillet", - "chamfer", - "shell", - "cut", - "union", - "intersect", - _OP_MAKE_EXTRUDE_RSOLID, - _OP_MAKE_REVOLVE_RSOLID, - _OP_MAKE_LOFT_RSOLID, - _OP_MAKE_SWEEP_RSOLID, - _OP_MAKE_TWISTED_SWEEP_RSOLID, - _OP_MAKE_FILLET_RSOLID, - _OP_MAKE_CHAMFER_RSOLID, - _OP_MAKE_SHELL_RSOLID, - _OP_MAKE_CUT_RSOLID, - _OP_MAKE_UNION_RSOLID, - _OP_MAKE_INTERSECT_RSOLID, - }: - resolved_entity_type = "Feature" - else: - resolved_entity_type = "Body" - else: - resolved_entity_type = "ShapeOutput" - - refs = tuple( - SemanticRef( - graph_id="pending", - node_id="pending", - entity_type=resolved_entity_type, - entity_id=f"{op}:{slot}", - ) - for slot in range(output_count) - ) - return SemanticDelta(created=refs, metadata={"op": op}) - - -def _finalize_primitive_shape( - shape: AnyShape, - *, - op: str, - params: Dict[str, object], - tags: Optional[Set[str]] = None, -) -> AnyShape: - _attach_track_summary(shape, op=op) - record_operation_if_active( - op=op, - params=params, - outputs=shape, - semantic_delta=_semantic_delta_for_output(op), - context=_current_context_metadata(), - tags=tags, - ) - return shape - - -def _finalize_primitive_solid( - solid: Solid, - *, - op: str, - params: Dict[str, object], - tags: Optional[Set[str]] = None, -) -> Solid: - return cast( - Solid, - _finalize_primitive_shape(solid, op=op, params=params, tags=tags), - ) - - -def _topology_identity_payload(binding: TagBinding) -> Optional[Dict[str, Any]]: - for key in ("topology_name", "source_topology_name"): - value = binding.evidence.data.get(key) - if isinstance(value, dict): - return value - return None - - -def _copy_exact_topology_identity_tags( - target: AnyShape, - sources: Sequence[AnyShape], - *, - operation: str, -) -> AnyShape: - source_members = [ - member - for source in sources - for member in (source.get_edges() if hasattr(source, "get_edges") else [source]) - if isinstance(member, Edge) - ] - target_members = target.get_edges() if hasattr(target, "get_edges") else [target] - result = target - for target_member in target_members: - if not isinstance(target_member, Edge): - continue - matches = [ - source - for source in source_members - if source.wrapped.IsSame(target_member.wrapped) - ] - if len(matches) != 1: - continue - source = matches[0] - for binding in source._local_tag_bindings(): - topology_identity = _topology_identity_payload(binding) - if topology_identity is None: - continue - local_name = topology_identity.get("local_name") - if not isinstance(local_name, str) or not local_name: - continue - result = _apply_topology_identity_tag( - result, - [target_member], - binding.tag, - kind="edge", - local_name=local_name, - authoring_source=f"simplecadapi.{operation}.identity_tag", - ) - return result - - -def _apply_topology_identity_tag( - scope: AnyShape, - targets: Union[ShapeSelector, Sequence[AnyShape]], - tag: str, - *, - kind: str, - local_name: str, - authoring_source: str, -) -> AnyShape: - normalized = normalize_tag(tag, strict=True) - return _apply_tag_rselection( - scope, - targets, - normalized, - (TopologyPropagation.DOWNWARD if kind == "face" else TopologyPropagation.LOCAL), - LineagePolicy.CONTINUATION_FRAGMENT, - authoring_source=authoring_source, - extra_evidence={ - "topology_name": { - "kind": kind, - "name": normalized, - "local_name": normalize_tag(local_name, strict=True), - } - }, - ) - - -def _apply_shape_tag_prefix( - shape: AnyShape, - tag_prefix: Optional[str], - *, - kind: str, - authoring_source: str, -) -> AnyShape: - if tag_prefix is None: - return shape - prefix = normalize_tag(tag_prefix, strict=True) - tag = f"{prefix}.{kind}" - return _apply_topology_identity_tag( - shape, - ShapeSelector(kind).exactly(1), - tag, - kind=kind, - local_name=kind, - authoring_source=authoring_source, - ) - - -def _apply_profile_tag_prefix( - shape: Union[Wire, Face], - tag_prefix: Optional[str], - edge_tags: Optional[Sequence[str]], - *, - authoring_source: str, -) -> Union[Wire, Face]: - if tag_prefix is None and edge_tags is None: - return shape - prefix = normalize_tag(tag_prefix, strict=True) if tag_prefix is not None else None - result: AnyShape = ( - _apply_shape_tag_prefix( - shape, - prefix, - kind=shape.__class__.__name__.lower(), - authoring_source=authoring_source, - ) - if prefix is not None - else shape - ) - edges = list(shape.get_edges()) - local_names = ( - [str(value) for value in edge_tags] - if edge_tags is not None - else [f"line{index + 1}" for index in range(len(edges))] - ) - if len(local_names) != len(edges): - raise ValueError( - f"edge_tags must contain exactly {len(edges)} tags, got {len(local_names)}" - ) - for edge, raw_local_name in zip(edges, local_names): - local_name = normalize_tag(raw_local_name, strict=True) - edge_tag = f"{prefix}.edge.{local_name}" if prefix else local_name - result = _apply_topology_identity_tag( - result, - [edge], - edge_tag, - kind="edge", - local_name=local_name, - authoring_source=authoring_source, - ) - return cast(Union[Wire, Face], result) - - -def _finalize_derived_shape( - shape: AnyShape, - *, - op: str, - params: Dict[str, object], - input_shapes: Sequence[AnyShape], - tags: Optional[Set[str]] = None, - topo_delta: Optional[TopoDelta] = None, -) -> AnyShape: - _attach_track_summary(shape, op=op) - prepared_inputs = list(_ensure_geo_selection_input_nodes(input_shapes) or ()) - recorded_params = dict(params) - if get_active_session() is not None and op in { - "make_ruled_surface_rface", - "make_gordon_surface_rface", - "make_surface_patch_rface", - "trim_surface_rface", - "make_loft_rshell", - "sew_faces_rshell", - "make_solid_from_shell_rsolid", - "fill_holes_rshell", - }: - input_refs = _serialize_shape_refs(prepared_inputs) - if len(input_refs) != len(prepared_inputs): - raise ValueError( - f"{op} requires every ordered input to have a graph reference" - ) - recorded_params["input_refs"] = input_refs - record_operation_if_active( - op=op, - params=recorded_params, - outputs=shape, - input_shapes=prepared_inputs, - semantic_delta=_semantic_delta_for_output(op), - topo_delta=topo_delta, - context=_current_context_metadata(), - tags=tags, - ) - return shape - - -def _finalize_runtime_object( - output: object, - *, - op: str, - params: Dict[str, object], - input_objects: Optional[Sequence[object]] = None, - tags: Optional[Set[str]] = None, - entity_type: str = "Sketch", -) -> object: - record_operation_if_active( - op=op, - params=params, - outputs=output, - input_shapes=input_objects, - semantic_delta=_semantic_delta_for_output(op, entity_type=entity_type), - context=_current_context_metadata(), - tags=tags, - ) - return output - - -def _finalize_tracked_solid( - solid: Solid, - *, - op: str, - params: Dict[str, object], - source_solid: Optional[Solid] = None, - source_solids: Optional[Sequence[Solid]] = None, - delta: Optional[object] = None, - delta_entries: Optional[Dict[str, Dict[str, object]]] = None, - input_shapes: Optional[Sequence[AnyShape]] = None, -) -> Solid: - if current_tracking_policy() == TrackingPolicy.GRAPH: - delta = None - delta_entries = None - if delta is not None: - apply_tracking_tags_to_delta( - solid, - cast(TopoDelta, delta), - cast(Optional[Dict[str, Dict[str, Any]]], delta_entries), - op=op, - source_solid=source_solid, - source_solids=source_solids, - source_shapes=input_shapes, - ) - _attach_track_summary( - solid, - op=op, - delta=delta, - delta_entries=delta_entries, - ) - record_operation_if_active( - op=op, - params=params, - outputs=solid, - input_shapes=_ensure_geo_selection_input_nodes(input_shapes), - semantic_delta=_semantic_delta_for_output(op), - topo_delta=cast(Optional[TopoDelta], delta), - context=_current_context_metadata(), - ) - return solid - - -def _normalize_operation_role_tags( - op: str, - named_tags: Sequence[Tuple[str, Optional[str]]], -) -> List[Tuple[str, str, str]]: - role_specs = _OPERATION_OUTPUT_ROLE_CARDINALITY[op] - cardinality_by_role = dict(role_specs) - requested: Dict[str, str] = {} - - for role, raw_tag in named_tags: - if raw_tag is None: - continue - if role in requested: - raise ValueError(f"duplicate role tag assignment: {role}") - requested[role] = normalize_tag(raw_tag, strict=True) - - unknown = sorted(set(requested) - set(cardinality_by_role)) - if unknown: - raise ValueError( - f"unsupported output role(s) for {op}: {', '.join(unknown)}; " - f"expected one of {', '.join(cardinality_by_role)}" - ) - return [ - (role, cardinality, requested[role]) - for role, cardinality in role_specs - if role in requested - ] - - -def _validate_operation_output_roles( - delta: TopoDelta, - assignments: Sequence[Tuple[str, str, str]], -) -> Dict[str, str]: - target_kinds: Dict[str, str] = {} - for role, cardinality, _tag in assignments: - role_entries = { - (entry.ref, entry.ref.kind.name.lower()) - for entry in delta.roles - if entry.role == role - and str(entry.metadata.get("coverage", "complete")).lower() == "complete" - and str(entry.metadata.get("status", "proven")).lower() == "proven" - } - refs = {ref for ref, _kind in role_entries} - kinds = {kind for _ref, kind in role_entries} - if cardinality == "one" and len(refs) != 1: - raise SemanticCapabilityError( - f"operation output role '{role}' requires exactly one kernel-proven result, got {len(refs)}" - ) - if cardinality == "many" and not refs: - raise SemanticCapabilityError( - f"operation output role '{role}' requires at least one kernel-proven result" - ) - if len(kinds) != 1: - raise SemanticCapabilityError( - f"operation output role '{role}' does not resolve to one topology kind" - ) - target_kinds[role] = next(iter(kinds)) - return target_kinds - - -def _apply_operation_role_tags( - shape: AnyShape, - *, - op: str, - assignments: Sequence[Tuple[str, str, str]], - target_kinds: Mapping[str, str], - result_tag: Optional[str] = None, -) -> AnyShape: - if not assignments and result_tag is None: - return shape - - role_source_node = _active_graph_node_for_shape(shape) - role_source_slot = int(shape._get_runtime("graph.output_slot", 0)) - result: AnyShape = shape - for role, cardinality, tag in assignments: - selector = ShapeSelector(target_kinds[role]).where(output_role(role)) - selector = selector.exactly(1) if cardinality == "one" else selector.at_least(1) - result = _apply_tag_rselection( - result, - selector, - tag, - TopologyPropagation.LOCAL, - LineagePolicy.CONTINUATION_FRAGMENT, - authoring_source=f"simplecadapi.{op}.role_tag", - extra_evidence={ - "operation_output_role": { - "source_node_id": ( - role_source_node.node_id - if role_source_node is not None - else None - ), - "source_output_slot": role_source_slot, - "operation": op, - "role": role, - "cardinality": cardinality, - } - }, - ) - if result_tag is not None: - result = _apply_tag_rselection( - result, - ShapeSelector(_shape_kind_token(shape)).exactly(1), - result_tag, - TopologyPropagation.LOCAL, - LineagePolicy.CONTINUATION_FRAGMENT, - authoring_source=f"simplecadapi.{op}.result_tag", - extra_evidence={ - "operation_result": { - "source_node_id": ( - role_source_node.node_id - if role_source_node is not None - else None - ), - "source_output_slot": role_source_slot, - "operation": op, - } - }, - ) - return result - - -def _topology_identity_local_name(shape: AnyShape) -> Optional[str]: - for binding in shape._local_tag_bindings(): - payload = _topology_identity_payload(binding) - if ( - payload is not None - and payload.get("kind") == shape.__class__.__name__.lower() - ): - local_name = payload.get("local_name") - if isinstance(local_name, str) and local_name: - return local_name - return None - - -def _apply_feature_tag_prefix( - solid: Solid, - *, - tag_prefix: Optional[str], - op: str, - delta: TopoDelta, - start_role: Optional[str] = None, - end_role: Optional[str] = None, - side_role: Optional[str] = None, - source_shapes: Sequence[AnyShape] = (), - edge_roles: Sequence[Tuple[str, str]] = (), - face_roles: Sequence[Tuple[str, str]] = (), -) -> Solid: - if tag_prefix is None: - return solid - prefix = normalize_tag(tag_prefix, strict=True) - result: AnyShape = _apply_topology_identity_tag( - solid, - ShapeSelector("solid").exactly(1), - f"{prefix}.solid", - kind="solid", - local_name="solid", - authoring_source=f"simplecadapi.{op}.tag_prefix", - ) - - for role, local_name in ( - (start_role, "start"), - (end_role, "end"), - (side_role, "side"), - ): - if role is None: - continue - cardinality = "one" if local_name in {"start", "end"} else "many" - selector = ShapeSelector("face").where(output_role(role)) - selector = selector.exactly(1) if cardinality == "one" else selector.at_least(1) - result = _apply_topology_identity_tag( - cast(Solid, result), - selector, - f"{prefix}.face.{local_name}", - kind="face", - local_name=local_name, - authoring_source=f"simplecadapi.{op}.tag_prefix", - ) - - source_edges = { - _topo_id(edge.wrapped): edge - for source in source_shapes - for edge in ( - source.get_edges() - if hasattr(source, "get_edges") - else ([source] if isinstance(source, Edge) else []) - ) - } - result_faces = { - _topo_id(face.wrapped): face for face in cast(Solid, result).get_faces() - } - if side_role is not None: - # A side Face may have multiple source profile Edges (for example, a - # loft side joins the corresponding Edges from two sections). A - # A topology-identity tag is safe only when kernel history proves a bijection. - side_correspondence: List[Tuple[str, str]] = [] - for role_entry in delta.roles: - if role_entry.role != side_role: - continue - parent_edges = [ - parent - for parent in role_entry.parent_refs - if parent.kind == TopoKind.EDGE - ] - if len(parent_edges) != 1: - continue - side_correspondence.append( - (role_entry.ref.topo_id, parent_edges[0].topo_id) - ) - - target_sources: Dict[str, Set[str]] = {} - source_targets: Dict[str, Set[str]] = {} - for target_id, source_id in side_correspondence: - target_sources.setdefault(target_id, set()).add(source_id) - source_targets.setdefault(source_id, set()).add(target_id) - - for target_id, source_id in side_correspondence: - if len(target_sources[target_id]) != 1: - continue - if len(source_targets[source_id]) != 1: - continue - source_edge = source_edges.get(source_id) - target_face = result_faces.get(target_id) - if source_edge is None or target_face is None: - continue - edge_local_name = _topology_identity_local_name(source_edge) - if edge_local_name is None: - continue - result = _apply_topology_identity_tag( - cast(Solid, result), - [target_face], - f"{prefix}.face.side.{edge_local_name}", - kind="face", - local_name=f"side.{edge_local_name}", - authoring_source=f"simplecadapi.{op}.profile_edge_tag", - ) - - for role, local_name in edge_roles: - result = _apply_topology_identity_tag( - cast(Solid, result), - ShapeSelector("edge").where(output_role(role)).exactly(1), - f"{prefix}.edge.{local_name}", - kind="edge", - local_name=local_name, - authoring_source=f"simplecadapi.{op}.tag_prefix", - ) - for role, local_name in face_roles: - result = _apply_topology_identity_tag( - cast(Solid, result), - ShapeSelector("face").where(output_role(role)).exactly(1), - f"{prefix}.face.{local_name}", - kind="face", - local_name=local_name, - authoring_source=f"simplecadapi.{op}.tag_prefix", - ) - return cast(Solid, result) - - -# ============================================================================= -# 基础图形创建函数 -# ============================================================================= - - -def make_point_rvertex(x: ScalarLike, y: ScalarLike, z: ScalarLike) -> Vertex: - """Create a point in 3D space and return it as a vertex.""" - try: - cs = get_current_cs() - point_value = cast(Tuple[float, float, float], evaluate_value((x, y, z))) - global_point = cs.transform_point(np.array(point_value)) - vertex_shape = BRepBuilderAPI_MakeVertex( - gp_Pnt( - float(global_point[0]), float(global_point[1]), float(global_point[2]) - ) - ).Vertex() - return cast( - Vertex, - _finalize_primitive_shape( - Vertex(vertex_shape), - op=_OP_MAKE_POINT_RVERTEX, - params={"x": x, "y": y, "z": z}, - tags={"primitive", "vertex"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_point_rvertex", - what_happened="Failed to create a point vertex.", - possible_causes=[ - "One or more coordinate values are not valid finite scalars.", - "The current coordinate system rejected the transformed point.", - ], - how_to_fix=[ - "Pass numeric x, y, and z values or valid scalar expressions.", - "Inspect the coordinate values and the active workplane before retrying.", - ], - error=e, - ) - - -def make_sketch_rsketch( - name: Optional[str] = None, - *, - plane: Any = "XY", - sketch_id: Optional[str] = None, -) -> Sketch: - """Create an empty declarative sketch document. - - Use this API, not concrete edge/wire constructors, when the intent is to - build a sketch profile with constraints. - """ - try: - session = get_active_session() - resolved_sketch_id = ( - sketch_id - if sketch_id is not None or session is None - else session.allocate_object_id("sketch") - ) - sketch = Sketch( - name=name, - plane=_sketch_plane_in_current_coordinates(plane), - sketch_id=resolved_sketch_id, - ) - return cast( - Sketch, - _finalize_runtime_object( - sketch, - op=_OP_MAKE_SKETCH_RSKETCH, - params={"name": name, "plane": plane, "sketch_id": sketch.sketch_id}, - tags={"sketch"}, - entity_type="Sketch", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_sketch_rsketch", - what_happened="Failed to create a sketch document.", - possible_causes=["The sketch name or plane payload is invalid."], - how_to_fix=["Use plane='XY', 'XZ', 'YZ', or a valid plane mapping."], - error=e, - ) - - -def _safe_semantic_tag(prefix: str, value: object) -> str: - raw = str(value or "unnamed").strip().lower() - raw = re.sub(r"[^a-z0-9_-]+", ".", raw).strip(".") - raw = re.sub(r"\.+", ".", raw) - segments: List[str] = [] - for segment in raw.split("."): - if not segment: - continue - if not segment[0].isalpha(): - segment = f"id_{segment}" - segments.append(segment) - if not segments: - segments = ["unnamed"] - return normalize_tag(f"{prefix}.{'.'.join(segments)}", strict=True) - - -def _sketch_target_to_path(target: SketchRef) -> str: - if target.kind == "point" and target.subentity != "geometry": - return f"{target.entity_id}.{target.subentity}" - return target.entity_id - - -def _resolve_sketch_target( - sketch: Sketch, - target: Union[SketchRef, str], - *, - expected: Optional[Union[str, Sequence[str]]] = None, -) -> SketchRef: - return sketch.resolve_target(target, expected=expected) - - -def _resolve_sketch_targets( - sketch: Sketch, - targets: Sequence[Union[SketchRef, str]], - *, - expected: Optional[Sequence[Optional[Union[str, Sequence[str]]]]] = None, -) -> List[SketchRef]: - refs: List[SketchRef] = [] - for index, target in enumerate(targets): - target_expected = expected[index] if expected is not None else None - refs.append(_resolve_sketch_target(sketch, target, expected=target_expected)) - return refs - - -def _begin_linear_sketch_edits(sketch: Sketch) -> Sketch: - """Enable in-place edits for one private, linear sketch construction chain.""" - sketch._set_runtime("sketch.linear_edit", True) - return sketch - - -def _end_linear_sketch_edits(sketch: Sketch) -> Sketch: - sketch._set_runtime("sketch.linear_edit", False) - return sketch - - -def _sketch_update_target(sketch: Sketch) -> Sketch: - if sketch._get_runtime("sketch.linear_edit", False): - sketch._last_solve_result = None - return sketch - return sketch.clone(include_solve=False) - - -def add_point_rsketch( - sketch: Sketch, - point_id: str, - x: ScalarLike, - y: ScalarLike, -) -> Sketch: - """Add a named point entity and return an updated sketch document.""" - try: - updated = _sketch_update_target(sketch) - updated.add_point(point_id, x, y) - return cast( - Sketch, - _finalize_runtime_object( - updated, - op=_OP_ADD_POINT_RSKETCH, - params={ - "sketch_id": updated.sketch_id, - "point_id": point_id, - "x": x, - "y": y, - }, - input_objects=[sketch], - tags={"sketch", "point"}, - entity_type="Sketch", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="add_point_rsketch", - what_happened="Failed to add a point to the sketch.", - possible_causes=[ - "The sketch is invalid.", - "The point id is duplicated.", - "The x or y value is not a valid scalar or expression.", - ], - how_to_fix=[ - "Use a unique point id within the sketch.", - "Pass numeric x/y values or valid scalar expressions.", - ], - error=e, - ) - - -def get_sketch_entity_rsketchref( - sketch: Sketch, - entity_id: str, -) -> SketchRef: - """Return a stable ref for a named sketch entity.""" - return sketch.ref(entity_id) - - -def get_sketch_point_rsketchref( - sketch: Sketch, - point_path: str, -) -> SketchRef: - """Return a stable ref for a sketch point or endpoint path.""" - return sketch.point_ref(point_path) - - -def add_line_rsketch( - sketch: Sketch, - entity_id: str, - start: Union[SketchRef, str], - end: Union[SketchRef, str], - *, - construction: bool = False, -) -> Sketch: - """Add a named line entity and return an updated sketch document.""" - try: - start_ref = _resolve_sketch_target(sketch, start, expected="point") - end_ref = _resolve_sketch_target(sketch, end, expected="point") - updated = _sketch_update_target(sketch) - updated.add_line(entity_id, start_ref, end_ref, construction=construction) - return cast( - Sketch, - _finalize_runtime_object( - updated, - op=_OP_ADD_LINE_RSKETCH, - params={ - "sketch_id": updated.sketch_id, - "entity_id": entity_id, - "start": _sketch_target_to_path(start_ref), - "end": _sketch_target_to_path(end_ref), - "construction": construction, - }, - input_objects=[sketch], - tags={"sketch", "line"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="add_line_rsketch", - what_happened="Failed to add a line to the sketch.", - possible_causes=[ - "The line id is duplicated.", - "One of the endpoint refs does not belong to this sketch.", - "Both endpoints resolve to the same point.", - ], - how_to_fix=[ - "Use a unique line id.", - "Create endpoints with add_point_rsketch(...) and refer to them by id.", - ], - error=e, - ) - - -def add_circle_rsketch( - sketch: Sketch, - entity_id: str, - center: Union[SketchRef, str], - radius: ScalarLike, - *, - construction: bool = False, -) -> Sketch: - """Add a named circle entity and return an updated sketch document.""" - try: - center_ref = _resolve_sketch_target(sketch, center, expected="point") - updated = _sketch_update_target(sketch) - updated.add_circle(entity_id, center_ref, radius, construction=construction) - return cast( - Sketch, - _finalize_runtime_object( - updated, - op=_OP_ADD_CIRCLE_RSKETCH, - params={ - "sketch_id": updated.sketch_id, - "entity_id": entity_id, - "center": _sketch_target_to_path(center_ref), - "radius": radius, - "construction": construction, - }, - input_objects=[sketch], - tags={"sketch", "circle"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="add_circle_rsketch", - what_happened="Failed to add a circle to the sketch.", - possible_causes=[ - "The circle id is duplicated.", - "The center ref does not belong to this sketch.", - "The radius is not positive.", - ], - how_to_fix=[ - "Use a unique circle id and a positive radius.", - "Create the center with add_point_rsketch(...) and refer to it by id.", - ], - error=e, - ) - - -def add_bspline_rsketch( - sketch: Sketch, - entity_id: str, - start: Union[SketchRef, str], - end: Union[SketchRef, str], - control_points: Sequence[Any], - degree: int = 3, - knots: Optional[Sequence[float]] = None, - multiplicities: Optional[Sequence[int]] = None, - weights: Optional[Sequence[float]] = None, - periodic: bool = False, - *, - construction: bool = False, -) -> Sketch: - """Add a B-spline curve entity to a sketch. - - The start/end point refs link the B-spline into a closed profile - loop. Control points may be literal 2-D coordinates or point refs. - """ - try: - start_ref = _resolve_sketch_target(sketch, start, expected="point") - end_ref = _resolve_sketch_target(sketch, end, expected="point") - updated = _sketch_update_target(sketch) - updated.add_bspline( - entity_id, - start_ref, - end_ref, - control_points=control_points, - degree=degree, - knots=knots, - multiplicities=multiplicities, - weights=weights, - periodic=periodic, - construction=construction, - ) - bspline_data = updated.entities[str(entity_id)].data - return cast( - Sketch, - _finalize_runtime_object( - updated, - op=_OP_ADD_BSPLINE_RSKETCH, - params={ - "sketch_id": updated.sketch_id, - "entity_id": entity_id, - "start": _sketch_target_to_path(start_ref), - "end": _sketch_target_to_path(end_ref), - "control_points": bspline_data["control_points"], - "degree": bspline_data["degree"], - "knots": bspline_data["knots"], - "multiplicities": bspline_data["multiplicities"], - "weights": bspline_data["weights"], - "periodic": bspline_data["periodic"], - "construction": construction, - }, - input_objects=[sketch], - tags={"sketch", "bspline"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="add_bspline_rsketch", - what_happened="Failed to add a B-spline to the sketch.", - possible_causes=[ - "The entity id is duplicated.", - "The start or end ref does not belong to this sketch.", - "Too few control points for the requested degree.", - ], - how_to_fix=[ - "Use a unique entity id.", - "Create start and end points with add_point_rsketch(...) first.", - "Pass at least degree+1 control points.", - ], - error=e, - ) - - -def add_arc_rsketch( - sketch: Sketch, - entity_id: str, - start: Union[SketchRef, str], - end: Union[SketchRef, str], - center: Union[SketchRef, str], - *, - construction: bool = False, -) -> Sketch: - """Add an arc entity to a sketch.""" - try: - start_ref = _resolve_sketch_target(sketch, start, expected="point") - end_ref = _resolve_sketch_target(sketch, end, expected="point") - center_ref = _resolve_sketch_target(sketch, center, expected="point") - updated = _sketch_update_target(sketch) - updated.add_arc( - entity_id, - start_ref, - end_ref, - center_ref, - construction=construction, - ) - return cast( - Sketch, - _finalize_runtime_object( - updated, - op=_OP_ADD_ARC_RSKETCH, - params={ - "sketch_id": updated.sketch_id, - "entity_id": entity_id, - "start": _sketch_target_to_path(start_ref), - "end": _sketch_target_to_path(end_ref), - "center": _sketch_target_to_path(center_ref), - "construction": construction, - }, - input_objects=[sketch], - tags={"sketch", "arc"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="add_arc_rsketch", - what_happened="Failed to add an arc to the sketch.", - possible_causes=[ - "The entity id is duplicated.", - "The start, end, or center ref does not belong to this sketch.", - "The start and end points are the same.", - ], - how_to_fix=[ - "Use a unique entity id.", - "Create start, end, and center points with add_point_rsketch(...) first.", - ], - error=e, - ) - - -def _constrain_rsketch( - sketch: Sketch, - kind: str, - targets: Sequence[Union[SketchRef, str]], - *, - value: Any = None, - constraint_id: Optional[str] = None, - driving: bool = True, - metadata: Optional[Dict[str, Any]] = None, - expected: Optional[Sequence[Optional[Union[str, Sequence[str]]]]] = None, -) -> Sketch: - target_refs = _resolve_sketch_targets(sketch, targets, expected=expected) - updated = _sketch_update_target(sketch) - updated.add_constraint( - kind, - target_refs, - value=value, - constraint_id=constraint_id, - driving=driving, - metadata=metadata, - ) - op = _SKETCH_CONSTRAINT_OPS[kind] - return cast( - Sketch, - _finalize_runtime_object( - updated, - op=op, - params={ - "sketch_id": updated.sketch_id, - "kind": kind, - "targets": [_sketch_target_to_path(target) for target in target_refs], - "value": value, - "constraint_id": constraint_id, - "driving": driving, - "metadata": metadata or {}, - }, - input_objects=[sketch], - tags={"sketch", "constraint"}, - ), - ) - - -def constrain_coincident_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain two sketch points to be coincident.""" - return _constrain_rsketch( - sketch, - "coincident", - [a, b], - constraint_id=constraint_id, - expected=["point", "point"], - ) - - -def constrain_connect_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Alias for `constrain_coincident_rsketch` using connection wording.""" - return _constrain_rsketch( - sketch, - "coincident", - [a, b], - constraint_id=constraint_id, - expected=["point", "point"], - ) - - -def constrain_point_on_rsketch( - sketch: Sketch, - point: Union[SketchRef, str], - entity: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain a sketch point to lie on a line, circle, or circular arc.""" - return _constrain_rsketch( - sketch, - "point_on", - [point, entity], - constraint_id=constraint_id, - expected=["point", ("line", "circle", "arc")], - ) - - -def constrain_horizontal_rsketch( - sketch: Sketch, line: Union[SketchRef, str], *, constraint_id: Optional[str] = None -) -> Sketch: - """Constrain a sketch line to be horizontal.""" - return _constrain_rsketch( - sketch, "horizontal", [line], constraint_id=constraint_id, expected=["line"] - ) - - -def constrain_vertical_rsketch( - sketch: Sketch, line: Union[SketchRef, str], *, constraint_id: Optional[str] = None -) -> Sketch: - """Constrain a sketch line to be vertical.""" - return _constrain_rsketch( - sketch, "vertical", [line], constraint_id=constraint_id, expected=["line"] - ) - - -def constrain_parallel_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain two sketch lines to be parallel.""" - return _constrain_rsketch( - sketch, - "parallel", - [a, b], - constraint_id=constraint_id, - expected=["line", "line"], - ) - - -def constrain_perpendicular_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain two sketch lines to be perpendicular.""" - return _constrain_rsketch( - sketch, - "perpendicular", - [a, b], - constraint_id=constraint_id, - expected=["line", "line"], - ) - - -def constrain_collinear_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain two sketch lines to lie on the same infinite line.""" - return _constrain_rsketch( - sketch, - "collinear", - [a, b], - constraint_id=constraint_id, - expected=["line", "line"], - ) - - -def constrain_tangent_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - at_a: Optional[str] = None, - at_b: Optional[str] = None, - mode: str = "external", - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain supported curves to be tangent on an explicit branch. - - ``at_a``/``at_b`` select ``"start"`` or ``"end"`` for arc and - B-spline endpoint tangency. Circle-circle tangency accepts - ``mode="external"`` or ``mode="internal"``. - """ - if at_a not in {None, "start", "end"} or at_b not in {None, "start", "end"}: - raise ValueError("Tangent endpoint selectors must be 'start' or 'end'") - if mode not in {"external", "internal"}: - raise ValueError("Tangent mode must be 'external' or 'internal'") - return _constrain_rsketch( - sketch, - "tangent", - [a, b], - constraint_id=constraint_id, - metadata={"at_a": at_a, "at_b": at_b, "mode": mode}, - expected=[ - ("line", "circle", "arc", "bspline"), - ("line", "circle", "arc", "bspline"), - ], - ) - - -def constrain_concentric_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain two sketch circles to share a center.""" - return _constrain_rsketch( - sketch, - "concentric", - [a, b], - constraint_id=constraint_id, - expected=[("circle", "arc"), ("circle", "arc")], - ) - - -def constrain_midpoint_rsketch( - sketch: Sketch, - point: Union[SketchRef, str], - line: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain a sketch point to the midpoint of a line.""" - return _constrain_rsketch( - sketch, - "midpoint", - [point, line], - constraint_id=constraint_id, - expected=["point", "line"], - ) - - -def constrain_symmetric_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - axis: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain two sketch points to be symmetric about a line axis.""" - return _constrain_rsketch( - sketch, - "symmetric", - [a, b, axis], - constraint_id=constraint_id, - expected=["point", "point", "line"], - ) - - -def constrain_equal_length_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain two sketch lines to have equal length.""" - return _constrain_rsketch( - sketch, - "equal_length", - [a, b], - constraint_id=constraint_id, - expected=["line", "line"], - ) - - -def constrain_equal_radius_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Constrain two circles/arcs to have equal radius.""" - return _constrain_rsketch( - sketch, - "equal_radius", - [a, b], - constraint_id=constraint_id, - expected=[("circle", "arc"), ("circle", "arc")], - ) - - -def constrain_distance_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - value: ScalarLike, - *, - constraint_id: Optional[str] = None, - driving: bool = True, -) -> Sketch: - """Add a driving point-to-point distance constraint.""" - return _constrain_rsketch( - sketch, - "distance", - [a, b], - value=value, - constraint_id=constraint_id, - driving=driving, - expected=["point", "point"], - ) - - -def constrain_distance_x_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - value: ScalarLike, - *, - constraint_id: Optional[str] = None, - driving: bool = True, -) -> Sketch: - """Add a driving horizontal distance constraint.""" - return _constrain_rsketch( - sketch, - "distance_x", - [a, b], - value=value, - constraint_id=constraint_id, - driving=driving, - expected=["point", "point"], - ) - - -def constrain_distance_y_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - value: ScalarLike, - *, - constraint_id: Optional[str] = None, - driving: bool = True, -) -> Sketch: - """Add a driving vertical distance constraint.""" - return _constrain_rsketch( - sketch, - "distance_y", - [a, b], - value=value, - constraint_id=constraint_id, - driving=driving, - expected=["point", "point"], - ) - - -def constrain_length_rsketch( - sketch: Sketch, - line: Union[SketchRef, str], - value: ScalarLike, - *, - constraint_id: Optional[str] = None, - driving: bool = True, -) -> Sketch: - """Add a driving length constraint to a line, arc, or B-spline.""" - return _constrain_rsketch( - sketch, - "length", - [line], - value=value, - constraint_id=constraint_id, - driving=driving, - expected=[("line", "arc", "bspline")], - ) - - -def constrain_angle_rsketch( - sketch: Sketch, - a: Union[SketchRef, str], - b: Union[SketchRef, str], - value: ScalarLike, - *, - constraint_id: Optional[str] = None, - driving: bool = True, -) -> Sketch: - """Add a driving angle constraint between two sketch lines.""" - return _constrain_rsketch( - sketch, - "angle", - [a, b], - value=value, - constraint_id=constraint_id, - driving=driving, - expected=["line", "line"], - ) - - -def constrain_radius_rsketch( - sketch: Sketch, - circle: Union[SketchRef, str], - value: ScalarLike, - *, - constraint_id: Optional[str] = None, - driving: bool = True, -) -> Sketch: - """Add a driving circle or arc radius constraint.""" - return _constrain_rsketch( - sketch, - "radius", - [circle], - value=value, - constraint_id=constraint_id, - driving=driving, - expected=[("circle", "arc")], - ) - - -def constrain_diameter_rsketch( - sketch: Sketch, - circle: Union[SketchRef, str], - value: ScalarLike, - *, - constraint_id: Optional[str] = None, - driving: bool = True, -) -> Sketch: - """Add a driving circle or arc diameter constraint.""" - return _constrain_rsketch( - sketch, - "diameter", - [circle], - value=value, - constraint_id=constraint_id, - driving=driving, - expected=[("circle", "arc")], - ) - - -def constrain_fix_rsketch( - sketch: Sketch, - target: Union[SketchRef, str], - *, - constraint_id: Optional[str] = None, -) -> Sketch: - """Fix a sketch point or entity to its initial coordinates.""" - return _constrain_rsketch(sketch, "fix", [target], constraint_id=constraint_id) - - -def inspect_sketch_rsketchresult( - sketch: Sketch, - *, - require_fully_constrained: bool = False, - strict: bool = True, - tolerance: float = 1e-7, - max_iterations: int = 80, -) -> SketchSolveResult: - """Inspect sketch constraints by running the solver without recording graph nodes.""" - try: - result = sketch.clone(include_solve=False).solve( - require_fully_constrained=require_fully_constrained, - strict=strict, - tolerance=tolerance, - max_iterations=max_iterations, - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="inspect_sketch_rsketchresult", - what_happened="Failed to inspect the sketch constraints.", - possible_causes=[ - "The sketch has invalid, conflicting, or underconstrained constraints.", - "A constraint references a missing or wrong-kind entity.", - ], - how_to_fix=[ - "Inspect diagnostics with strict=False if needed.", - "Add fix/dimension constraints until the intended profile is fully constrained.", - ], - error=e, - ) - - -def _sketch_solve_snapshot(result: SketchSolveResult) -> Dict[str, Any]: - return result.to_dict() - - -def _sketch_source_metadata( - sketch: Sketch, - profile: int | str, - profile_payload: Dict[str, Any], - inner_profile_payloads: Sequence[Tuple[int | str, Dict[str, Any]]] = (), -) -> Dict[str, Any]: - return { - "sketch_id": sketch.sketch_id, - "name": sketch.name, - "plane": sketch.plane, - "profile": profile, - "profile_id": profile_payload.get("id"), - "profile_kind": profile_payload.get("kind"), - "inner_profiles": [ - { - "profile": inner_profile, - "profile_id": inner_payload.get("id"), - "profile_kind": inner_payload.get("kind"), - } - for inner_profile, inner_payload in inner_profile_payloads - ], - } - - -def _sketch_edge_metadata( - sketch: Sketch, - entity_id: str, - profile: int | str, - profile_payload: Dict[str, Any], - *, - loop_role: str = "outer", -) -> Dict[str, Any]: - entity = sketch.entities[str(entity_id)] - return { - "sketch_id": sketch.sketch_id, - "sketch_name": sketch.name, - "entity_id": str(entity_id), - "kind": entity.kind, - "profile": profile, - "profile_id": profile_payload.get("id"), - "loop_role": loop_role, - } - - -def _sketch_promotion_tags( - sketch: Sketch, - profile_payload: Dict[str, Any], -) -> Tuple[str, str]: - sketch_tag = _safe_semantic_tag("sketch", sketch.name or sketch.sketch_id) - profile_tag = _safe_semantic_tag( - "sketch_profile", profile_payload.get("id", "profile") - ) - return sketch_tag, profile_tag - - -def _sketch_promotion_map( - sketch: Sketch, - profile: int | str, - profile_payload: Dict[str, Any], - *, - inner_profile_payloads: Sequence[Tuple[int | str, Dict[str, Any]]] = (), - target_kind: Optional[str] = None, -) -> Dict[str, Any]: - sketch_tag, profile_tag = _sketch_promotion_tags(sketch, profile_payload) - profile_local_name = _sketch_topology_tag_local_name( - profile_payload.get("id", "profile") - ) - profile_identity_tag = f"{sketch_tag}.profile.{profile_local_name}" - edges: List[Dict[str, Any]] = [] - loops: List[Dict[str, Any]] = [] - loop_specs = [ - (profile, profile_payload, "outer"), - *[ - (inner_profile, inner_payload, "inner") - for inner_profile, inner_payload in inner_profile_payloads - ], - ] - for loop_profile, loop_payload, loop_role in loop_specs: - loop_sketch_tag, loop_profile_tag = _sketch_promotion_tags(sketch, loop_payload) - loop_edges: List[Dict[str, Any]] = [] - for entity_id in loop_payload.get("entity_ids", []): - entity_tag = _safe_semantic_tag("sketch_entity", entity_id) - entity_local_name = _sketch_topology_tag_local_name(entity_id) - edge_payload = { - "entity_id": str(entity_id), - "profile": loop_profile, - "profile_id": loop_payload.get("id"), - "loop_role": loop_role, - "target_kind": "edge", - "tags": [loop_sketch_tag, loop_profile_tag, entity_tag], - "topology_name": { - "kind": "edge", - "name": f"{loop_sketch_tag}.entity.{entity_local_name}", - "local_name": entity_local_name, - }, - "metadata": { - "sketch_ref": _sketch_edge_metadata( - sketch, - str(entity_id), - loop_profile, - loop_payload, - loop_role=loop_role, - ) - }, - } - loop_edges.append(edge_payload) - edges.append(edge_payload) - loop_local_name = _sketch_topology_tag_local_name( - loop_payload.get("id", "profile") - ) - loops.append( - { - "role": loop_role, - "profile": loop_profile, - "profile_id": loop_payload.get("id"), - "profile_kind": loop_payload.get("kind"), - "topology_name": { - "kind": "wire", - "name": f"{loop_sketch_tag}.profile.{loop_local_name}", - "local_name": loop_local_name, - }, - "edges": loop_edges, - } - ) - return { - "schema_version": "2.0", - "profile": profile, - "profile_id": profile_payload.get("id"), - "profile_kind": profile_payload.get("kind"), - "tags": [sketch_tag, profile_tag], - "topology_name": { - "kind": target_kind or "profile", - "name": profile_identity_tag, - "local_name": profile_local_name, - }, - "loops": loops, - "edges": edges, - } - - -def _apply_sketch_promotion_metadata( - shape: Union[Wire, Face], - *, - sketch: Sketch, - profile: int | str, - profile_payload: Dict[str, Any], - inner_profile_payloads: Sequence[Tuple[int | str, Dict[str, Any]]], - source_wires: Sequence[Tuple[int | str, Dict[str, Any], str, Wire]], - solve_snapshot: Dict[str, Any], -) -> None: - source_sketch = _sketch_source_metadata( - sketch, - profile, - profile_payload, - inner_profile_payloads, - ) - promotion_map = _sketch_promotion_map( - sketch, - profile, - profile_payload, - inner_profile_payloads=inner_profile_payloads, - target_kind="wire" if isinstance(shape, Wire) else "face", - ) - sketch_tag, profile_tag = _sketch_promotion_tags(sketch, profile_payload) - - shape.set_metadata("source_sketch", source_sketch) - shape.set_metadata("sketch_solve", solve_snapshot) - shape.set_metadata("sketch_promotion", promotion_map) - shape._apply_tag(sketch_tag, propagate=False) - shape._apply_tag(profile_tag, propagate=False) - - wires: List[Wire] = [] - if isinstance(shape, Wire): - wires = [shape] - elif isinstance(shape, Face): - wires = cast(List[Wire], shape.get_wires()) - - for wire in wires: - matches = [ - source for source in source_wires if source[3].wrapped.IsSame(wire.wrapped) - ] - if len(matches) != 1: - raise ValueError( - "Sketch promotion cannot establish exact profile-to-wire correspondence" - ) - loop_profile, loop_payload, _loop_role, _source_wire = matches[0] - loop_sketch_tag, loop_profile_tag = _sketch_promotion_tags(sketch, loop_payload) - wire.set_metadata("source_sketch", source_sketch) - wire.set_metadata("sketch_solve", solve_snapshot) - wire.set_metadata("sketch_promotion", promotion_map) - wire.set_metadata( - "sketch_profile", - _sketch_source_metadata(sketch, loop_profile, loop_payload), - ) - wire._apply_tag(loop_sketch_tag, propagate=False) - wire._apply_tag(loop_profile_tag, propagate=False) - - source_edges = [ - (loop_profile, loop_payload, loop_role, str(entity_id), source_edge) - for loop_profile, loop_payload, loop_role, source_wire in source_wires - for entity_id, source_edge in source_wire._get_runtime( - "sketch.entity_edges", [] - ) - ] - for edge in cast(List[Edge], shape.get_edges()): - matches = [source for source in source_edges if source[4].IsSame(edge.wrapped)] - if len(matches) != 1: - raise ValueError( - "Sketch promotion cannot establish exact entity-to-edge correspondence" - ) - loop_profile, loop_payload, loop_role, entity_id, _source_edge = matches[0] - loop_sketch_tag, loop_profile_tag = _sketch_promotion_tags(sketch, loop_payload) - entity_tag = _safe_semantic_tag("sketch_entity", entity_id) - edge.set_metadata( - "sketch_ref", - _sketch_edge_metadata( - sketch, - entity_id, - loop_profile, - loop_payload, - loop_role=loop_role, - ), - ) - edge.set_metadata("source_sketch", source_sketch) - edge._apply_tag(loop_sketch_tag, propagate=False) - edge._apply_tag(loop_profile_tag, propagate=False) - edge._apply_tag(entity_tag, propagate=False) - - -def _sketch_topology_tag_local_name(value: object) -> str: - """Return the normalized local segment for a sketch topology tag.""" - - return _safe_semantic_tag("name", value).split(".", 1)[1] - - -def _sketch_topology_identity_binding( - tag: str, - *, - kind: str, - local_name: str, - operation: str, - sketch: Sketch, - profile_id: str, - target_topo_id: str, - entity_id: Optional[str] = None, -) -> TagBinding: - rule_id = "simplecad.sketch_promotion_topology_name" - binding_key = "|".join( - ( - rule_id, - operation, - sketch.sketch_id, - profile_id, - entity_id or "", - target_topo_id, - tag, - ) - ) - return TagBinding( - tag=tag, - producer=TagProducer( - "auto_rule", - rule_id=rule_id, - rule_version="1.0", - ), - target=TagTarget("scope_root"), - propagation=TagPropagation( - topology=( - TopologyPropagation.DOWNWARD - if kind == "face" - else TopologyPropagation.LOCAL - ), - lineage=LineagePolicy.CONTINUATION_FRAGMENT, - ), - evidence=TagEvidence( - "topology_change", - { - "operation": operation, - "target_topo_id": target_topo_id, - "evidence_method": "SketchPromotionMap", - "sketch_promotion": { - "sketch_id": sketch.sketch_id, - "profile_id": profile_id, - **({"entity_id": entity_id} if entity_id is not None else {}), - }, - "topology_name": { - "kind": kind, - "name": tag, - "local_name": local_name, - }, - }, - ), - certainty=TagCertainty.PROVEN, - lifecycle=TagLifecycle.RECOMPUTE, - binding_id=f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, binding_key).hex}", - ) - - -def _apply_sketch_promotion_identity_tags( - shape: Union[Wire, Face], - *, - sketch: Sketch, - profile_payload: Dict[str, Any], - source_wires: Sequence[Tuple[int | str, Dict[str, Any], str, Wire]], - operation: str, -) -> Union[Wire, Face]: - """Attach topology-identity tags from an exact sketch promotion map.""" - - sketch_prefix = _safe_semantic_tag("sketch", sketch.name or sketch.sketch_id) - profile_local_name = _sketch_topology_tag_local_name( - profile_payload.get("id", "profile") - ) - profile_kind = "wire" if isinstance(shape, Wire) else "face" - profile_tag = f"{sketch_prefix}.profile.{profile_local_name}" - shape._add_tag_binding( - _sketch_topology_identity_binding( - profile_tag, - kind=profile_kind, - local_name=profile_local_name, - operation=operation, - sketch=sketch, - profile_id=str(profile_payload.get("id", "profile")), - target_topo_id=shape.topo_id, - ) - ) - - if isinstance(shape, Face): - for wire in cast(List[Wire], shape.get_wires()): - matches = [ - source - for source in source_wires - if source[3].wrapped.IsSame(wire.wrapped) - ] - if len(matches) != 1: - raise ValueError( - "Sketch promotion cannot establish exact profile-to-wire correspondence" - ) - _loop_profile, loop_payload, _loop_role, _source_wire = matches[0] - loop_local_name = _sketch_topology_tag_local_name( - loop_payload.get("id", "profile") - ) - wire._add_tag_binding( - _sketch_topology_identity_binding( - f"{sketch_prefix}.profile.{loop_local_name}", - kind="wire", - local_name=loop_local_name, - operation=operation, - sketch=sketch, - profile_id=str(loop_payload.get("id", "profile")), - target_topo_id=wire.topo_id, - ) - ) - - source_edges = [ - (loop_payload, str(entity_id), source_edge) - for _loop_profile, loop_payload, _loop_role, source_wire in source_wires - for entity_id, source_edge in source_wire._get_runtime( - "sketch.entity_edges", [] - ) - ] - for edge in cast(List[Edge], shape.get_edges()): - matches = [source for source in source_edges if source[2].IsSame(edge.wrapped)] - if len(matches) != 1: - raise ValueError( - "Sketch promotion cannot establish exact entity-to-edge correspondence" - ) - loop_payload, entity_id, _source_edge = matches[0] - entity_local_name = _sketch_topology_tag_local_name(entity_id) - edge._add_tag_binding( - _sketch_topology_identity_binding( - f"{sketch_prefix}.entity.{entity_local_name}", - kind="edge", - local_name=entity_local_name, - operation=operation, - sketch=sketch, - profile_id=str(loop_payload.get("id", "profile")), - entity_id=entity_id, - target_topo_id=edge.topo_id, - ) - ) - return shape - - -def _promote_sketch_profile( - sketch: Sketch, - profile: int | str, - *, - target_kind: str, - inner_profiles: Sequence[int | str] = (), - require_fully_constrained: bool, - strict: bool, - tolerance: float, - max_iterations: int, -) -> Tuple[ - Union[Wire, Face], - SketchSolveResult, - Dict[str, Any], - List[Tuple[int | str, Dict[str, Any]]], - List[Tuple[int | str, Dict[str, Any], str, Wire]], -]: - working = sketch.clone(include_solve=False) - solve_result = working.solve( - require_fully_constrained=require_fully_constrained, - strict=strict, - tolerance=tolerance, - max_iterations=max_iterations, - ) - profile_payload = sketch._profile_payload(profile, solve_result=solve_result) - inner_profile_payloads: List[Tuple[int | str, Dict[str, Any]]] = [] - seen_profile_ids = {str(profile_payload.get("id"))} - for inner_profile in inner_profiles: - inner_payload = sketch._profile_payload( - inner_profile, - solve_result=solve_result, - ) - inner_profile_id = str(inner_payload.get("id")) - if inner_profile_id in seen_profile_ids: - raise ValueError( - f"Sketch profile '{inner_profile_id}' was selected more than once" - ) - seen_profile_ids.add(inner_profile_id) - inner_profile_payloads.append((inner_profile, inner_payload)) - solve_snapshot = _sketch_solve_snapshot(solve_result) - with suspend_graph_recording(), use_coordinate_system(WORLD_CS): - outer_wire = sketch._wire_from_profile_payload(profile_payload) - source_wires: List[Tuple[int | str, Dict[str, Any], str, Wire]] = [ - (profile, profile_payload, "outer", outer_wire) - ] - if target_kind == "wire": - if inner_profile_payloads: - raise ValueError("A Wire promotion accepts exactly one sketch profile") - shape = outer_wire - elif target_kind == "face": - inner_wires: List[Wire] = [] - for inner_profile, inner_payload in inner_profile_payloads: - inner_wire = sketch._wire_from_profile_payload(inner_payload) - inner_wires.append(inner_wire) - source_wires.append((inner_profile, inner_payload, "inner", inner_wire)) - expected_normal = np.array(sketch._plane_normal_tuple(), dtype=float) - expected_normal = expected_normal / np.linalg.norm(expected_normal) - - def aligned_wire(wire: Wire): - loop_face = Face(make_face_from_wire_ocp(wire.wrapped)) - loop_normal = loop_face.get_normal_at() - loop_normal_vec = np.array( - [loop_normal.x, loop_normal.y, loop_normal.z], - dtype=float, - ) - return ( - wire.wrapped - if np.dot(expected_normal, loop_normal_vec) >= 0.0 - else TopoDS.Wire_s(wire.wrapped.Reversed()) - ) - - raw_face = ( - make_face_from_wires_ocp( - aligned_wire(outer_wire), - [aligned_wire(wire) for wire in inner_wires], - ) - if inner_wires - else make_face_from_wire_ocp(aligned_wire(outer_wire)) - ) - if inner_wires and not BRepCheck_Analyzer(raw_face).IsValid(): - raise ValueError( - "Sketch hole profiles must lie strictly inside the outer profile and must not touch or intersect another loop" - ) - face = Face(raw_face) - actual_normal = face.get_normal_at() - if ( - np.dot( - expected_normal, - np.array( - [actual_normal.x, actual_normal.y, actual_normal.z], - dtype=float, - ), - ) - < 0.0 - ): - face = Face(TopoDS.Face_s(raw_face.Reversed())) - shape = face - else: - raise ValueError( - f"Unsupported sketch promotion target kind '{target_kind}'" - ) - _apply_sketch_promotion_metadata( - cast(Union[Wire, Face], shape), - sketch=sketch, - profile=profile, - profile_payload=profile_payload, - inner_profile_payloads=inner_profile_payloads, - source_wires=source_wires, - solve_snapshot=solve_snapshot, - ) - return ( - cast(Union[Wire, Face], shape), - solve_result, - profile_payload, - inner_profile_payloads, - source_wires, - ) - - -def _assert_sketch_solve_snapshot_matches( - result: SketchSolveResult, - snapshot: Dict[str, Any], - *, - tolerance: float = 1e-7, -) -> None: - _assert_sketch_solve_snapshot_dict_matches( - result.to_dict(), snapshot, tolerance=tolerance - ) - - -def _assert_sketch_solve_snapshot_dict_matches( - actual: Dict[str, Any], - snapshot: Dict[str, Any], - *, - tolerance: float = 1e-7, -) -> None: - if str(actual.get("status")) != str(snapshot.get("status")): - raise ValueError( - f"Sketch solve status changed from {snapshot.get('status')!r} to {actual.get('status')!r}" - ) - if int(actual.get("dof", -1)) != int(snapshot.get("dof", -1)): - raise ValueError( - f"Sketch solve DOF changed from {snapshot.get('dof')!r} to {actual.get('dof')!r}" - ) - if ( - abs( - float(actual.get("residual_norm", 0.0)) - - float(snapshot.get("residual_norm", 0.0)) - ) - > tolerance - ): - raise ValueError("Sketch solve residual changed beyond recorded tolerance") - - actual_points = cast(Dict[str, Any], actual.get("solved_points", {})) - expected_points = cast(Dict[str, Any], snapshot.get("solved_points", {})) - if set(actual_points) != set(expected_points): - raise ValueError("Sketch solve point set changed") - for point_id, point in actual_points.items(): - expected = expected_points[point_id] - if ( - math.dist( - (float(point[0]), float(point[1])), - (float(expected[0]), float(expected[1])), - ) - > tolerance - ): - raise ValueError( - f"Sketch solve point '{point_id}' changed beyond recorded tolerance" - ) - - actual_scalars = cast(Dict[str, Any], actual.get("solved_scalars", {})) - expected_scalars = cast(Dict[str, Any], snapshot.get("solved_scalars", {})) - if set(actual_scalars) != set(expected_scalars): - raise ValueError("Sketch solve scalar set changed") - for scalar_id, value in actual_scalars.items(): - if abs(float(value) - float(expected_scalars[scalar_id])) > tolerance: - raise ValueError( - f"Sketch solve scalar '{scalar_id}' changed beyond recorded tolerance" - ) - - actual_entities = cast(Dict[str, Any], actual.get("solved_entities", {})) - expected_entities = cast(Dict[str, Any], snapshot.get("solved_entities", {})) - _assert_sketch_solved_entities_match( - actual_entities, - expected_entities, - tolerance=tolerance, - ) - - -def _assert_sketch_solved_entities_match( - actual: Dict[str, Any], - expected: Dict[str, Any], - *, - tolerance: float, -) -> None: - if set(actual) != set(expected): - raise ValueError("Sketch solve entity set changed") - for entity_id, entity in actual.items(): - _assert_sketch_solved_value_matches( - entity, - expected[entity_id], - tolerance=tolerance, - path=f"Sketch solve entity '{entity_id}'", - ) - - -def _assert_sketch_solved_value_matches( - actual: Any, - expected: Any, - *, - tolerance: float, - path: str, -) -> None: - if isinstance(actual, Mapping) and isinstance(expected, Mapping): - if set(actual) != set(expected): - raise ValueError(f"{path} field set changed") - for key, value in actual.items(): - _assert_sketch_solved_value_matches( - value, - expected[key], - tolerance=tolerance, - path=f"{path}.{key}", - ) - return - if isinstance(actual, (list, tuple)) and isinstance(expected, (list, tuple)): - if len(actual) != len(expected): - raise ValueError(f"{path} sequence length changed") - for index, value in enumerate(actual): - _assert_sketch_solved_value_matches( - value, - expected[index], - tolerance=tolerance, - path=f"{path}[{index}]", - ) - return - if ( - isinstance(actual, (int, float)) - and not isinstance(actual, bool) - and isinstance(expected, (int, float)) - and not isinstance(expected, bool) - ): - if abs(float(actual) - float(expected)) > tolerance: - raise ValueError(f"{path} changed beyond recorded tolerance") - return - if actual != expected: - raise ValueError(f"{path} changed") - - -def make_line_redge( - start: Tuple[ScalarLike, ScalarLike, ScalarLike], - end: Tuple[ScalarLike, ScalarLike, ScalarLike], - *, - tag_prefix: Optional[str] = None, -) -> Edge: - """Create a straight edge between two points.""" - try: - cs = get_current_cs() - start_value = cast(Tuple[float, float, float], evaluate_value(start)) - end_value = cast(Tuple[float, float, float], evaluate_value(end)) - start_global = cs.transform_point(np.array(start_value)) - end_global = cs.transform_point(np.array(end_value)) - - edge_shape = make_line_edge(start_global, end_global) - edge = cast( - Edge, - _finalize_primitive_shape( - Edge(edge_shape), - op=_OP_MAKE_LINE_REDGE, - params={"start": start, "end": end}, - tags={"primitive", "edge"}, - ), - ) - return cast( - Edge, - _apply_shape_tag_prefix( - edge, - tag_prefix, - kind="edge", - authoring_source="simplecadapi.make_line_redge.tag_prefix", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_line_redge", - what_happened="Failed to create a line edge.", - possible_causes=[ - "The start or end point is not a valid finite 3D point.", - "The transformed points are degenerate or rejected by the kernel.", - ], - how_to_fix=[ - "Pass start and end as 3-element numeric tuples or valid expressions.", - "Ensure the two points are distinct and finite.", - ], - error=e, - ) - - -def make_segment_redge( - start: Tuple[float, float, float], end: Tuple[float, float, float] -) -> Edge: - """Alias of `make_line_redge` that returns a straight edge.""" - return make_line_redge(start, end) - - -def make_segment_rwire( - start: Tuple[float, float, float], end: Tuple[float, float, float] -) -> Wire: - """Create a wire containing a single straight segment.""" - try: - if get_active_session() is not None: - edge = make_line_redge(start, end) - return make_wire_from_edges_rwire([edge]) - - with suspend_graph_recording(): - edge = make_line_redge(start, end) - wire_shape = make_wire_from_edges_ocp([edge.wrapped]) - return cast( - Wire, - _finalize_primitive_shape( - Wire(wire_shape), - op="make_segment_wire", - params={"start": start, "end": end}, - tags={"primitive", "wire"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_segment_rwire", - what_happened="Failed to create a single-segment wire.", - possible_causes=[ - "The segment endpoints are invalid.", - "The kernel could not assemble the segment into a wire.", - ], - how_to_fix=[ - "Pass two valid 3D endpoints.", - "If the segment is computed dynamically, log the two endpoints before retrying.", - ], - error=e, - ) - - -def make_circle_redge( - center: Tuple[float, float, float], - radius: ScalarLike, - normal: Tuple[float, float, float] = (0, 0, 1), - *, - tag_prefix: Optional[str] = None, -) -> Edge: - """Create a circular edge.""" - try: - radius_value = evaluate_scalar(radius) - if radius_value <= 0: - raise ValueError("半径必须大于0") - - cs = get_current_cs() - center_value = cast(Tuple[float, float, float], evaluate_value(center)) - normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) - center_global = cs.transform_point(np.array(center_value)) - normal_global = cs.transform_vector(np.array(normal_value)) - x_direction_global = cs.transform_vector( - _default_plane_x_direction(normal_value) - ) - - edge_shape = make_circle_edge( - center_global, - radius_value, - normal_global, - x_direction=x_direction_global, - ) - edge = cast( - Edge, - _finalize_primitive_shape( - Edge(edge_shape), - op=_OP_MAKE_CIRCLE_REDGE, - params={"center": center, "radius": radius, "normal": normal}, - tags={"primitive", "edge"}, - ), - ) - return cast( - Edge, - _apply_shape_tag_prefix( - edge, - tag_prefix, - kind="edge", - authoring_source="simplecadapi.make_circle_redge.tag_prefix", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_circle_redge", - what_happened="Failed to create a circular edge.", - possible_causes=[ - "The radius is not a positive finite scalar.", - "The center or normal is not a valid finite 3D vector.", - "The kernel rejected the circle definition.", - ], - how_to_fix=[ - "Use a radius greater than zero.", - "Pass finite center and normal vectors.", - "If the normal is computed dynamically, verify it is not zero-length.", - ], - error=e, - ) - - -def make_circle_rwire( - center: Tuple[float, float, float], - radius: ScalarLike, - normal: Tuple[float, float, float] = (0, 0, 1), - *, - tag_prefix: Optional[str] = None, - edge_tag: Optional[str] = None, -) -> Wire: - """Create a circular wire.""" - try: - if get_active_session() is not None: - edge = make_circle_redge(center, radius, normal) - wire = make_wire_from_edges_rwire([edge]) - local_edge_tag = edge_tag or "circle" - return cast( - Wire, - _apply_profile_tag_prefix( - wire, - tag_prefix, - ( - [local_edge_tag] - if tag_prefix is not None or edge_tag is not None - else None - ), - authoring_source="simplecadapi.make_circle_rwire.tag_prefix", - ), - ) - - with suspend_graph_recording(): - edge = make_circle_redge(center, radius, normal) - wire_shape = make_wire_from_edges_ocp([edge.wrapped]) - wire = cast( - Wire, - _finalize_primitive_shape( - Wire(wire_shape), - op="make_circle_wire", - params={"center": center, "radius": radius, "normal": normal}, - tags={"primitive", "wire"}, - ), - ) - local_edge_tag = edge_tag or "circle" - return cast( - Wire, - _apply_profile_tag_prefix( - wire, - tag_prefix, - ( - [local_edge_tag] - if tag_prefix is not None or edge_tag is not None - else None - ), - authoring_source="simplecadapi.make_circle_rwire.tag_prefix", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_circle_rwire", - what_happened="Failed to create a circular wire.", - possible_causes=[ - "The circle edge could not be created.", - "The wire assembly step rejected the generated edge.", - ], - how_to_fix=[ - "Check the center, radius, and normal inputs.", - "Retry with a positive radius and a valid normal vector.", - ], - error=e, - ) - - -def make_circle_rface( - center: Tuple[float, float, float], - radius: ScalarLike, - normal: Tuple[float, float, float] = (0, 0, 1), - *, - tag_prefix: Optional[str] = None, - edge_tag: Optional[str] = None, -) -> Face: - """Create a circular face.""" - try: - if get_active_session() is not None: - wire = make_circle_rwire( - center, - radius, - normal, - tag_prefix=tag_prefix, - edge_tag=edge_tag, - ) - return make_face_from_wire_rface(wire, normal=normal, tag_prefix=tag_prefix) - - with suspend_graph_recording(): - wire = make_circle_rwire( - center, - radius, - normal, - tag_prefix=tag_prefix, - edge_tag=edge_tag, - ) - face_shape = make_face_from_wire_ocp(wire.wrapped) - face = Face(face_shape) - face._metadata = wire._metadata.copy() - result = cast( - Face, - _finalize_primitive_shape( - face, - op="make_circle_face", - params={"center": center, "radius": radius, "normal": normal}, - tags={"primitive", "face"}, - ), - ) - result = cast( - Face, - _copy_exact_topology_identity_tags( - result, [wire], operation="make_circle_rface" - ), - ) - return cast( - Face, - _apply_shape_tag_prefix( - result, - tag_prefix, - kind="face", - authoring_source="simplecadapi.make_circle_rface.tag_prefix", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_circle_rface", - what_happened="Failed to create a circular face.", - possible_causes=[ - "The underlying circular wire could not be created.", - "The kernel could not create a face from the wire.", - ], - how_to_fix=[ - "Verify the center, radius, and normal values.", - "Use a positive radius and a valid non-zero normal vector.", - ], - error=e, - ) - - -def make_rectangle_rwire( - width: ScalarLike, - height: ScalarLike, - center: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 0), - normal: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 1), - *, - tag_prefix: Optional[str] = None, - edge_tags: Optional[Sequence[str]] = None, -) -> Wire: - """Create a rectangular wire.""" - try: - width_value = evaluate_scalar(width) - height_value = evaluate_scalar(height) - if width_value <= 0 or height_value <= 0: - raise ValueError("宽度和高度必须大于0") - - if get_active_session() is not None: - normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) - _, x_axis, y_axis = _orthonormal_plane_axes(normal_value) - half_w = width / 2 - half_h = height / 2 - corners = [ - _offset_point_expr(center, x_axis, y_axis, -half_w, -half_h), - _offset_point_expr(center, x_axis, y_axis, half_w, -half_h), - _offset_point_expr(center, x_axis, y_axis, half_w, half_h), - _offset_point_expr(center, x_axis, y_axis, -half_w, half_h), - ] - wire = _make_closed_profile_rwire(corners) - return cast( - Wire, - _apply_profile_tag_prefix( - wire, - tag_prefix, - edge_tags, - authoring_source="simplecadapi.make_rectangle_rwire.tag_prefix", - ), - ) - - cs = get_current_cs() - center_value = cast(Tuple[float, float, float], evaluate_value(center)) - normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) - center_global = cs.transform_point(np.array(center_value)) - normal_global = cs.transform_vector(np.array(normal_value)) - - normal_norm = float(np.linalg.norm(normal_global)) - if normal_norm <= 1e-15 or not np.isfinite(normal_norm): - raise ValueError("法向量不能是零向量") - - _, local_x, local_y = _orthonormal_plane_axes(normal_value) - plane_x = cs.transform_vector(local_x) - plane_y = cs.transform_vector(local_y) - - # 创建矩形的四个顶点(在本地坐标系中) - half_w, half_h = width_value / 2, height_value / 2 - local_points = [ - (-half_w, -half_h), - (half_w, -half_h), - (half_w, half_h), - (-half_w, half_h), - ] - - # 转换到全局坐标系 - global_points = [] - for local_point in local_points: - # 在本地坐标系中的点 - point_3d = ( - center_global + local_point[0] * plane_x + local_point[1] * plane_y - ) - global_points.append(tuple(float(v) for v in point_3d)) - - # 创建边 - wire_points = [ - (float(point[0]), float(point[1]), float(point[2])) - for point in global_points - ] - wire_shape = make_polyline_wire(wire_points, closed=True) - wire = cast( - Wire, - _finalize_primitive_shape( - Wire(wire_shape), - op="make_rectangle_wire", - params={ - "width": width, - "height": height, - "center": center, - "normal": normal, - }, - tags={"primitive", "wire"}, - ), - ) - return cast( - Wire, - _apply_profile_tag_prefix( - wire, - tag_prefix, - edge_tags, - authoring_source="simplecadapi.make_rectangle_rwire.tag_prefix", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_rectangle_rwire", - what_happened="Failed to create a rectangular wire.", - possible_causes=[ - "Width or height is not a positive finite scalar.", - "The center or normal is not a valid finite 3D vector.", - "The local rectangle basis became degenerate.", - ], - how_to_fix=[ - "Use width and height values greater than zero.", - "Pass a valid center and a non-zero normal vector.", - "If the normal is near zero, normalize or replace it before retrying.", - ], - error=e, - ) - - -def make_rectangle_rface( - width: ScalarLike, - height: ScalarLike, - center: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 0), - normal: Tuple[ScalarLike, ScalarLike, ScalarLike] = (0, 0, 1), - *, - tag_prefix: Optional[str] = None, - edge_tags: Optional[Sequence[str]] = None, -) -> Face: - """Create a rectangular face.""" - try: - if get_active_session() is not None: - wire = make_rectangle_rwire( - width, - height, - center, - normal, - tag_prefix=tag_prefix, - edge_tags=edge_tags, - ) - return make_face_from_wire_rface( - wire, normal=cast(Any, normal), tag_prefix=tag_prefix - ) - - with suspend_graph_recording(): - wire = make_rectangle_rwire( - width, - height, - center, - normal, - tag_prefix=tag_prefix, - edge_tags=edge_tags, - ) - face_shape = make_face_from_wire_ocp(wire.wrapped) - face = Face(face_shape) - face._metadata = wire._metadata.copy() - result = cast( - Face, - _finalize_primitive_shape( - face, - op="make_rectangle_face", - params={ - "width": width, - "height": height, - "center": center, - "normal": normal, - }, - tags={"primitive", "face"}, - ), - ) - result = cast( - Face, - _copy_exact_topology_identity_tags( - result, [wire], operation="make_rectangle_rface" - ), - ) - return cast( - Face, - _apply_shape_tag_prefix( - result, - tag_prefix, - kind="face", - authoring_source="simplecadapi.make_rectangle_rface.tag_prefix", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_rectangle_rface", - what_happened="Failed to create a rectangular face.", - possible_causes=[ - "The rectangular wire could not be created.", - "The face construction step rejected the generated wire.", - ], - how_to_fix=[ - "Verify width, height, center, and normal.", - "Retry with positive dimensions and a valid non-zero normal vector.", - ], - error=e, - ) - - -def make_face_from_wire_rface( - wire: Wire, - normal: Tuple[float, float, float] = (0, 0, 1), - *, - tag_prefix: Optional[str] = None, -) -> Face: - """Create a face from a closed wire.""" - try: - if not isinstance(wire, Wire): - raise ValueError("输入必须是Wire类型") - - # 检查Wire是否封闭 - if not wire.is_closed(): - raise ValueError("Wire必须是封闭的才能创建面") - - # The wire is already global geometry; only the requested local normal - # is resolved through the active workplane chain. - cs = get_current_cs() - global_normal = cs.transform_vector(np.array(normal)) - - # 标准化法向量 - normal_vec = global_normal / np.linalg.norm(global_normal) - - # 创建面 - face_shape = make_face_from_wire_ocp(wire.wrapped) - face = Face(face_shape) - - # 检查面的法向量是否与期望方向一致 - face_normal = face.get_normal_at() - face_normal_vec = np.array([face_normal.x, face_normal.y, face_normal.z]) - - # 计算法向量的点积,如果小于0则需要反向 - dot_product = np.dot(normal_vec, face_normal_vec) - - if dot_product < 0: - # 反向面(通过反向Wire的方向) - # OCP Wire 没有直接的 reverse 包装方法,这里重新构建 - # 简单的方法是使用makeFromWires的orientation参数 - # 或者我们接受当前面的方向,添加一个警告 - print(f"警告: 创建的面的法向量与期望方向相反 (点积: {dot_product:.3f})") - - face._metadata = wire._metadata.copy() - - result = cast( - Face, - _finalize_derived_shape( - face, - op=_OP_MAKE_FACE_FROM_WIRE_RFACE, - params={"normal": normal}, - input_shapes=[wire], - tags={"derived", "face"}, - ), - ) - result = cast( - Face, - _copy_exact_topology_identity_tags( - result, [wire], operation="make_face_from_wire_rface" - ), - ) - return cast( - Face, - _apply_shape_tag_prefix( - result, - tag_prefix, - kind="face", - authoring_source="simplecadapi.make_face_from_wire_rface.tag_prefix", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_face_from_wire_rface", - what_happened="Failed to create a face from the input wire.", - possible_causes=[ - "The input is not a Wire instance.", - "The wire is open or geometrically invalid.", - "The kernel rejected the closed wire when building a face.", - ], - how_to_fix=[ - "Pass a Wire object, not an Edge or a list of points.", - "Ensure the wire is closed before calling this API.", - "If the wire was assembled from edges, verify the edges connect end-to-end.", - ], - error=e, - ) - - -def make_face_from_wires_rface( - outer_wire: Wire, - inner_wires: Sequence[Wire], - normal: Tuple[float, float, float] = (0, 0, 1), -) -> Face: - """Create a face from one outer closed wire and optional inner closed wires.""" - try: - if not isinstance(outer_wire, Wire): - raise ValueError("outer_wire must be a Wire") - if not outer_wire.is_closed(): - raise ValueError("outer_wire must be closed") - - inner_list = list(inner_wires or []) - for inner_wire in inner_list: - if not isinstance(inner_wire, Wire): - raise ValueError("inner_wires must contain only Wire objects") - if not inner_wire.is_closed(): - raise ValueError("inner wires must be closed") - - cs = get_current_cs() - global_normal = cs.transform_vector(np.array(normal)) - normal_norm = float(np.linalg.norm(global_normal)) - if normal_norm <= 1e-15 or not np.isfinite(normal_norm): - raise ValueError("normal must be a non-zero finite vector") - normal_vec = global_normal / normal_norm - - face_shape = make_face_from_wires_ocp( - outer_wire.wrapped, - [inner_wire.wrapped for inner_wire in inner_list], - ) - face = Face(face_shape) - - face_normal = face.get_normal_at() - face_normal_vec = np.array([face_normal.x, face_normal.y, face_normal.z]) - dot_product = float(np.dot(normal_vec, face_normal_vec)) - if dot_product < 0: - print(f"警告: 创建的面的法向量与期望方向相反 (点积: {dot_product:.3f})") - - face._metadata = outer_wire._metadata.copy() - - return cast( - Face, - _finalize_derived_shape( - face, - op=_OP_MAKE_FACE_FROM_WIRES_RFACE, - params={"normal": normal, "inner_wire_count": len(inner_list)}, - input_shapes=[outer_wire, *inner_list], - tags={"derived", "face"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_face_from_wires_rface", - what_happened="Failed to create a face from the input outer and inner wires.", - possible_causes=[ - "The outer wire is not a Wire instance or is not closed.", - "One or more inner wires are not Wire instances or are not closed.", - "The inner wires are not contained by the outer wire or are geometrically invalid.", - "The kernel rejected the multi-loop face definition.", - ], - how_to_fix=[ - "Pass one closed outer Wire and zero or more closed inner Wire objects.", - "Ensure every inner wire lies inside the outer wire and does not intersect other loops.", - "Use a valid non-zero normal vector.", - ], - error=e, - ) - - -def make_wire_from_edges_rwire( - edges: List[Edge], *, tag_prefix: Optional[str] = None -) -> Wire: - """Create a wire from a list of connected edges.""" - try: - if not edges: - raise ValueError("边列表不能为空") - - wire_shape = make_wire_from_edges_ocp([edge.wrapped for edge in edges]) - result = cast( - Wire, - _finalize_derived_shape( - Wire(wire_shape), - op=_OP_MAKE_WIRE_FROM_EDGES_RWIRE, - params={"edge_count": len(edges)}, - input_shapes=edges, - tags={"derived", "wire"}, - ), - ) - result = cast( - Wire, - _copy_exact_topology_identity_tags( - result, edges, operation="make_wire_from_edges_rwire" - ), - ) - return cast( - Wire, - _apply_shape_tag_prefix( - result, - tag_prefix, - kind="wire", - authoring_source="simplecadapi.make_wire_from_edges_rwire.tag_prefix", - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_wire_from_edges_rwire", - what_happened="Failed to assemble a wire from the input edges.", - possible_causes=[ - "The edge list is empty.", - "One or more items are invalid edges.", - "The edges do not connect into a valid wire chain.", - ], - how_to_fix=[ - "Pass a non-empty list of Edge objects.", - "Ensure consecutive edges share matching endpoints.", - "Inspect the edge order if the wire should form a closed loop.", - ], - error=e, - ) - - -def make_wire_from_sketch_rwire( - sketch: Sketch, - profile: int | str = 0, - *, - require_fully_constrained: bool = False, - strict: bool = True, - tolerance: float = 1e-7, - max_iterations: int = 80, -) -> Wire: - """Promote a sketch profile to a concrete wire, solving internally.""" - try: - if not isinstance(sketch, Sketch): - raise ValueError("Input must be a Sketch") - ( - wire, - solve_result, - profile_payload, - inner_profile_payloads, - source_wires, - ) = _promote_sketch_profile( - sketch, - profile, - target_kind="wire", - require_fully_constrained=require_fully_constrained, - strict=strict, - tolerance=tolerance, - max_iterations=max_iterations, - ) - solve_snapshot = _sketch_solve_snapshot(solve_result) - finalized = cast( - Wire, - _finalize_derived_shape( - cast(Wire, wire), - op=_OP_MAKE_WIRE_FROM_SKETCH_RWIRE, - params={ - "profile": profile, - "sketch": sketch.to_dict(), - "require_fully_constrained": require_fully_constrained, - "strict": strict, - "tolerance": tolerance, - "max_iterations": max_iterations, - "solve_snapshot": solve_snapshot, - "promotion_map": _sketch_promotion_map( - sketch, - profile, - profile_payload, - inner_profile_payloads=inner_profile_payloads, - target_kind="wire", - ), - }, - input_shapes=cast(Sequence[AnyShape], [sketch]), - tags={"derived", "wire", "sketch"}, - ), - ) - return cast( - Wire, - _apply_sketch_promotion_identity_tags( - finalized, - sketch=sketch, - profile_payload=profile_payload, - source_wires=source_wires, - operation=_OP_MAKE_WIRE_FROM_SKETCH_RWIRE, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_wire_from_sketch_rwire", - what_happened="Failed to create a wire from the sketch.", - possible_causes=[ - "The sketch has no closed non-construction profile.", - "The sketch constraints are conflicting or invalid.", - "The requested profile index or id does not exist.", - ], - how_to_fix=[ - "Build sketch profiles only through sketch APIs and close all profile loops.", - "Call inspect_sketch_rsketchresult(..., strict=False) to inspect diagnostics.", - ], - error=e, - ) - - -def make_face_from_sketch_rface( - sketch: Sketch, - profile: int | str = 0, - *, - inner_profiles: Sequence[int | str] = (), - require_fully_constrained: bool = False, - strict: bool = True, - tolerance: float = 1e-7, - max_iterations: int = 80, -) -> Face: - """Promote one outer and optional inner sketch profiles to a face.""" - try: - if not isinstance(sketch, Sketch): - raise ValueError("Input must be a Sketch") - normalized_inner_profiles = tuple(inner_profiles) - ( - face, - solve_result, - profile_payload, - inner_profile_payloads, - source_wires, - ) = _promote_sketch_profile( - sketch, - profile, - target_kind="face", - inner_profiles=normalized_inner_profiles, - require_fully_constrained=require_fully_constrained, - strict=strict, - tolerance=tolerance, - max_iterations=max_iterations, - ) - solve_snapshot = _sketch_solve_snapshot(solve_result) - finalized = cast( - Face, - _finalize_derived_shape( - cast(Face, face), - op=_OP_MAKE_FACE_FROM_SKETCH_RFACE, - params={ - "profile": profile, - "inner_profiles": normalized_inner_profiles, - "sketch": sketch.to_dict(), - "require_fully_constrained": require_fully_constrained, - "strict": strict, - "tolerance": tolerance, - "max_iterations": max_iterations, - "solve_snapshot": solve_snapshot, - "promotion_map": _sketch_promotion_map( - sketch, - profile, - profile_payload, - inner_profile_payloads=inner_profile_payloads, - target_kind="face", - ), - }, - input_shapes=cast(Sequence[AnyShape], [sketch]), - tags={"derived", "face", "sketch"}, - ), - ) - return cast( - Face, - _apply_sketch_promotion_identity_tags( - finalized, - sketch=sketch, - profile_payload=profile_payload, - source_wires=source_wires, - operation=_OP_MAKE_FACE_FROM_SKETCH_RFACE, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_face_from_sketch_rface", - what_happened="Failed to create a face from the sketch.", - possible_causes=[ - "The sketch has no closed non-construction profile.", - "The sketch constraints are conflicting or invalid.", - "The requested profile index or id does not exist.", - "An inner profile is outside, intersects, or duplicates the outer profile.", - ], - how_to_fix=[ - "Build a closed profile with add_line_rsketch(...) or add_circle_rsketch(...).", - "Add constraints until the profile can solve cleanly.", - "Pass hole loops explicitly with inner_profiles=[...].", - ], - error=e, - ) - - -def load_brep_region_rsolid( - path: str | Path, - sha256: str, - *, - tag_prefix: Optional[str] = None, -) -> Solid: - """Load a hash-pinned, target-derived BREP region snapshot as one Solid. - - The complete artifact SHA-256 is verified before native BREP decoding. In a - GraphSession, ``path`` must be relative and is replayed relative to the replay - process working directory. Model JSON records the locator and digest, not the - sidecar bytes. - """ - - try: - return cast( - Solid, - _load_brep_region_rshape( - path, - sha256, - root_kind="solid", - tag_prefix=tag_prefix, - replay_root=(Path.cwd() if get_active_session() is not None else None), - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="load_brep_region_rsolid", - what_happened="Failed to load the BREP region snapshot.", - possible_causes=[ - "The snapshot path does not exist or is not readable.", - "The supplied SHA-256 does not match the snapshot bytes.", - "The snapshot is corrupt, unsupported, invalid, or not one solid.", - ], - how_to_fix=[ - "Create the snapshot with copy_step_region_rpath(...).", - "Pass the SHA-256 of the complete .scadbrep file.", - "Keep the sidecar at the same path when replaying model JSON.", - ], - error=e, - ) - - -def _carry_face_provenance( - shape: Shell | Solid, - source_faces: Sequence[Face], - *, - result_face_indices: Optional[Sequence[int]] = None, - allow_orientation_change: bool = False, - replace_local_bindings: bool = True, -) -> None: - result_faces = list(shape.get_faces()) - if result_face_indices is None: - mapped_indices = [] - for source in source_faces: - matches = [ - index - for index, result in enumerate(result_faces) - if result.wrapped.IsSame(source.wrapped) - ] - if len(matches) != 1: - raise ValueError("face continuation mapping is incomplete or ambiguous") - mapped_indices.append(matches[0]) - else: - mapped_indices = [int(index) for index in result_face_indices] - if len(mapped_indices) != len(source_faces) or len(set(mapped_indices)) != len( - result_faces - ): - raise ValueError("face continuation mapping is not one-to-one") - for source, result_index in zip(source_faces, mapped_indices): - if result_index < 0 or result_index >= len(result_faces): - raise ValueError( - "face continuation mapping contains an invalid result index" - ) - face = result_faces[result_index] - provenance = source.get_metadata("provenance") - if ( - isinstance(provenance, dict) - and provenance.get("construction") == "exact_transcription" - and not allow_orientation_change - and not face.wrapped.IsEqual(source.wrapped) - ): - raise ValueError("sewing modified an exact-transcription input face") - projected_bindings = [ - binding - for binding in source._local_tag_bindings() - if lineage_policy_allows(binding.propagation, "continuation") - ] - if replace_local_bindings: - face._replace_local_tag_bindings(projected_bindings) - _attach_lineage_from_source( - source, - face, - derivation="continuation", - op="face_continuation", - coverage="complete", - ) - if isinstance(provenance, dict): - face.set_metadata("provenance", dict(provenance)) - face._set_runtime("semantic.lineage.coverage", "complete") - - -def load_brep_region_rshell( - path: str | Path, - sha256: str, - *, - tag_prefix: Optional[str] = None, -) -> Shell: - """Load a hash-pinned, target-derived BREP face region as one Shell. - - The Shell keeps target-derived topology and is tagged with imported-sidecar - provenance. Use ordinary replayable surface operations to join it to fitted - or analytic feature faces. GraphSession requires a relative sidecar path. - """ - - try: - return cast( - Shell, - _load_brep_region_rshape( - path, - sha256, - root_kind="shell", - tag_prefix=tag_prefix, - replay_root=(Path.cwd() if get_active_session() is not None else None), - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="load_brep_region_rshell", - what_happened="Failed to load the BREP face-region snapshot.", - possible_causes=[ - "The snapshot path or SHA-256 is incorrect.", - "The snapshot is corrupt, unsupported, invalid, or not one Shell.", - ], - how_to_fix=[ - "Create a face-region snapshot with copy_step_region_rpath(..., face_ids=[...]).", - "Pass the SHA-256 of the complete .scadbrep file.", - ], - error=e, - ) - - -def _load_brep_region_rshape( - path: str | Path, - sha256: str, - *, - root_kind: str, - tag_prefix: Optional[str], - replay_root: Path | None, -) -> Shell | Solid: - source_path = _brep_region_path(path, for_graph=replay_root is not None) - wrapped, manifest, canonical_hash = read_artifact( - source_path, - sha256, - expected_root_kind=cast(Any, root_kind), - replay_root=replay_root, - ) - shape: Shell | Solid = Solid(wrapped) if root_kind == "solid" else Shell(wrapped) - shape._add_tag("imported") - shape._add_tag("sidecar") - shape._add_tag(root_kind) - normalized_prefix = ( - normalize_tag(tag_prefix, strict=True) if tag_prefix is not None else None - ) - if normalized_prefix is not None: - shape._apply_tag(f"{normalized_prefix}.{root_kind}", propagate=False) - shape.set_metadata( - "brep_region", - { - "artifact_sha256": canonical_hash, - "profile": manifest["profile"], - "provenance": manifest["provenance"], - "source_face_ids": manifest["region"].get("source_face_ids"), - }, - ) - _attach_brep_region_provenance(shape, manifest, canonical_hash) - op = ( - _OP_LOAD_BREP_REGION_RSOLID - if root_kind == "solid" - else _OP_LOAD_BREP_REGION_RSHELL - ) - return cast( - Shell | Solid, - _finalize_primitive_shape( - shape, - op=op, - params={ - "path": source_path, - "sha256": canonical_hash, - "tag_prefix": normalized_prefix, - }, - tags={"imported", "sidecar", root_kind}, - ), - ) - - -def _attach_brep_region_provenance( - shape: Shell | Solid, - manifest: Mapping[str, Any], - artifact_sha256: str, -) -> None: - source = manifest["source"] - region = manifest["region"] - evidence = { - "artifact_sha256": artifact_sha256, - "profile": manifest["profile"], - "source_sha256": source["content_hash"], - "source_name": source["name"], - "source_face_ids": region.get("source_face_ids"), - "construction": "exact_transcription", - "topology_origin": "retained", - "runtime_dependency": "embedded_target_derived", - } - root_binding = TagBinding( - tag="provenance.exact_transcription", - producer=TagProducer(TagProducerKind.IMPORTED_SIDECAR), - target=TagTarget(TagTargetKind.SCOPE_ROOT), - propagation=TagPropagation( - topology=TopologyPropagation.DOWNWARD, - lineage=LineagePolicy.CONTINUATION_FRAGMENT, - ), - evidence=TagEvidence(TagEvidenceKind.IMPORTED_SIDECAR, evidence), - certainty=TagCertainty.ASSERTED, - lifecycle=TagLifecycle.SNAPSHOT, - binding_id=f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, '|'.join(('simplecad.brep_region.root', artifact_sha256, str(region['kind'])))).hex}", - ) - shape._add_tag_binding(root_binding) - source_face_ids = tuple(region.get("source_face_ids") or ()) - for index, face in enumerate(shape.get_faces()): - face_evidence = { - **evidence, - "source_face_id": ( - source_face_ids[index] if index < len(source_face_ids) else None - ), - } - face.set_metadata("provenance", face_evidence) - face._add_tag_binding( - TagBinding( - tag="provenance.exact_transcription", - producer=TagProducer(TagProducerKind.IMPORTED_SIDECAR), - target=TagTarget(TagTargetKind.SCOPE_ROOT), - propagation=TagPropagation( - topology=TopologyPropagation.LOCAL, - lineage=LineagePolicy.CONTINUATION_FRAGMENT, - ), - evidence=TagEvidence(TagEvidenceKind.IMPORTED_SIDECAR, face_evidence), - certainty=TagCertainty.ASSERTED, - lifecycle=TagLifecycle.SNAPSHOT, - binding_id=f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, '|'.join(('simplecad.brep_region.face', artifact_sha256, str(face_evidence['source_face_id'])))).hex}", - ) - ) - face._set_runtime("semantic.lineage.coverage", "complete") - - -def _brep_region_path(path: str | Path, *, for_graph: bool) -> str: - source = Path(path) - if ":" in source.name: - raise ValueError(".scadbrep filenames must not contain ':'") - if for_graph and source.is_absolute(): - raise ValueError( - "GraphSession requires a relative .scadbrep path so model JSON does " - "not record machine-specific absolute paths" - ) - if for_graph and source.drive: - raise ValueError("GraphSession .scadbrep paths must not contain a drive") - if for_graph and ".." in source.parts: - raise ValueError(".scadbrep paths must not traverse parent directories") - if for_graph and "\\" in str(path): - raise ValueError("GraphSession .scadbrep paths must use '/' separators") - if source.suffix.lower() != ".scadbrep": - raise ValueError("path must end in .scadbrep") - return source.as_posix() if for_graph else str(source) - - -def make_box_rsolid( - width: ScalarLike, - height: ScalarLike, - depth: ScalarLike, - bottom_face_center: Tuple[float, float, float] = (0, 0, 0), - *, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - bottom_face_tag: Optional[str] = None, - top_face_tag: Optional[str] = None, - front_face_tag: Optional[str] = None, - back_face_tag: Optional[str] = None, - left_face_tag: Optional[str] = None, - right_face_tag: Optional[str] = None, -) -> Solid: - """Create a box with native kernel-backed Face topology tags.""" - try: - assignments = _normalize_operation_role_tags( - "make_box_rsolid", - ( - ("box.bottom", bottom_face_tag), - ("box.top", top_face_tag), - ("box.front", front_face_tag), - ("box.back", back_face_tag), - ("box.left", left_face_tag), - ("box.right", right_face_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - width_value = evaluate_scalar(width) - height_value = evaluate_scalar(height) - depth_value = evaluate_scalar(depth) - - if width_value <= 0 or height_value <= 0 or depth_value <= 0: - raise ValueError("宽度、高度和深度必须大于0") - - cs = get_current_cs() - center_value = cast( - Tuple[float, float, float], evaluate_value(bottom_face_center) - ) - center_global = cs.transform_point(np.array(center_value)) - corner_global = ( - center_global - - np.asarray(cs.x_axis, dtype=float) * (width_value / 2.0) - - np.asarray(cs.y_axis, dtype=float) * (height_value / 2.0) - ) - tracked = cast( - TrackedResult, - tracked_box( - tuple(float(value) for value in corner_global), - width_value, - height_value, - depth_value, - x_axis=tuple(float(value) for value in cs.x_axis), - y_axis=tuple(float(value) for value in cs.y_axis), - z_axis=tuple(float(value) for value in cs.z_axis), - ), - ) - solid = cast(Solid, tracked.shape) - - # 自动标记面 - solid.auto_tag_faces("box") - solid._apply_tag("geom.primitive.box", propagate=False) - solid._add_tag("box") - solid.set_metadata( - "geo", - { - "type": "box", - "size": {"x": width_value, "y": height_value, "z": depth_value}, - "bottom_face_center": bottom_face_center, - }, - ) - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - solid, - op="make_box_rsolid", - params={ - "width": width, - "height": height, - "depth": depth, - "bottom_face_center": bottom_face_center, - }, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - ) - tagged = _apply_operation_role_tags( - finalized, - op="make_box_rsolid", - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - return _apply_feature_tag_prefix( - tagged, - tag_prefix=tag_prefix, - op="make_box_rsolid", - delta=tracked.delta, - face_roles=( - ("box.bottom", "bottom"), - ("box.top", "top"), - ("box.front", "front"), - ("box.back", "back"), - ("box.left", "left"), - ("box.right", "right"), - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_box_rsolid", - what_happened="Failed to create a box solid.", - possible_causes=[ - "Width, height, or depth is not a positive finite scalar.", - "The bottom face center is not a valid finite 3D point.", - "The kernel rejected the box dimensions or placement.", - ], - how_to_fix=[ - "Use width, height, and depth values greater than zero.", - "Pass bottom_face_center as a finite 3D tuple.", - "If dimensions come from expressions, inspect the evaluated numeric values.", - ], - error=e, - ) - - -def make_cylinder_rsolid( - radius: ScalarLike, - height: ScalarLike, - bottom_face_center: Tuple[float, float, float] = (0, 0, 0), - axis: Tuple[float, float, float] = (0, 0, 1), - *, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - start_face_tag: Optional[str] = None, - end_face_tag: Optional[str] = None, - side_face_tag: Optional[str] = None, - start_edge_tag: Optional[str] = None, - end_edge_tag: Optional[str] = None, - seam_edge_tag: Optional[str] = None, -) -> Solid: - """Create a cylinder with native kernel-backed Face and Edge topology tags.""" - try: - assignments = _normalize_operation_role_tags( - "make_cylinder_rsolid", - ( - ("cylinder.start", start_face_tag), - ("cylinder.end", end_face_tag), - ("cylinder.side", side_face_tag), - ("cylinder.start_boundary", start_edge_tag), - ("cylinder.end_boundary", end_edge_tag), - ("cylinder.seam", seam_edge_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - radius_value = evaluate_scalar(radius) - height_value = evaluate_scalar(height) - if radius_value <= 0 or height_value <= 0: - raise ValueError("半径和高度必须大于0") - - cs = get_current_cs() - center_value = cast( - Tuple[float, float, float], evaluate_value(bottom_face_center) - ) - axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) - center_global = cs.transform_point(np.array(center_value)) - axis_global = cs.transform_vector(np.array(axis_value)) - - resolved_center = tuple(float(value) for value in center_global) - resolved_axis = tuple(float(value) for value in axis_global) - tracked = cast( - TrackedResult, - tracked_cylinder( - resolved_center, - resolved_axis, - radius_value, - height_value, - ), - ) - solid = cast(Solid, tracked.shape) - - # 自动标记面 - solid.auto_tag_faces("cylinder") - solid._apply_tag("geom.primitive.cylinder", propagate=False) - solid._add_tag("cylinder") - solid.set_metadata( - "geo", - { - "type": "cylinder", - "radius": radius_value, - "height": height_value, - "bottom_face_center": bottom_face_center, - "axis": axis, - }, - ) - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - solid, - op="make_cylinder_rsolid", - params={ - "radius": radius, - "height": height, - "bottom_face_center": bottom_face_center, - "axis": axis, - }, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - ) - tagged = _apply_operation_role_tags( - finalized, - op="make_cylinder_rsolid", - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - return _apply_feature_tag_prefix( - tagged, - tag_prefix=tag_prefix, - op="make_cylinder_rsolid", - delta=tracked.delta, - start_role="cylinder.start", - end_role="cylinder.end", - side_role="cylinder.side", - edge_roles=( - ("cylinder.start_boundary", "start"), - ("cylinder.end_boundary", "end"), - ("cylinder.seam", "seam"), - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_cylinder_rsolid", - what_happened="Failed to create a cylinder solid.", - possible_causes=[ - "Radius or height is not a positive finite scalar.", - "The bottom face center or axis is not a valid finite 3D vector.", - "The axis is degenerate or rejected by the kernel.", - ], - how_to_fix=[ - "Use radius and height values greater than zero.", - "Pass a valid bottom_face_center and a non-zero axis vector.", - "If the axis is computed dynamically, inspect its evaluated numeric value.", - ], - error=e, - ) - - -def make_cone_rsolid( - bottom_radius: ScalarLike, - height: ScalarLike, - top_radius: ScalarLike = 0.0, - bottom_face_center: Tuple[float, float, float] = (0, 0, 0), - axis: Tuple[float, float, float] = (0, 0, 1), - *, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - start_face_tag: Optional[str] = None, - end_face_tag: Optional[str] = None, - side_face_tag: Optional[str] = None, - start_edge_tag: Optional[str] = None, - end_edge_tag: Optional[str] = None, - seam_edge_tag: Optional[str] = None, -) -> Solid: - """Create a cone or frustum with native kernel-backed topology tags.""" - try: - assignments = _normalize_operation_role_tags( - "make_cone_rsolid", - ( - ("cone.start", start_face_tag), - ("cone.end", end_face_tag), - ("cone.side", side_face_tag), - ("cone.start_boundary", start_edge_tag), - ("cone.end_boundary", end_edge_tag), - ("cone.seam", seam_edge_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - bottom_radius_value = evaluate_scalar(bottom_radius) - height_value = evaluate_scalar(height) - top_radius_value = evaluate_scalar(top_radius) - if bottom_radius_value <= 0 or height_value <= 0: - raise ValueError("底面半径和高度必须大于0") - - cs = get_current_cs() - center_value = cast( - Tuple[float, float, float], evaluate_value(bottom_face_center) - ) - axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) - center_global = cs.transform_point(np.array(center_value)) - axis_global = cs.transform_vector(np.array(axis_value)) - - resolved_center = tuple(float(value) for value in center_global) - resolved_axis = tuple(float(value) for value in axis_global) - tracked = cast( - TrackedResult, - tracked_cone( - resolved_center, - resolved_axis, - bottom_radius_value, - top_radius_value, - height_value, - ), - ) - solid = cast(Solid, tracked.shape) - - # 自动标记面 - solid._apply_tag("geom.primitive.cone", propagate=False) - solid._add_tag("cone") - solid.set_metadata( - "geo", - { - "type": "cone", - "bottom_radius": bottom_radius_value, - "top_radius": top_radius_value, - "height": height_value, - "bottom_face_center": bottom_face_center, - "axis": axis, - }, - ) - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - solid, - op="make_cone_rsolid", - params={ - "bottom_radius": bottom_radius, - "top_radius": top_radius, - "height": height, - "bottom_face_center": bottom_face_center, - "axis": axis, - }, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - ) - tagged = _apply_operation_role_tags( - finalized, - op="make_cone_rsolid", - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - return _apply_feature_tag_prefix( - tagged, - tag_prefix=tag_prefix, - op="make_cone_rsolid", - delta=tracked.delta, - start_role="cone.start", - end_role="cone.end" if top_radius_value > 0.0 else None, - side_role="cone.side", - edge_roles=( - ("cone.start_boundary", "start"), - ("cone.end_boundary", "end"), - ("cone.seam", "seam"), - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_cone_rsolid", - what_happened="Failed to create a cone or truncated cone solid.", - possible_causes=[ - "Bottom radius or height is not a positive finite scalar.", - "The bottom face center or axis is not a valid finite 3D vector.", - "The kernel rejected the cone dimensions or orientation.", - ], - how_to_fix=[ - "Use a positive bottom radius and a positive height.", - "Pass a valid center point and non-zero axis vector.", - "If top_radius is used, make sure it is a finite scalar.", - ], - error=e, - ) - - -def make_sphere_rsolid( - radius: ScalarLike, center: Tuple[float, float, float] = (0, 0, 0) -) -> Solid: - """Create a sphere solid.""" - try: - radius_value = evaluate_scalar(radius) - if radius_value <= 0: - raise ValueError("半径必须大于0") - - cs = get_current_cs() - center_value = cast(Tuple[float, float, float], evaluate_value(center)) - center_global = cs.transform_point(np.array(center_value)) - - resolved_center = tuple(float(value) for value in center_global) - solid = cast( - Solid, - Solid(make_sphere_solid(resolved_center, radius_value)), - ) - - # 自动标记面 - solid.auto_tag_faces("sphere") - solid._apply_tag("geom.primitive.sphere", propagate=False) - solid._add_tag("sphere") - solid.set_metadata( - "geo", - { - "type": "sphere", - "radius": radius_value, - "center": center, - }, - ) - - return _finalize_primitive_solid( - solid, - op="make_sphere_rsolid", - params={ - "radius": radius, - "center": center, - }, - tags={"primitive", "solid"}, - ) - except Exception as e: - _wrap_public_api_error( - operation="make_sphere_rsolid", - what_happened="Failed to create a sphere solid.", - possible_causes=[ - "The radius is not a positive finite scalar.", - "The center is not a valid finite 3D point.", - "The kernel rejected the sphere definition.", - ], - how_to_fix=[ - "Use a radius greater than zero.", - "Pass center as a finite 3D tuple.", - "If the center is expression-driven, inspect the evaluated coordinates.", - ], - error=e, - ) - - -def make_three_point_arc_redge( - start: Tuple[float, float, float], - middle: Tuple[float, float, float], - end: Tuple[float, float, float], -) -> Edge: - """Create an arc edge from three points.""" - try: - cs = get_current_cs() - start_value = cast(Tuple[float, float, float], evaluate_value(start)) - middle_value = cast(Tuple[float, float, float], evaluate_value(middle)) - end_value = cast(Tuple[float, float, float], evaluate_value(end)) - start_global = cs.transform_point(np.array(start_value)) - middle_global = cs.transform_point(np.array(middle_value)) - end_global = cs.transform_point(np.array(end_value)) - - edge_shape = make_arc_three_point_edge(start_global, middle_global, end_global) - return cast( - Edge, - _finalize_primitive_shape( - Edge(edge_shape), - op=_OP_MAKE_THREE_POINT_ARC_REDGE, - params={"start": start, "middle": middle, "end": end}, - tags={"primitive", "edge"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_three_point_arc_redge", - what_happened="Failed to create a three-point arc edge.", - possible_causes=[ - "One or more points are invalid.", - "The three points are collinear or nearly collinear.", - "The kernel rejected the derived arc geometry.", - ], - how_to_fix=[ - "Pass three finite 3D points.", - "Make sure the three points do not lie on the same straight line.", - "If points are computed dynamically, log them before retrying.", - ], - error=e, - ) - - -def make_three_point_arc_rwire( - start: Tuple[float, float, float], - middle: Tuple[float, float, float], - end: Tuple[float, float, float], -) -> Wire: - """Create a wire containing an arc defined by three points.""" - try: - if get_active_session() is not None: - edge = make_three_point_arc_redge(start, middle, end) - return make_wire_from_edges_rwire([edge]) - - with suspend_graph_recording(): - edge = make_three_point_arc_redge(start, middle, end) - wire_shape = make_wire_from_edges_ocp([edge.wrapped]) - return cast( - Wire, - _finalize_primitive_shape( - Wire(wire_shape), - op="make_three_point_arc_wire", - params={"start": start, "middle": middle, "end": end}, - tags={"primitive", "wire"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_three_point_arc_rwire", - what_happened="Failed to create a wire from the three-point arc.", - possible_causes=[ - "The arc edge could not be created.", - "The wire assembly step rejected the generated edge.", - ], - how_to_fix=[ - "Verify the three arc points first.", - "If the edge is valid but the wire still fails, inspect the generated arc geometry.", - ], - error=e, - ) - - -def make_angle_arc_redge( - center: Tuple[float, float, float], - radius: ScalarLike, - start_angle: ScalarLike, - end_angle: ScalarLike, - normal: Tuple[float, float, float] = (0, 0, 1), -) -> Edge: - """Create an arc edge from a center, radius, and angle range.""" - try: - radius_value = evaluate_scalar(radius) - start_angle_value = evaluate_scalar(start_angle) - end_angle_value = evaluate_scalar(end_angle) - if radius_value <= 0: - raise ValueError("半径必须大于0") - if start_angle_value == end_angle_value: - raise ValueError("起始角度和结束角度不能相同") - - cs = get_current_cs() - center_value = cast(Tuple[float, float, float], evaluate_value(center)) - normal_value = cast(Tuple[float, float, float], evaluate_value(normal)) - center_global = cs.transform_point(np.array(center_value)) - normal_global = cs.transform_vector(np.array(normal_value)) - x_direction_global = cs.transform_vector( - _default_plane_x_direction(normal_value) - ) - - edge_shape = make_arc_angle_edge( - center_global, - radius_value, - start_angle_value, - end_angle_value, - normal_global, - x_direction=x_direction_global, - ) - return cast( - Edge, - _finalize_primitive_shape( - Edge(edge_shape), - op=_OP_MAKE_ANGLE_ARC_REDGE, - params={ - "center": center, - "radius": radius, - "start_angle": start_angle, - "end_angle": end_angle, - "normal": normal, - }, - tags={"primitive", "edge"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_angle_arc_redge", - what_happened="Failed to create an angle-defined arc edge.", - possible_causes=[ - "The radius is not positive.", - "The start and end angles collapse to the same value.", - "The center or normal is invalid, or the kernel rejected the arc.", - ], - how_to_fix=[ - "Use a positive radius.", - "Make sure start_angle and end_angle are different.", - "Pass a valid finite center and a non-zero normal vector.", - ], - error=e, - ) - - -def make_angle_arc_rwire( - center: Tuple[float, float, float], - radius: float, - start_angle: float, - end_angle: float, - normal: Tuple[float, float, float] = (0, 0, 1), -) -> Wire: - """Create a wire containing an arc defined by a center, radius, and angle range.""" - - try: - if get_active_session() is not None: - edge = make_angle_arc_redge(center, radius, start_angle, end_angle, normal) - return make_wire_from_edges_rwire([edge]) - - with suspend_graph_recording(): - edge = make_angle_arc_redge(center, radius, start_angle, end_angle, normal) - wire_shape = make_wire_from_edges_ocp([edge.wrapped]) - return cast( - Wire, - _finalize_primitive_shape( - Wire(wire_shape), - op="make_angle_arc_wire", - params={ - "center": center, - "radius": radius, - "start_angle": start_angle, - "end_angle": end_angle, - "normal": normal, - }, - tags={"primitive", "wire"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_angle_arc_rwire", - what_happened="Failed to create a wire from the angle-defined arc.", - possible_causes=[ - "The underlying arc edge could not be created.", - "The wire assembly step rejected the generated edge.", - ], - how_to_fix=[ - "Check the center, radius, angle range, and normal.", - "Retry after validating the arc edge input values.", - ], - error=e, - ) - - -def _normalize_bspline_control_points( - control_points: Sequence[Sequence[ScalarLike]], -) -> Tuple[Tuple[float, float, float], ...]: - points = list(control_points) - if not points: - raise ValueError("control_points must contain at least one point") - normalized: List[Tuple[float, float, float]] = [] - for index, point in enumerate(points): - value = cast(Sequence[float], evaluate_value(point)) - if len(value) == 2: - coords = (float(value[0]), float(value[1]), 0.0) - elif len(value) == 3: - coords = (float(value[0]), float(value[1]), float(value[2])) - else: - raise ValueError(f"control point {index} must be 2D or 3D") - if not all(math.isfinite(component) for component in coords): - raise ValueError(f"control point {index} contains a non-finite coordinate") - normalized.append(coords) - return tuple(normalized) - - -def _collapse_knot_vector( - knots: Sequence[ScalarLike], -) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: - values = [float(evaluate_scalar(knot)) for knot in knots] - if not values: - raise ValueError("knots must not be empty") - if any(not math.isfinite(value) for value in values): - raise ValueError("knots must contain only finite values") - for previous, current in zip(values, values[1:]): - if current < previous: - raise ValueError( - "knots must be non-decreasing when passed as a full knot vector" - ) - unique: List[float] = [] - multiplicities: List[int] = [] - for value in values: - if unique and abs(value - unique[-1]) <= 1e-12: - multiplicities[-1] += 1 - else: - unique.append(value) - multiplicities.append(1) - return tuple(unique), tuple(multiplicities) - - -def _default_bspline_knots( - control_count: int, degree: int, periodic: bool -) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: - if periodic: - knot_count = control_count + 1 - return ( - tuple(index / (knot_count - 1) for index in range(knot_count)), - tuple(1 for _ in range(knot_count)), - ) - knot_count = control_count - degree + 1 - if knot_count < 2: - raise ValueError("control point count must be at least degree + 1") - knots = tuple(index / (knot_count - 1) for index in range(knot_count)) - multiplicities = [degree + 1] - multiplicities.extend(1 for _ in range(max(0, knot_count - 2))) - multiplicities.append(degree + 1) - return knots, tuple(multiplicities) - - -def _normalize_bspline_knots( - *, - control_count: int, - degree: int, - periodic: bool, - knots: Optional[Sequence[ScalarLike]], - multiplicities: Optional[Sequence[int]], -) -> Tuple[Tuple[float, ...], Tuple[int, ...]]: - if knots is None: - if multiplicities is not None: - raise ValueError("multiplicities require explicit knots") - unique_knots, mults = _default_bspline_knots(control_count, degree, periodic) - elif multiplicities is None: - unique_knots, mults = _collapse_knot_vector(knots) - else: - unique_knots = tuple(float(evaluate_scalar(knot)) for knot in knots) - mults = tuple(int(value) for value in multiplicities) - - if len(unique_knots) != len(mults): - raise ValueError("knots and multiplicities must have the same length") - if len(unique_knots) < 2: - raise ValueError("at least two unique knots are required") - if any(not math.isfinite(knot) for knot in unique_knots): - raise ValueError("knots must contain only finite values") - for previous, current in zip(unique_knots, unique_knots[1:]): - if current <= previous: - raise ValueError("unique knots must be strictly increasing") - if any(multiplicity <= 0 for multiplicity in mults): - raise ValueError("multiplicities must be positive integers") - if any(multiplicity > degree + 1 for multiplicity in mults): - raise ValueError("multiplicities must not exceed degree + 1") - - expected_sum = control_count + (1 if periodic else degree + 1) - actual_sum = sum(mults) - if actual_sum != expected_sum: - raise ValueError( - "sum(multiplicities) must equal " - f"{expected_sum} for this {'periodic' if periodic else 'non-periodic'} B-spline" - ) - return tuple(unique_knots), tuple(mults) - - -def _normalize_bspline_weights( - weights: Optional[Sequence[ScalarLike]], control_count: int -) -> Optional[Tuple[float, ...]]: - if weights is None: - return None - values = tuple(float(evaluate_scalar(weight)) for weight in weights) - if len(values) != control_count: - raise ValueError("weights must contain exactly one value per control point") - if any(not math.isfinite(value) or value <= 0.0 for value in values): - raise ValueError("weights must be finite positive values") - return values - - -def make_spline_redge( - *, - control_points: Sequence[Sequence[ScalarLike]], - degree: int = 3, - knots: Optional[Sequence[ScalarLike]] = None, - multiplicities: Optional[Sequence[int]] = None, - weights: Optional[Sequence[ScalarLike]] = None, - periodic: bool = False, -) -> Edge: - """Create an exact B-spline edge from named control-point parameters. - - Pass sampled curve points through `fit_cubic_bspline_control_points(...)` first, - then pass the result fields explicitly as `control_points=...`, `knots=...`, - and `multiplicities=...`. `control_points` are poles, not interpolation - points; the curve generally does not pass through interior poles. - """ - try: - if isinstance(degree, bool) or int(degree) != degree: - raise ValueError("degree must be an integer") - degree_value = int(degree) - if degree_value < 1: - raise ValueError("degree must be at least 1") - if degree_value > 25: - raise ValueError("degree must be 25 or lower") - periodic_value = bool(periodic) - - local_control_points = _normalize_bspline_control_points(control_points) - if len(local_control_points) < degree_value + 1: - raise ValueError("control point count must be at least degree + 1") - resolved_knots, resolved_multiplicities = _normalize_bspline_knots( - control_count=len(local_control_points), - degree=degree_value, - periodic=periodic_value, - knots=knots, - multiplicities=multiplicities, - ) - resolved_weights = _normalize_bspline_weights( - weights, len(local_control_points) - ) - - cs = get_current_cs() - global_control_points = tuple( - tuple(float(component) for component in cs.transform_point(np.array(point))) - for point in local_control_points - ) - edge_shape = make_bspline_edge( - control_points=global_control_points, - degree=degree_value, - knots=resolved_knots, - multiplicities=resolved_multiplicities, - weights=resolved_weights, - periodic=periodic_value, - ) - edge = Edge(edge_shape) - edge.set_metadata( - "geo", - { - "type": "bspline", - "degree": degree_value, - "control_points": [list(point) for point in global_control_points], - "knots": list(resolved_knots), - "multiplicities": list(resolved_multiplicities), - "weights": ( - list(resolved_weights) if resolved_weights is not None else None - ), - "periodic": periodic_value, - }, - ) - - return cast( - Edge, - _finalize_primitive_shape( - edge, - op=_OP_MAKE_SPLINE_REDGE, - params={ - "control_points": control_points, - "degree": degree_value, - "knots": resolved_knots, - "multiplicities": resolved_multiplicities, - "weights": weights, - "periodic": periodic_value, - }, - tags={"primitive", "edge"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_spline_redge", - what_happened="Failed to create a spline edge.", - possible_causes=[ - "The exact B-spline definition is inconsistent.", - "Control points, knots, multiplicities, or weights are invalid.", - "A sampled-point list was passed directly instead of fitted control points.", - ], - how_to_fix=[ - "Pass keyword arguments such as control_points=..., degree=3, knots=..., multiplicities=....", - "Use fit_cubic_bspline_control_points(sample_points) for sampled curves, then pass its result fields explicitly.", - "Ensure sum(multiplicities) matches the exact B-spline degree/control-count rule.", - ], - error=e, - ) - - -def _normalize_interpolation_points( - points: Sequence[Sequence[ScalarLike]], - *, - periodic: bool, - tolerance: float, -) -> Tuple[Tuple[float, float, float], ...]: - normalized = list(_normalize_bspline_control_points(points)) - if periodic and len(normalized) >= 2: - if ( - np.linalg.norm(np.asarray(normalized[0]) - np.asarray(normalized[-1])) - <= tolerance - ): - normalized.pop() - minimum = 3 if periodic else 2 - if len(normalized) < minimum: - qualifier = "distinct" if periodic else "" - raise ValueError( - f"interpolation requires at least {minimum} {qualifier} points".replace( - " ", " " - ) - ) - adjacent_pairs = list(zip(normalized, normalized[1:])) - if periodic: - adjacent_pairs.append((normalized[-1], normalized[0])) - for index, (first, second) in enumerate(adjacent_pairs): - if np.linalg.norm(np.asarray(first) - np.asarray(second)) <= tolerance: - second_index = (index + 1) % len(normalized) - raise ValueError( - f"interpolation points {index} and {second_index} are within " - f"the interpolation tolerance" - ) - return tuple(normalized) - - -def make_interpolated_spline_redge( - *, - points: Sequence[Sequence[ScalarLike]], - periodic: bool = False, - tolerance: ScalarLike = 1.0e-6, -) -> Edge: - """Interpolate an exact B-spline edge through the supplied points.""" - try: - periodic_value = bool(periodic) - tolerance_value = float(evaluate_scalar(tolerance)) - if not math.isfinite(tolerance_value) or tolerance_value <= 0.0: - raise ValueError("tolerance must be a finite positive value") - local_points = _normalize_interpolation_points( - points, - periodic=periodic_value, - tolerance=tolerance_value, - ) - cs = get_current_cs() - global_points = tuple( - tuple(float(component) for component in cs.transform_point(np.array(point))) - for point in local_points - ) - edge = Edge( - make_interpolated_bspline_edge( - global_points, - periodic=periodic_value, - tolerance=tolerance_value, - ) - ) - edge.set_metadata( - "geo", - { - "type": "bspline", - "construction": "interpolated", - "interpolation_points": [list(point) for point in global_points], - "periodic": periodic_value, - "tolerance": tolerance_value, - }, - ) - return cast( - Edge, - _finalize_primitive_shape( - edge, - op=_OP_MAKE_INTERPOLATED_SPLINE_REDGE, - params={ - "points": points, - "periodic": periodic_value, - "tolerance": tolerance, - }, - tags={"primitive", "edge"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_interpolated_spline_redge", - what_happened="Failed to interpolate a B-spline edge through the input points.", - possible_causes=[ - "Too few distinct interpolation points were provided.", - "Consecutive points are duplicated or contain invalid coordinates.", - "The requested periodic interpolation is geometrically inconsistent.", - ], - how_to_fix=[ - "Provide at least two open-curve points or three periodic-curve points.", - "Remove consecutive duplicate points; a repeated periodic endpoint is optional.", - "Use a smaller positive tolerance when nearby points must remain distinct.", - ], - error=e, - ) - - -def make_interpolated_spline_rwire( - *, - points: Sequence[Sequence[ScalarLike]], - periodic: bool = False, - tolerance: ScalarLike = 1.0e-6, -) -> Wire: - """Create a one-edge wire that interpolates the supplied points.""" - try: - edge_kwargs = { - "points": points, - "periodic": periodic, - "tolerance": tolerance, - } - if get_active_session() is not None: - edge = make_interpolated_spline_redge(**edge_kwargs) - return make_wire_from_edges_rwire([edge]) - - with suspend_graph_recording(): - edge = make_interpolated_spline_redge(**edge_kwargs) - wire_shape = make_wire_from_edges_ocp([edge.wrapped]) - return cast( - Wire, - _finalize_primitive_shape( - Wire(wire_shape), - op="make_interpolated_spline_wire", - params=edge_kwargs, - tags={"primitive", "wire"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_interpolated_spline_rwire", - what_happened="Failed to create an interpolated spline wire.", - possible_causes=[ - "The interpolated spline edge could not be created.", - "The kernel rejected the resulting one-edge wire.", - ], - how_to_fix=[ - "Validate the interpolation points and tolerance.", - "Use periodic=True for a closed profile and omit a duplicated final point.", - ], - error=e, - ) - - -def make_periodic_spline_rwire( - *, - points: Sequence[Sequence[ScalarLike]], - tolerance: ScalarLike = 1.0e-6, -) -> Wire: - """Create a closed periodic spline wire interpolating the supplied points.""" - return make_interpolated_spline_rwire( - points=points, - periodic=True, - tolerance=tolerance, - ) - - -def make_spline_rwire( - *, - control_points: Sequence[Sequence[ScalarLike]], - degree: int = 3, - knots: Optional[Sequence[ScalarLike]] = None, - multiplicities: Optional[Sequence[int]] = None, - weights: Optional[Sequence[ScalarLike]] = None, - periodic: bool = False, -) -> Wire: - """Create a wire containing one exact B-spline edge.""" - try: - edge_kwargs = { - "control_points": control_points, - "degree": degree, - "knots": knots, - "multiplicities": multiplicities, - "weights": weights, - "periodic": periodic, - } - if get_active_session() is not None: - edge = make_spline_redge(**edge_kwargs) - return make_wire_from_edges_rwire([edge]) - - with suspend_graph_recording(): - edge = make_spline_redge(**edge_kwargs) - wire_shape = make_wire_from_edges_ocp([edge.wrapped]) - rv = Wire(wire_shape) - return cast( - Wire, - _finalize_primitive_shape( - rv, - op="make_spline_wire", - params=edge_kwargs, - tags={"primitive", "wire"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_spline_rwire", - what_happened="Failed to create a spline wire.", - possible_causes=[ - "The spline edge could not be created.", - "The exact B-spline definition is inconsistent.", - "The kernel rejected the resulting wire geometry.", - ], - how_to_fix=[ - "Validate the B-spline control points, degree, knots, multiplicities, and weights first.", - "For sampled curves, call fit_cubic_bspline_control_points(...) and pass the result fields explicitly.", - "Retry after inspecting the evaluated spline inputs.", - ], - error=e, - ) - - -def make_polyline_rwire( - points: List[Tuple[ScalarLike, ScalarLike, ScalarLike]], closed: bool = False -) -> Wire: - """Create a polyline wire from a point list.""" - try: - if len(points) < 2: - raise ValueError("至少需要2个点") - - if get_active_session() is not None: - edges = [ - make_line_redge(points[idx], points[idx + 1]) - for idx in range(len(points) - 1) - ] - if closed and len(points) > 2: - edges.append(make_line_redge(points[-1], points[0])) - return make_wire_from_edges_rwire(edges) - - cs = get_current_cs() - - # 转换所有点到全局坐标系 - global_points = [] - for point in points: - point_value = cast(Tuple[float, float, float], evaluate_value(point)) - global_point = cs.transform_point(np.array(point_value)) - global_points.append(tuple(float(v) for v in global_point)) - - wire_shape = make_polyline_wire( - [ - (float(point[0]), float(point[1]), float(point[2])) - for point in global_points - ], - closed=closed, - ) - return cast( - Wire, - _finalize_primitive_shape( - Wire(wire_shape), - op="make_polyline_wire", - params={"points": points, "closed": closed}, - tags={"primitive", "wire"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_polyline_rwire", - what_happened="Failed to create a polyline wire.", - possible_causes=[ - "Fewer than two points were provided.", - "One or more points are invalid or non-finite.", - "The kernel rejected the resulting polyline geometry.", - ], - how_to_fix=[ - "Pass at least two finite 3D points.", - "If closed=True, ensure the sequence describes a valid loop.", - "Inspect the evaluated points before retrying.", - ], - error=e, - ) - - -def make_helix_redge( - pitch: ScalarLike, - height: ScalarLike, - radius: ScalarLike, - center: Tuple[float, float, float] = (0, 0, 0), - dir: Tuple[float, float, float] = (0, 0, 1), -) -> Edge: - """Create a helix edge.""" - try: - pitch_value = evaluate_scalar(pitch) - height_value = evaluate_scalar(height) - radius_value = evaluate_scalar(radius) - if pitch_value <= 0: - raise ValueError("螺距必须大于0") - if height_value <= 0: - raise ValueError("高度必须大于0") - if radius_value <= 0: - raise ValueError("半径必须大于0") - - cs = get_current_cs() - center_value = cast(Tuple[float, float, float], evaluate_value(center)) - dir_value = cast(Tuple[float, float, float], evaluate_value(dir)) - global_center = cs.transform_point(np.array(center_value)) - global_dir = cs.transform_vector(np.array(dir_value)) - global_x_direction = cs.transform_vector(_default_plane_x_direction(dir_value)) - - wire_shape = make_helix_wire( - pitch_value, - height_value, - radius_value, - global_center, - global_dir, - x_direction=global_x_direction, - ) - wire = Wire(wire_shape) - edges = wire.get_edges() - if not edges: - raise ValueError("无法从螺旋线中提取边") - helix_edge = edges[0] - return cast( - Edge, - _finalize_primitive_shape( - helix_edge, - op=_OP_MAKE_HELIX_REDGE, - params={ - "pitch": pitch, - "height": height, - "radius": radius, - "center": center, - "dir": dir, - }, - tags={"primitive", "edge"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_helix_redge", - what_happened="Failed to create a helix edge.", - possible_causes=[ - "Pitch, height, or radius is not positive.", - "The center or direction vector is invalid.", - "The kernel rejected the helix definition.", - ], - how_to_fix=[ - "Use positive pitch, height, and radius values.", - "Pass a valid center and a non-zero direction vector.", - "Inspect the evaluated helix parameters before retrying.", - ], - error=e, - ) - - -def make_helix_rwire( - pitch: float, - height: float, - radius: float, - center: Tuple[float, float, float] = (0, 0, 0), - dir: Tuple[float, float, float] = (0, 0, 1), -) -> Wire: - """Create a helix wire.""" - try: - if get_active_session() is not None: - edge = make_helix_redge(pitch, height, radius, center=center, dir=dir) - return make_wire_from_edges_rwire([edge]) - - cs = get_current_cs() - global_center = cs.transform_point(np.array(center)) - global_dir = cs.transform_vector(np.array(dir)) - global_x_direction = cs.transform_vector(_default_plane_x_direction(dir)) - - wire_shape = make_helix_wire( - pitch, - height, - radius, - global_center, - global_dir, - x_direction=global_x_direction, - ) - return cast( - Wire, - _finalize_primitive_shape( - Wire(wire_shape), - op="make_helix_wire", - params={ - "pitch": pitch, - "height": height, - "radius": radius, - "center": center, - "dir": dir, - }, - tags={"primitive", "wire"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_helix_rwire", - what_happened="Failed to create a helix wire.", - possible_causes=[ - "The helix parameters are invalid.", - "The direction vector is zero or malformed.", - "The kernel rejected the wire geometry.", - ], - how_to_fix=[ - "Use positive pitch, height, and radius values.", - "Pass a valid center and a non-zero direction vector.", - "Retry after logging the evaluated helix parameters.", - ], - error=e, - ) - - -# ============================================================================= -# 变换操作函数 -# ============================================================================= - - -def translate_shape(shape: AnyShape, vector: Tuple[float, float, float]) -> AnyShape: - """Translate a shape by an offset vector.""" - try: - cs = get_current_cs() - vector_value = cast(Tuple[float, float, float], evaluate_value(vector)) - global_vector = cs.transform_vector(np.array(vector_value)) - resolved_vector = tuple(float(value) for value in global_vector) - if isinstance(shape, Solid): - tracked = cast( - TrackedResult, - tracked_translate(shape, resolved_vector), - ) - translated = cast(Solid, tracked.shape) - translated._metadata = shape._metadata.copy() - _attach_lineage_from_source( - shape, - translated, - derivation="continuation", - op=_OP_MAKE_TRANSLATE_RSHAPE, - ) - return _finalize_tracked_solid( - translated, - op=_OP_MAKE_TRANSLATE_RSHAPE, - params={"vector": vector}, - source_solid=shape, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[shape], - ) - - new_shape = translate_shape_ocp(shape, resolved_vector) - - new_shape._metadata = shape._metadata.copy() - _copy_runtime_state(shape, new_shape) - _attach_lineage_from_source( - shape, - new_shape, - derivation="continuation", - op=_OP_MAKE_TRANSLATE_RSHAPE, - ) - record_operation_if_active( - op=_OP_MAKE_TRANSLATE_RSHAPE, - params={"vector": vector}, - outputs=new_shape, - input_shapes=[shape], - context=_current_context_metadata(), - ) - - return new_shape - except Exception as e: - _wrap_public_api_error( - operation="translate_shape", - what_happened="Failed to translate the shape.", - possible_causes=[ - "The shape is invalid or has been corrupted by an earlier operation.", - "The translation vector is not a valid finite 3D vector.", - "The kernel rejected the transform.", - ], - how_to_fix=[ - "Pass a valid SimpleCAD shape object.", - "Pass vector as a finite 3-element tuple or expression-backed vector.", - "Inspect the shape and vector values before retrying.", - ], - error=e, - ) - - -def rotate_shape( - shape: AnyShape, - angle: ScalarLike, - axis: Tuple[float, float, float] = (0, 0, 1), - origin: Tuple[float, float, float] = (0, 0, 0), -) -> AnyShape: - """Rotate a shape around an axis.""" - angle_value = evaluate_scalar(angle) - if angle_value == 0: - return shape - else: - try: - cs = get_current_cs() - axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) - origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) - global_axis = cs.transform_vector(np.array(axis_value)) - global_origin = cs.transform_point(np.array(origin_value)) - resolved_axis = tuple(float(value) for value in global_axis) - resolved_origin = tuple(float(value) for value in global_origin) - if isinstance(shape, Solid): - tracked = cast( - TrackedResult, - tracked_rotate( - shape, - angle_value, - axis=resolved_axis, - origin=resolved_origin, - ), - ) - rotated = cast(Solid, tracked.shape) - rotated._metadata = shape._metadata.copy() - _attach_lineage_from_source( - shape, - rotated, - derivation="continuation", - op=_OP_MAKE_ROTATE_RSHAPE, - ) - return _finalize_tracked_solid( - rotated, - op=_OP_MAKE_ROTATE_RSHAPE, - params={"angle": angle, "axis": axis, "origin": origin}, - source_solid=shape, - delta=tracked.delta, - delta_entries=cast( - Dict[str, Dict[str, object]], tracked.delta_entries - ), - input_shapes=[shape], - ) - - new_shape = rotate_shape_ocp( - shape, - angle_value, - resolved_axis, - resolved_origin, - ) - - new_shape._metadata = shape._metadata.copy() - _copy_runtime_state(shape, new_shape) - _attach_lineage_from_source( - shape, - new_shape, - derivation="continuation", - op=_OP_MAKE_ROTATE_RSHAPE, - ) - record_operation_if_active( - op=_OP_MAKE_ROTATE_RSHAPE, - params={"angle": angle, "axis": axis, "origin": origin}, - outputs=new_shape, - input_shapes=[shape], - context=_current_context_metadata(), - ) - - return new_shape - except Exception as e: - _wrap_public_api_error( - operation="rotate_shape", - what_happened="Failed to rotate the shape.", - possible_causes=[ - "The shape is invalid.", - "The rotation angle is invalid or non-finite.", - "The axis or origin is not a valid finite 3D vector.", - ], - how_to_fix=[ - "Pass a valid shape and a finite rotation angle.", - "Use a non-zero axis vector and a valid origin point.", - "Log the evaluated angle, axis, and origin before retrying.", - ], - error=e, - ) - - -# ============================================================================= -# 3D操作函数 -# ============================================================================= - - -def extrude_rsolid( - profile: Union[Wire, Face], - direction: Tuple[float, float, float], - distance: ScalarLike, - *, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - start_face_tag: Optional[str] = None, - end_face_tag: Optional[str] = None, - side_faces_tag: Optional[str] = None, -) -> Solid: - """Create a solid by extruding a profile, with optional role-based tags.""" - try: - assignments = _normalize_operation_role_tags( - _OP_MAKE_EXTRUDE_RSOLID, - ( - ("extrusion.start", start_face_tag), - ("extrusion.end", end_face_tag), - ("extrusion.side", side_faces_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - distance_value = evaluate_scalar(distance) - if distance_value <= 0: - raise ValueError("拉伸距离必须大于0") - - cs = get_current_cs() - direction_value = cast(Tuple[float, float, float], evaluate_value(direction)) - global_direction = cs.transform_vector(np.array(direction_value)) - - direction_norm = float(np.linalg.norm(global_direction)) - if direction_norm <= 1e-15: - raise ValueError("拉伸方向不能是零向量") - direction_vec = tuple( - (global_direction / direction_norm * distance_value).tolist() - ) - - if isinstance(profile, Wire): - # 如果是线,先转换为面 - if profile.is_closed(): - face = Face(make_face_from_wire_ocp(profile.wrapped)) - else: - raise ValueError( - "如果传入线框作为拉伸对象,那么线框必须是闭合的, 而你的线框没有闭合,请检查构成线框的点是否正确" - ) - elif isinstance(profile, Face): - face = profile - else: - raise ValueError("只能拉伸线或面") # type: ignore[unreachable] - - resolved_direction = tuple(float(value) for value in global_direction) - tracked = cast( - TrackedResult, - tracked_extrude( - face, - resolved_direction, - distance_value, - ), - ) - solid = cast(Solid, tracked.shape) - - solid._apply_tag("solid.extrusion", propagate=False) - solid._metadata = profile._metadata.copy() - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - solid, - op=_OP_MAKE_EXTRUDE_RSOLID, - params={ - "direction": direction, - "distance": distance, - }, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[profile], - ) - tagged = _apply_operation_role_tags( - finalized, - op=_OP_MAKE_EXTRUDE_RSOLID, - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - return _apply_feature_tag_prefix( - tagged, - tag_prefix=tag_prefix, - op=_OP_MAKE_EXTRUDE_RSOLID, - delta=tracked.delta, - start_role="extrusion.start", - end_role="extrusion.end", - side_role="extrusion.side", - source_shapes=[profile], - ) - except Exception as e: - _wrap_public_api_error( - operation="extrude_rsolid", - what_happened="Failed to extrude the profile into a solid.", - possible_causes=[ - "The distance is not a positive finite scalar.", - "The direction vector is invalid.", - "A wire profile was provided but it is not closed.", - "The kernel rejected the profile or the extrusion direction.", - ], - how_to_fix=[ - "Use a distance greater than zero.", - "Pass a valid finite direction vector.", - "If you extrude a wire, make sure the wire is closed or convert it to a face first.", - "Inspect the evaluated profile and direction before retrying.", - ], - error=e, - ) - - -def revolve_rsolid( - profile: Union[Wire, Face], - axis: Tuple[float, float, float] = (0, 0, 1), - angle: ScalarLike = 360, - origin: Tuple[float, float, float] = (0, 0, 0), - *, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - start_face_tag: Optional[str] = None, - end_face_tag: Optional[str] = None, - side_faces_tag: Optional[str] = None, -) -> Solid: - """Create a revolved solid, with optional kernel-role-based tags.""" - try: - assignments = _normalize_operation_role_tags( - _OP_MAKE_REVOLVE_RSOLID, - ( - ("revolution.start", start_face_tag), - ("revolution.end", end_face_tag), - ("revolution.side", side_faces_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - angle_value = evaluate_scalar(angle) - if angle_value <= 0: - raise ValueError("旋转角度必须大于0") - - cs = get_current_cs() - axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) - origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) - global_axis = cs.transform_vector(np.array(axis_value)) - global_origin = cs.transform_point(np.array(origin_value)) - - # 获取轮廓对应的面 - if isinstance(profile, Wire): - # 如果是线,先转换为面 - if profile.is_closed(): - face = Face(make_face_from_wire_ocp(profile.wrapped)) - else: - raise ValueError("旋转的线必须是闭合的") - elif isinstance(profile, Face): - face = profile - else: - raise ValueError("只能旋转线或面") - - resolved_axis = tuple(float(value) for value in global_axis) - resolved_origin = tuple(float(value) for value in global_origin) - tracked = cast( - TrackedResult, - tracked_revolve( - face, - resolved_axis, - resolved_origin, - angle_value, - ), - ) - solid = cast(Solid, tracked.shape) - - solid._metadata = profile._metadata.copy() - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - solid, - op=_OP_MAKE_REVOLVE_RSOLID, - params={ - "axis": axis, - "angle": angle, - "origin": origin, - }, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[profile], - ) - tagged = _apply_operation_role_tags( - finalized, - op=_OP_MAKE_REVOLVE_RSOLID, - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - return _apply_feature_tag_prefix( - tagged, - tag_prefix=tag_prefix, - op=_OP_MAKE_REVOLVE_RSOLID, - delta=tracked.delta, - start_role="revolution.start" if angle_value < 360.0 else None, - end_role="revolution.end" if angle_value < 360.0 else None, - side_role="revolution.side", - source_shapes=[profile], - ) - except Exception as e: - _wrap_public_api_error( - operation="revolve_rsolid", - what_happened="Failed to revolve the profile into a solid.", - possible_causes=[ - "The angle is not a positive finite scalar.", - "The axis or origin is invalid.", - "A wire profile was provided but it is not closed.", - "The kernel rejected the revolve definition.", - ], - how_to_fix=[ - "Use an angle greater than zero.", - "Pass a valid non-zero axis vector and a valid origin point.", - "If you revolve a wire, ensure it is closed or convert it to a face first.", - "Inspect the evaluated axis, origin, and profile before retrying.", - ], - error=e, - ) - - -# ============================================================================= -# 标签和选择函数 -# ============================================================================= - - -def _semantic_view_target(view: AnyShape, target: AnyShape) -> AnyShape: - candidates = [ - wrapper - for entity in view._topology_cache.entities() - if entity.kind == target._entity.kind - for wrapper in entity.wrappers - if isinstance(wrapper, type(target)) - ] - matches = [] - for candidate in candidates: - try: - if _same_semantic_topology( - target._entity.kind, - candidate.wrapped, - target.wrapped, - ): - matches.append(candidate) - except Exception: - continue - unique = {candidate.topo_id: candidate for candidate in matches} - if not unique: - raise ValueError("tag target does not belong to the assignment scope") - if len(unique) != 1: - raise ValueError("tag target resolves ambiguously inside the assignment scope") - return cast(AnyShape, next(iter(unique.values()))) - - -def apply_tag_rselection( - scope: AnyShape, - targets: Union[ShapeSelector, Sequence[AnyShape]], - tag: str, - topology_propagation: str | TopologyPropagation = TopologyPropagation.LOCAL, - lineage_policy: str | LineagePolicy = LineagePolicy.CONTINUATION_FRAGMENT, -) -> AnyShape: - """Return a semantic shape view with a canonical tag assignment.""" - - try: - return _apply_tag_rselection( - scope, - targets, - tag, - topology_propagation, - lineage_policy, - ) - except Exception as e: - _wrap_public_api_error( - operation="apply_tag_rselection", - what_happened="Failed to attach the tag to the selected shapes.", - possible_causes=[ - "The assignment scope or target selection is invalid.", - "The tag value is empty or malformed.", - "The selector resolved no targets or references foreign topology.", - ], - how_to_fix=[ - "Pass a valid scope and a non-empty ShapeSelector or shape sequence.", - "Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'.", - "Ensure every explicit target belongs to the assignment scope.", - ], - error=e, - ) - - -def _apply_tag_rselection( - scope: AnyShape, - targets: Union[ShapeSelector, Sequence[AnyShape]], - tag: str, - topology_propagation: str | TopologyPropagation, - lineage_policy: str | LineagePolicy, - *, - authoring_source: str = "simplecadapi.apply_tag_rselection", - extra_evidence: Optional[Dict[str, Any]] = None, - clone_scope: bool = True, -) -> AnyShape: - normalized_tag = normalize_tag(tag, strict=True) - topology = TopologyPropagation(topology_propagation) - lineage = LineagePolicy(lineage_policy) - session = get_active_session() - source_node = _active_graph_node_for_shape(scope) - source_output_slot = int(scope._get_runtime("graph.output_slot", 0)) - if session is not None and source_node is None: - raise ValueError("assignment scope is not produced by the active GraphSession") - - view = clone_semantic_shape_view(scope) if clone_scope else scope - if isinstance(targets, ShapeSelector): - selector = targets - if source_node is not None: - if selector.source_node_id is None: - selector = selector.from_source(source_node.node_id, source_output_slot) - elif ( - selector.source_node_id != source_node.node_id - or int(selector.source_output_slot or 0) != source_output_slot - ): - raise ValueError( - "tag selector source does not match the assignment scope" - ) - selected = cast(List[AnyShape], selector.resolve(view)) - target = TagTarget("selection_query", selector=selector.to_dict()) - else: - if isinstance(targets, (str, bytes)): - raise TypeError("targets must be a ShapeSelector or shape sequence") - target_shapes = list(targets) - if not target_shapes: - raise ValueError("tag assignment targets cannot be empty") - if not all( - isinstance(item, (Vertex, Edge, Wire, Face, Shell, Solid, Compound)) - for item in target_shapes - ): - raise TypeError("tag assignment targets must contain only shapes") - selected = [ - _semantic_view_target(view, cast(AnyShape, item)) for item in target_shapes - ] - refs = tuple( - ref for ref in _serialize_shape_refs(target_shapes) if isinstance(ref, dict) - ) - if len(refs) != len(target_shapes): - refs = tuple( - {"kind": _shape_kind_token(item), "topo_id": item.topo_id} - for item in target_shapes - ) - target = TagTarget("explicit_refs", refs=refs) - - selected_by_topo_id = {item.topo_id: item for item in selected} - if len(selected_by_topo_id) != len(selected): - raise ValueError("tag assignment targets contain ambiguous duplicate entities") - selected = list(selected_by_topo_id.values()) - if not selected: - raise ValueError("tag assignment resolved no targets") - - selected_refs = _serialize_shape_refs(selected) - if len(selected_refs) != len(selected): - selected_refs = [ - {"kind": _shape_kind_token(item), "topo_id": item.topo_id} - for item in selected - ] - - assignment_node_id = ( - session.graph.allocate_node_id("n") - if source_node is not None and session is not None - else None - ) - evidence_data = { - "authoring_source": authoring_source, - "selected_count": len(selected), - "selected_refs": selected_refs, - **dict(extra_evidence or {}), - } - binding = TagBinding( - tag=normalized_tag, - producer=TagProducer("user_operation", node_id=assignment_node_id), - scope=TagBindingScope( - node_id=(source_node.node_id if source_node is not None else None), - output_slot=source_output_slot, - ), - target=target, - propagation=TagPropagation(topology=topology, lineage=lineage), - evidence=TagEvidence("query_execution", evidence_data), - certainty=TagCertainty.ASSERTED, - lifecycle=TagLifecycle.ASSERTION, - binding_id=( - f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, f'simplecad:user-tag:{session.graph.graph_id}:{assignment_node_id}:{normalized_tag}').hex}" - if assignment_node_id is not None and session is not None - else f"tag_binding_{uuid.uuid4().hex}" - ), - ) - - for selected_shape in selected: - selected_shape._add_tag_binding(binding) - - if source_node is not None and session is not None: - node = record_operation( - op=_OP_APPLY_TAG_RSELECTION, - params={"tag_binding": binding.to_dict()}, - inputs=[source_node], - node_id=assignment_node_id, - output_count=1, - context=_current_context_metadata(), - ) - attach_semantic_graph_node( - view, - node, - output_slot=0, - graph_id=session.graph.graph_id, - ) - return view - - -def apply_tag(shape: AnyShape, tag: str) -> AnyShape: - """Attach a local user tag with continuation/fragment lineage policy.""" - - try: - _ensure_source_shape_has_own_selection_node(shape) - selector = ShapeSelector(_shape_kind_token(shape)).exactly(1) - return _apply_tag_rselection( - shape, - selector, - tag, - TopologyPropagation.LOCAL, - LineagePolicy.CONTINUATION_FRAGMENT, - clone_scope=False, - ) - except Exception as e: - _wrap_public_api_error( - operation="apply_tag", - what_happened="Failed to attach the tag to the shape.", - possible_causes=[ - "The shape is invalid.", - "The tag value is empty or malformed.", - ], - how_to_fix=[ - "Pass a valid shape object.", - "Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'.", - ], - error=e, - ) - - -def list_tags( - shape: AnyShape, - scope: str | TagScope = TagScope.EFFECTIVE, -) -> List[str]: - """Return shape tags in deterministic sorted order for one scope.""" - try: - return shape._list_tags(normalize_tag_scope(scope)) - except Exception as e: - _wrap_public_api_error( - operation="list_tags", - what_happened="Failed to list tags on the shape.", - possible_causes=[ - "The shape is invalid.", - "The object is not a SimpleCAD shape.", - ], - how_to_fix=[ - "Pass a valid Vertex, Edge, Wire, Face, or Solid object.", - ], - error=e, - ) - - -def explain_tag( - shape: AnyShape, - tag: str, - scope: str | TagScope = TagScope.EFFECTIVE, -) -> List[Dict[str, Any]]: - """Explain every visible binding that produces a tag token.""" - - try: - return shape._explain_tag( - normalize_tag(tag, strict=True), normalize_tag_scope(scope) - ) - except Exception as e: - _wrap_public_api_error( - operation="explain_tag", - what_happened="Failed to explain the tag on the shape.", - possible_causes=[ - "The shape or tag is invalid.", - "The requested scope requires unavailable semantic evidence.", - ], - how_to_fix=[ - "Pass a valid shape and normalized tag token.", - "Request a supported scope or provide complete topology history.", - ], - error=e, - ) - - -def select_faces_by_tag( - solid: Solid, - tag: str, - scope: str | TagScope = TagScope.EFFECTIVE, -) -> List[Face]: - """Select faces by tag.""" - try: - normalized = normalize_tag(tag, strict=True) - resolved_scope = normalize_tag_scope(scope) - faces = solid.get_faces() - return [face for face in faces if face._has_tag(normalized, resolved_scope)] - except Exception as e: - _wrap_public_api_error( - operation="select_faces_by_tag", - what_happened="Failed to select faces by tag.", - possible_causes=[ - "The solid is invalid.", - "The tag string is invalid.", - ], - how_to_fix=[ - "Pass a valid Solid object.", - "Use the exact face tag that was previously assigned.", - ], - error=e, - ) - - -def select_edges_by_tag( - shape: Union[Face, Solid], - tag: str, - scope: str | TagScope = TagScope.EFFECTIVE, -) -> List[Edge]: - """Select edges by tag.""" - try: - normalized = normalize_tag(tag, strict=True) - resolved_scope = normalize_tag_scope(scope) - if isinstance(shape, Face): - edges = shape.get_edges() - elif isinstance(shape, Solid): - edges = shape.get_edges() - else: - raise ValueError("只能从面或实体中选择边") - - return [edge for edge in edges if edge._has_tag(normalized, resolved_scope)] - except Exception as e: - _wrap_public_api_error( - operation="select_edges_by_tag", - what_happened="Failed to select edges by tag.", - possible_causes=[ - "The input shape is neither a Face nor a Solid.", - "The shape is invalid.", - "The tag string is invalid.", - ], - how_to_fix=[ - "Pass a Face or Solid object.", - "Use the exact edge tag that was previously assigned.", - "If selection is empty unexpectedly, inspect the available edge tags first.", - ], - error=e, - ) - - -# ============================================================================= -# 布尔运算函数 -# ============================================================================= - - -def union_rsolid( - *solids: Union[Solid, Sequence[Solid]], - clean: bool = True, - glue: bool = _DEFAULT_UNION_GLUE, - tol: Optional[float] = None, - tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, -) -> Solid: - """Compute the boolean union and return one manifold solid. - - Face-area contact and positive-volume overlap can produce one solid without - artificial embedding. Edge-only, vertex-only, and point/curve tangencies - are non-manifold connections and cannot satisfy the one-Solid contract. - - ``glue`` is an OCC optimization for compatible touching or coincident - topology, not a geometry repair switch. If the optimized pass does not - return one solid, SimpleCAD automatically retries the normal fuse algorithm. - - Args: - solids: One or more Solid objects or sequences of Solid. Nested sequences are - flattened before processing. - clean: Unify same-domain faces and remove splitter edges when possible. - glue: Try OCC glue optimization first, then fall back to normal fuse if - necessary. Defaults to False. - tol: Optional finite non-negative fuzzy-boolean tolerance used by OCC. It - may intentionally bridge a small gap but cannot make a non-manifold - point or edge contact into a valid solid. - tracking_policy: FULL computes topology history and lineage. GRAPH keeps - the replayable operation node without computing a TopoDelta. - - Returns: - Solid: The merged union result. - - Usage: - Accepts standalone `Solid` objects, lists of `Solid`, and nested sequences, - but always returns exactly one `Solid`. If the kernel cannot produce - exactly one solid result, the API raises a clear error instead of - returning multiple pieces. - - Examples: - body = make_box_rsolid(10, 4, 4, bottom_face_center=(0, 0, 0)) - rib = make_box_rsolid(2, 4, 4, bottom_face_center=(4, 0, 0)) - merged = union_rsolid(body, rib) - print(merged.get_volume()) - """ - - try: - policy = ( - TrackingPolicy.GRAPH - if current_tracking_policy() == TrackingPolicy.GRAPH - else TrackingPolicy(tracking_policy) - ) - remaining = _flatten_boolean_solids(solids, "union_rsolid") - - if not remaining: - raise ValueError("union_rsolid 至少需要一个Solid输入") - - for solid in remaining: - if solid.wrapped.IsNull(): - raise ValueError("输入实体无效,无法进行并集运算。") - - if len(remaining) == 1 and not clean: - return remaining[0] - - effective_tol = _resolve_union_tol(remaining, tol) - tracked_union_result: Optional[TrackedBooleanResult] = None - if policy == TrackingPolicy.FULL and len(remaining) >= 2: - tracked_union_result = cast( - TrackedBooleanResult, - _evaluate_tracked_union( - remaining, - glue=glue, - tol=effective_tol, - clean=clean, - ), - ) - if tracked_union_result.solid is None: - raise ValueError("union did not produce a valid solid") - fused_solid = tracked_union_result.solid - else: - fused_solid = cast( - Solid, - _require_union_solid( - fuse_shapes( - [solid.wrapped for solid in remaining], - glue=glue, - tol=effective_tol, - clean=clean, - ), - effective_tol, - ), - ) - - all_metadata = {} - for solid in remaining: - all_metadata.update(solid._metadata) - - fused_solid._metadata = all_metadata.copy() - - params: Dict[str, object] = { - "input_count": len(remaining), - "clean": clean, - "glue": glue, - "tol": effective_tol, - "tracking_policy": policy.value, - } - if tracked_union_result is not None: - fused_solid = _finalize_tracked_solid( - fused_solid, - op=_OP_MAKE_UNION_RSOLID, - params=params, - source_solids=remaining, - delta=tracked_union_result.delta, - delta_entries=cast( - Dict[str, Dict[str, object]], - tracked_union_result.delta_entries, - ), - input_shapes=remaining, - ) - elif policy == TrackingPolicy.GRAPH: - fused_solid = cast( - Solid, - _finalize_derived_shape( - fused_solid, - op=_OP_MAKE_UNION_RSOLID, - params=params, - input_shapes=remaining, - ), - ) - else: - _attach_track_summary(fused_solid, op=_OP_MAKE_UNION_RSOLID) - record_operation_if_active( - op=_OP_MAKE_UNION_RSOLID, - params=params, - outputs=fused_solid, - input_shapes=remaining, - context=_current_context_metadata(), - ) - - return fused_solid - except Exception as e: - _wrap_public_api_error( - operation="union_rsolid", - what_happened=( - str(e) - if isinstance(e, ValueError) and str(e).startswith("union produced ") - else "Failed to compute the boolean union." - ), - possible_causes=[ - "One or more inputs are not Solid objects.", - "At least one input solid is null or invalid.", - "The inputs are separated beyond tol, so the kernel cannot produce exactly one solid.", - "The inputs meet only along an edge, vertex, tangent point, or tangent curve, so their union is not one manifold solid.", - ], - how_to_fix=[ - "Pass only valid Solid objects or sequences of Solid objects.", - "For intended face contact, make the solids share a finite-area face and retry; no artificial overlap is required.", - "For a real small gap, pass an explicit tol only when approximating that gap is acceptable.", - "Do not expect glue or tol to turn point-, edge-, or tangent-only contact into a valid single solid.", - ], - error=e, - ) - - -def cut_rsolid( - *solids: Union[Solid, Sequence[Solid]], - skip_non_intersecting: bool = True, - tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, -) -> Solid: - """Compute the boolean difference of solids. - - Args: - solids: One or more Solid objects or sequences of Solid. Nested sequences are - flattened before processing; the first solid is the base, the rest are - subtracted in order. - skip_non_intersecting: When True, tools with no meaningful intersection are - ignored for interactive convenience. Graph replay records this flag and - should use False for strict diagnostic workflows. - tracking_policy: FULL computes topology history and lineage. GRAPH keeps - the replayable operation node without computing a TopoDelta. - - Returns: - Solid: The cut result solid. - - Usage: - Accepts a base solid followed by one or more tool solids, including nested - sequences, and returns a single `Solid`. - """ - try: - policy = ( - TrackingPolicy.GRAPH - if current_tracking_policy() == TrackingPolicy.GRAPH - else TrackingPolicy(tracking_policy) - ) - remaining = _flatten_boolean_solids(solids, "cut_rsolid") - - if not remaining: - raise ValueError("cut_rsolid 至少需要一个Solid输入") - - if len(remaining) == 1: - return remaining[0] - - # 从第一个实体开始,依次减去其他实体 - result_solid = remaining[0] - deltas: List[TopoDelta] = [] - merged_delta_entries: Dict[str, Dict[str, object]] = {} - cut_performed = False - - for i in range(1, len(remaining)): - candidate = remaining[i] - - s1 = result_solid.wrapped - s2 = candidate.wrapped - - if s1.IsNull() or s2.IsNull(): - raise ValueError("输入实体无效,无法进行差集运算。") - - # 检查是否有交集 - intersection = common_shapes([s1, s2]) - intersection_solids = solids_of(intersection) - if not intersection_solids: - if skip_non_intersecting: - continue - raise ValueError("差集工具实体与当前实体没有交集。") - intersection_obj = Solid(intersection_solids[0]) - - if intersection_obj.get_volume() < 1e-12: - # 没有有效的交集,跳过此次切割 - if skip_non_intersecting: - continue - raise ValueError("差集工具实体与当前实体交集体积过小。") - - tracked = ( - cast( - TrackedBooleanResult, - tracked_cut(result_solid, candidate), - ) - if policy == TrackingPolicy.FULL and len(remaining) == 2 - else ( - tracked_cut(result_solid, candidate) - if policy == TrackingPolicy.FULL - else None - ) - ) - if tracked is not None: - if tracked.solid is None: - raise ValueError("差集运算失败: OCC 未返回有效实体") - new_result = tracked.solid - else: - new_result = _require_single_boolean_solid( - solids_of(cut_shapes(s1, [s2])), - operation="cut_rsolid", - failure_reason="差集运算失败: OCC 未返回有效实体", - ) - new_result._metadata = result_solid._metadata.copy() - result_solid = new_result - if tracked is not None: - deltas.append(tracked.delta) - merged_delta_entries.update( - cast(Dict[str, Dict[str, object]], tracked.delta_entries) - ) - cut_performed = True - - result_solid._metadata = remaining[0]._metadata.copy() - result_solid._apply_tag("solid.boolean.cut", propagate=False) - - merged_delta = _merge_topo_deltas(deltas) - params: Dict[str, object] = { - "tool_count": len(remaining) - 1, - "skip_non_intersecting": bool(skip_non_intersecting), - "tracking_policy": policy.value, - } - if cut_performed and merged_delta is not None: - result_solid = _finalize_tracked_solid( - result_solid, - op=_OP_MAKE_CUT_RSOLID, - params=params, - source_solids=remaining, - delta=merged_delta, - delta_entries=merged_delta_entries or None, - input_shapes=remaining, - ) - elif policy == TrackingPolicy.GRAPH: - result_solid = cast( - Solid, - _finalize_derived_shape( - result_solid, - op=_OP_MAKE_CUT_RSOLID, - params=params, - input_shapes=remaining, - ), - ) - else: - _attach_track_summary(result_solid, op=_OP_MAKE_CUT_RSOLID) - record_operation_if_active( - op=_OP_MAKE_CUT_RSOLID, - params=params, - outputs=result_solid, - input_shapes=remaining, - context=_current_context_metadata(), - ) - - return result_solid - except Exception as e: - _wrap_public_api_error( - operation="cut_rsolid", - what_happened="Failed to compute the boolean cut.", - possible_causes=[ - "One or more inputs are not Solid objects.", - "The base solid or tool solids are invalid.", - "The kernel could not compute a valid cut result for the current geometry.", - ], - how_to_fix=[ - "Pass a valid base solid followed by valid tool solids.", - "Check whether the tool geometry actually intersects the base solid.", - "If the cut depends on earlier union results, verify those results first.", - ], - error=e, - ) - - -def intersect_rsolid(*solids: Union[Solid, Sequence[Solid]]) -> Solid: - """Compute the boolean intersection of solids. - - Args: - solids: One or more Solid objects or sequences of Solid. Nested sequences are - flattened before processing. - - Returns: - Solid: The overlap region as a single solid. - - Usage: - Accepts one or more solids, including nested sequences, and returns a single - `Solid`. If the inputs do not overlap meaningfully, the API raises a clear - error instead of returning an empty list. - """ - try: - remaining = _flatten_boolean_solids(solids, "intersect_rsolid") - - if not remaining: - raise ValueError("intersect_rsolid 至少需要一个Solid输入") - - if len(remaining) == 1: - return remaining[0] - - # 从第一个实体开始,依次与后续实体进行交集运算 - result_solid = remaining[0] - deltas: List[TopoDelta] = [] - merged_delta_entries: Dict[str, Dict[str, object]] = {} - intersect_performed = False - - for i in range(1, len(remaining)): - candidate = remaining[i] - - s1 = result_solid.wrapped - s2 = candidate.wrapped - - if s1.IsNull() or s2.IsNull(): - raise ValueError("输入实体无效,无法进行交集运算。") - - tracked = ( - cast( - TrackedBooleanResult, - tracked_intersect(result_solid, candidate), - ) - if len(remaining) == 2 - else tracked_intersect(result_solid, candidate) - ) - if tracked.solid is None: - raise ValueError("交集结果为空或 OCC 未返回有效实体") - - result_solid = tracked.solid - deltas.append(tracked.delta) - merged_delta_entries.update( - cast(Dict[str, Dict[str, object]], tracked.delta_entries) - ) - intersect_performed = True - - # 检查交集是否为空 - if result_solid.get_volume() < 1e-12: - raise ValueError("交集结果为空或体积过小") - - all_metadata: dict = {} - for solid in remaining: - all_metadata.update(solid._metadata) - - result_solid._metadata = all_metadata - result_solid._apply_tag("solid.boolean.intersect", propagate=False) - - merged_delta = _merge_topo_deltas(deltas) - if intersect_performed and merged_delta is not None: - result_solid = _finalize_tracked_solid( - result_solid, - op=_OP_MAKE_INTERSECT_RSOLID, - params={"input_count": len(remaining)}, - source_solids=remaining, - delta=merged_delta, - delta_entries=merged_delta_entries or None, - input_shapes=remaining, - ) - else: - _attach_track_summary(result_solid, op=_OP_MAKE_INTERSECT_RSOLID) - record_operation_if_active( - op=_OP_MAKE_INTERSECT_RSOLID, - params={"input_count": len(remaining)}, - outputs=result_solid, - input_shapes=remaining, - context=_current_context_metadata(), - ) - - return result_solid - except Exception as e: - _wrap_public_api_error( - operation="intersect_rsolid", - what_happened="Failed to compute the boolean intersection.", - possible_causes=[ - "One or more inputs are not Solid objects.", - "At least one input solid is invalid.", - "The solids do not overlap enough to produce a non-empty single solid.", - "The kernel could not compute a stable overlap region.", - ], - how_to_fix=[ - "Pass only valid Solid objects.", - "Verify that the solids truly overlap in space.", - "Move the solids so they share a meaningful overlap volume before intersecting.", - ], - error=e, - ) - - -# ============================================================================= -# 2D Face boolean operations -# ============================================================================= - - -def _extract_single_face(shape_ocp, operation: str) -> Face: - """Extract exactly one Face from an OCP shape result.""" - result_faces = faces_of_ocp(shape_ocp) - if len(result_faces) != 1: - raise ValueError( - f"{operation} expected exactly 1 face in the result, got {len(result_faces)}" - ) - return Face(result_faces[0]) - - -def make_2d_cut_rface(body: Face, tool: Face) -> Face: - """Subtract one 2D face from another (2D boolean difference). - - Parameters - ---------- - body : Face - The face to subtract from. - tool : Face - The face to subtract (the cutter). - - Returns - ------- - Face - The resulting face after subtraction. The result may contain - inner wires (holes) if the tool was fully inside the body. - """ - try: - if not isinstance(body, Face): - raise ValueError("body must be a Face") - if not isinstance(tool, Face): - raise ValueError("tool must be a Face") - - result_shape = cut_shapes(body.wrapped, [tool.wrapped]) - result_face = _extract_single_face(result_shape, "make_2d_cut_rface") - - result_face._metadata = body._metadata.copy() - - return cast( - Face, - _finalize_derived_shape( - result_face, - op=_OP_MAKE_CUT_RFACE, - params={}, - input_shapes=[body, tool], - tags={"derived", "face"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_2d_cut_rface", - what_happened="Failed to subtract one face from another.", - possible_causes=[ - "The body or tool is not a Face.", - "The faces do not overlap or are not coplanar.", - "The kernel could not compute a stable 2D difference.", - ], - how_to_fix=[ - "Pass two valid Face objects.", - "Ensure both faces lie on the same plane.", - "Verify the tool face overlaps the body face.", - ], - error=e, - ) - - -def make_2d_union_rface(face_a: Face, face_b: Face) -> Face: - """Compute the boolean union of two 2D faces. - - Parameters - ---------- - face_a : Face - First face. - face_b : Face - Second face. - - Returns - ------- - Face - The merged face. Both inputs must overlap or touch so that the - result is a single connected face. - """ - try: - if not isinstance(face_a, Face): - raise ValueError("face_a must be a Face") - if not isinstance(face_b, Face): - raise ValueError("face_b must be a Face") - - result_shape = fuse_shapes([face_a.wrapped, face_b.wrapped], clean=True) - result_face = _extract_single_face(result_shape, "make_2d_union_rface") - - result_face._metadata = {**face_a._metadata, **face_b._metadata} - - return cast( - Face, - _finalize_derived_shape( - result_face, - op=_OP_MAKE_UNION_RFACE, - params={}, - input_shapes=[face_a, face_b], - tags={"derived", "face"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_2d_union_rface", - what_happened="Failed to union two faces.", - possible_causes=[ - "One or both inputs are not Face objects.", - "The faces do not overlap or touch.", - "The faces are not coplanar.", - ], - how_to_fix=[ - "Pass two valid Face objects.", - "Ensure the faces overlap or share a boundary.", - "Ensure both faces lie on the same plane.", - ], - error=e, - ) - - -def make_2d_intersect_rface(face_a: Face, face_b: Face) -> Face: - """Compute the boolean intersection of two 2D faces. - - Parameters - ---------- - face_a : Face - First face. - face_b : Face - Second face. - - Returns - ------- - Face - The overlapping region of the two faces. - """ - try: - if not isinstance(face_a, Face): - raise ValueError("face_a must be a Face") - if not isinstance(face_b, Face): - raise ValueError("face_b must be a Face") - - result_shape = common_shapes([face_a.wrapped, face_b.wrapped]) - result_face = _extract_single_face(result_shape, "make_2d_intersect_rface") - - result_face._metadata = {**face_a._metadata, **face_b._metadata} - - return cast( - Face, - _finalize_derived_shape( - result_face, - op=_OP_MAKE_INTERSECT_RFACE, - params={}, - input_shapes=[face_a, face_b], - tags={"derived", "face"}, - ), - ) - except Exception as e: - _wrap_public_api_error( - operation="make_2d_intersect_rface", - what_happened="Failed to intersect two faces.", - possible_causes=[ - "One or both inputs are not Face objects.", - "The faces do not overlap.", - "The faces are not coplanar.", - ], - how_to_fix=[ - "Pass two valid Face objects.", - "Ensure the faces have a non-empty overlap region.", - "Ensure both faces lie on the same plane.", - ], - error=e, - ) - - -# ============================================================================= -# Product semantic functions -# ============================================================================= - - -def make_material_rmaterial( - material_id: str, - name: Optional[str] = None, - density: Optional[float] = None, - density_unit: Optional[str] = None, - color: Optional[Tuple[float, float, float]] = None, -) -> Material: - """Create a material definition for later Part assignment. - - Material is deliberately separate from `make_part_rpart(...)`; the only - correct workflow is to create a material and then assign it to a Part with - `assign_material_rpart(...)`. - """ - - try: - material = Material( - material_id, - name=name, - density=density, - density_unit=density_unit, - color=color, - ) - _reserve_semantic_id("material", material.material_id) - record_operation_if_active( - _OP_MAKE_MATERIAL_RMATERIAL, - _material_params(material), - outputs=material, - semantic_delta=_semantic_created( - "Material", material.material_id, material.to_dict() - ), - context=_current_context_metadata(), - ) - return material - except Exception as e: - _wrap_public_api_error( - operation="make_material_rmaterial", - what_happened="Failed to create the material definition.", - possible_causes=[ - "The material_id is empty or uses unsupported characters.", - "The density is non-finite, non-positive, or missing a density_unit.", - "The color is not a 3-tuple in the [0.0, 1.0] range.", - ], - how_to_fix=[ - "Use a stable identifier such as 'aluminum_6061'.", - "Provide density and density_unit together, or omit both.", - "Pass RGB color components as floats between 0.0 and 1.0.", - ], - error=e, - ) - - -def make_placement_rplacement( - origin: Tuple[float, float, float], - x_axis: Tuple[float, float, float] = (1.0, 0.0, 0.0), - y_axis: Tuple[float, float, float] = (0.0, 1.0, 0.0), -) -> Placement: - """Create a canonical right-handed placement in the active workplane.""" - - try: - cs = get_current_cs() - origin_global = cs.transform_point(np.asarray(origin, dtype=float)) - x_axis_global = cs.transform_vector(np.asarray(x_axis, dtype=float)) - y_axis_global = cs.transform_vector(np.asarray(y_axis, dtype=float)) - placement = Placement( - tuple(float(value) for value in origin_global), - x_axis=tuple(float(value) for value in x_axis_global), - y_axis=tuple(float(value) for value in y_axis_global), - ) - record_operation_if_active( - _OP_MAKE_PLACEMENT_RPLACEMENT, - {"origin": origin, "x_axis": x_axis, "y_axis": y_axis}, - outputs=placement, - context=_current_context_metadata(), - ) - return placement - except Exception as e: - _wrap_public_api_error( - operation="make_placement_rplacement", - what_happened="Failed to create the placement.", - possible_causes=[ - "The origin is not a finite 3D point.", - "One of the axes is zero-length or non-finite.", - "x_axis and y_axis are not orthogonal.", - ], - how_to_fix=[ - "Pass origin, x_axis, and y_axis as finite 3-element tuples.", - "Use one canonical representation; do not mix Euler, quaternion, or axis-angle payloads.", - "Make sure x_axis and y_axis form a right-handed frame.", - ], - error=e, - ) - - -def identity_placement_rplacement() -> Placement: - """Create the identity placement of the active workplane.""" - - try: - cs = get_current_cs() - placement = Placement( - tuple(float(value) for value in cs.origin), - x_axis=tuple(float(value) for value in cs.x_axis), - y_axis=tuple(float(value) for value in cs.y_axis), - ) - record_operation_if_active( - _OP_MAKE_IDENTITY_PLACEMENT_RPLACEMENT, - {}, - outputs=placement, - context=_current_context_metadata(), - ) - return placement - except Exception as e: - _wrap_public_api_error( - operation="identity_placement_rplacement", - what_happened="Failed to create the identity placement.", - possible_causes=["Internal placement validation failed."], - how_to_fix=["Report this as a SimpleCADAPI bug if it reproduces."], - error=e, - ) - - -def make_part_rpart( - part_id: str, - body: Solid, - name: Optional[str] = None, -) -> Part: - """Wrap exactly one Solid as a semantic single-body Part.""" - - try: - part = Part(part_id, body, name=name) - _reserve_semantic_id("part", part.part_id) - record_operation_if_active( - _OP_MAKE_PART_RPART, - _part_params(part), - outputs=part, - input_shapes=[body], - semantic_delta=_semantic_created("Part", part.part_id, part.to_dict()), - context=_current_context_metadata(), - ) - return part - except Exception as e: - _wrap_public_api_error( - operation="make_part_rpart", - what_happened="Failed to create the single-body Part.", - possible_causes=[ - "The part_id is empty or uses unsupported characters.", - "The body is not a Solid.", - "A Part with the same part_id already exists in the active GraphSession.", - ], - how_to_fix=[ - "Pass a stable part_id such as 'base_plate'.", - "Union intended multiple bodies into one Solid before creating the Part.", - "Do not pass material to make_part_rpart; use assign_material_rpart instead.", - ], - error=e, - ) - - -def assign_material_rpart(part: Part, material: Material) -> Part: - """Assign a Material to a Part and return the updated Part.""" - - try: - if not isinstance(part, Part): - raise TypeError("part must be a Part") - if not isinstance(material, Material): - raise TypeError("material must be a Material") - result = part.with_material(material) - record_operation_if_active( - _OP_MAKE_ASSIGN_MATERIAL_RPART, - { - "part_id": part.part_id, - "material_id": material.material_id, - "material": _material_params(material), - }, - outputs=result, - input_shapes=[part, material], - semantic_delta=_semantic_modified( - "Part", - part.part_id, - {"material_id": material.material_id}, - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="assign_material_rpart", - what_happened="Failed to assign the material to the Part.", - possible_causes=[ - "The part input is not a Part.", - "The material input is not a Material.", - ], - how_to_fix=[ - "Create parts with make_part_rpart(...).", - "Create materials with make_material_rmaterial(...).", - ], - error=e, - ) - - -def make_assembly_rassembly( - assembly_id: str, - name: Optional[str] = None, -) -> Assembly: - """Create an empty assembly product structure.""" - - try: - assembly = Assembly(assembly_id, name=name) - _reserve_semantic_id("assembly", assembly.assembly_id) - record_operation_if_active( - _OP_MAKE_ASSEMBLY_RASSEMBLY, - _assembly_params(assembly), - outputs=assembly, - semantic_delta=_semantic_created( - "Assembly", assembly.assembly_id, assembly.to_dict() - ), - context=_current_context_metadata(), - ) - return assembly - except Exception as e: - _wrap_public_api_error( - operation="make_assembly_rassembly", - what_happened="Failed to create the assembly.", - possible_causes=[ - "The assembly_id is empty or uses unsupported characters.", - "An Assembly with the same assembly_id already exists in the active GraphSession.", - ], - how_to_fix=["Pass a stable assembly_id such as 'fixture_assembly'."], - error=e, - ) - - -def add_component_rassembly( - assembly: Assembly, - item: Union[Part, Assembly], - component_id: str, - placement: Placement, - name: Optional[str] = None, -) -> Assembly: - """Add a placed Part or subassembly component instance to an Assembly.""" - - try: - if not isinstance(assembly, Assembly): - raise TypeError("assembly must be an Assembly") - if not isinstance(item, (Part, Assembly)): - raise TypeError("item must be a Part or Assembly") - if not isinstance(placement, Placement): - raise TypeError("placement must be a Placement") - component = Component(component_id, item, placement, name=name) - result = assembly.with_component(component) - item_kind = "assembly" if isinstance(item, Assembly) else "part" - item_id = item.assembly_id if isinstance(item, Assembly) else item.part_id - record_operation_if_active( - _OP_MAKE_ADD_COMPONENT_RASSEMBLY, - { - "assembly_id": assembly.assembly_id, - "component_id": component.component_id, - "name": component.name, - "item_kind": item_kind, - "item_id": item_id, - "placement": placement.to_dict(), - }, - outputs=result, - input_shapes=[assembly, item, placement], - semantic_delta=SemanticDelta( - created=( - SemanticRef( - graph_id="pending", - node_id="pending", - entity_type="Component", - entity_id=f"{assembly.assembly_id}:{component.component_id}", - ), - ), - modified=( - SemanticRef( - graph_id="pending", - node_id="pending", - entity_type="Assembly", - entity_id=assembly.assembly_id, - ), - ), - metadata={"component": component.to_dict()}, - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="add_component_rassembly", - what_happened="Failed to add the component to the assembly.", - possible_causes=[ - "The assembly input is not an Assembly.", - "The item input is not a Part or Assembly.", - "The component_id is empty, malformed, or duplicated in the assembly.", - "The placement is invalid or missing.", - "Adding this subassembly would create an assembly cycle.", - ], - how_to_fix=[ - "Wrap solids explicitly with make_part_rpart before adding them to assemblies.", - "Use a unique component_id within the parent assembly.", - "Create placements with make_placement_rplacement or identity_placement_rplacement.", - ], - error=e, - ) - - -def place_component_rassembly( - assembly: Assembly, - component_id: str, - placement: Placement, -) -> Assembly: - """Move an existing assembly component by replacing its placement.""" - - try: - if not isinstance(assembly, Assembly): - raise TypeError("assembly must be an Assembly") - if not isinstance(placement, Placement): - raise TypeError("placement must be a Placement") - result = assembly.with_component_placement(component_id, placement) - record_operation_if_active( - _OP_MAKE_PLACE_COMPONENT_RASSEMBLY, - { - "assembly_id": assembly.assembly_id, - "component_id": component_id, - "placement": placement.to_dict(), - }, - outputs=result, - input_shapes=[assembly, placement], - semantic_delta=_semantic_modified( - "Component", - f"{assembly.assembly_id}:{component_id}", - {"placement": placement.to_dict()}, - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="place_component_rassembly", - what_happened="Failed to place the assembly component.", - possible_causes=[ - "The assembly input is not an Assembly.", - "The component_id does not exist in the assembly.", - "The placement is invalid or missing.", - ], - how_to_fix=[ - "Use add_component_rassembly before placing a component.", - "Use a component_id returned in assembly.component_ids().", - "Create placements with make_placement_rplacement.", - ], - error=e, - ) - - -def _make_geometry_backed_connector( - connector_id: str, - shape: AnyShape, - *, - op: str, - operation_name: str, - name: Optional[str] = None, - flip: bool = False, -) -> Connector: - source_shape = _selection_source_for_shape(shape) or shape - node_ids = _ensure_geo_selection_node_ids(source_shape, [shape]) - source_node_id = node_ids[0] if node_ids else None - geo_selector = _make_geo_selector(shape, source_shape=source_shape) - kind = _shape_kind_token(shape) - geometry_ref = GeometryRef( - kind=kind, - source_node_id=source_node_id, - geo_selector=geo_selector, - flip=bool(flip), - ) - connector = Connector(connector_id, geometry_ref, name=name) - record_operation_if_active( - op, - _connector_params(connector), - outputs=connector, - input_shapes=[shape], - context=_current_context_metadata(), - ) - return connector - - -def make_face_connector_rconnector( - connector_id: str, - face: Face, - name: Optional[str] = None, - flip: bool = False, -) -> Connector: - """Create a connector anchored to a Face. - - Z axis follows the face normal; origin is the face center. - Set flip=True to negate the Z axis (point it opposite to the normal). - """ - try: - if not isinstance(face, Face): - raise TypeError("face must be a Face") - return _make_geometry_backed_connector( - connector_id, - face, - op=_OP_MAKE_FACE_CONNECTOR_RCONNECTOR, - operation_name="make_face_connector_rconnector", - name=name, - flip=flip, - ) - except Exception as e: - _wrap_public_api_error( - operation="make_face_connector_rconnector", - what_happened="Failed to create the face connector.", - possible_causes=[ - "The connector_id is empty or malformed.", - "The face is not a valid Face object.", - ], - how_to_fix=[ - "Use a stable connector_id such as 'mount_face'.", - "Select a face via ql.faces().resolve(solid) or solid.get_faces()[i].", - ], - error=e, - ) - - -def make_edge_connector_rconnector( - connector_id: str, - edge: Edge, - name: Optional[str] = None, - flip: bool = False, -) -> Connector: - """Create a connector anchored to an Edge. - - Z axis follows the edge direction (start->end); origin is the edge midpoint. - Set flip=True to negate the Z axis. - """ - try: - if not isinstance(edge, Edge): - raise TypeError("edge must be an Edge") - return _make_geometry_backed_connector( - connector_id, - edge, - op=_OP_MAKE_EDGE_CONNECTOR_RCONNECTOR, - operation_name="make_edge_connector_rconnector", - name=name, - flip=flip, - ) - except Exception as e: - _wrap_public_api_error( - operation="make_edge_connector_rconnector", - what_happened="Failed to create the edge connector.", - possible_causes=[ - "The connector_id is empty or malformed.", - "The edge is not a valid Edge object.", - ], - how_to_fix=[ - "Use a stable connector_id such as 'hinge_axis'.", - "Select an edge via ql.edges().resolve(solid) or solid.get_edges()[i].", - ], - error=e, - ) - - -def make_vertex_connector_rconnector( - connector_id: str, - vertex: Vertex, - name: Optional[str] = None, - flip: bool = False, -) -> Connector: - """Create a connector anchored to a Vertex. - - Origin is the vertex point; axes are identity. - flip has no effect on vertex connectors (no direction). - """ - try: - if not isinstance(vertex, Vertex): - raise TypeError("vertex must be a Vertex") - return _make_geometry_backed_connector( - connector_id, - vertex, - op=_OP_MAKE_VERTEX_CONNECTOR_RCONNECTOR, - operation_name="make_vertex_connector_rconnector", - name=name, - flip=flip, - ) - except Exception as e: - _wrap_public_api_error( - operation="make_vertex_connector_rconnector", - what_happened="Failed to create the vertex connector.", - possible_causes=[ - "The connector_id is empty or malformed.", - "The vertex is not a valid Vertex object.", - ], - how_to_fix=[ - "Use a stable connector_id such as 'pivot_point'.", - "Select a vertex via ql.vertices().resolve(solid) or solid.get_vertices()[i].", - ], - error=e, - ) - - -def make_placement_connector_rconnector( - connector_id: str, - placement: Placement, - name: Optional[str] = None, -) -> Connector: - """Create a connector anchored to an explicit local placement frame. - - Use this when a datum should be defined by a stable coordinate frame - instead of a selected BREP face, edge, or vertex. - """ - - try: - if not isinstance(placement, Placement): - raise TypeError("placement must be a Placement") - anchor = ConnectorAnchor("placement", placement=placement) - connector = Connector(connector_id, None, name=name, anchor=anchor) - record_operation_if_active( - _OP_MAKE_PLACEMENT_CONNECTOR_RCONNECTOR, - { - "connector_id": connector.connector_id, - "placement": placement.to_dict(), - "name": connector.name, - }, - outputs=connector, - input_shapes=[placement], - context=_current_context_metadata(), - ) - return connector - except Exception as e: - _wrap_public_api_error( - operation="make_placement_connector_rconnector", - what_happened="Failed to create the placement connector.", - possible_causes=[ - "The connector_id is empty or malformed.", - "The placement input is not a Placement.", - ], - how_to_fix=[ - "Create placements with make_placement_rplacement.", - "Use a stable connector_id such as 'bearing_axis'.", - ], - error=e, - ) - - -def add_connector_rpart(part: Part, connector: Connector) -> Part: - """Attach a connector datum frame to a Part definition.""" - - try: - if not isinstance(part, Part): - raise TypeError("part must be a Part") - result = part.with_connector(connector) - record_operation_if_active( - _OP_MAKE_ADD_CONNECTOR_RPART, - {"part_id": part.part_id, "connector_id": connector.connector_id}, - outputs=result, - input_shapes=[part, connector], - semantic_delta=_semantic_modified( - "Part", part.part_id, {"connector": connector.to_dict()} - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="add_connector_rpart", - what_happened="Failed to add the connector to the Part.", - possible_causes=[ - "The part input is not a Part.", - "The connector input is not a Connector.", - "The connector_id is duplicated in the Part.", - ], - how_to_fix=[ - "Create a connector with make_face_connector_rconnector, make_edge_connector_rconnector, or make_vertex_connector_rconnector.", - "Use unique connector ids within one Part.", - ], - error=e, - ) - - -def add_connector_rassembly(assembly: Assembly, connector: Connector) -> Assembly: - """Attach a connector datum frame to an Assembly definition.""" - - try: - if not isinstance(assembly, Assembly): - raise TypeError("assembly must be an Assembly") - result = assembly.with_connector(connector) - record_operation_if_active( - _OP_MAKE_ADD_CONNECTOR_RASSEMBLY, - { - "assembly_id": assembly.assembly_id, - "connector_id": connector.connector_id, - }, - outputs=result, - input_shapes=[assembly, connector], - semantic_delta=_semantic_modified( - "Assembly", assembly.assembly_id, {"connector": connector.to_dict()} - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="add_connector_rassembly", - what_happened="Failed to add the connector to the Assembly.", - possible_causes=[ - "The assembly input is not an Assembly.", - "The connector input is not a Connector.", - "The connector_id is duplicated in the Assembly.", - ], - how_to_fix=[ - "Create a connector with make_face_connector_rconnector, make_edge_connector_rconnector, or make_vertex_connector_rconnector.", - "Use unique connector ids within one Assembly.", - ], - error=e, - ) - - -def forward_connector_rassembly( - assembly: Assembly, - connector_id: str, - source_component_id: str, - source_connector_id: str, - name: Optional[str] = None, - offset: Optional[Placement] = None, -) -> Assembly: - """Expose an internal component connector as an assembly-level connector. - - The forwarded connector resolves to `source_component.placement * - source_connector.placement`, followed by the optional `offset` placement. - Parent assemblies can constrain to the subassembly's public connector - without depending on its private component structure. - """ - - try: - if not isinstance(assembly, Assembly): - raise TypeError("assembly must be an Assembly") - if offset is not None and not isinstance(offset, Placement): - raise TypeError("offset must be a Placement") - anchor = ConnectorAnchor( - "forwarded", - source_component_id=source_component_id, - source_connector_id=source_connector_id, - offset=offset, - ) - connector = Connector(connector_id, None, name=name, anchor=anchor) - result = assembly.with_connector(connector) - record_operation_if_active( - _OP_MAKE_FORWARD_CONNECTOR_RASSEMBLY, - { - "assembly_id": assembly.assembly_id, - "connector_id": connector.connector_id, - "source_component_id": anchor.source_component_id, - "source_connector_id": anchor.source_connector_id, - "name": connector.name, - "offset": offset.to_dict() if offset is not None else None, - }, - outputs=result, - input_shapes=[assembly] + ([offset] if offset is not None else []), - semantic_delta=_semantic_modified( - "Assembly", assembly.assembly_id, {"connector": connector.to_dict()} - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="forward_connector_rassembly", - what_happened="Failed to forward the assembly connector.", - possible_causes=[ - "The assembly input is not an Assembly.", - "The connector_id is duplicated in the Assembly.", - "The source component or source connector does not exist.", - "The optional offset is not a Placement.", - ], - how_to_fix=[ - "Add the source component before forwarding its connector.", - "Use a connector_id unique within the Assembly.", - "Create offsets with make_placement_rplacement when needed.", - ], - error=e, - ) - - -def make_connector_ref_rconnectorref( - component_id: str, connector_id: str -) -> ConnectorRef: - """Reference a connector through a component instance.""" - - try: - connector_ref = ConnectorRef(component_id, connector_id) - record_operation_if_active( - _OP_MAKE_CONNECTOR_REF_RCONNECTORREF, - _connector_ref_params(connector_ref), - outputs=connector_ref, - context=_current_context_metadata(), - ) - return connector_ref - except Exception as e: - _wrap_public_api_error( - operation="make_connector_ref_rconnectorref", - what_happened="Failed to create the connector reference.", - possible_causes=["The component_id or connector_id is empty or malformed."], - how_to_fix=["Use stable ids from the owning Assembly and component item."], - error=e, - ) - - -def make_scalar_limit_rscalarlimit( - lower_value: float, upper_value: float -) -> ScalarLimit: - """Create a closed scalar limit for driven constraint coordinates.""" - - try: - limit = ScalarLimit(lower_value, upper_value) - record_operation_if_active( - _OP_MAKE_SCALAR_LIMIT_RSCALARLIMIT, - _scalar_limit_params(limit), - outputs=limit, - context=_current_context_metadata(), - ) - return limit - except Exception as e: - _wrap_public_api_error( - operation="make_scalar_limit_rscalarlimit", - what_happened="Failed to create the scalar limit.", - possible_causes=[ - "One of the limit values is non-finite.", - "lower_value is greater than upper_value.", - ], - how_to_fix=["Pass finite lower and upper values in increasing order."], - error=e, - ) - - -def ground_component_rassembly(assembly: Assembly, component_id: str) -> Assembly: - """Ground a component at its current authored placement.""" - - try: - if not isinstance(assembly, Assembly): - raise TypeError("assembly must be an Assembly") - result = assembly.with_grounded_component(component_id) - record_operation_if_active( - _OP_MAKE_GROUND_COMPONENT_RASSEMBLY, - {"assembly_id": assembly.assembly_id, "component_id": component_id}, - outputs=result, - input_shapes=[assembly], - semantic_delta=_semantic_modified( - "Assembly", - assembly.assembly_id, - {"grounded_component_id": component_id}, - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="ground_component_rassembly", - what_happened="Failed to ground the assembly component.", - possible_causes=[ - "The assembly input is not an Assembly.", - "The component_id does not exist in the Assembly.", - ], - how_to_fix=["Use a component_id already added to the Assembly."], - error=e, - ) - - -def unground_component_rassembly(assembly: Assembly, component_id: str) -> Assembly: - """Remove a component grounding marker.""" - - try: - if not isinstance(assembly, Assembly): - raise TypeError("assembly must be an Assembly") - result = assembly.without_grounded_component(component_id) - record_operation_if_active( - _OP_MAKE_UNGROUND_COMPONENT_RASSEMBLY, - {"assembly_id": assembly.assembly_id, "component_id": component_id}, - outputs=result, - input_shapes=[assembly], - semantic_delta=_semantic_modified( - "Assembly", - assembly.assembly_id, - {"ungrounded_component_id": component_id}, - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="unground_component_rassembly", - what_happened="Failed to unground the assembly component.", - possible_causes=[ - "The assembly input is not an Assembly.", - "The component_id does not exist in the Assembly.", - ], - how_to_fix=["Use a component_id already added to the Assembly."], - error=e, - ) - - -def add_fixed_constraint_rassembly( - assembly: Assembly, - constraint_id: str, - connector_a: ConnectorRef, - connector_b: ConnectorRef, - name: Optional[str] = None, -) -> Assembly: - """Constrain two component connectors to the same frame.""" - - return _add_constraint_rassembly( - assembly, - Constraint( - constraint_id, - "fixed", - connector_a, - connector_b, - name=name, - ), - _OP_MAKE_FIXED_CONSTRAINT_RASSEMBLY, - "add_fixed_constraint_rassembly", - ) - - -def add_revolute_constraint_rassembly( - assembly: Assembly, - constraint_id: str, - connector_a: ConnectorRef, - connector_b: ConnectorRef, - drive_angle_degrees: Optional[float] = None, - angle_limit: Optional[ScalarLimit] = None, - name: Optional[str] = None, -) -> Assembly: - """Constrain two connectors as a revolute axis pair.""" - - return _add_constraint_rassembly( - assembly, - Constraint( - constraint_id, - "revolute", - connector_a, - connector_b, - drive_angle_degrees=drive_angle_degrees, - angle_limit=angle_limit, - name=name, - ), - _OP_MAKE_REVOLUTE_CONSTRAINT_RASSEMBLY, - "add_revolute_constraint_rassembly", - ) - - -def add_prismatic_constraint_rassembly( - assembly: Assembly, - constraint_id: str, - connector_a: ConnectorRef, - connector_b: ConnectorRef, - drive_distance: Optional[float] = None, - distance_limit: Optional[ScalarLimit] = None, - name: Optional[str] = None, -) -> Assembly: - """Constrain two connectors as a prismatic slider pair.""" - - return _add_constraint_rassembly( - assembly, - Constraint( - constraint_id, - "prismatic", - connector_a, - connector_b, - drive_distance=drive_distance, - distance_limit=distance_limit, - name=name, - ), - _OP_MAKE_PRISMATIC_CONSTRAINT_RASSEMBLY, - "add_prismatic_constraint_rassembly", - ) - - -def add_gear_constraint_rassembly( - assembly: Assembly, - constraint_id: str, - connector_a: ConnectorRef, - connector_b: ConnectorRef, - pitch_radius_a: float, - pitch_radius_b: float, - phase_offset: Optional[float] = None, - name: Optional[str] = None, -) -> Assembly: - """Couple two revolute axes as meshing gears with inverse rotation.""" - - constraint = Constraint( - constraint_id, - "gear", - connector_a, - connector_b, - pitch_radius_a=pitch_radius_a, - pitch_radius_b=pitch_radius_b, - phase_offset=phase_offset, - name=name, - ) - if phase_offset is None: - constraint = Constraint( - constraint_id, - "gear", - connector_a, - connector_b, - pitch_radius_a=pitch_radius_a, - pitch_radius_b=pitch_radius_b, - phase_offset=coupling_phase_offset(assembly, constraint), - name=name, - ) - return _add_constraint_rassembly( - assembly, - constraint, - _OP_MAKE_GEAR_CONSTRAINT_RASSEMBLY, - "add_gear_constraint_rassembly", - ) - - -def add_belt_constraint_rassembly( - assembly: Assembly, - constraint_id: str, - connector_a: ConnectorRef, - connector_b: ConnectorRef, - pulley_radius_a: float, - pulley_radius_b: float, - phase_offset: Optional[float] = None, - name: Optional[str] = None, -) -> Assembly: - """Couple two revolute axes as belt-linked pulleys with same-direction rotation.""" - - constraint = Constraint( - constraint_id, - "belt", - connector_a, - connector_b, - pulley_radius_a=pulley_radius_a, - pulley_radius_b=pulley_radius_b, - phase_offset=phase_offset, - name=name, - ) - if phase_offset is None: - constraint = Constraint( - constraint_id, - "belt", - connector_a, - connector_b, - pulley_radius_a=pulley_radius_a, - pulley_radius_b=pulley_radius_b, - phase_offset=coupling_phase_offset(assembly, constraint), - name=name, - ) - return _add_constraint_rassembly( - assembly, - constraint, - _OP_MAKE_BELT_CONSTRAINT_RASSEMBLY, - "add_belt_constraint_rassembly", - ) - - -def add_rack_pinion_constraint_rassembly( - assembly: Assembly, - constraint_id: str, - rack_connector: ConnectorRef, - pinion_connector: ConnectorRef, - pitch_radius: float, - phase_offset: Optional[float] = None, - name: Optional[str] = None, -) -> Assembly: - """Couple a prismatic rack axis to a revolute pinion axis.""" - - constraint = Constraint( - constraint_id, - "rack_pinion", - rack_connector, - pinion_connector, - pitch_radius=pitch_radius, - phase_offset=phase_offset, - name=name, - ) - if phase_offset is None: - constraint = Constraint( - constraint_id, - "rack_pinion", - rack_connector, - pinion_connector, - pitch_radius=pitch_radius, - phase_offset=coupling_phase_offset(assembly, constraint), - name=name, - ) - return _add_constraint_rassembly( - assembly, - constraint, - _OP_MAKE_RACK_PINION_CONSTRAINT_RASSEMBLY, - "add_rack_pinion_constraint_rassembly", - ) - - -def _add_constraint_rassembly( - assembly: Assembly, - constraint: Constraint, - op_name: str, - public_name: str, -) -> Assembly: - try: - if not isinstance(assembly, Assembly): - raise TypeError("assembly must be an Assembly") - result = assembly.with_constraint(constraint) - inputs: List[object] = [ - assembly, - constraint.connector_a, - constraint.connector_b, - ] - if constraint.distance_limit is not None: - inputs.append(constraint.distance_limit) - if constraint.angle_limit is not None: - inputs.append(constraint.angle_limit) - record_operation_if_active( - op_name, - _constraint_params(constraint), - outputs=result, - input_shapes=inputs, - semantic_delta=_semantic_modified( - "Assembly", assembly.assembly_id, {"constraint": constraint.to_dict()} - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation=public_name, - what_happened="Failed to add the assembly constraint.", - possible_causes=[ - "The assembly input is not an Assembly.", - "A connector ref references a missing component or connector.", - "The constraint_id is duplicated in the Assembly.", - "A drive value violates its scalar limit.", - ], - how_to_fix=[ - "Create connector refs with make_connector_ref_rconnectorref.", - "Add connectors to Parts or Assemblies before adding constrained components.", - "Use unique constraint ids within one Assembly.", - ], - error=e, - ) - - -def solve_assembly_constraints_rassembly( - assembly: Assembly, strict: bool = True -) -> Assembly: - """Solve fixed, revolute, and prismatic assembly constraints. - - Solving is limit-aware: when a constraint carries a ``ScalarLimit`` - (``angle_limit`` or ``distance_limit``), the drive scalar is clamped - into the closed range before placement propagation. When no drive - scalar is present but a limit exists, the current relative-frame - scalar is projected into the bounds. Unresolvable closed kinematic - loops fall back to a golden-section search over the limit bounds. - - A ``ConstraintReport`` is recorded on the returned assembly under the - ``constraint_report`` runtime key for later inspection via - ``inspect_assembly_constraints_rassembly``. - """ - - try: - result = solve_assembly_constraints(assembly, strict=bool(strict)) - solved_component_placements = { - component.component_id: component.placement.to_dict() - for component in result.components - } - record_operation_if_active( - _OP_MAKE_SOLVE_ASSEMBLY_CONSTRAINTS_RASSEMBLY, - { - "assembly_id": assembly.assembly_id, - "strict": bool(strict), - "component_placements": solved_component_placements, - }, - outputs=result, - input_shapes=[assembly], - semantic_delta=_semantic_modified( - "Assembly", assembly.assembly_id, {"constraints_solved": True} - ), - context=_current_context_metadata(), - ) - return result - except Exception as e: - _wrap_public_api_error( - operation="solve_assembly_constraints_rassembly", - what_happened="Failed to solve the assembly constraints.", - possible_causes=[ - "No component is grounded.", - "A constraint graph references missing connectors.", - "A connected component cannot be reached from a grounded component.", - "A closed-loop residual exceeds tolerance.", - ], - how_to_fix=[ - "Ground at least one component with ground_component_rassembly.", - "Ensure every constrained component has the required connectors.", - "Inspect constraint residuals before strict solving.", - ], - error=e, - ) - - -def measure_constraint_residual_rconstraintresidual( - assembly: Assembly, constraint_id: str -) -> ConstraintResidual: - """Measure residual for one assembly constraint without mutating the assembly.""" - - return measure_constraint_residual(assembly, constraint_id) - - -def inspect_assembly_constraints_rconstraintreport( - assembly: Assembly, -) -> ConstraintReport: - """Inspect all assembly constraint residuals without mutating the assembly.""" - - return inspect_assembly_constraints(assembly) - - -def _placed_solids_from_item( - item: Union[Part, Assembly], placement: Placement -) -> List[Solid]: - if isinstance(item, Part): - placed = place_shape_ocp( - item.body, - placement.origin, - placement.x_axis, - placement.y_axis, - placement.z_axis, - ) - return [cast(Solid, placed)] - if isinstance(item, Assembly): - solids: List[Solid] = [] - for component in item.components: - solids.extend( - _placed_solids_from_item( - component.item, - compose_placements(placement, component.placement), - ) - ) - return solids - raise TypeError("item must be a Part or Assembly") - - -def make_compound_from_assembly_rcompound(assembly: Assembly) -> Compound: - """Project an Assembly into an explicit flattened Compound geometry value.""" - - try: - if not isinstance(assembly, Assembly): - raise TypeError("assembly must be an Assembly") - if not assembly.components: - raise ValueError("assembly must contain at least one component to project") - solids = _placed_solids_from_item(assembly, identity_placement()) - if not solids: - raise ValueError("assembly projection produced no solids") - compound = Compound(make_compound_always([solid.wrapped for solid in solids])) - compound.set_metadata( - "assembly_projection", - { - "assembly_id": assembly.assembly_id, - "component_count": len(assembly.components), - "solid_count": len(solids), - }, - ) - record_operation_if_active( - _OP_MAKE_COMPOUND_FROM_ASSEMBLY_RCOMPOUND, - { - "assembly_id": assembly.assembly_id, - "component_count": len(assembly.components), - }, - outputs=compound, - input_shapes=[assembly], - semantic_delta=_semantic_modified( - "Assembly", - assembly.assembly_id, - {"projection": "compound", "solid_count": len(solids)}, - ), - context=_current_context_metadata(), - ) - return compound - except Exception as e: - _wrap_public_api_error( - operation="make_compound_from_assembly_rcompound", - what_happened="Failed to project the assembly into a Compound.", - possible_causes=[ - "The input is not an Assembly.", - "The assembly has no components.", - "A component placement is invalid.", - "The kernel could not transform or combine the component bodies.", - ], - how_to_fix=[ - "Create an assembly with make_assembly_rassembly and add at least one component.", - "Ensure every component references a valid Part or subassembly.", - "Validate placements before projection.", - ], - error=e, - ) - - -# ============================================================================= -# 导出函数 -# ============================================================================= - - -_EXPORTABLE_TYPES = (Compound, Solid, Shell, Face, Wire, Edge, Vertex) - - -def _normalize_shape_input( - shapes: Union[AnyShape, Sequence[AnyShape]], -) -> List[AnyShape]: - """Normalize rendering input into a flat list of shapes.""" - - if isinstance(shapes, _EXPORTABLE_TYPES): - return [shapes] - - if isinstance(shapes, Sequence) and not isinstance(shapes, (str, bytes)): - normalized: List[AnyShape] = [] - for item in shapes: - normalized.extend(_normalize_shape_input(cast(AnyShape, item))) - return normalized - - raise ValueError( - "rendering accepts Compound, Solid, Shell, Face, Wire, Edge, Vertex, or nested sequences of those types" - ) - - -def render_screenshot_rpath( - shapes: Union[Solid, Sequence[Solid]], - output_path: str, - highlight_tags: Optional[Sequence[str]] = None, - tag_labels: Optional[Dict[str, str]] = None, - image_size: Tuple[int, int] = (1400, 900), - view: Union[Tuple[float, float], str] = "auto", - show_axes: bool = True, - show_legend: bool = True, - zoom: float = 4.0, - show_callouts: bool = True, -) -> str: - """Render SDK solids through the shared OCCT/VTK BREP renderer.""" - try: - from .inspect.brep.render import _render_sdk_screenshot_rpath - - shape_list = _normalize_shape_input(shapes) - solids = [shape for shape in shape_list if isinstance(shape, Solid)] - if len(solids) != len(shape_list) or not solids: - raise ValueError("render_screenshot_rpath only supports Solid inputs") - return str( - _render_sdk_screenshot_rpath( - solids, - output_path, - highlight_tags=tuple(highlight_tags or ()), - tag_labels=tag_labels, - image_size=image_size, - view=view, - show_axes=show_axes, - show_legend=show_legend, - zoom=zoom, - show_callouts=show_callouts, - ) - ) - except Exception as e: - _wrap_public_api_error( - operation="render_screenshot_rpath", - what_happened="Failed to render the screenshot.", - possible_causes=[ - "The input does not contain any valid Solid objects.", - "The rendering view or zoom configuration is invalid.", - "The output path is invalid or not writable.", - ], - how_to_fix=[ - "Pass a Solid or a sequence of Solid objects.", - "Use a supported view preset or a valid (elev, azim) tuple.", - "Check that the output path is writable.", - ], - error=e, - ) - - -# ============================================================================= -# 高级特征操作函数 -# ============================================================================= - - -def fillet_rsolid( - solid: Solid, - edges: Union[Sequence[Edge], ShapeSelector], - radius: ScalarLike, - *, - result_tag: Optional[str] = None, - generated_faces_tag: Optional[str] = None, -) -> Solid: - """Apply fillets, with optional tagging of kernel-proven patch faces.""" - try: - assignments = _normalize_operation_role_tags( - _OP_MAKE_FILLET_RSOLID, - (("fillet.patch", generated_faces_tag),), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - radius_value = evaluate_scalar(radius) - if radius_value <= 0: - raise ValueError("圆角半径必须大于0") - - selected_edges = cast(List[Edge], _resolve_selector_or_shapes(solid, edges)) - if not selected_edges: - raise ValueError("圆角操作至少需要一条边") - - tracked = cast( - TrackedResult, - tracked_fillet(solid, selected_edges, radius_value), - ) - result = cast(Solid, tracked.shape) - - result._metadata = solid._metadata.copy() - - selected_edge_refs = _serialize_shape_refs(selected_edges) - selected_edge_node_ids = _ensure_geo_selection_node_ids(solid, selected_edges) - - selection_params: Dict[str, object] = { - "radius": radius, - "edge_count": len(selected_edges), - "selected_edges": selected_edge_refs, - } - if selected_edge_node_ids: - selection_params["selected_edge_node_ids"] = selected_edge_node_ids - else: - selection_params["selected_edge_indices"] = _serialize_selection_indices( - selected_edges, solid.get_edges() - ) - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - result, - op=_OP_MAKE_FILLET_RSOLID, - params=selection_params, - source_solid=solid, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[solid, *selected_edges], - ) - return _apply_operation_role_tags( - finalized, - op=_OP_MAKE_FILLET_RSOLID, - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - except Exception as e: - _wrap_public_api_error( - operation="fillet_rsolid", - what_happened="Failed to apply the fillet operation.", - possible_causes=[ - "The radius is not a positive finite scalar.", - "No valid edges were selected.", - "The selected edges are incompatible with the requested fillet radius.", - ], - how_to_fix=[ - "Use a positive fillet radius.", - "Select at least one valid edge or use a selector that resolves to edges.", - "If the kernel rejects the fillet, try a smaller radius or a simpler edge set.", - ], - error=e, - ) - - -def chamfer_rsolid( - solid: Solid, - edges: Union[Sequence[Edge], ShapeSelector], - distance: ScalarLike, - *, - result_tag: Optional[str] = None, - generated_faces_tag: Optional[str] = None, -) -> Solid: - """Apply chamfers, with optional tagging of kernel-proven patch faces.""" - try: - assignments = _normalize_operation_role_tags( - _OP_MAKE_CHAMFER_RSOLID, - (("chamfer.patch", generated_faces_tag),), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - distance_value = evaluate_scalar(distance) - if distance_value <= 0: - raise ValueError("倒角距离必须大于0") - - selected_edges = cast(List[Edge], _resolve_selector_or_shapes(solid, edges)) - if not selected_edges: - raise ValueError("倒角操作至少需要一条边") - - tracked = cast( - TrackedResult, - tracked_chamfer(solid, selected_edges, distance_value), - ) - result = cast(Solid, tracked.shape) - - result._metadata = solid._metadata.copy() - - selected_edge_refs = _serialize_shape_refs(selected_edges) - selected_edge_node_ids = _ensure_geo_selection_node_ids(solid, selected_edges) - - selection_params: Dict[str, object] = { - "distance": distance, - "edge_count": len(selected_edges), - "selected_edges": selected_edge_refs, - } - if selected_edge_node_ids: - selection_params["selected_edge_node_ids"] = selected_edge_node_ids - else: - selection_params["selected_edge_indices"] = _serialize_selection_indices( - selected_edges, solid.get_edges() - ) - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - result, - op=_OP_MAKE_CHAMFER_RSOLID, - params=selection_params, - source_solid=solid, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[solid, *selected_edges], - ) - return _apply_operation_role_tags( - finalized, - op=_OP_MAKE_CHAMFER_RSOLID, - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - except Exception as e: - _wrap_public_api_error( - operation="chamfer_rsolid", - what_happened="Failed to apply the chamfer operation.", - possible_causes=[ - "The distance is not a positive finite scalar.", - "No valid edges were selected.", - "The selected edges are incompatible with the requested chamfer size.", - ], - how_to_fix=[ - "Use a positive chamfer distance.", - "Select at least one valid edge or use a selector that resolves to edges.", - "If the kernel rejects the chamfer, try a smaller distance or fewer edges.", - ], - error=e, - ) - - -def shell_rsolid( - solid: Solid, - faces_to_remove: Union[Sequence[Face], ShapeSelector], - thickness: ScalarLike, - *, - result_tag: Optional[str] = None, - body_faces_tag: Optional[str] = None, - offset_faces_tag: Optional[str] = None, - closing_faces_tag: Optional[str] = None, - wall_edges_tag: Optional[str] = None, -) -> Solid: - """Shell a solid, with optional kernel-role-based face tags.""" - try: - assignments = _normalize_operation_role_tags( - _OP_MAKE_SHELL_RSOLID, - ( - ("shell.body_face", body_faces_tag), - ("shell.offset_face", offset_faces_tag), - ("shell.closing_descendant", closing_faces_tag), - ("shell.wall", wall_edges_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - thickness_value = evaluate_scalar(thickness) - if thickness_value <= 0: - raise ValueError("壁厚必须大于0") - - selected_faces = cast( - List[Face], _resolve_selector_or_shapes(solid, faces_to_remove) - ) - if not selected_faces: - raise ValueError("抽壳操作至少需要一个待移除面") - - tracked = cast( - TrackedResult, - tracked_shell(solid, selected_faces, thickness_value), - ) - result = cast(Solid, tracked.shape) - - result._metadata = solid._metadata.copy() - - selected_face_refs = _serialize_shape_refs(selected_faces) - selected_face_node_ids = _ensure_geo_selection_node_ids(solid, selected_faces) - - selection_params: Dict[str, object] = { - "thickness": thickness, - "removed_face_count": len(selected_faces), - "selected_faces": selected_face_refs, - } - if selected_face_node_ids: - selection_params["selected_face_node_ids"] = selected_face_node_ids - else: - selection_params["selected_face_indices"] = _serialize_selection_indices( - selected_faces, solid.get_faces() - ) - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - result, - op=_OP_MAKE_SHELL_RSOLID, - params=selection_params, - source_solid=solid, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[solid, *selected_faces], - ) - return _apply_operation_role_tags( - finalized, - op=_OP_MAKE_SHELL_RSOLID, - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - except Exception as e: - _wrap_public_api_error( - operation="shell_rsolid", - what_happened="Failed to apply the shell operation.", - possible_causes=[ - "The thickness is not a positive finite scalar.", - "No valid faces were selected for removal.", - "The requested shell thickness is incompatible with the current solid.", - ], - how_to_fix=[ - "Use a positive shell thickness.", - "Select at least one valid face to remove.", - "If the shell fails, try a smaller thickness or a different face selection.", - ], - error=e, - ) - - -def loft_rsolid( - profiles: Sequence[Union[Wire, Vertex]], - ruled: bool = False, - *, - tracking_policy: TrackingPolicy | str = TrackingPolicy.FULL, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - start_face_tag: Optional[str] = None, - end_face_tag: Optional[str] = None, - side_faces_tag: Optional[str] = None, -) -> Solid: - """Create a lofted solid, with optional kernel-role-based tags.""" - try: - profile_list = _validated_loft_sections(profiles, operation="loft_rsolid") - if start_face_tag is not None and isinstance(profile_list[0], Vertex): - raise ValueError("start_face_tag requires a Wire start section") - if end_face_tag is not None and isinstance(profile_list[-1], Vertex): - raise ValueError("end_face_tag requires a Wire end section") - policy = ( - TrackingPolicy.GRAPH - if current_tracking_policy() == TrackingPolicy.GRAPH - else TrackingPolicy(tracking_policy) - ) - assignments = _normalize_operation_role_tags( - _OP_MAKE_LOFT_RSOLID, - ( - ("loft.start", start_face_tag), - ("loft.end", end_face_tag), - ("loft.side", side_faces_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - profiles = profile_list - - if policy == TrackingPolicy.GRAPH and (assignments or tag_prefix is not None): - raise ValueError( - "GRAPH tracking does not provide loft face-role evidence; " - "use FULL tracking for tag_prefix, start_face_tag, end_face_tag, " - "or side_faces_tag" - ) - - tracked = ( - cast( - TrackedResult, - tracked_loft(profiles, ruled=ruled), - ) - if policy == TrackingPolicy.FULL - else None - ) - result = ( - cast(Solid, tracked.shape) - if tracked is not None - else Solid( - make_loft_solid((profile.wrapped for profile in profiles), ruled=ruled) - ) - ) - - all_metadata = {} - for profile in profiles: - all_metadata.update(profile._metadata) - - result._metadata = all_metadata - - params: Dict[str, object] = { - "profile_count": len(profiles), - "ruled": ruled, - "tracking_policy": policy.value, - } - if tracked is not None: - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - result, - op=_OP_MAKE_LOFT_RSOLID, - params=params, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=profiles, - ) - else: - target_kinds = {} - finalized = cast( - Solid, - _finalize_derived_shape( - result, - op=_OP_MAKE_LOFT_RSOLID, - params=params, - input_shapes=profiles, - ), - ) - tagged = _apply_operation_role_tags( - finalized, - op=_OP_MAKE_LOFT_RSOLID, - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - if tracked is None: - return tagged - return _apply_feature_tag_prefix( - tagged, - tag_prefix=tag_prefix, - op=_OP_MAKE_LOFT_RSOLID, - delta=tracked.delta, - start_role=("loft.start" if isinstance(profiles[0], Wire) else None), - end_role=("loft.end" if isinstance(profiles[-1], Wire) else None), - side_role="loft.side", - source_shapes=profiles, - ) - except Exception as e: - _wrap_public_api_error( - operation="loft_rsolid", - what_happened="Failed to loft the input profiles into a solid.", - possible_causes=[ - "Fewer than two sections were provided.", - "A Vertex section was used away from the start or end.", - "One or more Wire/Vertex sections are invalid or incompatible.", - "The kernel rejected the loft because the section geometry is inconsistent.", - ], - how_to_fix=[ - "Pass at least two Wire or endpoint Vertex sections.", - "Keep Wire topology compatible across sections.", - "If loft fails, inspect each section individually and simplify its geometry.", - ], - error=e, - ) - - -def sweep_rsolid( - profile: Face, - path: Wire, - is_frenet: bool = False, - *, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - start_face_tag: Optional[str] = None, - end_face_tag: Optional[str] = None, - side_faces_tag: Optional[str] = None, -) -> Solid: - """Create a swept solid, with optional kernel-role-based tags.""" - make_solid = True # 默认创建实体 - try: - assignments = _normalize_operation_role_tags( - _OP_MAKE_SWEEP_RSOLID, - ( - ("sweep.start", start_face_tag), - ("sweep.end", end_face_tag), - ("sweep.side", side_faces_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - tracked = cast( - TrackedResult, - tracked_sweep(profile, path, is_frenet=is_frenet), - ) - result = cast(Solid, tracked.shape) - - result._metadata = {**profile._metadata, **path._metadata} - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - result, - op=_OP_MAKE_SWEEP_RSOLID, - params={"is_frenet": bool(is_frenet)}, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[profile, path], - ) - tagged = _apply_operation_role_tags( - finalized, - op=_OP_MAKE_SWEEP_RSOLID, - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - return _apply_feature_tag_prefix( - tagged, - tag_prefix=tag_prefix, - op=_OP_MAKE_SWEEP_RSOLID, - delta=tracked.delta, - start_role="sweep.start", - end_role="sweep.end", - side_role="sweep.side", - source_shapes=[profile], - ) - except Exception as e: - _wrap_public_api_error( - operation="sweep_rsolid", - what_happened="Failed to sweep the profile along the path.", - possible_causes=[ - "The profile face is invalid.", - "The path wire is invalid or unsuitable for sweep.", - "The kernel rejected the sweep orientation or geometry.", - ], - how_to_fix=[ - "Pass a valid Face profile and a valid Wire path.", - "Check that the path wire is continuous and geometrically reasonable.", - "If sweep fails, simplify the profile or path before retrying.", - ], - error=e, - ) - - -def twisted_sweep_rsolid( - profile: Face, - distance: ScalarLike, - twist_angle: ScalarLike, - axis: Tuple[float, float, float] = (0.0, 0.0, 1.0), - origin: Tuple[float, float, float] = (0.0, 0.0, 0.0), - *, - guide_radius: ScalarLike = 1.0, - tag_prefix: Optional[str] = None, - result_tag: Optional[str] = None, - start_face_tag: Optional[str] = None, - end_face_tag: Optional[str] = None, - side_faces_tag: Optional[str] = None, -) -> Solid: - """Sweep a planar profile along a straight axis with linear rotation. - - ``twist_angle`` is the signed total rotation in degrees. The operation uses - a cylindrical auxiliary spine to define a continuous rotation law, yielding - one continuous side face per profile edge instead of a segmented ruled loft. - """ - try: - if not isinstance(profile, Face): - raise TypeError("profile must be a Face") - distance_value = float(evaluate_scalar(distance)) - twist_value = float(evaluate_scalar(twist_angle)) - guide_radius_value = float(evaluate_scalar(guide_radius)) - if not math.isfinite(distance_value) or distance_value <= 0.0: - raise ValueError("distance must be a finite positive number") - if not math.isfinite(twist_value): - raise ValueError("twist_angle must be finite") - if not math.isfinite(guide_radius_value) or guide_radius_value <= 0.0: - raise ValueError("guide_radius must be a finite positive number") - - axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) - origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) - if len(axis_value) != 3 or len(origin_value) != 3: - raise ValueError("axis and origin must each contain three values") - cs = get_current_cs() - global_axis = cs.transform_vector(np.asarray(axis_value, dtype=float)) - global_origin = cs.transform_point(np.asarray(origin_value, dtype=float)) - axis_norm = float(np.linalg.norm(global_axis)) - if not math.isfinite(axis_norm) or axis_norm <= 1.0e-15: - raise ValueError("axis must be a finite non-zero vector") - global_axis /= axis_norm - resolved_axis = tuple(float(value) for value in global_axis) - resolved_origin = tuple(float(value) for value in global_origin) - - assignments = _normalize_operation_role_tags( - _OP_MAKE_TWISTED_SWEEP_RSOLID, - ( - ("twisted_sweep.start", start_face_tag), - ("twisted_sweep.end", end_face_tag), - ("twisted_sweep.side", side_faces_tag), - ), - ) - normalized_result_tag = ( - normalize_tag(result_tag, strict=True) if result_tag is not None else None - ) - tracked = cast( - TrackedResult, - tracked_twisted_sweep( - profile, - axis=resolved_axis, - origin=resolved_origin, - distance=distance_value, - twist_angle=twist_value, - guide_radius=guide_radius_value, - ), - ) - result = cast(Solid, tracked.shape) - kernel_metadata = result.get_metadata("twisted_sweep.kernel", {}) - result._metadata = profile._metadata.copy() - result.set_metadata("twisted_sweep.kernel", kernel_metadata) - - target_kinds = _validate_operation_output_roles(tracked.delta, assignments) - finalized = _finalize_tracked_solid( - result, - op=_OP_MAKE_TWISTED_SWEEP_RSOLID, - params={ - "axis": axis, - "origin": origin, - "distance": distance, - "twist_angle": twist_angle, - "guide_radius": guide_radius, - }, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[profile], - ) - tagged = _apply_operation_role_tags( - finalized, - op=_OP_MAKE_TWISTED_SWEEP_RSOLID, - assignments=assignments, - target_kinds=target_kinds, - result_tag=normalized_result_tag, - ) - return _apply_feature_tag_prefix( - tagged, - tag_prefix=tag_prefix, - op=_OP_MAKE_TWISTED_SWEEP_RSOLID, - delta=tracked.delta, - start_role="twisted_sweep.start", - end_role="twisted_sweep.end", - side_role="twisted_sweep.side", - source_shapes=[profile], - ) - except Exception as e: - _wrap_public_api_error( - operation="twisted_sweep_rsolid", - what_happened="Failed to sweep the profile with a linear axial rotation.", - possible_causes=[ - "The profile is invalid or contains inner wires.", - "The distance, twist angle, axis, or guide radius is invalid.", - "The requested twist causes self-intersection or kernel failure.", - ], - how_to_fix=[ - "Pass a valid planar Face without inner wires.", - "Use a positive distance and guide radius with a non-zero axis.", - "Reduce the twist angle or simplify the profile.", - ], - error=e, - ) - - -def linear_pattern_rsolidlist( - shape: AnyShape, direction: Tuple[float, float, float], count: int, spacing: float -) -> List[Solid]: - """Create a linear pattern of solids.""" - try: - if count <= 0: - raise ValueError("阵列数量必须大于0") - if spacing <= 0: - raise ValueError("阵列间距必须大于0") - - direction_value = cast(Tuple[float, float, float], evaluate_value(direction)) - direction_array = np.asarray(direction_value, dtype=float) - direction_norm = float(np.linalg.norm(direction_array)) - if direction_norm <= 1e-15 or not np.isfinite(direction_norm): - raise ValueError("阵列方向不能是零向量") - local_direction = direction_array / direction_norm - - if get_active_session() is not None: - rv: List[Solid] = [] - for i in range(count): - offset = local_direction * (spacing * i) - translated_shape = translate_shape( - shape, (float(offset[0]), float(offset[1]), float(offset[2])) - ) - translated_shape._apply_tag("solid.pattern.linear", propagate=False) - geo = dict(translated_shape.get_metadata("geo", {})) - geo["pattern"] = {"type": "linear", "index": i + 1} - translated_shape.set_metadata("geo", geo) - _attach_track_summary(translated_shape, op="linear_pattern") - rv.append(cast(Solid, translated_shape)) - return rv - - shapes = [] - with suspend_graph_recording(): - for i in range(count): - offset = local_direction * (spacing * i) - translated_shape = translate_shape( - shape, (float(offset[0]), float(offset[1]), float(offset[2])) - ) - shapes.append(translated_shape) - - rv = [] - for i, s in enumerate(shapes): - s._apply_tag("solid.pattern.linear", propagate=False) - geo = dict(s.get_metadata("geo", {})) - geo["pattern"] = {"type": "linear", "index": i + 1} - s.set_metadata("geo", geo) - _attach_track_summary(s, op="linear_pattern") - rv.append(s) - - record_operation_if_active( - op="linear_pattern", - params={ - "direction": direction, - "count": count, - "spacing": spacing, - }, - outputs=rv, - input_shapes=[shape], - context=_current_context_metadata(), - ) - - return rv - - except Exception as e: - _wrap_public_api_error( - operation="linear_pattern_rsolidlist", - what_happened="Failed to create the linear pattern.", - possible_causes=[ - "The count is not a positive integer.", - "The spacing is not positive.", - "The direction vector is invalid.", - ], - how_to_fix=[ - "Use count >= 1.", - "Use spacing > 0.", - "Pass a valid finite direction vector.", - ], - error=e, - ) - - -def radial_pattern_rsolidlist( - shape: AnyShape, - center: Tuple[float, float, float], - axis: Tuple[float, float, float], - count: int, - total_rotation_angle: float, -) -> List[Solid]: - """Create a radial pattern of solids.""" - try: - if count <= 0: - raise ValueError("阵列数量必须大于0") - if total_rotation_angle <= 0: - raise ValueError("角度必须大于0") - - shapes = [] - angle_step = total_rotation_angle / count # 修正角度计算,均匀分布 - - if get_active_session() is not None: - rv: List[Solid] = [] - for i in range(count): - rotation_angle = angle_step * i - rotated_shape = ( - cast(Solid, translate_shape(shape, (0.0, 0.0, 0.0))) - if i == 0 - else cast(Solid, rotate_shape(shape, rotation_angle, axis, center)) - ) - rotated_shape._apply_tag("solid.pattern.radial", propagate=False) - geo = dict(rotated_shape.get_metadata("geo", {})) - geo["pattern"] = {"type": "radial", "index": i + 1} - rotated_shape.set_metadata("geo", geo) - _attach_track_summary(rotated_shape, op="radial_pattern") - rv.append(cast(Solid, rotated_shape)) - return rv - - with suspend_graph_recording(): - for i in range(count): - rotation_angle = angle_step * i - rotated_shape = rotate_shape(shape, rotation_angle, axis, center) - shapes.append(rotated_shape) - - rv = [] - for i, s in enumerate(shapes): - s._apply_tag("solid.pattern.radial", propagate=False) - geo = dict(s.get_metadata("geo", {})) - geo["pattern"] = {"type": "radial", "index": i + 1} - s.set_metadata("geo", geo) - _attach_track_summary(s, op="radial_pattern") - rv.append(s) - - record_operation_if_active( - op="radial_pattern", - params={ - "center": center, - "axis": axis, - "count": count, - "total_rotation_angle": total_rotation_angle, - }, - outputs=rv, - input_shapes=[shape], - context=_current_context_metadata(), - ) - - return rv - except Exception as e: - _wrap_public_api_error( - operation="radial_pattern_rsolidlist", - what_happened="Failed to create the radial pattern.", - possible_causes=[ - "The count is not a positive integer.", - "The total rotation angle is not positive.", - "The center or axis is invalid.", - ], - how_to_fix=[ - "Use count >= 1.", - "Use a total rotation angle greater than zero.", - "Pass a valid center point and a non-zero axis vector.", - ], - error=e, - ) - - -def mirror_shape( - shape: AnyShape, - plane_origin: Tuple[float, float, float], - plane_normal: Tuple[float, float, float], -) -> AnyShape: - """Mirror a shape across a plane.""" - try: - cs = get_current_cs() - plane_origin_value = cast( - Tuple[float, float, float], evaluate_value(plane_origin) - ) - plane_normal_value = cast( - Tuple[float, float, float], evaluate_value(plane_normal) - ) - global_origin = cs.transform_point(np.array(plane_origin_value)) - global_normal = cs.transform_vector(np.array(plane_normal_value)) - - # 确保法向量不是零向量 - if np.linalg.norm(global_normal) < 1e-10: - raise ValueError("镜像平面法向量不能是零向量") - - if isinstance(shape, Solid): - resolved_origin = tuple(float(value) for value in global_origin) - resolved_normal = tuple(float(value) for value in global_normal) - tracked = cast( - TrackedResult, - tracked_mirror( - shape, - resolved_origin, - resolved_normal, - ), - ) - new_shape = cast(Solid, tracked.shape) - new_shape._metadata = shape._metadata.copy() - _attach_lineage_from_source( - shape, - new_shape, - derivation="continuation", - op=_OP_MAKE_MIRROR_RSHAPE, - ) - new_shape._apply_tag("solid.transform.mirrored", propagate=False) - return _finalize_tracked_solid( - new_shape, - op=_OP_MAKE_MIRROR_RSHAPE, - params={ - "plane_origin": plane_origin, - "plane_normal": plane_normal, - }, - source_solid=shape, - delta=tracked.delta, - delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), - input_shapes=[shape], - ) - - else: - new_shape = mirror_shape_ocp( - shape, - ( - float(global_origin[0]), - float(global_origin[1]), - float(global_origin[2]), - ), - ( - float(global_normal[0]), - float(global_normal[1]), - float(global_normal[2]), - ), - ) - - new_shape._metadata = shape._metadata.copy() - _attach_lineage_from_source( - shape, - new_shape, - derivation="continuation", - op=_OP_MAKE_MIRROR_RSHAPE, - ) - new_shape._apply_tag("solid.transform.mirrored", propagate=False) - - _attach_track_summary(new_shape, op=_OP_MAKE_MIRROR_RSHAPE) - record_operation_if_active( - op=_OP_MAKE_MIRROR_RSHAPE, - params={ - "plane_origin": plane_origin, - "plane_normal": plane_normal, - }, - outputs=new_shape, - input_shapes=[shape], - context=_current_context_metadata(), - ) - - return new_shape - except Exception as e: - _wrap_public_api_error( - operation="mirror_shape", - what_happened="Failed to mirror the shape across the plane.", - possible_causes=[ - "The plane origin or plane normal is invalid.", - "The plane normal is zero-length.", - "The kernel rejected the mirror transform.", - ], - how_to_fix=[ - "Pass a valid plane origin and a non-zero plane normal.", - "Validate the shape before mirroring.", - "If the plane is computed dynamically, inspect the evaluated values first.", - ], - error=e, - ) - - -def helical_sweep_rsolid( - profile: Wire, - pitch: float, - height: float, - radius: float, - center: Tuple[float, float, float] = (0, 0, 0), - dir: Tuple[float, float, float] = (0, 0, 1), -) -> Solid: - """Create a solid by sweeping a profile along a helical path.""" - try: - if get_active_session() is not None: - helix = make_helix_rwire(pitch, height, radius, center=center, dir=dir) - return sweep_rsolid( - make_face_from_wire_rface(profile), helix, is_frenet=True - ) - - if pitch <= 0: - raise ValueError("螺距必须大于0") - if height <= 0: - raise ValueError("高度必须大于0") - if radius <= 0: - raise ValueError("半径必须大于0") - - cs = get_current_cs() - global_center = cs.transform_point(np.array(center)) - global_dir = cs.transform_vector(np.array(dir)) - global_x_direction = cs.transform_vector(_default_plane_x_direction(dir)) - - result_shape = make_helical_sweep_solid( - profile.wrapped, - pitch, - height, - radius, - global_center, - global_dir, - x_direction=global_x_direction, - ) - result = Solid(result_shape) - - result._metadata = profile._metadata.copy() - result._apply_tag("solid.feature.helical_sweep", propagate=False) - - return result - except Exception as e: - _wrap_public_api_error( - operation="helical_sweep_rsolid", - what_happened="Failed to create the helical sweep solid.", - possible_causes=[ - "Pitch, height, or radius is not positive.", - "The input profile wire is invalid or cannot form a face.", - "The center or direction vector is invalid.", - "The underlying helix or sweep construction failed.", - ], - how_to_fix=[ - "Use positive pitch, height, and radius values.", - "Pass a valid profile wire that can be turned into a face.", - "Validate the center and direction inputs before retrying.", - "If the sweep still fails, try the explicit macro path: helix wire -> face from profile -> sweep.", - ], - error=e, - ) +_sys.modules[__name__].__class__ = _OperationsFacade diff --git a/src/simplecadapi/scene/compiler.py b/src/simplecadapi/scene/compiler.py index 322f8fe8..06c84cc7 100644 --- a/src/simplecadapi/scene/compiler.py +++ b/src/simplecadapi/scene/compiler.py @@ -37,8 +37,8 @@ from OCP.TopAbs import ( from ..core import Compound, Edge, Face, Solid, Vertex from ..kernel.ocp_properties import center_of_mass -from ..assembly import Assembly -from ..connector import Connector, resolve_connector_placement +from ..assembly import Assembly, PublicConnectorRef +from ..connector import Connector, resolve_connector_placement, resolve_item_connector_placement from ..material import Material from ..part import Part from ..placement import Placement, identity_placement @@ -313,7 +313,7 @@ class _PendingConnector: owner_kind: str owner_definition_id: str owner: Part | Assembly - connector: Connector + connector: Connector | PublicConnectorRef def _compile_root(root: SceneRoot, *, source: SceneSource, options: SceneCompileOptions, definitions: dict[str, dict[str, Any]], nodes: list[dict[str, Any]], products: dict[str, dict[str, Any]], renderables: dict[str, _Renderable], appearances: dict[str, dict[str, Any]], pending_connectors: list[_PendingConnector]) -> None: @@ -641,12 +641,15 @@ def _appearance(material: Material | None, root_id: str, appearances: dict[str, def _pending_connectors(root_id: str, owner_kind: str, owner: Part | Assembly, definition_id: str) -> list[_PendingConnector]: + connectors: Sequence[Connector | PublicConnectorRef] + if isinstance(owner, Part): + connectors = owner.connectors + else: + connectors = owner.public_connectors return [ _PendingConnector(root_id, owner_kind, definition_id, owner, connector) - for connector in owner.connectors + for connector in connectors ] - - def _finalize_connectors( pending: Sequence[_PendingConnector], *, @@ -668,18 +671,36 @@ def _finalize_connectors( if snapshot_id in snapshots: return snapshots[snapshot_id] if snapshot_id in resolving: - raise ValueError(f"cyclic forwarded connector source: {snapshot_id}") + raise ValueError(f"cyclic public connector source: {snapshot_id}") item = pending_by_id.get(snapshot_id) if item is None: - raise ValueError(f"forwarded connector source is not compiled: {snapshot_id}") + raise ValueError(f"public connector source is not compiled: {snapshot_id}") resolving.add(snapshot_id) connector = item.connector - definition = definitions[item.owner_definition_id] - if item.owner_kind == "part" and connector.anchor_kind == "forwarded": - raise ValueError("forwarded connectors cannot be owned by Parts") - if item.owner_kind == "assembly" and connector.anchor_kind == "geometry": - raise ValueError("assembly geometry connectors are not supported") - if connector.anchor_kind == "geometry": + if isinstance(connector, PublicConnectorRef): + if item.owner_kind != "assembly" or not isinstance(item.owner, Assembly): + raise ValueError("public connectors require an Assembly owner") + component = item.owner.get_component(connector.component_id) + source_snapshot_id = _source_connector_snapshot_id( + item.root_id, component.item, connector.connector_id + ) + finalize(source_snapshot_id) + payload = { + "connector_snapshot_id": snapshot_id, + "owner_definition_id": item.owner_definition_id, + "connector_id": connector.public_connector_id, + "name": connector.name, + "anchor_kind": "public", + "local_transform": component.placement.compose( + resolve_item_connector_placement( + component.item, connector.connector_id + ) + ).to_dict(), + "source_connector_snapshot_id": source_snapshot_id, + "source": _connector_source(source, item.owner, connector), + "sdk_metadata": {}, + } + elif connector.anchor_kind == "geometry": if not isinstance(item.owner, Part): raise ValueError("geometry connectors require a Part owner") target = _resolve_connector_target(item.owner.body, connector) @@ -698,10 +719,11 @@ def _finalize_connectors( "anchor_kind": "geometry", "local_transform": resolve_connector_placement(connector).to_dict(), "target": {"entity_asset_id": entity_asset_id, "entity_id": entity_id}, + "source_connector_snapshot_id": None, "source": _connector_source(source, item.owner, connector), "sdk_metadata": {}, } - elif connector.anchor_kind == "placement": + else: payload = { "connector_snapshot_id": snapshot_id, "owner_definition_id": item.owner_definition_id, @@ -709,40 +731,7 @@ def _finalize_connectors( "name": connector.name, "anchor_kind": "placement", "local_transform": resolve_connector_placement(connector).to_dict(), - "source": _connector_source(source, item.owner, connector), - "sdk_metadata": {}, - } - else: - if not isinstance(item.owner, Assembly): - raise ValueError("forwarded connectors require an Assembly owner") - anchor = connector.anchor - assert anchor is not None - source_component_id = anchor.source_component_id - source_connector_id = anchor.source_connector_id - assert source_component_id is not None and source_connector_id is not None - component = item.owner.get_component(source_component_id) - source_item = component.item - source_kind = "assembly" if isinstance(source_item, Assembly) else "part" - source_semantic_id = source_item.assembly_id if isinstance(source_item, Assembly) else source_item.part_id - source_snapshot_id = ( - f"connector/{item.root_id}/{source_kind}/{_encode(source_semantic_id)}/" - f"{_encode(source_connector_id)}" - ) - finalize(source_snapshot_id) - payload = { - "connector_snapshot_id": snapshot_id, - "owner_definition_id": item.owner_definition_id, - "connector_id": connector.connector_id, - "name": connector.name, - "anchor_kind": "forwarded", - "local_transform": resolve_connector_placement(connector, owner_assembly=item.owner).to_dict(), - "forwarded_from": { - "source_component_id": source_component_id, - "source_definition_id": pending_by_id[source_snapshot_id].owner_definition_id, - "source_connector_id": source_connector_id, - "source_connector_snapshot_id": source_snapshot_id, - "offset": anchor.offset.to_dict() if anchor.offset is not None else None, - }, + "source_connector_snapshot_id": None, "source": _connector_source(source, item.owner, connector), "sdk_metadata": {}, } @@ -752,21 +741,40 @@ def _finalize_connectors( for snapshot_id in sorted(pending_by_id, key=lambda value: value.encode("utf-8")): finalize(snapshot_id) - return sorted(snapshots.values(), key=lambda item: item["connector_snapshot_id"].encode("utf-8")) + return sorted( + snapshots.values(), + key=lambda item: item["connector_snapshot_id"].encode("utf-8"), + ) def _connector_snapshot_id(item: _PendingConnector) -> str: semantic_id = item.owner.assembly_id if isinstance(item.owner, Assembly) else item.owner.part_id + connector_id = ( + item.connector.public_connector_id + if isinstance(item.connector, PublicConnectorRef) + else item.connector.connector_id + ) return ( f"connector/{item.root_id}/{item.owner_kind}/" - f"{_encode(semantic_id)}/{_encode(item.connector.connector_id)}" + f"{_encode(semantic_id)}/{_encode(connector_id)}" + ) + + +def _source_connector_snapshot_id( + root_id: str, item: Part | Assembly, connector_id: str +) -> str: + owner_kind = "assembly" if isinstance(item, Assembly) else "part" + semantic_id = item.assembly_id if isinstance(item, Assembly) else item.part_id + return ( + f"connector/{root_id}/{owner_kind}/" + f"{_encode(semantic_id)}/{_encode(connector_id)}" ) def _connector_source( source: SceneSource, owner: Part | Assembly, - connector: Connector, + connector: Connector | PublicConnectorRef, ) -> dict[str, Any] | None: if source.kind == "manual": if not source.source_id: @@ -805,22 +813,24 @@ def _connector_producer( graph: OperationGraph, owner_node_id: str, owner: Part | Assembly, - connector: Connector, + connector: Connector | PublicConnectorRef, ) -> OperationNode: if isinstance(owner, Part): expected_op = "make_add_connector_rpart" semantic_type = "Part" semantic_id = owner.part_id semantic_id_param = "part_id" + connector_param = "connector_id" + connector_id = connector.connector_id + expected_record = {"connector": connector.to_dict()} else: - expected_op = ( - "make_forward_connector_rassembly" - if connector.anchor_kind == "forwarded" - else "make_add_connector_rassembly" - ) + expected_op = "make_set_public_connector_rassembly" semantic_type = "Assembly" semantic_id = owner.assembly_id semantic_id_param = "assembly_id" + connector_param = "public_connector_id" + connector_id = connector.public_connector_id + expected_record = {"public_connector": connector.to_dict()} matches: list[OperationNode] = [] visited: set[str] = set() @@ -828,9 +838,7 @@ def _connector_producer( while node is not None and node.node_id not in visited: visited.add(node.node_id) delta = node.semantic_delta - connector_record = ( - delta.metadata.get("connector") if delta is not None else None - ) + connector_record = delta.metadata if delta is not None else None modifies_owner = delta is not None and any( ref.entity_type == semantic_type and ref.entity_id == semantic_id for ref in delta.modified @@ -838,9 +846,9 @@ def _connector_producer( if ( node.op == expected_op and node.params.get(semantic_id_param) == semantic_id - and node.params.get("connector_id") == connector.connector_id + and node.params.get(connector_param) == connector_id and modifies_owner - and connector_record == connector.to_dict() + and connector_record == expected_record ): matches.append(node) if not node.inputs: @@ -850,11 +858,13 @@ def _connector_producer( if len(matches) != 1: raise ValueError( "connector source is not uniquely proven by the owner product lineage: " - f"{semantic_type} {semantic_id!r} connector {connector.connector_id!r}" + f"{semantic_type} {semantic_id!r} connector {connector_id!r}" ) return matches[0] + + def _resolve_connector_target(solid: Solid, connector: Connector) -> Face | Edge | Vertex: geometry_ref = connector.geometry_ref if geometry_ref is None: @@ -918,7 +928,7 @@ def _normalized_part(part: Part) -> dict[str, Any]: def _normalized_assembly(assembly: Assembly, root_id: str) -> dict[str, Any]: - return {"kind": "assembly", "assembly_id": assembly.assembly_id, "name": assembly.name, "components": [{"component_id": component.component_id, "name": component.name, "definition_ref": f"definition/{root_id}/" + ("assembly/" if isinstance(component.item, Assembly) else "part/") + _encode(component.item.assembly_id if isinstance(component.item, Assembly) else component.item.part_id), "local_placement": component.placement.to_dict()} for component in assembly.components], "connectors": [connector.to_dict() for connector in assembly.connectors], "constraints": [constraint.to_dict() for constraint in assembly.constraints], "grounded_component_ids": sorted(assembly.grounded_component_ids, key=lambda item: item.encode("utf-8")), "metadata": _metadata(assembly)} + return {"kind": "assembly", "assembly_id": assembly.assembly_id, "name": assembly.name, "components": [{"component_id": component.component_id, "name": component.name, "definition_ref": f"definition/{root_id}/" + ("assembly/" if isinstance(component.item, Assembly) else "part/") + _encode(component.item.assembly_id if isinstance(component.item, Assembly) else component.item.part_id), "local_placement": component.placement.to_dict()} for component in assembly.components], "public_connectors": [connector.to_dict() for connector in assembly.public_connectors], "constraints": [constraint.to_dict() for constraint in assembly.constraints], "grounded_component_ids": sorted(assembly.grounded_component_ids, key=lambda item: item.encode("utf-8")), "metadata": _metadata(assembly)} def _compound_solid(compound: Compound) -> Solid: diff --git a/src/simplecadapi/scene/contracts/profiles/scene-1.0-ocp-glb-2.profile.json b/src/simplecadapi/scene/contracts/profiles/scene-1.0-ocp-glb-2.profile.json index bb54064c..2a475c1f 100644 --- a/src/simplecadapi/scene/contracts/profiles/scene-1.0-ocp-glb-2.profile.json +++ b/src/simplecadapi/scene/contracts/profiles/scene-1.0-ocp-glb-2.profile.json @@ -168,10 +168,9 @@ "schema_uri": "schemas/normalized-product-1.schema.json", "serialization": "RFC8785_JCS_UTF8", "part_fields": ["body_source", "connectors", "kind", "material", "metadata", "name", "part_id"], - "assembly_fields": ["assembly_id", "components", "connectors", "constraints", "grounded_component_ids", "kind", "metadata", "name"], + "assembly_fields": ["assembly_id", "components", "constraints", "grounded_component_ids", "kind", "metadata", "name", "public_connectors"], "component_fields": ["component_id", "definition_ref", "local_placement", "name"], - "declaration_order_arrays": ["assembly.components", "assembly.connectors", "assembly.constraints", "part.connectors"], - "set_like_arrays": {"assembly.grounded_component_ids": "unsigned_utf8"}, + "declaration_order_arrays": ["assembly.components", "assembly.public_connectors", "assembly.constraints", "part.connectors"], "material": "complete_normalized_JSON_safe_record", "metadata": "evaluated_profile_metadata_projection", "connector_runtime_metadata": "forbidden", diff --git a/src/simplecadapi/scene/contracts/rules/scene-1.0-rules.json b/src/simplecadapi/scene/contracts/rules/scene-1.0-rules.json index 6b66c182..0220bd28 100644 --- a/src/simplecadapi/scene/contracts/rules/scene-1.0-rules.json +++ b/src/simplecadapi/scene/contracts/rules/scene-1.0-rules.json @@ -11,7 +11,7 @@ {"artifacts": ["entities", "package"], "id": "analytic_geometry_invalid", "phase": "semantic", "pointer_policy": "nearest_record", "precedence": 0, "summary": "Analytic axes and direction vectors must be finite, normalized, and mutually orthogonal where required."}, {"artifacts": ["scene", "entities", "presentation", "connector_binding", "normalized_product", "package"], "id": "array_order_invalid", "phase": "semantic", "pointer_policy": "exact", "precedence": 1, "summary": "Set-like arrays must use the registered unsigned UTF-8 ordering."}, {"artifacts": ["scene", "entities", "presentation", "normalized_product", "package"], "id": "bounds_invalid", "phase": "semantic", "pointer_policy": "nearest_record", "precedence": 2, "summary": "Bounds and contained points must satisfy the numeric profile."}, - {"artifacts": ["scene", "entities", "connector_binding", "package"], "id": "connector_invalid", "phase": "semantic", "pointer_policy": "nearest_record", "precedence": 3, "summary": "Connector owner, source, target, forwarding, and frame rules must hold."}, + {"artifacts": ["scene", "entities", "connector_binding", "package"], "id": "connector_invalid", "phase": "semantic", "pointer_policy": "nearest_record", "precedence": 3, "summary": "Connector owner, public source, target, and frame rules must hold."}, {"artifacts": ["entities", "package"], "id": "entity_range_invalid", "phase": "semantic", "pointer_policy": "nearest_record", "precedence": 4, "summary": "Face and rendered-edge ranges must form exact positive partitions."}, {"artifacts": ["entities", "package"], "id": "entity_topology_invalid", "phase": "semantic", "pointer_policy": "nearest_record", "precedence": 5, "summary": "Entity ownership, cardinality, and reciprocal adjacency must be valid."}, {"artifacts": ["scene", "package"], "id": "hierarchy_invalid", "phase": "semantic", "pointer_policy": "nearest_record", "precedence": 6, "summary": "Scene hierarchy must be acyclic, rooted, and continuously ordered."}, diff --git a/src/simplecadapi/scene/contracts/schemas/normalized-product-1.schema.json b/src/simplecadapi/scene/contracts/schemas/normalized-product-1.schema.json index d9fcce32..857e6280 100644 --- a/src/simplecadapi/scene/contracts/schemas/normalized-product-1.schema.json +++ b/src/simplecadapi/scene/contracts/schemas/normalized-product-1.schema.json @@ -19,63 +19,38 @@ }}, "bodySource": {"oneOf": [{"$ref": "#/$defs/modelBodySource"}, {"$ref": "#/$defs/manualBodySource"}]}, "material": {"type": "object", "additionalProperties": false, "required": ["material_id", "name", "density", "density_unit", "color", "metadata"], "properties": { - "material_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, - "density": {"type": ["number", "null"]}, "density_unit": {"type": ["string", "null"]}, - "color": {"oneOf": [{"type": "null"}, {"type": "array", "prefixItems": [ - {"type": "number", "minimum": 0, "maximum": 1}, {"type": "number", "minimum": 0, "maximum": 1}, {"type": "number", "minimum": 0, "maximum": 1} - ], "minItems": 3, "maxItems": 3}]}, "metadata": {"type": "object"} + "material_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, "density": {"type": ["number", "null"]}, "density_unit": {"type": ["string", "null"]}, + "color": {"oneOf": [{"type": "null"}, {"type": "array", "prefixItems": [{"type": "number", "minimum": 0, "maximum": 1}, {"type": "number", "minimum": 0, "maximum": 1}, {"type": "number", "minimum": 0, "maximum": 1}], "minItems": 3, "maxItems": 3}]}, "metadata": {"type": "object"} }}, "geometryRef": {"type": "object", "additionalProperties": false, "required": ["kind", "source_node_id", "geo_selector", "flip"], "properties": { "kind": {"enum": ["face", "edge", "vertex"]}, "source_node_id": {"type": ["string", "null"]}, "geo_selector": {"type": "object"}, "flip": {"type": "boolean"} }}, - "geometryAnchor": {"type": "object", "additionalProperties": false, "required": ["anchor_kind", "geometry_ref"], "properties": { - "anchor_kind": {"const": "geometry"}, "geometry_ref": {"$ref": "#/$defs/geometryRef"} - }}, - "placementAnchor": {"type": "object", "additionalProperties": false, "required": ["anchor_kind", "placement"], "properties": { - "anchor_kind": {"const": "placement"}, "placement": {"$ref": "#/$defs/transform"} - }}, - "forwardedAnchor": {"type": "object", "additionalProperties": false, "required": ["anchor_kind", "source_component_id", "source_connector_id", "offset"], "properties": { - "anchor_kind": {"const": "forwarded"}, "source_component_id": {"$ref": "#/$defs/productId"}, "source_connector_id": {"$ref": "#/$defs/productId"}, - "offset": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/transform"}]} + "geometryAnchor": {"type": "object", "additionalProperties": false, "required": ["anchor_kind", "geometry_ref"], "properties": {"anchor_kind": {"const": "geometry"}, "geometry_ref": {"$ref": "#/$defs/geometryRef"}}}, + "placementAnchor": {"type": "object", "additionalProperties": false, "required": ["anchor_kind", "placement"], "properties": {"anchor_kind": {"const": "placement"}, "placement": {"$ref": "#/$defs/transform"}}}, + "publicConnector": {"type": "object", "additionalProperties": false, "required": ["public_connector_id", "component_id", "connector_id", "name"], "properties": { + "public_connector_id": {"$ref": "#/$defs/productId"}, "component_id": {"$ref": "#/$defs/productId"}, "connector_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]} }}, "connector": {"type": "object", "additionalProperties": false, "required": ["connector_id", "name", "anchor"], "properties": { - "connector_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, - "anchor": {"oneOf": [{"$ref": "#/$defs/geometryAnchor"}, {"$ref": "#/$defs/placementAnchor"}, {"$ref": "#/$defs/forwardedAnchor"}]}, - "geometry_ref": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/geometryRef"}]} + "connector_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, "anchor": {"oneOf": [{"$ref": "#/$defs/geometryAnchor"}, {"$ref": "#/$defs/placementAnchor"}]}, "geometry_ref": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/geometryRef"}]} }, "allOf": [ {"if": {"properties": {"anchor": {"properties": {"anchor_kind": {"const": "geometry"}}, "required": ["anchor_kind"]}}, "required": ["anchor"]}, "then": {"required": ["geometry_ref"]}}, - {"if": {"properties": {"anchor": {"properties": {"anchor_kind": {"enum": ["placement", "forwarded"]}}, "required": ["anchor_kind"]}}, "required": ["anchor"]}, "then": {"not": {"required": ["geometry_ref"]}}} + {"if": {"properties": {"anchor": {"properties": {"anchor_kind": {"const": "placement"}}, "required": ["anchor_kind"]}}, "required": ["anchor"]}, "then": {"not": {"required": ["geometry_ref"]}}} ]}, "component": {"type": "object", "additionalProperties": false, "required": ["component_id", "name", "definition_ref", "local_placement"], "properties": { "component_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, "definition_ref": {"$ref": "#/$defs/structuralId"}, "local_placement": {"$ref": "#/$defs/transform"} }}, - "connectorRef": {"type": "object", "additionalProperties": false, "required": ["component_id", "connector_id"], "properties": { - "component_id": {"$ref": "#/$defs/productId"}, "connector_id": {"$ref": "#/$defs/productId"} - }}, - "limit": {"type": "object", "additionalProperties": false, "required": ["lower_value", "upper_value"], "properties": { - "lower_value": {"type": "number"}, "upper_value": {"type": "number"} - }}, - "constraint": {"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/productId"}, "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/limit"}]}, - "drive_angle_degrees": {"type": ["number", "null"]}, "angle_limit": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/limit"}]}, - "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"]} + "connectorRef": {"type": "object", "additionalProperties": false, "required": ["component_id", "connector_id"], "properties": {"component_id": {"$ref": "#/$defs/productId"}, "connector_id": {"$ref": "#/$defs/productId"}}}, + "limit": {"type": "object", "additionalProperties": false, "required": ["lower_value", "upper_value"], "properties": {"lower_value": {"type": "number"}, "upper_value": {"type": "number"}}}, + "constraint": {"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/productId"}, "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/limit"}]}, "drive_angle_degrees": {"type": ["number", "null"]}, "angle_limit": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/limit"}]}, + "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"]} }}, "part": {"type": "object", "additionalProperties": false, "required": ["kind", "part_id", "body_source", "name", "material", "connectors", "metadata"], "properties": { - "kind": {"const": "part"}, "part_id": {"$ref": "#/$defs/productId"}, "body_source": {"$ref": "#/$defs/bodySource"}, "name": {"type": ["string", "null"]}, - "material": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/material"}]}, "connectors": {"type": "array", "items": {"$ref": "#/$defs/connector"}}, "metadata": {"type": "object"} + "kind": {"const": "part"}, "part_id": {"$ref": "#/$defs/productId"}, "body_source": {"$ref": "#/$defs/bodySource"}, "name": {"type": ["string", "null"]}, "material": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/material"}]}, "connectors": {"type": "array", "items": {"$ref": "#/$defs/connector"}}, "metadata": {"type": "object"} }}, - "assembly": {"type": "object", "additionalProperties": false, "required": ["kind", "assembly_id", "name", "components", "connectors", "constraints", "grounded_component_ids", "metadata"], "properties": { - "kind": {"const": "assembly"}, "assembly_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, - "components": {"type": "array", "items": {"$ref": "#/$defs/component"}}, "connectors": {"type": "array", "items": {"$ref": "#/$defs/connector"}}, - "constraints": {"type": "array", "items": {"$ref": "#/$defs/constraint"}}, "grounded_component_ids": {"type": "array", "items": {"$ref": "#/$defs/productId"}, "uniqueItems": true}, - "metadata": {"type": "object"} + "assembly": {"type": "object", "additionalProperties": false, "required": ["kind", "assembly_id", "name", "components", "public_connectors", "constraints", "grounded_component_ids", "metadata"], "properties": { + "kind": {"const": "assembly"}, "assembly_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, "components": {"type": "array", "items": {"$ref": "#/$defs/component"}}, "public_connectors": {"type": "array", "items": {"$ref": "#/$defs/publicConnector"}}, "constraints": {"type": "array", "items": {"$ref": "#/$defs/constraint"}}, "grounded_component_ids": {"type": "array", "items": {"$ref": "#/$defs/productId"}, "uniqueItems": true}, "metadata": {"type": "object"} }} } } diff --git a/src/simplecadapi/scene/contracts/schemas/render-profile-2.schema.json b/src/simplecadapi/scene/contracts/schemas/render-profile-2.schema.json index 472ac485..f57a2ac9 100644 --- a/src/simplecadapi/scene/contracts/schemas/render-profile-2.schema.json +++ b/src/simplecadapi/scene/contracts/schemas/render-profile-2.schema.json @@ -172,10 +172,9 @@ "schema_uri": "schemas/normalized-product-1.schema.json", "serialization": "RFC8785_JCS_UTF8", "part_fields": ["body_source", "connectors", "kind", "material", "metadata", "name", "part_id"], - "assembly_fields": ["assembly_id", "components", "connectors", "constraints", "grounded_component_ids", "kind", "metadata", "name"], + "assembly_fields": ["assembly_id", "components", "constraints", "grounded_component_ids", "kind", "metadata", "name", "public_connectors"], "component_fields": ["component_id", "definition_ref", "local_placement", "name"], - "declaration_order_arrays": ["assembly.components", "assembly.connectors", "assembly.constraints", "part.connectors"], - "set_like_arrays": {"assembly.grounded_component_ids": "unsigned_utf8"}, + "declaration_order_arrays": ["assembly.components", "assembly.public_connectors", "assembly.constraints", "part.connectors"], "material": "complete_normalized_JSON_safe_record", "metadata": "evaluated_profile_metadata_projection", "connector_runtime_metadata": "forbidden", diff --git a/src/simplecadapi/scene/contracts/schemas/scene-1.0.schema.json b/src/simplecadapi/scene/contracts/schemas/scene-1.0.schema.json index a291a0af..0dd9a041 100644 --- a/src/simplecadapi/scene/contracts/schemas/scene-1.0.schema.json +++ b/src/simplecadapi/scene/contracts/schemas/scene-1.0.schema.json @@ -369,29 +369,20 @@ "type": "object", "additionalProperties": false, "required": ["entity_asset_id", "entity_id"], "properties": {"entity_asset_id": {"$ref": "#/$defs/hash"}, "entity_id": {"type": "string", "pattern": "^entity/(face|edge|vertex)/(0|[1-9][0-9]*)$"}} }, - "forwardedFrom": { - "type": "object", "additionalProperties": false, - "required": ["source_component_id", "source_definition_id", "source_connector_id", "source_connector_snapshot_id", "offset"], - "properties": { - "source_component_id": {"$ref": "#/$defs/productId"}, "source_definition_id": {"$ref": "#/$defs/structuralId"}, - "source_connector_id": {"$ref": "#/$defs/productId"}, "source_connector_snapshot_id": {"$ref": "#/$defs/structuralId"}, - "offset": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/transform"}]} - } - }, "connector": { "type": "object", "additionalProperties": false, - "required": ["connector_snapshot_id", "owner_definition_id", "connector_id", "name", "anchor_kind", "local_transform", "source", "sdk_metadata"], + "required": ["connector_snapshot_id", "owner_definition_id", "connector_id", "name", "anchor_kind", "local_transform", "source_connector_snapshot_id", "source", "sdk_metadata"], "properties": { "connector_snapshot_id": {"$ref": "#/$defs/structuralId"}, "owner_definition_id": {"$ref": "#/$defs/structuralId"}, - "connector_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, "anchor_kind": {"enum": ["geometry", "placement", "forwarded"]}, - "local_transform": {"$ref": "#/$defs/transform"}, "target": {"$ref": "#/$defs/connectorTarget"}, "forwarded_from": {"$ref": "#/$defs/forwardedFrom"}, + "connector_id": {"$ref": "#/$defs/productId"}, "name": {"type": ["string", "null"]}, "anchor_kind": {"enum": ["geometry", "placement", "public"]}, + "local_transform": {"$ref": "#/$defs/transform"}, "target": {"$ref": "#/$defs/connectorTarget"}, "source_connector_snapshot_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/structuralId"}]}, "source": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/modelOperationSource"}, {"$ref": "#/$defs/manualConnectorSource"}, {"$ref": "#/$defs/productPackageConnectorSource"}]}, "sdk_metadata": {"type": "object", "maxProperties": 0} }, "allOf": [ - {"if": {"properties": {"anchor_kind": {"const": "geometry"}}, "required": ["anchor_kind"]}, "then": {"required": ["target"], "not": {"required": ["forwarded_from"]}}}, - {"if": {"properties": {"anchor_kind": {"const": "placement"}}, "required": ["anchor_kind"]}, "then": {"not": {"anyOf": [{"required": ["target"]}, {"required": ["forwarded_from"]}]}}}, - {"if": {"properties": {"anchor_kind": {"const": "forwarded"}}, "required": ["anchor_kind"]}, "then": {"required": ["forwarded_from"], "not": {"required": ["target"]}}} + {"if": {"properties": {"anchor_kind": {"const": "geometry"}}, "required": ["anchor_kind"]}, "then": {"required": ["target"], "properties": {"source_connector_snapshot_id": {"type": "null"}}}}, + {"if": {"properties": {"anchor_kind": {"const": "placement"}}, "required": ["anchor_kind"]}, "then": {"not": {"required": ["target"]}, "properties": {"source_connector_snapshot_id": {"type": "null"}}}}, + {"if": {"properties": {"anchor_kind": {"const": "public"}}, "required": ["anchor_kind"]}, "then": {"required": ["source_connector_snapshot_id"], "not": {"required": ["target"]}}} ] }, "cameraBase": { diff --git a/src/simplecadapi/scene/contracts/schemas/scene-2.0.schema.json b/src/simplecadapi/scene/contracts/schemas/scene-2.0.schema.json index d22e2c91..f6c022ab 100644 --- a/src/simplecadapi/scene/contracts/schemas/scene-2.0.schema.json +++ b/src/simplecadapi/scene/contracts/schemas/scene-2.0.schema.json @@ -39,7 +39,7 @@ "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"}]}}}, + "connector": {"type": "object", "additionalProperties": false, "required": ["connector_snapshot_id", "node_id", "definition_id", "definition_kind", "connector_id", "name", "anchor_kind", "local_frame", "binding", "source_connector_snapshot_id", "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", "public"]}, "local_frame": {"$ref": "#/$defs/transform"}, "binding": {"type": ["object", "null"]}, "source_connector_snapshot_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}, "source_feature_id": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/id"}]}}, "allOf": [{"if": {"properties": {"anchor_kind": {"const": "public"}}, "required": ["anchor_kind"]}, "then": {"properties": {"binding": {"type": "null"}, "source_connector_snapshot_id": {"$ref": "#/$defs/id"}}}}, {"if": {"properties": {"anchor_kind": {"enum": ["geometry", "placement"]}}, "required": ["anchor_kind"]}, "then": {"properties": {"source_connector_snapshot_id": {"type": "null"}}}}]}, "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"}}}}, diff --git a/src/simplecadapi/scene/generated/normalized_product.py b/src/simplecadapi/scene/generated/normalized_product.py index 058cd805..7462ee2c 100644 --- a/src/simplecadapi/scene/generated/normalized_product.py +++ b/src/simplecadapi/scene/generated/normalized_product.py @@ -70,17 +70,17 @@ class PlacementAnchor(TypedDict): placement: Transform -class ForwardedAnchor(TypedDict): - anchor_kind: Literal["forwarded"] - source_component_id: ProductId - source_connector_id: ProductId - offset: Transform | None +class PublicConnector(TypedDict): + public_connector_id: ProductId + component_id: ProductId + connector_id: ProductId + name: str | None class Connector(TypedDict): connector_id: ProductId name: str | None - anchor: GeometryAnchor | PlacementAnchor | ForwardedAnchor + anchor: GeometryAnchor | PlacementAnchor geometry_ref: NotRequired[GeometryRef | None] @@ -136,7 +136,7 @@ class Assembly(TypedDict): assembly_id: ProductId name: str | None components: list[Component] - connectors: list[Connector] + public_connectors: list[PublicConnector] constraints: list[Constraint] grounded_component_ids: list[ProductId] metadata: dict[str, Any] diff --git a/src/simplecadapi/scene/generated/scene.py b/src/simplecadapi/scene/generated/scene.py index e6aefa2f..c2032ffd 100644 --- a/src/simplecadapi/scene/generated/scene.py +++ b/src/simplecadapi/scene/generated/scene.py @@ -308,23 +308,15 @@ class ConnectorTarget(TypedDict): entity_id: str -class ForwardedFrom(TypedDict): - source_component_id: ProductId - source_definition_id: StructuralId - source_connector_id: ProductId - source_connector_snapshot_id: StructuralId - offset: Transform | None - - class Connector(TypedDict): connector_snapshot_id: StructuralId owner_definition_id: StructuralId connector_id: ProductId name: str | None - anchor_kind: Literal["geometry", "placement", "forwarded"] + anchor_kind: Literal["geometry", "placement", "public"] local_transform: Transform target: NotRequired[ConnectorTarget] - forwarded_from: NotRequired[ForwardedFrom] + source_connector_snapshot_id: StructuralId | None source: ( ModelOperationSource | ManualConnectorSource diff --git a/src/simplecadapi/scene/product_scene.py b/src/simplecadapi/scene/product_scene.py index f457afd8..08613316 100644 --- a/src/simplecadapi/scene/product_scene.py +++ b/src/simplecadapi/scene/product_scene.py @@ -656,40 +656,42 @@ def _connectors( graph = feature_graphs[definition_id] for node_id in occurrences.get(definition_id, []): for interface in interfaces: + is_public = isinstance(definition, AssemblyDefinition) + connector_id = interface.connector_id feature_id = _producer_feature( definition_id, graph, - parameter="connector_id", - value=interface.connector_id, + parameter="public_connector_id" if is_public else "connector_id", + value=connector_id, op_prefix=( - "make_add_connector_rpart" - if isinstance(definition, PartDefinition) - else "make_forward_connector_rassembly" + "make_set_public_connector_rassembly" + if is_public + else "make_add_connector_rpart" ), ) - snapshot_id = _connector_snapshot_id( - node_id, interface.connector_id - ) + snapshot_id = _connector_snapshot_id(node_id, connector_id) + source_snapshot_id: str | None = None + if is_public: + source_node_id = f"{node_id}/{interface.source_component_id}" + source_snapshot_id = _connector_snapshot_id( + source_node_id, interface.source_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, + "connector_id": connector_id, + "name": interface.name or connector_id, + "anchor_kind": "public" if is_public else 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_connector_snapshot_id": source_snapshot_id, "source_feature_id": feature_id, } ) @@ -697,11 +699,11 @@ def _connectors( { "connector_index_id": ( f"connector-index/{node_id.removeprefix('node/')}" - f"/{interface.connector_id}" + f"/{connector_id}" ), "definition_id": definition_id, "node_id": node_id, - "connector_id": interface.connector_id, + "connector_id": connector_id, "connector_snapshot_id": snapshot_id, "source_feature_id": feature_id, } @@ -1124,21 +1126,35 @@ def validate_product_scene_package(package: ProductScenePackage) -> None: 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"] + connector_by_id = { + item["connector_snapshot_id"]: item for item in manifest["connectors"] } - if len(connector_ids) != len(manifest["connectors"]): + if len(connector_by_id) != 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_snapshot = connector["source_connector_snapshot_id"] + if connector["anchor_kind"] == "public": + if source_snapshot not in connector_by_id: + raise ProductSceneError("public connector source does not resolve") + elif source_snapshot is not None: + raise ProductSceneError("part connector cannot reference a public source") 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 start in connector_by_id: + seen: set[str] = set() + current = start + while connector_by_id[current]["source_connector_snapshot_id"] is not None: + if current in seen: + raise ProductSceneError("public connector graph contains a cycle") + seen.add(current) + current = connector_by_id[current]["source_connector_snapshot_id"] 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 + joint["connector_a"]["connector_snapshot_id"] not in connector_by_id + or joint["connector_b"]["connector_snapshot_id"] not in connector_by_id ): raise ProductSceneError("joint connector does not resolve") source_feature = joint["source_feature_id"] diff --git a/src/simplecadapi/scene/resources.py b/src/simplecadapi/scene/resources.py index 4fc9c0cb..ee3af532 100644 --- a/src/simplecadapi/scene/resources.py +++ b/src/simplecadapi/scene/resources.py @@ -31,7 +31,7 @@ class SceneResourceLimits: connectors: int = 100_000 cameras: int = 1_000 hierarchy_depth: int = 256 - forwarded_connector_depth: int = 64 + public_connector_depth: int = 64 entities_per_sidecar: int = 500_000 entities_total: int = 2_000_000 triangle_vertices_per_asset: int = 2_000_000 diff --git a/src/simplecadapi/scene/validation.py b/src/simplecadapi/scene/validation.py index 15ff22c1..d8e47910 100644 --- a/src/simplecadapi/scene/validation.py +++ b/src/simplecadapi/scene/validation.py @@ -24,7 +24,6 @@ from .canonical import ( ) from .glb import GlbInfo, preflight_glb from .resources import BASE_LIMITS, SceneResourceLimits, preflight_resource_count -from .transforms import compose_rigid_transforms, rigid_transforms_equal SCHEMA_FILES = { @@ -552,29 +551,29 @@ def _resource_count_issues( ) connectors = value.get("connectors") connector_records = connectors if isinstance(connectors, list) else [] - forward_edges = { + public_edges = { connector.get("connector_snapshot_id"): connector.get( - "forwarded_from", {} - ).get("source_connector_snapshot_id") + "source_connector_snapshot_id" + ) for connector in connector_records if isinstance(connector, dict) - and connector.get("anchor_kind") == "forwarded" - and isinstance(connector.get("forwarded_from"), dict) + and connector.get("anchor_kind") == "public" + and connector.get("source_connector_snapshot_id") is not None } - for start in forward_edges: + for start in public_edges: current = start seen: set[Any] = set() depth = 0 - while current in forward_edges and current not in seen: + while current in public_edges and current not in seen: seen.add(current) - current = forward_edges[current] + current = public_edges[current] depth += 1 - if depth > limits.forwarded_connector_depth: + if depth > limits.public_connector_depth: issues.append( _issue( "resource_limit_exceeded", "/connectors", - "forwarded connector depth exceeds resource limit", + "public connector depth exceeds resource limit", "budget", ) ) @@ -962,7 +961,7 @@ def _scene_semantic_issues(scene: Mapping[str, Any]) -> list[SceneValidationIssu issues.append(_issue("source_matrix_invalid", "/connectors", "imported scene connectors must be empty")) connector_map = {record.get("connector_snapshot_id"): record for record in connectors if isinstance(record, dict)} connector_ids_by_owner: dict[Any, set[Any]] = {} - forward_edges: dict[Any, Any] = {} + public_edges: dict[Any, Any] = {} for index, connector in enumerate(connectors): if not isinstance(connector, dict): continue @@ -984,10 +983,10 @@ def _scene_semantic_issues(scene: Mapping[str, Any]) -> list[SceneValidationIssu anchor_kind = connector.get("anchor_kind") if anchor_kind == "geometry" and owner.get("kind") != "part": issues.append(_issue("connector_invalid", path + "/owner_definition_id", "geometry connector owner must be a Part")) - if anchor_kind == "placement" and owner.get("kind") not in {"part", "assembly"}: - issues.append(_issue("connector_invalid", path + "/owner_definition_id", "connector owner must be a Product definition")) - if anchor_kind == "forwarded" and owner.get("kind") != "assembly": - issues.append(_issue("connector_invalid", path + "/owner_definition_id", "forwarded connector owner must be an Assembly")) + if anchor_kind == "placement" and owner.get("kind") != "part": + issues.append(_issue("connector_invalid", path + "/owner_definition_id", "placement connector owner must be a Part")) + if anchor_kind == "public" and owner.get("kind") != "assembly": + issues.append(_issue("connector_invalid", path + "/owner_definition_id", "public connector owner must be an Assembly")) connector_source = connector.get("source") if source_kind == "model": if not isinstance(connector_source, dict) or connector_source.get("kind") != "model_operation" or connector_source.get("graph_id") != graph_id: @@ -1009,110 +1008,27 @@ def _scene_semantic_issues(scene: Mapping[str, Any]) -> list[SceneValidationIssu transform_issue = _transform_issue(connector.get("local_transform"), path + "/local_transform") if transform_issue: issues.append(transform_issue) - if anchor_kind == "forwarded": - forwarded = connector.get("forwarded_from", {}) - source_snapshot = forwarded.get("source_connector_snapshot_id") if isinstance(forwarded, dict) else None + source_snapshot = connector.get("source_connector_snapshot_id") + if anchor_kind == "public": source_connector = connector_map.get(source_snapshot) - if source_connector is None or source_connector.get("owner_definition_id") != forwarded.get("source_definition_id") or source_connector.get("connector_id") != forwarded.get("source_connector_id"): - issues.append(_issue("connector_invalid", path + "/forwarded_from", "forwarded connector source snapshot ownership is invalid")) - forward_edges[connector.get("connector_snapshot_id")] = source_snapshot - if isinstance(forwarded, dict) and forwarded.get("offset") is not None: - transform_issue = _transform_issue(forwarded.get("offset"), path + "/forwarded_from/offset") - if transform_issue: - issues.append(transform_issue) - if isinstance(forwarded, dict) and owner.get("kind") == "assembly": - owner_nodes = [ - node - for node in nodes - if isinstance(node, dict) - and node.get("definition_id") == connector.get("owner_definition_id") - and isinstance(node.get("source"), dict) - and node["source"].get("kind") == "product_occurrence" - ] - source_children: list[Mapping[str, Any]] = [] - for owner_node in owner_nodes: - owner_node_source = owner_node["source"] - expected_path = [ - *owner_node_source.get("component_path", []), - forwarded.get("source_component_id"), - ] - matches = [ - node - for node in nodes - if isinstance(node, dict) - and isinstance(node.get("source"), dict) - and node["source"].get("kind") == "product_occurrence" - and node["source"].get("root_id") - == owner_node_source.get("root_id") - and node["source"].get("component_path") == expected_path - and node.get("parent_node_id") == owner_node.get("node_id") - ] - if ( - len(matches) != 1 - or matches[0].get("definition_id") - != forwarded.get("source_definition_id") - ): - issues.append( - _issue( - "connector_invalid", - path + "/forwarded_from", - "forwarded connector source component is not one exact direct child", - ) - ) - else: - source_children.append(matches[0]) - if source_children and any( - child.get("transform") != source_children[0].get("transform") - for child in source_children[1:] - ): - issues.append( - _issue( - "connector_invalid", - path + "/forwarded_from", - "forwarded connector source child transforms differ between owner occurrences", - ) - ) - if source_children and isinstance(source_connector, dict): - child_transform = source_children[0].get("transform") - source_transform = source_connector.get("local_transform") - offset = forwarded.get("offset") or { - "origin": [0, 0, 0], - "x_axis": [1, 0, 0], - "y_axis": [0, 1, 0], - "z_axis": [0, 0, 1], - } - if ( - all( - isinstance(value, dict) - and _transform_issue(value, "") is None - for value in (child_transform, source_transform, offset) - ) - and isinstance(connector.get("local_transform"), dict) - and _transform_issue(connector["local_transform"], "") is None - ): - expected_transform = compose_rigid_transforms( - compose_rigid_transforms(child_transform, source_transform), - offset, - ) - if not rigid_transforms_equal( - connector["local_transform"], expected_transform - ): - issues.append( - _issue( - "connector_invalid", - path + "/local_transform", - "forwarded connector transform does not match child, source, and offset composition", - ) - ) - for start in forward_edges: + if source_connector is None: + issues.append(_issue("connector_invalid", path + "/source_connector_snapshot_id", "public connector source snapshot does not exist")) + else: + if source_connector.get("anchor_kind") == "public": + public_edges[connector.get("connector_snapshot_id")] = source_snapshot + if source_connector.get("owner_definition_id") == connector.get("owner_definition_id"): + issues.append(_issue("connector_invalid", path + "/source_connector_snapshot_id", "public connector source must belong to a child definition")) + elif source_snapshot is not None: + issues.append(_issue("connector_invalid", path + "/source_connector_snapshot_id", "non-public connector cannot reference a source snapshot")) + for start in public_edges: seen: set[Any] = set() current = start - while current in forward_edges: + while current in public_edges: if current in seen: - issues.append(_issue("connector_invalid", "/connectors", "forwarded connector graph contains a cycle")) + issues.append(_issue("connector_invalid", "/connectors", "public connector graph contains a cycle")) break seen.add(current) - current = forward_edges[current] + current = public_edges[current] for index, camera in enumerate(scene.get("cameras", [])): if not isinstance(camera, dict): continue diff --git a/src/simplecadapi/selection.py b/src/simplecadapi/selection.py new file mode 100644 index 00000000..6376d25b --- /dev/null +++ b/src/simplecadapi/selection.py @@ -0,0 +1,326 @@ +"""Selection operators for the SimpleCAD public API.""" + +from __future__ import annotations + +from ._operation_support import * + +def _semantic_view_target(view: AnyShape, target: AnyShape) -> AnyShape: + candidates = [ + wrapper + for entity in view._topology_cache.entities() + if entity.kind == target._entity.kind + for wrapper in entity.wrappers + if isinstance(wrapper, type(target)) + ] + matches = [] + for candidate in candidates: + try: + if _same_semantic_topology( + target._entity.kind, + candidate.wrapped, + target.wrapped, + ): + matches.append(candidate) + except Exception: + continue + unique = {candidate.topo_id: candidate for candidate in matches} + if not unique: + raise ValueError("tag target does not belong to the assignment scope") + if len(unique) != 1: + raise ValueError("tag target resolves ambiguously inside the assignment scope") + return cast(AnyShape, next(iter(unique.values()))) + +def apply_tag_rselection( + scope: AnyShape, + targets: Union[ShapeSelector, Sequence[AnyShape]], + tag: str, + topology_propagation: str | TopologyPropagation = TopologyPropagation.LOCAL, + lineage_policy: str | LineagePolicy = LineagePolicy.CONTINUATION_FRAGMENT, +) -> AnyShape: + """Return a semantic shape view with a canonical tag assignment.""" + + try: + return _apply_tag_rselection( + scope, + targets, + tag, + topology_propagation, + lineage_policy, + ) + except Exception as e: + _wrap_public_api_error( + operation="apply_tag_rselection", + what_happened="Failed to attach the tag to the selected shapes.", + possible_causes=[ + "The assignment scope or target selection is invalid.", + "The tag value is empty or malformed.", + "The selector resolved no targets or references foreign topology.", + ], + how_to_fix=[ + "Pass a valid scope and a non-empty ShapeSelector or shape sequence.", + "Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'.", + "Ensure every explicit target belongs to the assignment scope.", + ], + error=e, + ) + +def _apply_tag_rselection( + scope: AnyShape, + targets: Union[ShapeSelector, Sequence[AnyShape]], + tag: str, + topology_propagation: str | TopologyPropagation, + lineage_policy: str | LineagePolicy, + *, + authoring_source: str = "simplecadapi.apply_tag_rselection", + extra_evidence: Optional[Dict[str, Any]] = None, + clone_scope: bool = True, +) -> AnyShape: + normalized_tag = normalize_tag(tag, strict=True) + topology = TopologyPropagation(topology_propagation) + lineage = LineagePolicy(lineage_policy) + session = get_active_session() + source_node = _active_graph_node_for_shape(scope) + source_output_slot = int(scope._get_runtime("graph.output_slot", 0)) + if session is not None and source_node is None: + raise ValueError("assignment scope is not produced by the active GraphSession") + + view = clone_semantic_shape_view(scope) if clone_scope else scope + if isinstance(targets, ShapeSelector): + selector = targets + if source_node is not None: + if selector.source_node_id is None: + selector = selector.from_source(source_node.node_id, source_output_slot) + elif ( + selector.source_node_id != source_node.node_id + or int(selector.source_output_slot or 0) != source_output_slot + ): + raise ValueError( + "tag selector source does not match the assignment scope" + ) + selected = cast(List[AnyShape], selector.resolve(view)) + target = TagTarget("selection_query", selector=selector.to_dict()) + else: + if isinstance(targets, (str, bytes)): + raise TypeError("targets must be a ShapeSelector or shape sequence") + target_shapes = list(targets) + if not target_shapes: + raise ValueError("tag assignment targets cannot be empty") + if not all( + isinstance(item, (Vertex, Edge, Wire, Face, Shell, Solid, Compound)) + for item in target_shapes + ): + raise TypeError("tag assignment targets must contain only shapes") + selected = [ + _semantic_view_target(view, cast(AnyShape, item)) for item in target_shapes + ] + refs = tuple( + ref for ref in _serialize_shape_refs(target_shapes) if isinstance(ref, dict) + ) + if len(refs) != len(target_shapes): + refs = tuple( + {"kind": _shape_kind_token(item), "topo_id": item.topo_id} + for item in target_shapes + ) + target = TagTarget("explicit_refs", refs=refs) + + selected_by_topo_id = {item.topo_id: item for item in selected} + if len(selected_by_topo_id) != len(selected): + raise ValueError("tag assignment targets contain ambiguous duplicate entities") + selected = list(selected_by_topo_id.values()) + if not selected: + raise ValueError("tag assignment resolved no targets") + + selected_refs = _serialize_shape_refs(selected) + if len(selected_refs) != len(selected): + selected_refs = [ + {"kind": _shape_kind_token(item), "topo_id": item.topo_id} + for item in selected + ] + + assignment_node_id = ( + session.graph.allocate_node_id("n") + if source_node is not None and session is not None + else None + ) + evidence_data = { + "authoring_source": authoring_source, + "selected_count": len(selected), + "selected_refs": selected_refs, + **dict(extra_evidence or {}), + } + binding = TagBinding( + tag=normalized_tag, + producer=TagProducer("user_operation", node_id=assignment_node_id), + scope=TagBindingScope( + node_id=(source_node.node_id if source_node is not None else None), + output_slot=source_output_slot, + ), + target=target, + propagation=TagPropagation(topology=topology, lineage=lineage), + evidence=TagEvidence("query_execution", evidence_data), + certainty=TagCertainty.ASSERTED, + lifecycle=TagLifecycle.ASSERTION, + binding_id=( + f"tag_binding_{uuid.uuid5(uuid.NAMESPACE_URL, f'simplecad:user-tag:{session.graph.graph_id}:{assignment_node_id}:{normalized_tag}').hex}" + if assignment_node_id is not None and session is not None + else f"tag_binding_{uuid.uuid4().hex}" + ), + ) + + for selected_shape in selected: + selected_shape._add_tag_binding(binding) + + if source_node is not None and session is not None: + node = record_operation( + op=_OP_APPLY_TAG_RSELECTION, + params={"tag_binding": binding.to_dict()}, + inputs=[source_node], + node_id=assignment_node_id, + output_count=1, + context=_current_context_metadata(), + ) + attach_semantic_graph_node( + view, + node, + output_slot=0, + graph_id=session.graph.graph_id, + ) + return view + +def apply_tag(shape: AnyShape, tag: str) -> AnyShape: + """Attach a local user tag with continuation/fragment lineage policy.""" + + try: + _ensure_source_shape_has_own_selection_node(shape) + selector = ShapeSelector(_shape_kind_token(shape)).exactly(1) + return _apply_tag_rselection( + shape, + selector, + tag, + TopologyPropagation.LOCAL, + LineagePolicy.CONTINUATION_FRAGMENT, + clone_scope=False, + ) + except Exception as e: + _wrap_public_api_error( + operation="apply_tag", + what_happened="Failed to attach the tag to the shape.", + possible_causes=[ + "The shape is invalid.", + "The tag value is empty or malformed.", + ], + how_to_fix=[ + "Pass a valid shape object.", + "Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'.", + ], + error=e, + ) + +def list_tags( + shape: AnyShape, + scope: str | TagScope = TagScope.EFFECTIVE, +) -> List[str]: + """Return shape tags in deterministic sorted order for one scope.""" + try: + return shape._list_tags(normalize_tag_scope(scope)) + except Exception as e: + _wrap_public_api_error( + operation="list_tags", + what_happened="Failed to list tags on the shape.", + possible_causes=[ + "The shape is invalid.", + "The object is not a SimpleCAD shape.", + ], + how_to_fix=[ + "Pass a valid Vertex, Edge, Wire, Face, or Solid object.", + ], + error=e, + ) + +def explain_tag( + shape: AnyShape, + tag: str, + scope: str | TagScope = TagScope.EFFECTIVE, +) -> List[Dict[str, Any]]: + """Explain every visible binding that produces a tag token.""" + + try: + return shape._explain_tag( + normalize_tag(tag, strict=True), normalize_tag_scope(scope) + ) + except Exception as e: + _wrap_public_api_error( + operation="explain_tag", + what_happened="Failed to explain the tag on the shape.", + possible_causes=[ + "The shape or tag is invalid.", + "The requested scope requires unavailable semantic evidence.", + ], + how_to_fix=[ + "Pass a valid shape and normalized tag token.", + "Request a supported scope or provide complete topology history.", + ], + error=e, + ) + +def select_faces_by_tag( + solid: Solid, + tag: str, + scope: str | TagScope = TagScope.EFFECTIVE, +) -> List[Face]: + """Select faces by tag.""" + try: + normalized = normalize_tag(tag, strict=True) + resolved_scope = normalize_tag_scope(scope) + faces = solid.get_faces() + return [face for face in faces if face._has_tag(normalized, resolved_scope)] + except Exception as e: + _wrap_public_api_error( + operation="select_faces_by_tag", + what_happened="Failed to select faces by tag.", + possible_causes=[ + "The solid is invalid.", + "The tag string is invalid.", + ], + how_to_fix=[ + "Pass a valid Solid object.", + "Use the exact face tag that was previously assigned.", + ], + error=e, + ) + +def select_edges_by_tag( + shape: Union[Face, Solid], + tag: str, + scope: str | TagScope = TagScope.EFFECTIVE, +) -> List[Edge]: + """Select edges by tag.""" + try: + normalized = normalize_tag(tag, strict=True) + resolved_scope = normalize_tag_scope(scope) + if isinstance(shape, Face): + edges = shape.get_edges() + elif isinstance(shape, Solid): + edges = shape.get_edges() + else: + raise ValueError("只能从面或实体中选择边") + + return [edge for edge in edges if edge._has_tag(normalized, resolved_scope)] + except Exception as e: + _wrap_public_api_error( + operation="select_edges_by_tag", + what_happened="Failed to select edges by tag.", + possible_causes=[ + "The input shape is neither a Face nor a Solid.", + "The shape is invalid.", + "The tag string is invalid.", + ], + how_to_fix=[ + "Pass a Face or Solid object.", + "Use the exact edge tag that was previously assigned.", + "If selection is empty unexpectedly, inspect the available edge tags first.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/src/simplecadapi/serializer.py b/src/simplecadapi/serializer.py index 0d5bcd1a..58997fe8 100644 --- a/src/simplecadapi/serializer.py +++ b/src/simplecadapi/serializer.py @@ -266,13 +266,9 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = { "op": "make_placement_connector_rconnector", }, "add_connector_rpart": {"status": "replayable", "op": "make_add_connector_rpart"}, - "add_connector_rassembly": { + "set_public_connector_rassembly": { "status": "replayable", - "op": "make_add_connector_rassembly", - }, - "forward_connector_rassembly": { - "status": "replayable", - "op": "make_forward_connector_rassembly", + "op": "make_set_public_connector_rassembly", }, "make_connector_ref_rconnectorref": { "status": "replayable", @@ -550,8 +546,7 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = ( "make_vertex_connector_rconnector", "make_placement_connector_rconnector", "make_add_connector_rpart", - "make_add_connector_rassembly", - "make_forward_connector_rassembly", + "make_set_public_connector_rassembly", "make_connector_ref_rconnectorref", "make_scalar_limit_rscalarlimit", "make_ground_component_rassembly", @@ -3099,67 +3094,49 @@ def _execute_graph( _store_outputs(node, result) continue - if op_name == "make_add_connector_rassembly": - assembly_outputs = _input_outputs(ctx, outputs, node, 0) - connector_outputs = _input_outputs(ctx, outputs, node, 1) - if assembly_outputs and connector_outputs: - result = ops.add_connector_rassembly( - cast(Assembly, assembly_outputs[0]), - cast(Connector, connector_outputs[0]), + if op_name == "make_set_public_connector_rassembly": + allowed_params = { + "assembly_id", + "public_connector_id", + "source_component_id", + "source_connector_id", + "name", + } + unexpected = sorted(set(params) - allowed_params) + if unexpected: + ctx.fail( + f"Graph node '{node.node_id}' ({op_name}) contains unsupported parameter(s): " + + ", ".join(unexpected) ) - _store_outputs(node, result) - continue - - if op_name == "make_forward_connector_rassembly": ctx.require_params( node.node_id, op_name, params, ( - "connector_id", + "public_connector_id", "source_component_id", "source_connector_id", ), ) assembly_outputs = _input_outputs(ctx, outputs, node, 0) - offset_outputs = ( - _input_outputs(ctx, outputs, node, 1) - if len(node.inputs) > 1 - else [] - ) - offset = ( - cast(Optional[Placement], offset_outputs[0]) - if offset_outputs - else None - ) - if offset is None and isinstance(params.get("offset"), dict): - offset_data = cast(Dict[str, Any], params["offset"]) - offset = Placement( - cast( - Any, - tuple(offset_data.get("origin", (0.0, 0.0, 0.0))), - ), - x_axis=cast( - Any, - tuple(offset_data.get("x_axis", (1.0, 0.0, 0.0))), - ), - y_axis=cast( - Any, - tuple(offset_data.get("y_axis", (0.0, 1.0, 0.0))), - ), - ) if assembly_outputs: - result = ops.forward_connector_rassembly( - cast(Assembly, assembly_outputs[0]), - str(params["connector_id"]), - str(params["source_component_id"]), - str(params["source_connector_id"]), + result = ops.set_public_connector_rassembly( + assembly=cast(Assembly, assembly_outputs[0]), + public_connector_id=str( + params["public_connector_id"] + ), + source_component_id=str( + params["source_component_id"] + ), + source_connector_id=str( + params["source_connector_id"] + ), name=cast(Optional[str], params.get("name")), - offset=offset, ) _store_outputs(node, result) continue + if op_name == "make_connector_ref_rconnectorref": ctx.require_params( node.node_id, diff --git a/src/simplecadapi/sketch.py b/src/simplecadapi/sketch.py index 7edc5f60..b3168057 100644 --- a/src/simplecadapi/sketch.py +++ b/src/simplecadapi/sketch.py @@ -241,7 +241,7 @@ class Sketch(TaggedMixin, TopoMixein): def to_faces(self) -> List[Face]: if self.entities: return [self.to_face()] - from .operations import make_face_from_wire_rface + from ._operators_geometry import make_face_from_wire_rface return [make_face_from_wire_rface(wire) for wire in self.closed_wires()] @@ -251,7 +251,7 @@ class Sketch(TaggedMixin, TopoMixein): *, inner_profiles: Sequence[int | str] = (), ) -> Face: - from .operations import make_face_from_sketch_rface + from ._operators_sketch import make_face_from_sketch_rface return make_face_from_sketch_rface( self, @@ -467,7 +467,7 @@ class Sketch(TaggedMixin, TopoMixein): this sketch. The first and last poles always share the declared start/end point entities. """ - from .operations import ( + from ._operators_geometry import ( _normalize_bspline_knots, _normalize_bspline_weights, ) @@ -648,7 +648,11 @@ class Sketch(TaggedMixin, TopoMixein): return self._wire_from_profile_payload(profile_payload) def _wire_from_profile_payload(self, profile_payload: Mapping[str, Any]) -> Wire: - from .operations import make_circle_redge, make_line_redge, make_wire_from_edges_rwire + from ._operators_geometry import ( + make_circle_redge, + make_line_redge, + make_wire_from_edges_rwire, + ) if profile_payload["kind"] == "circle": center = profile_payload["center"] @@ -684,7 +688,7 @@ class Sketch(TaggedMixin, TopoMixein): """Build a wire from a mixed-edge profile (line + arc + bspline).""" from OCP.TopoDS import TopoDS - from .operations import ( + from ._operators_geometry import ( make_line_redge, make_spline_redge, make_three_point_arc_redge, @@ -783,7 +787,7 @@ class Sketch(TaggedMixin, TopoMixein): inner_profiles: Sequence[int | str] = (), solve_result: Optional[SketchSolveResult] = None, ) -> Face: - from .operations import make_face_from_sketch_rface + from ._operators_sketch import make_face_from_sketch_rface if solve_result is not None: raise ValueError( diff --git a/src/simplecadapi/std/bearing.py b/src/simplecadapi/std/bearing.py index 5216b14c..778c5d4f 100644 --- a/src/simplecadapi/std/bearing.py +++ b/src/simplecadapi/std/bearing.py @@ -21,7 +21,6 @@ from ..operations import ( apply_tag, assign_material_rpart, chamfer_rsolid, - forward_connector_rassembly, identity_placement_rplacement, make_assembly_rassembly, make_connector_ref_rconnectorref, @@ -34,6 +33,7 @@ from ..operations import ( make_three_point_arc_redge, make_wire_from_edges_rwire, revolve_rsolid, + set_public_connector_rassembly, union_rsolid, ) from ..core import Face, Solid @@ -424,24 +424,19 @@ def make_ball_bearing_rassembly( drive_angle_degrees=drive_angle_degrees, name="Inner ring spins in outer ring", ) - public_axis_offset = make_placement_rplacement( - origin=(0.0, 0.0, -bearing_width_value / 2.0), - ) - assembly = forward_connector_rassembly( + assembly = set_public_connector_rassembly( assembly, - connector_id="outer_axis", + public_connector_id="outer_axis", source_component_id="outer_ring", source_connector_id="axis", name="Outer ring housing axis", - offset=public_axis_offset, ) - assembly = forward_connector_rassembly( + assembly = set_public_connector_rassembly( assembly, - connector_id="inner_axis", + public_connector_id="inner_axis", source_component_id="inner_ring", source_connector_id="axis", name="Inner ring shaft axis", - offset=public_axis_offset, ) assembly.set_metadata( "std.bearing.ball_bearing", diff --git a/src/simplecadapi/surface.py b/src/simplecadapi/surface.py index 92ac793f..e0c5e40c 100644 --- a/src/simplecadapi/surface.py +++ b/src/simplecadapi/surface.py @@ -1,12 +1,10 @@ """Public surface modeling namespace. -The constructors are implemented in :mod:`simplecadapi.operations` so they -participate in the same graph, coordinate-system, tagging, and error contracts -as the rest of the SDK. This module provides the focused namespace requested by -surface-heavy clients. +The constructors are implemented in the focused operator module so they +participate in the same graph, coordinate-system, tagging, and error contracts. """ -from .operations import ( +from ._operators_geometry import ( SurfaceBoundary, SurfaceFillingSettings, fill_holes_rshell, diff --git a/src/simplecadapi/transform.py b/src/simplecadapi/transform.py new file mode 100644 index 00000000..8615c61b --- /dev/null +++ b/src/simplecadapi/transform.py @@ -0,0 +1,433 @@ +"""Transform operators for the SimpleCAD public API.""" + +from __future__ import annotations + +from ._operation_support import * +from .geometry import rotate_shape, translate_shape + +def translate_shape(shape: AnyShape, vector: Tuple[float, float, float]) -> AnyShape: + """Translate a shape by an offset vector.""" + try: + cs = get_current_cs() + vector_value = cast(Tuple[float, float, float], evaluate_value(vector)) + global_vector = cs.transform_vector(np.array(vector_value)) + resolved_vector = tuple(float(value) for value in global_vector) + if isinstance(shape, Solid): + tracked = cast( + TrackedResult, + tracked_translate(shape, resolved_vector), + ) + translated = cast(Solid, tracked.shape) + translated._metadata = shape._metadata.copy() + _attach_lineage_from_source( + shape, + translated, + derivation="continuation", + op=_OP_MAKE_TRANSLATE_RSHAPE, + ) + return _finalize_tracked_solid( + translated, + op=_OP_MAKE_TRANSLATE_RSHAPE, + params={"vector": vector}, + source_solid=shape, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[shape], + ) + + new_shape = translate_shape_ocp(shape, resolved_vector) + + new_shape._metadata = shape._metadata.copy() + _copy_runtime_state(shape, new_shape) + _attach_lineage_from_source( + shape, + new_shape, + derivation="continuation", + op=_OP_MAKE_TRANSLATE_RSHAPE, + ) + record_operation_if_active( + op=_OP_MAKE_TRANSLATE_RSHAPE, + params={"vector": vector}, + outputs=new_shape, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return new_shape + except Exception as e: + _wrap_public_api_error( + operation="translate_shape", + what_happened="Failed to translate the shape.", + possible_causes=[ + "The shape is invalid or has been corrupted by an earlier operation.", + "The translation vector is not a valid finite 3D vector.", + "The kernel rejected the transform.", + ], + how_to_fix=[ + "Pass a valid SimpleCAD shape object.", + "Pass vector as a finite 3-element tuple or expression-backed vector.", + "Inspect the shape and vector values before retrying.", + ], + error=e, + ) + +def rotate_shape( + shape: AnyShape, + angle: ScalarLike, + axis: Tuple[float, float, float] = (0, 0, 1), + origin: Tuple[float, float, float] = (0, 0, 0), +) -> AnyShape: + """Rotate a shape around an axis.""" + angle_value = evaluate_scalar(angle) + if angle_value == 0: + return shape + else: + try: + cs = get_current_cs() + axis_value = cast(Tuple[float, float, float], evaluate_value(axis)) + origin_value = cast(Tuple[float, float, float], evaluate_value(origin)) + global_axis = cs.transform_vector(np.array(axis_value)) + global_origin = cs.transform_point(np.array(origin_value)) + resolved_axis = tuple(float(value) for value in global_axis) + resolved_origin = tuple(float(value) for value in global_origin) + if isinstance(shape, Solid): + tracked = cast( + TrackedResult, + tracked_rotate( + shape, + angle_value, + axis=resolved_axis, + origin=resolved_origin, + ), + ) + rotated = cast(Solid, tracked.shape) + rotated._metadata = shape._metadata.copy() + _attach_lineage_from_source( + shape, + rotated, + derivation="continuation", + op=_OP_MAKE_ROTATE_RSHAPE, + ) + return _finalize_tracked_solid( + rotated, + op=_OP_MAKE_ROTATE_RSHAPE, + params={"angle": angle, "axis": axis, "origin": origin}, + source_solid=shape, + delta=tracked.delta, + delta_entries=cast( + Dict[str, Dict[str, object]], tracked.delta_entries + ), + input_shapes=[shape], + ) + + new_shape = rotate_shape_ocp( + shape, + angle_value, + resolved_axis, + resolved_origin, + ) + + new_shape._metadata = shape._metadata.copy() + _copy_runtime_state(shape, new_shape) + _attach_lineage_from_source( + shape, + new_shape, + derivation="continuation", + op=_OP_MAKE_ROTATE_RSHAPE, + ) + record_operation_if_active( + op=_OP_MAKE_ROTATE_RSHAPE, + params={"angle": angle, "axis": axis, "origin": origin}, + outputs=new_shape, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return new_shape + except Exception as e: + _wrap_public_api_error( + operation="rotate_shape", + what_happened="Failed to rotate the shape.", + possible_causes=[ + "The shape is invalid.", + "The rotation angle is invalid or non-finite.", + "The axis or origin is not a valid finite 3D vector.", + ], + how_to_fix=[ + "Pass a valid shape and a finite rotation angle.", + "Use a non-zero axis vector and a valid origin point.", + "Log the evaluated angle, axis, and origin before retrying.", + ], + error=e, + ) + +def linear_pattern_rsolidlist( + shape: AnyShape, direction: Tuple[float, float, float], count: int, spacing: float +) -> List[Solid]: + """Create a linear pattern of solids.""" + try: + if count <= 0: + raise ValueError("阵列数量必须大于0") + if spacing <= 0: + raise ValueError("阵列间距必须大于0") + + direction_value = cast(Tuple[float, float, float], evaluate_value(direction)) + direction_array = np.asarray(direction_value, dtype=float) + direction_norm = float(np.linalg.norm(direction_array)) + if direction_norm <= 1e-15 or not np.isfinite(direction_norm): + raise ValueError("阵列方向不能是零向量") + local_direction = direction_array / direction_norm + + if get_active_session() is not None: + rv: List[Solid] = [] + for i in range(count): + offset = local_direction * (spacing * i) + translated_shape = translate_shape( + shape, (float(offset[0]), float(offset[1]), float(offset[2])) + ) + translated_shape._apply_tag("solid.pattern.linear", propagate=False) + geo = dict(translated_shape.get_metadata("geo", {})) + geo["pattern"] = {"type": "linear", "index": i + 1} + translated_shape.set_metadata("geo", geo) + _attach_track_summary(translated_shape, op="linear_pattern") + rv.append(cast(Solid, translated_shape)) + return rv + + shapes = [] + with suspend_graph_recording(): + for i in range(count): + offset = local_direction * (spacing * i) + translated_shape = translate_shape( + shape, (float(offset[0]), float(offset[1]), float(offset[2])) + ) + shapes.append(translated_shape) + + rv = [] + for i, s in enumerate(shapes): + s._apply_tag("solid.pattern.linear", propagate=False) + geo = dict(s.get_metadata("geo", {})) + geo["pattern"] = {"type": "linear", "index": i + 1} + s.set_metadata("geo", geo) + _attach_track_summary(s, op="linear_pattern") + rv.append(s) + + record_operation_if_active( + op="linear_pattern", + params={ + "direction": direction, + "count": count, + "spacing": spacing, + }, + outputs=rv, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return rv + + except Exception as e: + _wrap_public_api_error( + operation="linear_pattern_rsolidlist", + what_happened="Failed to create the linear pattern.", + possible_causes=[ + "The count is not a positive integer.", + "The spacing is not positive.", + "The direction vector is invalid.", + ], + how_to_fix=[ + "Use count >= 1.", + "Use spacing > 0.", + "Pass a valid finite direction vector.", + ], + error=e, + ) + +def radial_pattern_rsolidlist( + shape: AnyShape, + center: Tuple[float, float, float], + axis: Tuple[float, float, float], + count: int, + total_rotation_angle: float, +) -> List[Solid]: + """Create a radial pattern of solids.""" + try: + if count <= 0: + raise ValueError("阵列数量必须大于0") + if total_rotation_angle <= 0: + raise ValueError("角度必须大于0") + + shapes = [] + angle_step = total_rotation_angle / count # 修正角度计算,均匀分布 + + if get_active_session() is not None: + rv: List[Solid] = [] + for i in range(count): + rotation_angle = angle_step * i + rotated_shape = ( + cast(Solid, translate_shape(shape, (0.0, 0.0, 0.0))) + if i == 0 + else cast(Solid, rotate_shape(shape, rotation_angle, axis, center)) + ) + rotated_shape._apply_tag("solid.pattern.radial", propagate=False) + geo = dict(rotated_shape.get_metadata("geo", {})) + geo["pattern"] = {"type": "radial", "index": i + 1} + rotated_shape.set_metadata("geo", geo) + _attach_track_summary(rotated_shape, op="radial_pattern") + rv.append(cast(Solid, rotated_shape)) + return rv + + with suspend_graph_recording(): + for i in range(count): + rotation_angle = angle_step * i + rotated_shape = rotate_shape(shape, rotation_angle, axis, center) + shapes.append(rotated_shape) + + rv = [] + for i, s in enumerate(shapes): + s._apply_tag("solid.pattern.radial", propagate=False) + geo = dict(s.get_metadata("geo", {})) + geo["pattern"] = {"type": "radial", "index": i + 1} + s.set_metadata("geo", geo) + _attach_track_summary(s, op="radial_pattern") + rv.append(s) + + record_operation_if_active( + op="radial_pattern", + params={ + "center": center, + "axis": axis, + "count": count, + "total_rotation_angle": total_rotation_angle, + }, + outputs=rv, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return rv + except Exception as e: + _wrap_public_api_error( + operation="radial_pattern_rsolidlist", + what_happened="Failed to create the radial pattern.", + possible_causes=[ + "The count is not a positive integer.", + "The total rotation angle is not positive.", + "The center or axis is invalid.", + ], + how_to_fix=[ + "Use count >= 1.", + "Use a total rotation angle greater than zero.", + "Pass a valid center point and a non-zero axis vector.", + ], + error=e, + ) + +def mirror_shape( + shape: AnyShape, + plane_origin: Tuple[float, float, float], + plane_normal: Tuple[float, float, float], +) -> AnyShape: + """Mirror a shape across a plane.""" + try: + cs = get_current_cs() + plane_origin_value = cast( + Tuple[float, float, float], evaluate_value(plane_origin) + ) + plane_normal_value = cast( + Tuple[float, float, float], evaluate_value(plane_normal) + ) + global_origin = cs.transform_point(np.array(plane_origin_value)) + global_normal = cs.transform_vector(np.array(plane_normal_value)) + + # 确保法向量不是零向量 + if np.linalg.norm(global_normal) < 1e-10: + raise ValueError("镜像平面法向量不能是零向量") + + if isinstance(shape, Solid): + resolved_origin = tuple(float(value) for value in global_origin) + resolved_normal = tuple(float(value) for value in global_normal) + tracked = cast( + TrackedResult, + tracked_mirror( + shape, + resolved_origin, + resolved_normal, + ), + ) + new_shape = cast(Solid, tracked.shape) + new_shape._metadata = shape._metadata.copy() + _attach_lineage_from_source( + shape, + new_shape, + derivation="continuation", + op=_OP_MAKE_MIRROR_RSHAPE, + ) + new_shape._apply_tag("solid.transform.mirrored", propagate=False) + return _finalize_tracked_solid( + new_shape, + op=_OP_MAKE_MIRROR_RSHAPE, + params={ + "plane_origin": plane_origin, + "plane_normal": plane_normal, + }, + source_solid=shape, + delta=tracked.delta, + delta_entries=cast(Dict[str, Dict[str, object]], tracked.delta_entries), + input_shapes=[shape], + ) + + else: + new_shape = mirror_shape_ocp( + shape, + ( + float(global_origin[0]), + float(global_origin[1]), + float(global_origin[2]), + ), + ( + float(global_normal[0]), + float(global_normal[1]), + float(global_normal[2]), + ), + ) + + new_shape._metadata = shape._metadata.copy() + _attach_lineage_from_source( + shape, + new_shape, + derivation="continuation", + op=_OP_MAKE_MIRROR_RSHAPE, + ) + new_shape._apply_tag("solid.transform.mirrored", propagate=False) + + _attach_track_summary(new_shape, op=_OP_MAKE_MIRROR_RSHAPE) + record_operation_if_active( + op=_OP_MAKE_MIRROR_RSHAPE, + params={ + "plane_origin": plane_origin, + "plane_normal": plane_normal, + }, + outputs=new_shape, + input_shapes=[shape], + context=_current_context_metadata(), + ) + + return new_shape + except Exception as e: + _wrap_public_api_error( + operation="mirror_shape", + what_happened="Failed to mirror the shape across the plane.", + possible_causes=[ + "The plane origin or plane normal is invalid.", + "The plane normal is zero-length.", + "The kernel rejected the mirror transform.", + ], + how_to_fix=[ + "Pass a valid plane origin and a non-zero plane normal.", + "Validate the shape before mirroring.", + "If the plane is computed dynamically, inspect the evaluated values first.", + ], + error=e, + ) + +__all__ = tuple(name for name in globals() if not name.startswith("__")) diff --git a/test/fixtures/scene-contract/corpus.json b/test/fixtures/scene-contract/corpus.json index 815a4db6..cf9e9c30 100644 --- a/test/fixtures/scene-contract/corpus.json +++ b/test/fixtures/scene-contract/corpus.json @@ -657,7 +657,7 @@ { "expected": null, "name": "valid_normalized_assembly", - "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfV0sImNvbm5lY3RvcnMiOltdLCJjb25zdHJhaW50cyI6W10sImdyb3VuZGVkX2NvbXBvbmVudF9pZHMiOlsiY29tcG9uZW50X2EiXSwia2luZCI6ImFzc2VtYmx5IiwibWV0YWRhdGEiOnt9LCJuYW1lIjpudWxsfQ==", + "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfV0sImNvbnN0cmFpbnRzIjpbXSwiZ3JvdW5kZWRfY29tcG9uZW50X2lkcyI6WyJjb21wb25lbnRfYSJdLCJraW5kIjoiYXNzZW1ibHkiLCJtZXRhZGF0YSI6e30sIm5hbWUiOm51bGwsInB1YmxpY19jb25uZWN0b3JzIjpbXX0=", "valid": true }, { @@ -666,7 +666,7 @@ "path": "/grounded_component_ids" }, "name": "missing_grounded_component", - "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfV0sImNvbm5lY3RvcnMiOltdLCJjb25zdHJhaW50cyI6W10sImdyb3VuZGVkX2NvbXBvbmVudF9pZHMiOlsibWlzc2luZyJdLCJraW5kIjoiYXNzZW1ibHkiLCJtZXRhZGF0YSI6e30sIm5hbWUiOm51bGx9", + "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfV0sImNvbnN0cmFpbnRzIjpbXSwiZ3JvdW5kZWRfY29tcG9uZW50X2lkcyI6WyJtaXNzaW5nIl0sImtpbmQiOiJhc3NlbWJseSIsIm1ldGFkYXRhIjp7fSwibmFtZSI6bnVsbCwicHVibGljX2Nvbm5lY3RvcnMiOltdfQ==", "valid": false }, { @@ -675,7 +675,7 @@ "path": "/components" }, "name": "duplicate_components", - "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfSx7ImNvbXBvbmVudF9pZCI6ImNvbXBvbmVudF9hIiwiZGVmaW5pdGlvbl9yZWYiOiJkZWZpbml0aW9uL3Jvb3QvcGFydC9maXh0dXJlIiwibG9jYWxfcGxhY2VtZW50Ijp7Im9yaWdpbiI6WzAsMCwwXSwieF9heGlzIjpbMSwwLDBdLCJ5X2F4aXMiOlswLDEsMF0sInpfYXhpcyI6WzAsMCwxXX0sIm5hbWUiOm51bGx9XSwiY29ubmVjdG9ycyI6W10sImNvbnN0cmFpbnRzIjpbXSwiZ3JvdW5kZWRfY29tcG9uZW50X2lkcyI6WyJjb21wb25lbnRfYSJdLCJraW5kIjoiYXNzZW1ibHkiLCJtZXRhZGF0YSI6e30sIm5hbWUiOm51bGx9", + "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfSx7ImNvbXBvbmVudF9pZCI6ImNvbXBvbmVudF9hIiwiZGVmaW5pdGlvbl9yZWYiOiJkZWZpbml0aW9uL3Jvb3QvcGFydC9maXh0dXJlIiwibG9jYWxfcGxhY2VtZW50Ijp7Im9yaWdpbiI6WzAsMCwwXSwieF9heGlzIjpbMSwwLDBdLCJ5X2F4aXMiOlswLDEsMF0sInpfYXhpcyI6WzAsMCwxXX0sIm5hbWUiOm51bGx9XSwiY29uc3RyYWludHMiOltdLCJncm91bmRlZF9jb21wb25lbnRfaWRzIjpbImNvbXBvbmVudF9hIl0sImtpbmQiOiJhc3NlbWJseSIsIm1ldGFkYXRhIjp7fSwibmFtZSI6bnVsbCwicHVibGljX2Nvbm5lY3RvcnMiOltdfQ==", "valid": false }, { @@ -698,14 +698,8 @@ }, { "expected": null, - "name": "valid_forwarded_connector_null_offset", - "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfV0sImNvbm5lY3RvcnMiOlt7ImFuY2hvciI6eyJhbmNob3Jfa2luZCI6ImZvcndhcmRlZCIsIm9mZnNldCI6bnVsbCwic291cmNlX2NvbXBvbmVudF9pZCI6ImNvbXBvbmVudF9hIiwic291cmNlX2Nvbm5lY3Rvcl9pZCI6InBsYWNlbWVudCJ9LCJjb25uZWN0b3JfaWQiOiJmb3J3YXJkZWQiLCJuYW1lIjpudWxsfV0sImNvbnN0cmFpbnRzIjpbXSwiZ3JvdW5kZWRfY29tcG9uZW50X2lkcyI6WyJjb21wb25lbnRfYSJdLCJraW5kIjoiYXNzZW1ibHkiLCJtZXRhZGF0YSI6e30sIm5hbWUiOm51bGx9", - "valid": true - }, - { - "expected": null, - "name": "valid_forwarded_connector_offset", - "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfV0sImNvbm5lY3RvcnMiOlt7ImFuY2hvciI6eyJhbmNob3Jfa2luZCI6ImZvcndhcmRlZCIsIm9mZnNldCI6eyJvcmlnaW4iOlswLDAsNV0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJzb3VyY2VfY29tcG9uZW50X2lkIjoiY29tcG9uZW50X2EiLCJzb3VyY2VfY29ubmVjdG9yX2lkIjoicGxhY2VtZW50In0sImNvbm5lY3Rvcl9pZCI6ImZvcndhcmRlZCIsIm5hbWUiOm51bGx9XSwiY29uc3RyYWludHMiOltdLCJncm91bmRlZF9jb21wb25lbnRfaWRzIjpbImNvbXBvbmVudF9hIl0sImtpbmQiOiJhc3NlbWJseSIsIm1ldGFkYXRhIjp7fSwibmFtZSI6bnVsbH0=", + "name": "valid_public_connector", + "payload_base64": "eyJhc3NlbWJseV9pZCI6ImZpeHR1cmVfYXNzZW1ibHkiLCJjb21wb25lbnRzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImRlZmluaXRpb25fcmVmIjoiZGVmaW5pdGlvbi9yb290L3BhcnQvZml4dHVyZSIsImxvY2FsX3BsYWNlbWVudCI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJuYW1lIjpudWxsfV0sImNvbnN0cmFpbnRzIjpbXSwiZ3JvdW5kZWRfY29tcG9uZW50X2lkcyI6WyJjb21wb25lbnRfYSJdLCJraW5kIjoiYXNzZW1ibHkiLCJtZXRhZGF0YSI6e30sIm5hbWUiOm51bGwsInB1YmxpY19jb25uZWN0b3JzIjpbeyJjb21wb25lbnRfaWQiOiJjb21wb25lbnRfYSIsImNvbm5lY3Rvcl9pZCI6InBsYWNlbWVudCIsIm5hbWUiOm51bGwsInB1YmxpY19jb25uZWN0b3JfaWQiOiJwdWJsaWMifV19", "valid": true } ], @@ -1050,7 +1044,7 @@ "code": "connector_invalid", "path": "/entities/sha256-3ea2b1921b0c3ffc9684ba2ddcaa91f24a31ca1c6f037a09d31a0ea56d6fdb71.json/entities/6/connector_binding_status" }, - "manifest_base64": "eyJhbm5vdGF0aW9ucyI6W10sImFwcGVhcmFuY2VzIjpbeyJhbHBoYV9tb2RlIjoib3BhcXVlIiwiYXBwZWFyYW5jZV9pZCI6ImFwcGVhcmFuY2UvZXZhbHVhdGVkLzgxZjM4OWUyZThlMjcwYzllNGYwNzRlNDIxZTdiZTRhMGUxMDI2MTk2ZjVmZGVkODczMTkxZDlmOTFkYjA4NTIiLCJiYXNlX2NvbG9yIjpbMC43MiwwLjc1LDAuNzgsMV0sImRvdWJsZV9zaWRlZCI6ZmFsc2UsImVkZ2VfY29sb3IiOlswLjA4LDAuMDksMC4xLDFdLCJtZXRhbGxpYyI6MCw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JkZXIiOjAsInBhcmVudF9ub2RlX2lkIjoiaW5zdGFuY2Uvcm9vdC9zdWJhc3NlbWJseSIsInNka19tZXRhZGF0YSI6e30sInNlbGVjdGFibGUiOnRydWUsInNvdXJjZSI6eyJjb21wb25lbnRfcGF0aCI6WyJzdWJhc3NlbWJseSIsInBhcnQiXSwia2luZCI6InByb2R1Y3Rfb2NjdXJyZW5jZSIsInJvb3RfaWQiOiJyb290In0sInRyYW5zZm9ybSI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJ2aXNpYmxlIjp0cnVlfV0sInJldmlzaW9uIjoic2hhMjU2OmUwNDFhNjlmNmM4MWMyMmI3ZGFmNTE4ZDY1YzM0YTRkZWM4OTUzY2ZjMjVjY2M3MzU4NzdlMzIyZjJlMDA2N2MiLCJzY2VuZV9pZCI6Im5lc3RlZF9maXh0dXJlIiwic2NoZW1hX3ZlcnNpb24iOiIxLjAiLCJzb3VyY2UiOnsia2luZCI6Im1hbnVhbCIsInNvdXJjZV9pZCI6ImZpeHR1cmUifX0=", "name": "source_not_model_status_precedence", "valid": false }, @@ -1076,24 +1070,10 @@ ], "expected": { "code": "connector_invalid", - "path": "/connectors/1/local_transform" + "path": "/connectors/1/source_connector_snapshot_id" }, - "manifest_base64": "eyJhbm5vdGF0aW9ucyI6W10sImFwcGVhcmFuY2VzIjpbeyJhbHBoYV9tb2RlIjoib3BhcXVlIiwiYXBwZWFyYW5jZV9pZCI6ImFwcGVhcmFuY2UvZXZhbHVhdGVkLzgxZjM4OWUyZThlMjcwYzllNGYwNzRlNDIxZTdiZTRhMGUxMDI2MTk2ZjVmZGVkODczMTkxZDlmOTFkYjA4NTIiLCJiYXNlX2NvbG9yIjpbMC43MiwwLjc1LDAuNzgsMV0sImRvdWJsZV9zaWRlZCI6ZmFsc2UsImVkZ2VfY29sb3IiOlswLjA4LDAuMDksMC4xLDFdLC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pbiI6WzAsMCwwXSwieF9heGlzIjpbMSwwLDBdLCJ5X2F4aXMiOlswLDEsMF0sInpfYXhpcyI6WzAsMCwxXX0sInZpc2libGUiOnRydWV9LHsiYXBwZWFyYW5jZV9vdmVycmlkZV9pZCI6bnVsbCwiZGVmaW5pdGlvbl9pZCI6ImRlZmluaXRpb24vcm9vdC9wYXJ0L3NoYXJlZF9wYXJ0IiwibmFtZSI6InBhcnQiLCJub2RlX2lkIjoiaW5zdGFuY2Uvcm9vdC9zdWJhc3NlbWJseS9wYXJ0Iiwib3JkZXIiOjAsInBhcmVudF9ub2RlX2lkIjoiaW5zdGFuY2Uvcm9vdC9zdWJhc3NlbWJseSIsInNka19tZXRhZGF0YSI6e30sInNlbGVjdGFibGUiOnRydWUsInNvdXJjZSI6eyJjb21wb25lbnRfcGF0aCI6WyJzdWJhc3NlbWJseSIsInBhcnQiXSwia2luZCI6InByb2R1Y3Rfb2NjdXJyZW5jZSIsInJvb3RfaWQiOiJyb290In0sInRyYW5zZm9ybSI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJ2aXNpYmxlIjp0cnVlfV0sInJldmlzaW9uIjoic2hhMjU2OmU1ZmFjZTQ0MTQyZDQxNzdiZjFmZGNiYzA4ZDJiZjE1OGQwMWI5ZDBkYjk3OWViNDMzNThkMzEwMjJhZjUyOWIiLCJzY2VuZV9pZCI6Im5lc3RlZF9maXh0dXJlIiwic2NoZW1hX3ZlcnNpb24iOiIxLjAiLCJzb3VyY2UiOnsia2luZCI6Im1hbnVhbCIsInNvdXJjZV9pZCI6ImZpeHR1cmUifX0=", - "name": "forwarded_transform_mismatch", - "valid": false - }, - { - "blob_uris": [ - "edges/sha256-6ce481db1fe13bcfe7a2374423e6c72d757d51c99168b287c52f53aa625ccd67.glb", - "entities/sha256-ec65dbf3f594403b3969be03fb0047737db645cc3b473304b1403812bec5c2cb.json", - "geometry/sha256-200523414de281a8a155086a54cd0f880f640485765a48ccdd8ec230f67dd17c.glb" - ], - "expected": { - "code": "connector_invalid", - "path": "/connectors/1/forwarded_from" - }, - "manifest_base64": "eyJhbm5vdGF0aW9ucyI6W10sImFwcGVhcmFuY2VzIjpbeyJhbHBoYV9tb2RlIjoib3BhcXVlIiwiYXBwZWFyYW5jZV9pZCI6ImFwcGVhcmFuY2UvZXZhbHVhdGVkLzgxZjM4OWUyZThlMjcwYzllNGYwNzRlNDIxZTdiZTRhMGUxMDI2MTk2ZjVmZGVkODczMTkxZDlmOTFkYjA4NTIiLCJiYXNlX2NvbG9yIjpbMC43MiwwLjc1LDAuNzgsMV0sImRvdWJsZV9zaWRlZCI6ZmFsc2UsImVkZ2VfY29sb3IiOlswLjA4LDAuMDksMC4xLDFdLCJtZXRhbGxpYyI6MCwibmFtZSI6IkZpeHR1cmUgbWF0ZXJpYWwiLCJyb3VnaG5lc3MiOjAuNTUsInNka19tZXRhZGF0YSI6e30sInNvdXJjZSI6eyJraW5kIjoicHJvZHVjdF9tYXRlcmlhbCIsIm1hdGVyaWFsX2lkIjoiZml4dHVyZV9tYXRlcmlhbCIsInJvb3RfaWQiOiJyb290In19XSwiY2FtZXJhcyI6W10sImNvbXBpbGVfb3B0aW9ucyI6eyJhbmd1bGFyX3RvbGVyYW5jZSI6MC4yMiwiZW1iZWRfcHJlc2VudGF0aW9uIjpmYWxzZSwiZW1iZWRfc291cmNlIjpmYWxzZSwibGluZWFyX3RvbGVyYW5jZSI6MC4zNX0sImNvbm5lY3RvcnMiOlt7ImFuY2hvcl9raW5kIjoiZm9yd2FyZGVkIiwiY29ubmVjdG9yX2lkIjoibmVzdGVkX21vdW50IiwiY29ubmVjdG9yX3NuYXBzaG90X2lkIjoiY29ubmVjdG9yL3Jvb3QvYXNzZW1ibHkvbmVzdGVkX2Fzc2VtYmx5L25lc3RlZF9tb3VudCIsImZvcndhcmRlZF9mcm9tIjp7Im9mZnNldCI6bnVsbCwic291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VfaWQiOiJmaXh0dXJlIn19", + "name": "public_source_snapshot_missing", "valid": false }, { @@ -1106,8 +1086,8 @@ "code": "connector_invalid", "path": "/connectors/2/owner_definition_id" }, - "manifest_base64": "eyJhbm5vdGF0aW9ucyI6W10sImFwcGVhcmFuY2VzIjpbeyJhbHBoYV9tb2RlIjoib3BhcXVlIiwiYXBwZWFyYW5jZV9pZCI6ImFwcGVhcmFuY2UvZXZhbHVhdGVkLzgxZjM4OWUyZThlMjcwYzllNGYwNzRlNDIxZTdiZTRhMGUxMDI2MTk2ZjVmZGVkODczMTkxZDlmOTFkYjA4NTIiLCJiYXNlX2NvbG9yIjpbMC43MiwwLjc1LDAuNzgsMV0sImRvdWJsZV9zaWRlZCI6ZmFsc2UsImVkZ2VfY29sb3IiOlswLjA4LDAuMDksMC4xLDFdLCJtZXRhbGxpYyI6MCwibmFtZSI6IkZpeHR1cmUgbWF0ZXJpYWwiLCJyb3VnaG5lc3MiOjAuNTUsInNka19tZXRhZGF0YSI6e30sInNvdXJjZSI6eyJraW5kIjoicHJvZHVjdF9tYXRlcmlhbCIsIm1hdGVyaWFsX2lkIjoiZml4dHVyZV9tYXRlcmlhbCIsInJvb3RfaWQiOiJyb290In19XSwiY2FtZXJhcyI6W10sImNvbXBpbGVfb3B0aW9ucyI6eyJhbmd1bGFyX3RvbGVyYW5jZSI6MC4yMiwiZW1iZWRfcHJlc2VudGF0aW9uIjpmYWxzZSwiZW1iZWRfc291cmNlIjpmYWxzZSwibGluZWFyX3RvbGVyYW5jZSI6MC4zNX0sImNvbm5lY3RvcnMiOlt7ImFuY2hvcl9raW5kIjoiZm9yd2FyZGVkIiwiY29ubmVjdG9yX2lkIjoibmVzdGVkX21vdW50IiwiY29ubmVjdG9yX3NuYXBzaG90X2lkIjoiY29ubmVjdG9yL3Jvb3QvYXNzZW1ibHkvbmVzdGVkX2Fzc2VtYmx5L25lc3RlZF9tb3VudCIsImZvcndhcmRlZF9mcm9tIjp7Im9mZnNldCI6bnVsbCw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2543,16 +2523,16 @@ }, { "expected": null, - "name": "forwarded_connector_depth_exact_limit", + "name": "public_connector_depth_exact_limit", "operation": "resource_count", "parameters": { "artifact": "scene", "count": 2, "field": null, - "kind": "forwarded", + "kind": "public", "limits": { "connectors": 10, - "forwarded_connector_depth": 2 + "public_connector_depth": 2 } }, "valid": true @@ -2562,16 +2542,16 @@ "code": "resource_limit_exceeded", "path": "/connectors" }, - "name": "forwarded_connector_depth_over_limit", + "name": "public_connector_depth_over_limit", "operation": "resource_count", "parameters": { "artifact": "scene", "count": 3, "field": null, - "kind": "forwarded", + "kind": "public", "limits": { "connectors": 10, - "forwarded_connector_depth": 2 + "public_connector_depth": 2 } }, "valid": false @@ -3061,7 +3041,6 @@ "entities_per_sidecar": 500000, "entities_total": 2000000, "entity_json_bytes": 67108864, - "forwarded_connector_depth": 64, "hierarchy_depth": 256, "input_archive_bytes": 536870912, "json_depth": 64, @@ -3074,6 +3053,7 @@ "nodes": 100000, "one_member_bytes": 536870912, "presentation_json_bytes": 8388608, + "public_connector_depth": 64, "scene_json_bytes": 33554432, "static_decoded_buffer_bytes": 536870912, "structural_id_bytes": 4096, @@ -3094,11 +3074,11 @@ "sha256": "sha256:8637a4721af859fcd68ceff8522d79a6f101e29e6c8eab39fa74c9037ab15001" }, { - "canonical_base64": "eyJhbm5vdGF0aW9ucyI6W10sImFwcGVhcmFuY2VzIjpbeyJhbHBoYV9tb2RlIjoib3BhcXVlIiwiYXBwZWFyYW5jZV9pZCI6ImFwcGVhcmFuY2UvZXZhbHVhdGVkLzgxZjM4OWUyZThlMjcwYzllNGYwNzRlNDIxZTdiZTRhMGUxMDI2MTk2ZjVmZGVkODczMTkxZDlmOTFkYjA4NTIiLCJiYXNlX2NvbG9yIjpbMC43MiwwLjc1LDAuNzgsMV0sImRvdWJsZV9zaWRlZCI6ZmFsc2UsImVkZ2VfY29sb3IiOlswLjA4LDAuMDksMC4xLDFdLCJtZXRhbGxpYyI6MCwibmFtZSI6IkZpeHR1cmUg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In0sInRyYW5zZm9ybSI6eyJvcmlnaW4iOlswLDAsMF0sInhfYXhpcyI6WzEsMCwwXSwieV9heGlzIjpbMCwxLDBdLCJ6X2F4aXMiOlswLDAsMV19LCJ2aXNpYmxlIjp0cnVlfV0sInNjZW5lX2lkIjoibmVzdGVkX2ZpeHR1cmUiLCJzY2hlbWFfdmVyc2lvbiI6IjEuMCIsInNvdXJjZSI6eyJraW5kIjoibWFudWFsIiwic291cmNlX2lkIjoiZml4dHVyZSJ9fQ==", "name": "nested_assembly", - "revision": "sha256:e668afc126a3c7479f0f3bec0d1af1f883e23ee9a75d50a104ddb2d1abf70f2d", - "sha256": "sha256:a7ee380aead0a3b2e00e5d1c008af4ee1c62a93a5503fdc49d5a5a5b85a127ef" + "revision": "sha256:fc5f1f2fa970699ec9d1ba74c661c3f386b48c20551b83c14e2ef231993f3de2", + "sha256": "sha256:a0d1ae4a9fc6f2b55b24a9bc6088215eded47026c9f5ae3f9521b0bfd44578a7" }, { "canonical_base64": "eyJhbm5vdGF0aW9ucyI6W10sImFwcGVhcmFuY2VzIjpbeyJhbHBoYV9tb2RlIjoib3BhcXVlIiwiYXBwZWFyYW5jZV9pZCI6ImFwcGVhcmFuY2UvZXZhbHVhdGVkLzgxZjM4OWUyZThlMjcwYzllNGYwNzRlNDIxZTdiZTRhMGUxMDI2MTk2ZjVmZGVkODczMTkxZDlmOTFkYjA4NTIiLCJiYXNlX2NvbG9yIjpbMC43MiwwLjc1LDAuNzgsMV0sImRvdWJsZV9zaWRlZCI6ZmFsc2UsImVkZ2VfY29sb3IiOlswLjA4LDAuMDksMC4xLDFdLCJtZXRhbGxpYyI6MCwibmFtZSI6IkZpeHR1cmUgbWF0ZXJpYWwiLCJyb3VnaG5lc3MiOjAuNTUsInNka19tZXRhZGF0YSI6e30sInNvdXJjZSI6eyJraW5kIjoicHJvZHVjdF9tYXRlcmlhbCIsIm1hdGVyaWFsX2lkIjoiZml4dHVyZV9tYXRlcmlhbCIsInJvb3RfaWQiO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fV0sInJldmlzaW9uIjoic2hhMjU2OmZjNWYxZjJmYTk3MDY5OWVjOWQxYmE3NGM2NjFjM2YzODZiNDhjMjA1NTFiODNjMTRlMmVmMjMxOTkzZjNkZTIiLCJzY2VuZV9pZCI6Im5lc3RlZF9maXh0dXJlIiwic2NoZW1hX3ZlcnNpb24iOiIxLjAiLCJzb3VyY2UiOnsia2luZCI6Im1hbnVhbCIsInNvdXJjZV9pZCI6ImZpeHR1cmUifX0=", "name": "nested_assembly", "valid": true }, @@ -5622,6 +5602,19 @@ "name": "optional_embedded_artifact_byte_length_present", "valid": false }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "source_files" + ], + "value": [] + } + ], + "name": "optional_source_files_present", + "valid": false + }, { "mutations": [ { @@ -5637,6 +5630,13 @@ "embedded_artifact_byte_length" ], "value": 0 + }, + { + "operation": "set", + "path": [ + "source_files" + ], + "value": [] } ], "name": "optional_fields_all_present", @@ -5646,6 +5646,256 @@ "schema_pointer": "#/$defs/modelSource", "variant": "base" }, + { + "artifact": "scene", + "base": { + "artifact_hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "definition_id": "a", + "kind": "part_package", + "revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "kind" + ] + } + ], + "name": "missing_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "definition_id" + ] + } + ], + "name": "missing_definition_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "revision" + ] + } + ], + "name": "missing_revision", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "artifact_hash" + ] + } + ], + "name": "missing_artifact_hash", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/productPackageSource", + "variant": "kind=part_package" + }, + { + "artifact": "scene", + "base": { + "artifact_hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "definition_id": "a", + "kind": "assembly_package", + "revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "kind" + ] + } + ], + "name": "missing_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "definition_id" + ] + } + ], + "name": "missing_definition_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "revision" + ] + } + ], + "name": "missing_revision", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "artifact_hash" + ] + } + ], + "name": "missing_artifact_hash", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/productPackageSource", + "variant": "kind=assembly_package" + }, + { + "artifact": "scene", + "base": { + "byte_length": 0, + "content_hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "media_type": "text/x-python; charset=utf-8", + "path": "model.py", + "uri": "a" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "path" + ] + } + ], + "name": "missing_path", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "uri" + ] + } + ], + "name": "missing_uri", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "media_type" + ] + } + ], + "name": "missing_media_type", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "byte_length" + ] + } + ], + "name": "missing_byte_length", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "content_hash" + ] + } + ], + "name": "missing_content_hash", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/sourceFile", + "variant": "base" + }, { "artifact": "scene", "base": { @@ -6462,6 +6712,216 @@ "schema_pointer": "#/$defs/productManualSource", "variant": "semantic_type=Assembly" }, + { + "artifact": "scene", + "base": { + "kind": "product_package", + "package_kind": "part_package", + "package_revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "root_id": "a", + "semantic_id": "a", + "semantic_type": "Part" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "kind" + ] + } + ], + "name": "missing_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "root_id" + ] + } + ], + "name": "missing_root_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "semantic_type" + ] + } + ], + "name": "missing_semantic_type", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "semantic_id" + ] + } + ], + "name": "missing_semantic_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_kind" + ] + } + ], + "name": "missing_package_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_revision" + ] + } + ], + "name": "missing_package_revision", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/productPackageDefinitionSource", + "variant": "semantic_type=Part" + }, + { + "artifact": "scene", + "base": { + "kind": "product_package", + "package_kind": "part_package", + "package_revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "root_id": "a", + "semantic_id": "a", + "semantic_type": "Assembly" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "kind" + ] + } + ], + "name": "missing_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "root_id" + ] + } + ], + "name": "missing_root_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "semantic_type" + ] + } + ], + "name": "missing_semantic_type", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "semantic_id" + ] + } + ], + "name": "missing_semantic_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_kind" + ] + } + ], + "name": "missing_package_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_revision" + ] + } + ], + "name": "missing_package_revision", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/productPackageDefinitionSource", + "variant": "semantic_type=Assembly" + }, { "artifact": "scene", "base": { @@ -8511,6 +8971,164 @@ "schema_pointer": "#/$defs/manualConnectorSource", "variant": "base" }, + { + "artifact": "scene", + "base": { + "definition_id": "a", + "kind": "product_package", + "package_kind": "part_package", + "package_revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "kind" + ] + } + ], + "name": "missing_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_kind" + ] + } + ], + "name": "missing_package_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_revision" + ] + } + ], + "name": "missing_package_revision", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "definition_id" + ] + } + ], + "name": "missing_definition_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/productPackageConnectorSource", + "variant": "package_kind=part_package" + }, + { + "artifact": "scene", + "base": { + "definition_id": "a", + "kind": "product_package", + "package_kind": "assembly_package", + "package_revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "kind" + ] + } + ], + "name": "missing_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_kind" + ] + } + ], + "name": "missing_package_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_revision" + ] + } + ], + "name": "missing_package_revision", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "definition_id" + ] + } + ], + "name": "missing_definition_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/productPackageConnectorSource", + "variant": "package_kind=assembly_package" + }, { "artifact": "scene", "base": { @@ -8564,132 +9182,6 @@ "schema_pointer": "#/$defs/connectorTarget", "variant": "base" }, - { - "artifact": "scene", - "base": { - "offset": null, - "source_component_id": "a", - "source_connector_id": "a", - "source_connector_snapshot_id": "a", - "source_definition_id": "a" - }, - "cases": [ - { - "mutations": [], - "name": "base_valid", - "valid": true - }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "source_component_id" - ] - } - ], - "name": "missing_source_component_id", - "valid": false - }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "source_definition_id" - ] - } - ], - "name": "missing_source_definition_id", - "valid": false - }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "source_connector_id" - ] - } - ], - "name": "missing_source_connector_id", - "valid": false - }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "source_connector_snapshot_id" - ] - } - ], - "name": "missing_source_connector_snapshot_id", - "valid": false - }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "offset" - ] - } - ], - "name": "missing_offset", - "valid": false - }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "unknown" - ], - "value": true - } - ], - "name": "unknown_field", - "valid": false - }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "offset" - ], - "value": { - "origin": [ - 0, - 0, - 0 - ], - "x_axis": [ - 0, - 0, - 0 - ], - "y_axis": [ - 0, - 0, - 0 - ], - "z_axis": [ - 0, - 0, - 0 - ] - } - } - ], - "name": "nullable_offset_nonnull", - "valid": true - } - ], - "schema_pointer": "#/$defs/forwardedFrom", - "variant": "base" - }, { "artifact": "scene", "base": { @@ -8722,6 +9214,7 @@ "owner_definition_id": "a", "sdk_metadata": {}, "source": null, + "source_connector_snapshot_id": null, "target": { "entity_asset_id": "sha256:0000000000000000000000000000000000000000000000000000000000000000", "entity_id": "entity/face/0" @@ -8805,6 +9298,18 @@ "name": "missing_local_transform", "valid": false }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "source_connector_snapshot_id" + ] + } + ], + "name": "missing_source_connector_snapshot_id", + "valid": false + }, { "mutations": [ { @@ -8854,44 +9359,6 @@ "name": "unknown_field", "valid": false }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "forwarded_from" - ], - "value": { - "offset": null, - "source_component_id": "a", - "source_connector_id": "a", - "source_connector_snapshot_id": "a", - "source_definition_id": "a" - } - } - ], - "name": "optional_forwarded_from_present", - "valid": false - }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "forwarded_from" - ], - "value": { - "offset": null, - "source_component_id": "a", - "source_connector_id": "a", - "source_connector_snapshot_id": "a", - "source_definition_id": "a" - } - } - ], - "name": "optional_fields_all_present", - "valid": false - }, { "mutations": [ { @@ -8905,6 +9372,19 @@ "name": "nullable_name_nonnull", "valid": true }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "source_connector_snapshot_id" + ], + "value": "a" + } + ], + "name": "nullable_source_connector_snapshot_id_nonnull", + "valid": false + }, { "mutations": [ { @@ -8958,7 +9438,8 @@ "name": null, "owner_definition_id": "a", "sdk_metadata": {}, - "source": null + "source": null, + "source_connector_snapshot_id": null }, "cases": [ { @@ -9038,6 +9519,18 @@ "name": "missing_local_transform", "valid": false }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "source_connector_snapshot_id" + ] + } + ], + "name": "missing_source_connector_snapshot_id", + "valid": false + }, { "mutations": [ { @@ -9091,25 +9584,6 @@ "name": "optional_target_present", "valid": false }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "forwarded_from" - ], - "value": { - "offset": null, - "source_component_id": "a", - "source_connector_id": "a", - "source_connector_snapshot_id": "a", - "source_definition_id": "a" - } - } - ], - "name": "optional_forwarded_from_present", - "valid": false - }, { "mutations": [ { @@ -9121,19 +9595,6 @@ "entity_asset_id": "sha256:0000000000000000000000000000000000000000000000000000000000000000", "entity_id": "entity/face/0" } - }, - { - "operation": "set", - "path": [ - "forwarded_from" - ], - "value": { - "offset": null, - "source_component_id": "a", - "source_connector_id": "a", - "source_connector_snapshot_id": "a", - "source_definition_id": "a" - } } ], "name": "optional_fields_all_present", @@ -9152,6 +9613,19 @@ "name": "nullable_name_nonnull", "valid": true }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "source_connector_snapshot_id" + ], + "value": "a" + } + ], + "name": "nullable_source_connector_snapshot_id_nonnull", + "valid": false + }, { "mutations": [ { @@ -9177,16 +9651,9 @@ { "artifact": "scene", "base": { - "anchor_kind": "forwarded", + "anchor_kind": "public", "connector_id": "a", "connector_snapshot_id": "a", - "forwarded_from": { - "offset": null, - "source_component_id": "a", - "source_connector_id": "a", - "source_connector_snapshot_id": "a", - "source_definition_id": "a" - }, "local_transform": { "origin": [ 0, @@ -9212,7 +9679,8 @@ "name": null, "owner_definition_id": "a", "sdk_metadata": {}, - "source": null + "source": null, + "source_connector_snapshot_id": null }, "cases": [ { @@ -9292,6 +9760,18 @@ "name": "missing_local_transform", "valid": false }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "source_connector_snapshot_id" + ] + } + ], + "name": "missing_source_connector_snapshot_id", + "valid": false + }, { "mutations": [ { @@ -9316,18 +9796,6 @@ "name": "missing_sdk_metadata", "valid": false }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "forwarded_from" - ] - } - ], - "name": "missing_forwarded_from", - "valid": false - }, { "mutations": [ { @@ -9386,6 +9854,19 @@ "name": "nullable_name_nonnull", "valid": true }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "source_connector_snapshot_id" + ], + "value": "a" + } + ], + "name": "nullable_source_connector_snapshot_id_nonnull", + "valid": true + }, { "mutations": [ { @@ -9406,7 +9887,7 @@ } ], "schema_pointer": "#/$defs/connector", - "variant": "anchor_kind=forwarded" + "variant": "anchor_kind=public" }, { "artifact": "scene", @@ -10776,6 +11257,164 @@ "schema_pointer": "#/$defs/modelTopology", "variant": "topology_kind=VERTEX" }, + { + "artifact": "entities", + "base": { + "definition_id": "a", + "kind": "package_geometry", + "package_kind": "part_package", + "package_revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "kind" + ] + } + ], + "name": "missing_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_kind" + ] + } + ], + "name": "missing_package_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_revision" + ] + } + ], + "name": "missing_package_revision", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "definition_id" + ] + } + ], + "name": "missing_definition_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/packageGeometry", + "variant": "package_kind=part_package" + }, + { + "artifact": "entities", + "base": { + "definition_id": "a", + "kind": "package_geometry", + "package_kind": "assembly_package", + "package_revision": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + }, + "cases": [ + { + "mutations": [], + "name": "base_valid", + "valid": true + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "kind" + ] + } + ], + "name": "missing_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_kind" + ] + } + ], + "name": "missing_package_kind", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "package_revision" + ] + } + ], + "name": "missing_package_revision", + "valid": false + }, + { + "mutations": [ + { + "operation": "delete", + "path": [ + "definition_id" + ] + } + ], + "name": "missing_definition_id", + "valid": false + }, + { + "mutations": [ + { + "operation": "set", + "path": [ + "unknown" + ], + "value": true + } + ], + "name": "unknown_field", + "valid": false + } + ], + "schema_pointer": "#/$defs/packageGeometry", + "variant": "package_kind=assembly_package" + }, { "artifact": "entities", "base": { @@ -16317,10 +16956,10 @@ { "artifact": "normalized_product", "base": { - "anchor_kind": "forwarded", - "offset": null, - "source_component_id": "a", - "source_connector_id": "a" + "component_id": "a", + "connector_id": "a", + "name": null, + "public_connector_id": "a" }, "cases": [ { @@ -16333,11 +16972,11 @@ { "operation": "delete", "path": [ - "anchor_kind" + "public_connector_id" ] } ], - "name": "missing_anchor_kind", + "name": "missing_public_connector_id", "valid": false }, { @@ -16345,11 +16984,11 @@ { "operation": "delete", "path": [ - "source_component_id" + "component_id" ] } ], - "name": "missing_source_component_id", + "name": "missing_component_id", "valid": false }, { @@ -16357,11 +16996,11 @@ { "operation": "delete", "path": [ - "source_connector_id" + "connector_id" ] } ], - "name": "missing_source_connector_id", + "name": "missing_connector_id", "valid": false }, { @@ -16369,11 +17008,11 @@ { "operation": "delete", "path": [ - "offset" + "name" ] } ], - "name": "missing_offset", + "name": "missing_name", "valid": false }, { @@ -16394,37 +17033,16 @@ { "operation": "set", "path": [ - "offset" + "name" ], - "value": { - "origin": [ - 0, - 0, - 0 - ], - "x_axis": [ - 0, - 0, - 0 - ], - "y_axis": [ - 0, - 0, - 0 - ], - "z_axis": [ - 0, - 0, - 0 - ] - } + "value": "a" } ], - "name": "nullable_offset_nonnull", + "name": "nullable_name_nonnull", "valid": true } ], - "schema_pointer": "#/$defs/forwardedAnchor", + "schema_pointer": "#/$defs/publicConnector", "variant": "base" }, { @@ -16674,116 +17292,6 @@ "schema_pointer": "#/$defs/connector", "variant": "anchor=placement" }, - { - "artifact": "normalized_product", - "base": { - "anchor": { - "anchor_kind": "forwarded", - "offset": null, - "source_component_id": "a", - "source_connector_id": "a" - }, - "connector_id": "a", - "name": null - }, - "cases": [ - { - "mutations": [], - "name": "base_valid", - "valid": true - }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "connector_id" - ] - } - ], - "name": "missing_connector_id", - "valid": false - }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "name" - ] - } - ], - "name": "missing_name", - "valid": false - }, - { - "mutations": [ - { - "operation": "delete", - "path": [ - "anchor" - ] - } - ], - "name": "missing_anchor", - "valid": false - }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "unknown" - ], - "value": true - } - ], - "name": "unknown_field", - "valid": false - }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "geometry_ref" - ], - "value": null - } - ], - "name": "optional_geometry_ref_present", - "valid": false - }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "geometry_ref" - ], - "value": null - } - ], - "name": "optional_fields_all_present", - "valid": false - }, - { - "mutations": [ - { - "operation": "set", - "path": [ - "name" - ], - "value": "a" - } - ], - "name": "nullable_name_nonnull", - "valid": true - } - ], - "schema_pointer": "#/$defs/connector", - "variant": "anchor=forwarded" - }, { "artifact": "normalized_product", "base": { @@ -19426,12 +19934,12 @@ "base": { "assembly_id": "a", "components": [], - "connectors": [], "constraints": [], "grounded_component_ids": [], "kind": "assembly", "metadata": {}, - "name": null + "name": null, + "public_connectors": [] }, "cases": [ { @@ -19492,11 +20000,11 @@ { "operation": "delete", "path": [ - "connectors" + "public_connectors" ] } ], - "name": "missing_connectors", + "name": "missing_public_connectors", "valid": false }, { diff --git a/test/test_artifact_contract.py b/test/test_artifact_contract.py index 383aec3a..98b059da 100644 --- a/test/test_artifact_contract.py +++ b/test/test_artifact_contract.py @@ -18,7 +18,7 @@ from simplecadapi.artifacts.feature_graph import ( encode_feature_graph_artifact, ) from simplecadapi.artifacts.part_definition import PartDefinition -from simplecadapi.artifacts.references import BlobRef, InterfaceHashes +from simplecadapi.artifacts.references import BlobRef, ConnectorInterface, InterfaceHashes from simplecadapi.artifacts.validation import ( parse_artifact_json, validate_artifact_blobs, @@ -122,6 +122,22 @@ def _assembly_definition(): ) +def test_connector_interface_hash_includes_public_name() -> None: + common = { + "connector_id": "output_axis", + "anchor_kind": "public", + "local_frame": scad.identity_placement_rplacement().to_dict(), + "binding": None, + "source_component_id": "rotor", + "source_connector_id": "axis", + } + + unnamed = ConnectorInterface(name=None, **common) + named = ConnectorInterface(name="Output axis", **common) + + assert named.interface_hash != unnamed.interface_hash + + def test_part_definition_canonical_roundtrip_and_blob_validation(): definition = _part_definition() parsed = parse_artifact_json(definition.canonical_bytes, kind="part_definition") diff --git a/test/test_assembly_builder.py b/test/test_assembly_builder.py index 2ff8cf3c..ea6a463c 100644 --- a/test/test_assembly_builder.py +++ b/test/test_assembly_builder.py @@ -115,9 +115,9 @@ def _build_nested_gear_train(tmp_path: Path): pitch_radius_b=8.0, ) assembly = scad.solve_assembly_constraints_rassembly(assembly=assembly) - return scad.forward_connector_rassembly( + return scad.set_public_connector_rassembly( assembly=assembly, - connector_id="output_axis", + public_connector_id="output_axis", source_component_id="gear_b", source_connector_id="axis", ) @@ -142,9 +142,9 @@ def _build_nested_gear_train(tmp_path: Path): component_id="train_right", placement=scad.make_placement_rplacement(origin=(50.0, 0.0, 0.0)), ) - return scad.forward_connector_rassembly( + return scad.set_public_connector_rassembly( assembly=assembly, - connector_id="service_axis", + public_connector_id="service_axis", source_component_id="train_right", source_connector_id="output_axis", ) @@ -178,7 +178,7 @@ def test_assemble_external_reference_round_trip_preserves_hierarchy_and_coupling assert loaded.canonical_bytes == pair.definition.canonical_bytes assert isinstance(rebuilt, scad.Assembly) assert rebuilt.component_ids() == ("train_left", "train_right") - assert rebuilt.connector_ids() == ("service_axis",) + assert rebuilt.public_connector_ids() == ("service_axis",) left = rebuilt.get_component("train_left").item right = rebuilt.get_component("train_right").item assert left is right @@ -289,17 +289,18 @@ def test_nested_occurrence_placements_survive_materialization_and_replay( component_id="inner_ring", connector_id="axis", ), - drive_angle_degrees=None, + drive_angle_degrees=90.0, ) - assembly = scad.forward_connector_rassembly( + assembly = scad.solve_assembly_constraints_rassembly(assembly=assembly) + assembly = scad.set_public_connector_rassembly( assembly=assembly, - connector_id="outer_axis", + public_connector_id="outer_axis", source_component_id="outer_ring", source_connector_id="axis", ) - return scad.forward_connector_rassembly( + return scad.set_public_connector_rassembly( assembly=assembly, - connector_id="inner_axis", + public_connector_id="inner_axis", source_component_id="inner_ring", source_connector_id="axis", ) @@ -380,11 +381,9 @@ def test_nested_occurrence_placements_survive_materialization_and_replay( for record in fixture.definition.solved_snapshot["occurrence_placements"] } - assert occurrence_placements[("bearing", "inner_ring")]["x_axis"] == [ - 0.0, - 1.0, - 0.0, - ] + assert occurrence_placements[("bearing", "inner_ring")]["x_axis"] == pytest.approx( + quarter_turn.x_axis + ) for restored in ( fixture.value, @@ -676,7 +675,7 @@ def test_assemble_reuses_independent_constraint_components(tmp_path: Path) -> No assert scad.inspect_assembly_constraints_rconstraintreport(changed.value).solved -def test_nested_forwarded_connector_change_invalidates_parent_component( +def test_nested_public_connector_change_invalidates_parent_component( tmp_path: Path, ) -> None: policy = _policy(tmp_path / "cache") @@ -709,7 +708,7 @@ def test_nested_forwarded_connector_change_invalidates_parent_component( "child", scad.identity_placement_rplacement(), ) - return scad.forward_connector_rassembly( + return scad.set_public_connector_rassembly( assembly, "output", "child", diff --git a/test/test_part_interface.py b/test/test_part_interface.py index d975d57f..5cfc9f89 100644 --- a/test/test_part_interface.py +++ b/test/test_part_interface.py @@ -22,7 +22,6 @@ def _connector( anchor_kind="geometry" if binding is not None else "placement", local_frame=scad.make_placement_rplacement(origin=origin).to_dict(), binding=binding, - forwarded_from=None, ) diff --git a/test/test_product_assembly.py b/test/test_product_assembly.py index a09971fe..e6ff4b7a 100644 --- a/test/test_product_assembly.py +++ b/test/test_product_assembly.py @@ -48,8 +48,7 @@ def test_product_and_constraint_public_apis_do_not_use_bare_star_parameters(): scad.make_vertex_connector_rconnector, scad.make_placement_connector_rconnector, scad.add_connector_rpart, - scad.add_connector_rassembly, - scad.forward_connector_rassembly, + scad.set_public_connector_rassembly, scad.make_connector_ref_rconnectorref, scad.make_scalar_limit_rscalarlimit, scad.ground_component_rassembly, @@ -120,9 +119,13 @@ def test_assembly_components_reuse_part_and_project_to_compound(): compound = scad.make_compound_from_assembly_rcompound(assembly) assert isinstance(compound, scad.Compound) assert len(compound.get_solids()) == 2 - assert math.isclose(compound.get_volume(), 2.0 * bolt_body.get_volume(), rel_tol=1e-7) + assert math.isclose( + compound.get_volume(), 2.0 * bolt_body.get_volume(), rel_tol=1e-7 + ) - face_centers_x = sorted(round(face.get_center().x, 1) for face in ql.faces().resolve(compound)) + face_centers_x = sorted( + round(face.get_center().x, 1) for face in ql.faces().resolve(compound) + ) assert face_centers_x[0] < 0.0 assert face_centers_x[-1] > 0.0 @@ -146,7 +149,9 @@ def test_nested_assembly_projection_composes_component_placements(): ) compound = scad.make_compound_from_assembly_rcompound(root) - face_centers_x = sorted(round(face.get_center().x, 1) for face in ql.faces().resolve(compound)) + face_centers_x = sorted( + round(face.get_center().x, 1) for face in ql.faces().resolve(compound) + ) assert len(compound.get_solids()) == 1 assert face_centers_x[0] >= 11.5 @@ -195,30 +200,33 @@ def test_placement_connector_can_drive_fixed_constraints(): solved = scad.solve_assembly_constraints_rassembly(assembly) assert solved.get_component("follower").placement.origin == (1.0, 2.0, 3.0) - assert scad.measure_constraint_residual_rconstraintresidual(solved, "fixed").within_tolerance + assert scad.measure_constraint_residual_rconstraintresidual( + solved, "fixed" + ).within_tolerance -def test_forwarded_connector_resolves_and_solves_at_parent_level(): - inner_part = _part_with_placement_connector("forwarded_inner_part", (2.0, 0.0, 0.0)) - base_part = _part_with_placement_connector("forwarded_base_part") - child = scad.make_assembly_rassembly("forwarded_child") +def test_public_connector_resolves_and_solves_at_parent_level(): + inner_part = _part_with_placement_connector("public_inner_part", (2.0, 0.0, 0.0)) + base_part = _part_with_placement_connector("public_base_part") + child = scad.make_assembly_rassembly("public_child") child = scad.add_component_rassembly( child, inner_part, component_id="inner", placement=scad.make_placement_rplacement(origin=(5.0, 0.0, 0.0)), ) - child = scad.forward_connector_rassembly( + child = scad.set_public_connector_rassembly( child, - connector_id="public_axis", + public_connector_id="public_axis", source_component_id="inner", source_connector_id="axis", ) - assert child.connector_ids() == ("public_axis",) - assert child.get_connector("public_axis").placement.origin == (7.0, 0.0, 0.0) + assert child.public_connector_ids() == ("public_axis",) + public = child.get_public_connector("public_axis") + assert (public.component_id, public.connector_id) == ("inner", "axis") - root = scad.make_assembly_rassembly("forwarded_root") + root = scad.make_assembly_rassembly("public_root") root = scad.add_component_rassembly( root, base_part, @@ -234,7 +242,7 @@ def test_forwarded_connector_resolves_and_solves_at_parent_level(): root = scad.ground_component_rassembly(root, "base") root = scad.add_fixed_constraint_rassembly( root, - "bind_forwarded_axis", + "bind_public_axis", scad.make_connector_ref_rconnectorref("base", "axis"), scad.make_connector_ref_rconnectorref("child", "public_axis"), ) @@ -243,11 +251,11 @@ def test_forwarded_connector_resolves_and_solves_at_parent_level(): assert solved.get_component("child").placement.origin == (3.0, 0.0, 0.0) assert scad.measure_constraint_residual_rconstraintresidual( solved, - "bind_forwarded_axis", + "bind_public_axis", ).within_tolerance -def test_forwarded_connectors_close_nested_revolute_between_fixed_interfaces(): +def test_public_connectors_close_nested_revolute_between_fixed_interfaces(): ring = _part_with_placement_connector("nested_bearing_ring") bearing = scad.make_assembly_rassembly("nested_bearing") bearing = scad.add_component_rassembly( @@ -270,13 +278,13 @@ def test_forwarded_connectors_close_nested_revolute_between_fixed_interfaces(): scad.make_connector_ref_rconnectorref("inner_ring", "axis"), drive_angle_degrees=None, ) - bearing = scad.forward_connector_rassembly( + bearing = scad.set_public_connector_rassembly( bearing, "outer_axis", "outer_ring", "axis", ) - bearing = scad.forward_connector_rassembly( + bearing = scad.set_public_connector_rassembly( bearing, "inner_axis", "inner_ring", @@ -322,25 +330,17 @@ def test_forwarded_connectors_close_nested_revolute_between_fixed_interfaces(): scad.make_connector_ref_rconnectorref("bearing", "inner_axis"), ) - solved = scad.solve_assembly_constraints_rassembly(root) - solved_bearing = solved.get_component("bearing").item - - assert isinstance(solved_bearing, scad.Assembly) - assert solved_bearing.get_component("outer_ring").placement.origin == (0.0, 0.0, 0.0) - assert solved_bearing.get_component("inner_ring").placement.x_axis == pytest.approx( - quarter_turn.x_axis - ) - assert scad.inspect_assembly_constraints_rconstraintreport(solved_bearing).solved - assert scad.inspect_assembly_constraints_rconstraintreport(solved).solved + with pytest.raises(Exception, match="residual exceeds tolerance"): + scad.solve_assembly_constraints_rassembly(root) -def test_forwarded_connector_validation_reports_missing_sources(): - assembly = scad.make_assembly_rassembly("bad_forwarded_connector_asm") +def test_public_connector_validation_reports_missing_sources(): + assembly = scad.make_assembly_rassembly("bad_public_connector_asm") with pytest.raises(Exception, match="missing component"): - scad.forward_connector_rassembly( + scad.set_public_connector_rassembly( assembly, - connector_id="public_axis", + public_connector_id="public_axis", source_component_id="inner", source_connector_id="axis", ) @@ -401,8 +401,12 @@ def test_fixed_revolute_and_prismatic_constraints_solve_component_placements(): assert math.isclose(arm_placement.origin[0], 0.0, abs_tol=1e-12) assert math.isclose(arm_placement.origin[1], 0.0, abs_tol=1e-12) assert math.isclose(arm_placement.origin[2], 0.0, abs_tol=1e-12) - assert math.isclose(revolute_solved.get_component("arm").placement.x_axis[0], 0.0, abs_tol=1e-10) - assert math.isclose(revolute_solved.get_component("arm").placement.x_axis[1], 1.0, abs_tol=1e-10) + assert math.isclose( + revolute_solved.get_component("arm").placement.x_axis[0], 0.0, abs_tol=1e-10 + ) + assert math.isclose( + revolute_solved.get_component("arm").placement.x_axis[1], 1.0, abs_tol=1e-10 + ) prismatic_assembly = scad.make_assembly_rassembly("prismatic_asm") prismatic_assembly = scad.add_component_rassembly( @@ -451,7 +455,8 @@ def test_constraint_validation_rejects_missing_refs_and_limit_violations(): assembly_with_limit = scad.ground_component_rassembly(assembly, "base") assembly_with_limit = scad.add_prismatic_constraint_rassembly( - assembly_with_limit, "slide", + assembly_with_limit, + "slide", connector_a, connector_b, drive_distance=10.0, @@ -471,13 +476,20 @@ def test_constraint_validation_rejects_missing_refs_and_limit_violations(): with pytest.raises(Exception, match="grounded"): ungrounded = scad.make_assembly_rassembly("ungrounded_asm") ungrounded = scad.add_component_rassembly( - ungrounded, part, component_id="base", placement=scad.identity_placement_rplacement(), + ungrounded, + part, + component_id="base", + placement=scad.identity_placement_rplacement(), ) ungrounded = scad.add_component_rassembly( - ungrounded, part, component_id="slider", placement=scad.identity_placement_rplacement(), + ungrounded, + part, + component_id="slider", + placement=scad.identity_placement_rplacement(), ) ungrounded = scad.add_prismatic_constraint_rassembly( - ungrounded, "slide_ungrounded", + ungrounded, + "slide_ungrounded", scad.make_connector_ref_rconnectorref("base", "axis"), scad.make_connector_ref_rconnectorref("slider", "axis"), drive_distance=1.0, @@ -637,10 +649,7 @@ def test_boolean_named_face_connector_resolves_after_replay(): ), ) named_face = ( - ql.faces() - .where(ql.tag("cap.face.end")) - .exactly(1) - .resolve(result)[0] + ql.faces().where(ql.tag("cap.face.end")).exactly(1).resolve(result)[0] ) connector = scad.make_face_connector_rconnector("mount", named_face) part = scad.add_connector_rpart( @@ -652,10 +661,7 @@ def test_boolean_named_face_connector_resolves_after_replay(): replayed = scad.replay_model_json(scad.export_model_json(session))[0] assert isinstance(replayed, scad.Part) replayed_face = ( - ql.faces() - .where(ql.tag("cap.face.end")) - .exactly(1) - .resolve(replayed.body)[0] + ql.faces().where(ql.tag("cap.face.end")).exactly(1).resolve(replayed.body)[0] ) assert replayed.get_connector("mount").placement.origin == pytest.approx( tuple(replayed_face.get_center()) @@ -759,14 +765,21 @@ def test_limit_aware_prismatic_tree_clamps_scalar_to_bounds(): part = _part_with_face_connector("clamp_part") assembly = scad.make_assembly_rassembly("clamp_asm") assembly = scad.add_component_rassembly( - assembly, part, component_id="base", placement=scad.identity_placement_rplacement(), + assembly, + part, + component_id="base", + placement=scad.identity_placement_rplacement(), ) assembly = scad.add_component_rassembly( - assembly, part, component_id="slider", placement=scad.identity_placement_rplacement(), + assembly, + part, + component_id="slider", + placement=scad.identity_placement_rplacement(), ) assembly = scad.ground_component_rassembly(assembly, "base") assembly = scad.add_prismatic_constraint_rassembly( - assembly, "slide", + assembly, + "slide", scad.make_connector_ref_rconnectorref("base", "axis"), scad.make_connector_ref_rconnectorref("slider", "axis"), drive_distance=100.0, @@ -782,14 +795,21 @@ def test_limit_aware_prismatic_tree_uses_drive_when_within_bounds(): part = _part_with_face_connector("inrange_part") assembly = scad.make_assembly_rassembly("inrange_asm") assembly = scad.add_component_rassembly( - assembly, part, component_id="base", placement=scad.identity_placement_rplacement(), + assembly, + part, + component_id="base", + placement=scad.identity_placement_rplacement(), ) assembly = scad.add_component_rassembly( - assembly, part, component_id="slider", placement=scad.identity_placement_rplacement(), + assembly, + part, + component_id="slider", + placement=scad.identity_placement_rplacement(), ) assembly = scad.ground_component_rassembly(assembly, "base") assembly = scad.add_prismatic_constraint_rassembly( - assembly, "slide", + assembly, + "slide", scad.make_connector_ref_rconnectorref("base", "axis"), scad.make_connector_ref_rconnectorref("slider", "axis"), drive_distance=3.0, @@ -803,14 +823,21 @@ def test_limit_aware_revolute_tree_clamps_angle_to_bounds(): part = _part_with_face_connector("rev_clamp_part") assembly = scad.make_assembly_rassembly("rev_clamp_asm") assembly = scad.add_component_rassembly( - assembly, part, component_id="base", placement=scad.identity_placement_rplacement(), + assembly, + part, + component_id="base", + placement=scad.identity_placement_rplacement(), ) assembly = scad.add_component_rassembly( - assembly, part, component_id="arm", placement=scad.identity_placement_rplacement(), + assembly, + part, + component_id="arm", + placement=scad.identity_placement_rplacement(), ) assembly = scad.ground_component_rassembly(assembly, "base") assembly = scad.add_revolute_constraint_rassembly( - assembly, "hinge", + assembly, + "hinge", scad.make_connector_ref_rconnectorref("base", "axis"), scad.make_connector_ref_rconnectorref("arm", "axis"), drive_angle_degrees=999.0, @@ -829,19 +856,25 @@ def test_limit_aware_revolute_loop_finds_optimal_angle(): part_b = _part_with_face_connector("loop_b") assembly = scad.make_assembly_rassembly("rev_loop") assembly = scad.add_component_rassembly( - assembly, part_a, component_id="link1", + assembly, + part_a, + component_id="link1", placement=scad.make_placement_rplacement(origin=(5.0, 0.0, 0.0)), ) assembly = scad.add_component_rassembly( - assembly, part_b, component_id="link2", + assembly, + part_b, + component_id="link2", placement=scad.identity_placement_rplacement(), ) assembly = scad.ground_component_rassembly(assembly, "link1") connector_a = scad.make_connector_ref_rconnectorref("link1", "axis") connector_b = scad.make_connector_ref_rconnectorref("link2", "axis") assembly = scad.add_revolute_constraint_rassembly( - assembly, "hinge", - connector_a, connector_b, + assembly, + "hinge", + connector_a, + connector_b, angle_limit=scad.make_scalar_limit_rscalarlimit(0.0, 90.0), ) solved = scad.solve_assembly_constraints_rassembly(assembly, strict=False) @@ -869,10 +902,17 @@ def test_gear_and_belt_constraints_couple_revolute_support_joints(): ) gear_assembly = scad.ground_component_rassembly(gear_assembly, "base") gear_assembly = scad.add_revolute_constraint_rassembly( - gear_assembly, "drive_a", base_ref, gear_a_ref, drive_angle_degrees=90.0, + gear_assembly, + "drive_a", + base_ref, + gear_a_ref, + drive_angle_degrees=90.0, ) gear_assembly = scad.add_revolute_constraint_rassembly( - gear_assembly, "free_b", base_ref, gear_b_ref, + gear_assembly, + "free_b", + base_ref, + gear_b_ref, ) gear_assembly = scad.add_gear_constraint_rassembly( gear_assembly, @@ -902,10 +942,17 @@ def test_gear_and_belt_constraints_couple_revolute_support_joints(): ) belt_assembly = scad.ground_component_rassembly(belt_assembly, "base") belt_assembly = scad.add_revolute_constraint_rassembly( - belt_assembly, "drive_a", base_ref, gear_a_ref, drive_angle_degrees=90.0, + belt_assembly, + "drive_a", + base_ref, + gear_a_ref, + drive_angle_degrees=90.0, ) belt_assembly = scad.add_revolute_constraint_rassembly( - belt_assembly, "free_b", base_ref, gear_b_ref, + belt_assembly, + "free_b", + base_ref, + gear_b_ref, ) belt_assembly = scad.add_belt_constraint_rassembly( belt_assembly, @@ -941,10 +988,17 @@ def test_rack_pinion_constraint_couples_prismatic_and_revolute_support_joints(): ) assembly = scad.ground_component_rassembly(assembly, "base") assembly = scad.add_prismatic_constraint_rassembly( - assembly, "rack_slide", base_ref, rack_ref, + assembly, + "rack_slide", + base_ref, + rack_ref, ) assembly = scad.add_revolute_constraint_rassembly( - assembly, "pinion_axis", base_ref, pinion_ref, drive_angle_degrees=90.0, + assembly, + "pinion_axis", + base_ref, + pinion_ref, + drive_angle_degrees=90.0, ) assembly = scad.add_rack_pinion_constraint_rassembly( assembly, @@ -970,25 +1024,45 @@ def test_coupling_constraints_validate_positive_radii(): part = _part_with_face_connector("invalid_coupler_part") assembly = scad.make_assembly_rassembly("invalid_coupler_asm") assembly = scad.add_component_rassembly( - assembly, part, component_id="a", placement=scad.identity_placement_rplacement(), + assembly, + part, + component_id="a", + placement=scad.identity_placement_rplacement(), ) assembly = scad.add_component_rassembly( - assembly, part, component_id="b", placement=scad.identity_placement_rplacement(), + assembly, + part, + component_id="b", + placement=scad.identity_placement_rplacement(), ) ref_a = scad.make_connector_ref_rconnectorref("a", "axis") ref_b = scad.make_connector_ref_rconnectorref("b", "axis") with pytest.raises(Exception, match="pitch_radius_a"): scad.add_gear_constraint_rassembly( - assembly, "bad_gear", ref_a, ref_b, pitch_radius_a=0.0, pitch_radius_b=1.0, + assembly, + "bad_gear", + ref_a, + ref_b, + pitch_radius_a=0.0, + pitch_radius_b=1.0, ) with pytest.raises(Exception, match="pulley_radius_b"): scad.add_belt_constraint_rassembly( - assembly, "bad_belt", ref_a, ref_b, pulley_radius_a=1.0, pulley_radius_b=-1.0, + assembly, + "bad_belt", + ref_a, + ref_b, + pulley_radius_a=1.0, + pulley_radius_b=-1.0, ) with pytest.raises(Exception, match="pitch_radius"): scad.add_rack_pinion_constraint_rassembly( - assembly, "bad_rack", ref_a, ref_b, pitch_radius=0.0, + assembly, + "bad_rack", + ref_a, + ref_b, + pitch_radius=0.0, ) @@ -996,19 +1070,25 @@ def test_limit_aware_prismatic_loop_finds_optimal_distance(): part = _part_with_face_connector("ploop_part") assembly = scad.make_assembly_rassembly("prism_loop") assembly = scad.add_component_rassembly( - assembly, part, component_id="fixed_part", + assembly, + part, + component_id="fixed_part", placement=scad.make_placement_rplacement(origin=(0.0, 0.0, 2.0)), ) assembly = scad.add_component_rassembly( - assembly, part, component_id="movable", + assembly, + part, + component_id="movable", placement=scad.identity_placement_rplacement(), ) assembly = scad.ground_component_rassembly(assembly, "fixed_part") connector_a = scad.make_connector_ref_rconnectorref("fixed_part", "axis") connector_b = scad.make_connector_ref_rconnectorref("movable", "axis") assembly = scad.add_prismatic_constraint_rassembly( - assembly, "slide", - connector_a, connector_b, + assembly, + "slide", + connector_a, + connector_b, distance_limit=scad.make_scalar_limit_rscalarlimit(-5.0, 5.0), ) solved = scad.solve_assembly_constraints_rassembly(assembly, strict=False) diff --git a/test/test_product_packages.py b/test/test_product_packages.py index c7cbe5f4..879636be 100644 --- a/test/test_product_packages.py +++ b/test/test_product_packages.py @@ -74,12 +74,10 @@ def _build_nested_assembly(tmp_path: Path): drive_angle_degrees=15.0, ) assembly = scad.solve_assembly_constraints_rassembly(assembly=assembly) - return scad.forward_connector_rassembly( - assembly=assembly, - connector_id="public_mount", - source_component_id="inner_b", - source_connector_id="mount", - ) + return scad.set_public_connector_rassembly(assembly=assembly, + public_connector_id="public_mount", + source_component_id="inner_b", + source_connector_id="mount",) child = build_child() @@ -186,7 +184,7 @@ def test_nested_assembly_package_preserves_hierarchy_relations_and_dedup( assert nested.component_ids() == ("inner_a", "inner_b") assert nested.get_component("inner_a").item is nested.get_component("inner_b").item assert nested.get_component("inner_a").item is rebuilt.get_component("direct").item - assert nested.connector_ids() == ("public_mount",) + assert nested.public_connector_ids() == ("public_mount",) assert rebuilt.name == "Root assembly" assert rebuilt.get_component("direct").name == "Direct linked part" assert rebuilt.get_component("direct").item.name == "Part linked" diff --git a/test/test_scene_compiler.py b/test/test_scene_compiler.py index 517dbda2..9a3a8597 100644 --- a/test/test_scene_compiler.py +++ b/test/test_scene_compiler.py @@ -268,7 +268,7 @@ def test_export_scene_is_canonical_and_round_trips_through_archive_preflight(tmp assert report.valid, report.issues -def test_forwarded_connector_is_finalized_after_its_source_connector(): +def test_public_connector_is_finalized_after_its_source_connector(): part = scad.make_part_rpart( part_id="inner", body=scad.make_box_rsolid(width=2.0, height=2.0, depth=2.0), @@ -287,12 +287,10 @@ def test_forwarded_connector_is_finalized_after_its_source_connector(): component_id="inner", placement=scad.make_placement_rplacement(origin=(5.0, 0.0, 0.0)), ) - child = scad.forward_connector_rassembly( - assembly=child, - connector_id="public", - source_component_id="inner", - source_connector_id="axis", - ) + child = scad.set_public_connector_rassembly(assembly=child, + public_connector_id="public", + source_component_id="inner", + source_connector_id="axis",) root = scad.make_assembly_rassembly(assembly_id="root") root = scad.add_component_rassembly( assembly=root, @@ -302,12 +300,14 @@ def test_forwarded_connector_is_finalized_after_its_source_connector(): ) package = scene.compile_scene( - scene_id="forwarded", + scene_id="public-connector", roots=(scene.SceneRoot(root_id="main", value=root),), source=_manual_source(), ) - forwarded = next(item for item in package.manifest["connectors"] if item["connector_id"] == "public") + public = next(item for item in package.manifest["connectors"] if item["connector_id"] == "public") 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 public["anchor_kind"] == "public" + assert public["source_connector_snapshot_id"] == source["connector_snapshot_id"] + assert public["local_transform"]["origin"] == (6.0, 0.0, 0.0) assert validate_scene_package(package.manifest, package.blobs).valid diff --git a/test/test_scene_contract.py b/test/test_scene_contract.py index 9b57f85e..69e04f20 100644 --- a/test/test_scene_contract.py +++ b/test/test_scene_contract.py @@ -1378,7 +1378,7 @@ def test_shared_positive_case_names_cannot_drift_to_negative_expectations(): assert case["expected"] is None, positive_names[-1] if "error" in case: assert case["error"] is None, positive_names[-1] - assert len(positive_names) == 30 + assert len(positive_names) == 29 def test_accepted_package_fixtures_cover_every_connector_binding_status(): @@ -1623,15 +1623,13 @@ def test_python_matches_shared_resource_boundaries(): {"source": {"component_path": ["x"] * count}} ] } - elif kind == "forwarded": + elif kind == "public": value = { "connectors": [ { - "anchor_kind": "forwarded", + "anchor_kind": "public", "connector_snapshot_id": f"c{index}", - "forwarded_from": { - "source_connector_snapshot_id": f"c{index + 1}" - }, + "source_connector_snapshot_id": f"c{index + 1}", } for index in range(count) ] diff --git a/test/test_serialization.py b/test/test_serialization.py index 04222c2c..80896d54 100644 --- a/test/test_serialization.py +++ b/test/test_serialization.py @@ -188,8 +188,7 @@ class TestCoverageMatrix(unittest.TestCase): "make_vertex_connector_rconnector", "make_placement_connector_rconnector", "add_connector_rpart", - "add_connector_rassembly", - "forward_connector_rassembly", + "set_public_connector_rassembly", "make_connector_ref_rconnectorref", "make_scalar_limit_rscalarlimit", "ground_component_rassembly", @@ -328,8 +327,7 @@ class TestCoverageMatrix(unittest.TestCase): "make_vertex_connector_rconnector", "make_placement_connector_rconnector", "make_add_connector_rpart", - "make_add_connector_rassembly", - "make_forward_connector_rassembly", + "make_set_public_connector_rassembly", "make_connector_ref_rconnectorref", "make_scalar_limit_rscalarlimit", "make_ground_component_rassembly", @@ -713,28 +711,26 @@ class TestReplay(unittest.TestCase): self.assertIsInstance(results[0], scad.Solid) self.assertAlmostEqual(results[0].get_volume(), lofted.get_volume(), places=5) - def test_replay_forwarded_connector_without_offset_roundtrip(self): + def test_replay_public_connector_roundtrip(self): with scad.GraphSession() as session: body = scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) - part = scad.make_part_rpart(part_id="forwarded_part", body=body) + part = scad.make_part_rpart(part_id="public_part", body=body) connector = scad.make_placement_connector_rconnector( connector_id="axis", placement=scad.make_placement_rplacement(origin=(1.0, 2.0, 3.0)), ) part = scad.add_connector_rpart(part=part, connector=connector) - assembly = scad.make_assembly_rassembly(assembly_id="forwarded_parent") + assembly = scad.make_assembly_rassembly(assembly_id="public_parent") assembly = scad.add_component_rassembly( assembly=assembly, item=part, component_id="child", placement=scad.identity_placement_rplacement(), ) - scad.forward_connector_rassembly( - assembly=assembly, - connector_id="public_axis", - source_component_id="child", - source_connector_id="axis", - ) + scad.set_public_connector_rassembly(assembly=assembly, + public_connector_id="public_axis", + source_component_id="child", + source_connector_id="axis",) replayed = scad.replay_model_json( json_str=scad.export_model_json(session=session) @@ -742,11 +738,46 @@ class TestReplay(unittest.TestCase): assemblies = [item for item in replayed if isinstance(item, scad.Assembly)] self.assertTrue(assemblies) + public = assemblies[-1].get_public_connector("public_axis") self.assertEqual( - assemblies[-1].get_connector("public_axis").placement.origin, - (1.0, 2.0, 3.0), + (public.component_id, public.connector_id), + ("child", "axis"), ) + def test_replay_public_connector_rejects_removed_offset(self): + with scad.GraphSession() as session: + body = scad.make_box_rsolid(width=1.0, height=1.0, depth=1.0) + part = scad.make_part_rpart(part_id="public_part", body=body) + connector = scad.make_placement_connector_rconnector( + connector_id="axis", + placement=scad.identity_placement_rplacement(), + ) + part = scad.add_connector_rpart(part=part, connector=connector) + assembly = scad.make_assembly_rassembly(assembly_id="public_parent") + assembly = scad.add_component_rassembly( + assembly=assembly, + item=part, + component_id="child", + placement=scad.identity_placement_rplacement(), + ) + scad.set_public_connector_rassembly( + assembly=assembly, + public_connector_id="public_axis", + source_component_id="child", + source_connector_id="axis", + ) + + payload = json.loads(scad.export_model_json(session=session)) + public_node = next( + node + for node in payload["graph"]["nodes"] + if node["op"] == "make_set_public_connector_rassembly" + ) + public_node["params"]["offset"] = scad.identity_placement_rplacement().to_dict() + + with self.assertRaisesRegex(Exception, r"unsupported parameter\(s\): offset"): + scad.replay_model_json(json_str=json.dumps(payload)) + def test_replay_wire_face_extrude_edit_chain_roundtrip(self): with scad.GraphSession() as session: e1 = scad.make_line_redge((0, 0, 0), (1, 0, 0)) diff --git a/test/test_stdlib_bearing.py b/test/test_stdlib_bearing.py index c0e295f7..d628d490 100644 --- a/test/test_stdlib_bearing.py +++ b/test/test_stdlib_bearing.py @@ -24,7 +24,8 @@ class TestStdBearingSurface(unittest.TestCase): def test_public_bearing_factories_follow_make_rtype_naming(self): factory_names = [ - name for name in scad.std.bearing.__all__ + name + for name in scad.std.bearing.__all__ if callable(getattr(scad.std.bearing, name, None)) ] @@ -81,7 +82,7 @@ class TestBallBearingAssembly(unittest.TestCase): ), ) self.assertEqual(bearing.constraint_ids(), ("inner_outer_revolute",)) - self.assertEqual(bearing.connector_ids(), ("outer_axis", "inner_axis")) + self.assertEqual(bearing.public_connector_ids(), ("outer_axis", "inner_axis")) self.assertEqual(bearing.grounded_component_ids, ()) constraint = bearing.get_constraint("inner_outer_revolute") self.assertEqual(constraint.constraint_kind, "revolute") @@ -111,8 +112,12 @@ class TestBallBearingAssembly(unittest.TestCase): inner_ring_meta["outer_radius"], meta["ball_pitch_radius"] - ball_radius * 0.75, ) - self.assertLess(outer_ring_meta["raceway_mouth_z"], outer_ring_meta["groove_radius"]) - self.assertLess(inner_ring_meta["raceway_mouth_z"], inner_ring_meta["groove_radius"]) + self.assertLess( + outer_ring_meta["raceway_mouth_z"], outer_ring_meta["groove_radius"] + ) + self.assertLess( + inner_ring_meta["raceway_mouth_z"], inner_ring_meta["groove_radius"] + ) from OCP.BRepAdaptor import BRepAdaptor_Surface from OCP.GeomAbs import GeomAbs_Sphere, GeomAbs_Torus @@ -138,10 +143,12 @@ class TestBallBearingAssembly(unittest.TestCase): self.assertEqual(len(preview.get_solids()), 9) self.assertGreater(preview.get_volume(), 0.0) - self.assertTrue(scad.measure_constraint_residual_rconstraintresidual( - bearing, - "inner_outer_revolute", - ).within_tolerance) + self.assertTrue( + scad.measure_constraint_residual_rconstraintresidual( + bearing, + "inner_outer_revolute", + ).within_tolerance + ) payload = json.loads(model_json) ops = [node["op"] for node in payload["graph"]["nodes"]] @@ -149,7 +156,7 @@ class TestBallBearingAssembly(unittest.TestCase): self.assertEqual(ops.count("make_three_point_arc_redge"), 2) self.assertEqual(ops.count("make_revolve_rsolid"), 2) self.assertIn("make_revolute_constraint_rassembly", ops) - self.assertEqual(ops.count("make_forward_connector_rassembly"), 2) + self.assertEqual(ops.count("make_set_public_connector_rassembly"), 2) self.assertIn("make_compound_from_assembly_rcompound", ops) stdlib_nodes = [ node @@ -191,7 +198,9 @@ class TestBallBearingAssembly(unittest.TestCase): shaft_part = scad.make_part_rpart("shaft", shaft) top_face = max( shaft.get_faces(), - key=lambda face: face.get_center().z if face.get_normal_at().z > 0.7 else -999.0, + key=lambda face: ( + face.get_center().z if face.get_normal_at().z > 0.7 else -999.0 + ), ) shaft_axis = scad.make_face_connector_rconnector("axis", top_face) shaft_part = scad.add_connector_rpart(shaft_part, shaft_axis) @@ -214,12 +223,14 @@ class TestBallBearingAssembly(unittest.TestCase): bearing = scad.solve_assembly_constraints_rassembly(bearing, strict=False) self.assertIn("shaft", bearing.component_ids()) - self.assertTrue(scad.measure_constraint_residual_rconstraintresidual( - bearing, - "shaft_to_inner_ring", - ).within_tolerance) + self.assertTrue( + scad.measure_constraint_residual_rconstraintresidual( + bearing, + "shaft_to_inner_ring", + ).within_tolerance + ) - def test_parent_assembly_can_bind_to_bearing_forwarded_connectors(self): + def test_parent_assembly_can_bind_to_bearing_public_connectors(self): bearing = scad.std.bearing.make_ball_bearing_rassembly( 8.0, 22.0, @@ -239,7 +250,9 @@ class TestBallBearingAssembly(unittest.TestCase): shaft_part = scad.make_part_rpart("parent_bind_shaft", shaft) top_face = max( shaft.get_faces(), - key=lambda face: face.get_center().z if face.get_normal_at().z > 0.7 else -999.0, + key=lambda face: ( + face.get_center().z if face.get_normal_at().z > 0.7 else -999.0 + ), ) shaft_axis = scad.make_face_connector_rconnector("axis", top_face) shaft_part = scad.add_connector_rpart(shaft_part, shaft_axis) @@ -265,10 +278,12 @@ class TestBallBearingAssembly(unittest.TestCase): ) parent = scad.solve_assembly_constraints_rassembly(parent) - self.assertTrue(scad.measure_constraint_residual_rconstraintresidual( - parent, - "shaft_to_bearing_inner_axis", - ).within_tolerance) + self.assertTrue( + scad.measure_constraint_residual_rconstraintresidual( + parent, + "shaft_to_bearing_inner_axis", + ).within_tolerance + ) def test_invalid_params(self): with self.assertRaises(Exception): diff --git a/tools/generate_scene_contract_fixtures.py b/tools/generate_scene_contract_fixtures.py index e837f45e..68e25622 100644 --- a/tools/generate_scene_contract_fixtures.py +++ b/tools/generate_scene_contract_fixtures.py @@ -199,7 +199,7 @@ def main() -> int: "name": None, } ], - "connectors": [], + "public_connectors": [], "constraints": [], "grounded_component_ids": ["component_a"], "kind": "assembly", diff --git a/tools/scene_contract_fixtures/authored_cases.py b/tools/scene_contract_fixtures/authored_cases.py index 4ddf6d06..b9711a41 100644 --- a/tools/scene_contract_fixtures/authored_cases.py +++ b/tools/scene_contract_fixtures/authored_cases.py @@ -124,26 +124,15 @@ def build_normalized_product_matrix_cases( "name": None, } ] - forwarded = deepcopy(assembly) - forwarded["connectors"] = [ + public = deepcopy(assembly) + public["public_connectors"] = [ { - "anchor": { - "anchor_kind": "forwarded", - "offset": None, - "source_component_id": "component_a", - "source_connector_id": "placement", - }, - "connector_id": "forwarded", + "public_connector_id": "public", + "component_id": "component_a", + "connector_id": "placement", "name": None, } ] - forwarded_offset = deepcopy(forwarded) - forwarded_offset["connectors"][0]["anchor"]["offset"] = { - "origin": [0, 0, 5], - "x_axis": [1, 0, 0], - "y_axis": [0, 1, 0], - "z_axis": [0, 0, 1], - } return [ validation_case( "valid_complete_material", material_part, validate_normalized_product @@ -155,13 +144,8 @@ def build_normalized_product_matrix_cases( "valid_placement_connector", placement, validate_normalized_product ), validation_case( - "valid_forwarded_connector_null_offset", - forwarded, - validate_normalized_product, - ), - validation_case( - "valid_forwarded_connector_offset", - forwarded_offset, + "valid_public_connector", + public, validate_normalized_product, ), ] diff --git a/tools/scene_contract_fixtures/package_cases.py b/tools/scene_contract_fixtures/package_cases.py index 83234081..af469595 100644 --- a/tools/scene_contract_fixtures/package_cases.py +++ b/tools/scene_contract_fixtures/package_cases.py @@ -207,34 +207,18 @@ def build_package_matrix_cases( ) ) - forwarded_scene, _forwarded_entity, forwarded_blobs = deepcopy(nested) + missing_source_scene, _missing_source_entity, missing_source_blobs = deepcopy(nested) root_connector = next( record - for record in forwarded_scene["connectors"] + for record in missing_source_scene["connectors"] if record["connector_id"] == "root_mount" ) - root_connector["local_transform"]["origin"] = [0, 0, 6] + root_connector["source_connector_snapshot_id"] = "connector/root/assembly/nested_assembly/missing" cases.append( inline_package_case( - "forwarded_transform_mismatch", - with_scene_revision(forwarded_scene), - forwarded_blobs, - blob_pool, - ) - ) - - missing_child_scene, _missing_child_entity, missing_child_blobs = deepcopy(nested) - root_connector = next( - record - for record in missing_child_scene["connectors"] - if record["connector_id"] == "root_mount" - ) - root_connector["forwarded_from"]["source_component_id"] = "missing" - cases.append( - inline_package_case( - "forwarded_direct_child_missing", - with_scene_revision(missing_child_scene), - missing_child_blobs, + "public_source_snapshot_missing", + with_scene_revision(missing_source_scene), + missing_source_blobs, blob_pool, ) ) @@ -254,10 +238,11 @@ def build_package_matrix_cases( ) cases.append( inline_package_case( - "forwarded_owner_not_assembly", + "public_owner_not_assembly", with_scene_revision(part_owner_scene), part_owner_blobs, blob_pool, ) ) return cases + diff --git a/tools/scene_contract_fixtures/resource_cases.py b/tools/scene_contract_fixtures/resource_cases.py index 98313ca1..2c41855c 100644 --- a/tools/scene_contract_fixtures/resource_cases.py +++ b/tools/scene_contract_fixtures/resource_cases.py @@ -208,15 +208,13 @@ def _resource_count_value( return {field: [None] * count} if kind == "hierarchy": return {"nodes": [{"source": {"component_path": ["x"] * count}}]} - if kind == "forwarded": + if kind == "public": return { "connectors": [ { - "anchor_kind": "forwarded", + "anchor_kind": "public", "connector_snapshot_id": f"c{index}", - "forwarded_from": { - "source_connector_snapshot_id": f"c{index + 1}" - }, + "source_connector_snapshot_id": f"c{index + 1}", } for index in range(count) ] @@ -586,18 +584,18 @@ def build_resource_cases( {"hierarchy_depth": 2, "nodes": 10}, ), _resource_count_case( - "forwarded_connector_depth_exact_limit", + "public_connector_depth_exact_limit", "scene", - "forwarded", + "public", 2, - {"connectors": 10, "forwarded_connector_depth": 2}, + {"connectors": 10, "public_connector_depth": 2}, ), _resource_count_case( - "forwarded_connector_depth_over_limit", + "public_connector_depth_over_limit", "scene", - "forwarded", + "public", 3, - {"connectors": 10, "forwarded_connector_depth": 2}, + {"connectors": 10, "public_connector_depth": 2}, ), _glb_count_case( "triangle_vertices_per_asset_exact_limit", diff --git a/tools/scene_contract_fixtures/scene_cases.py b/tools/scene_contract_fixtures/scene_cases.py index 2cee6d6e..f4e4ae43 100644 --- a/tools/scene_contract_fixtures/scene_cases.py +++ b/tools/scene_contract_fixtures/scene_cases.py @@ -88,9 +88,9 @@ def _manual_connector( anchor_kind: str, local_transform: JsonObject, *, - forwarded_from: JsonObject | None = None, + source_connector_snapshot_id: str | None = None, ) -> JsonObject: - connector: JsonObject = { + return { "anchor_kind": anchor_kind, "connector_id": connector_id, "connector_snapshot_id": ( @@ -101,10 +101,8 @@ def _manual_connector( "owner_definition_id": owner_definition_id, "sdk_metadata": {}, "source": {"kind": "manual", "source_id": "fixture"}, + "source_connector_snapshot_id": source_connector_snapshot_id, } - if forwarded_from is not None: - connector["forwarded_from"] = forwarded_from - return connector def build_product_scene_package( @@ -152,35 +150,20 @@ def build_product_scene_package( "assembly", "nested_assembly", "nested_mount", - "forwarded", + "public", transform(), - forwarded_from={ - "offset": None, - "source_component_id": "part", - "source_connector_id": "mount", - "source_connector_snapshot_id": part_connector[ - "connector_snapshot_id" - ], - "source_definition_id": part_definition_id, - }, + source_connector_snapshot_id=part_connector["connector_snapshot_id"], ) - root_offset = transform([0, 0, 5]) root_connector = _manual_connector( root_definition_id, "assembly", "root_assembly", "root_mount", - "forwarded", - deepcopy(root_offset), - forwarded_from={ - "offset": root_offset, - "source_component_id": "subassembly", - "source_connector_id": "nested_mount", - "source_connector_snapshot_id": nested_connector[ - "connector_snapshot_id" - ], - "source_definition_id": nested_definition_id, - }, + "public", + transform([0, 0, 5]), + source_connector_snapshot_id=nested_connector[ + "connector_snapshot_id" + ], ) connectors = [part_connector, nested_connector, root_connector] scene["scene_id"] = "nested_fixture" diff --git a/tools/scene_contract_fixtures/schema_field_matrix.py b/tools/scene_contract_fixtures/schema_field_matrix.py index 7a1ca647..82eb7b73 100644 --- a/tools/scene_contract_fixtures/schema_field_matrix.py +++ b/tools/scene_contract_fixtures/schema_field_matrix.py @@ -45,6 +45,8 @@ def _wrapper(root: Mapping[str, Any], pointer: str) -> dict[str, Any]: def _string_example(schema: Mapping[str, Any]) -> str: pattern = str(schema.get("pattern", "")) + if pattern == "^[A-Za-z0-9][A-Za-z0-9._/-]*\\.py$": + return "model.py" if pattern == "^sha256:[0-9a-f]{64}$": return "sha256:" + "0" * 64 if pattern.startswith("^appearance/evaluated/"): @@ -304,7 +306,6 @@ def build_schema_field_matrices(schema_dir: Path) -> list[dict[str, Any]]: for anchor_name in ( "geometryAnchor", "placementAnchor", - "forwardedAnchor", ): anchor = _example(root, root["$defs"][anchor_name]) variants.append(