refactor: split operator facade and public connectors

This commit is contained in:
NiJingzhe
2026-08-20 14:52:07 +08:00
parent a976395f12
commit 2fc3029a86
66 changed files with 18123 additions and 12191 deletions
@@ -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";
+2 -13
View File
@@ -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".
+1 -1
View File
@@ -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,
+38 -87
View File
@@ -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<unknown, unknown>();
const publicEdges = new Map<unknown, unknown>();
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<unknown>();
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<unknown, JsonRecord>(connectors.map((record) => [record.connector_snapshot_id, record]));
const connectorIdsByOwner = new Map<unknown, Set<unknown>>();
const forwardEdges = new Map<unknown, unknown>();
const publicEdges = new Map<unknown, unknown>();
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<unknown>();
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) {
+4 -4
View File
@@ -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}`);
+4 -5
View File
@@ -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",
File diff suppressed because it is too large Load Diff
+603
View File
@@ -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("__"))
+952
View File
@@ -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("__"))
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+177
View File
@@ -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("__"))
File diff suppressed because it is too large Load Diff
+432
View File
@@ -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("__"))
@@ -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):
+17 -47
View File
@@ -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 = (
+38 -16
View File
@@ -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"]),
)
+101 -37
View File
@@ -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"]
+9 -170
View File
@@ -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)
@@ -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",
+26 -1
View File
@@ -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=[],
)
+603
View File
@@ -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("__"))
+12 -21
View File
@@ -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"),
)
+6 -8
View File
@@ -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,
-8
View File
@@ -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,
)
+91 -119
View File
@@ -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:
@@ -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"}}}
}
@@ -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"}
}
+1 -1
View File
@@ -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:
+5 -5
View File
@@ -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(
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+75 -65
View File
@@ -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:
@@ -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",
@@ -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."},
@@ -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"}
}}
}
}
@@ -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",
@@ -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": {
@@ -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"}}}},
@@ -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]
+2 -10
View File
@@ -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
+39 -23
View File
@@ -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"]
+1 -1
View File
@@ -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
+30 -114
View File
@@ -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
+326
View File
@@ -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("__"))
+29 -52
View File
@@ -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,
+10 -6
View File
@@ -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(
+5 -10
View File
@@ -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",
+3 -5
View File
@@ -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,
+433
View File
@@ -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("__"))
+921 -413
View File
File diff suppressed because one or more lines are too long
+17 -1
View File
@@ -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")
+16 -17
View File
@@ -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",
-1
View File
@@ -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,
)
+156 -76
View File
@@ -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)
+5 -7
View File
@@ -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"
+10 -10
View File
@@ -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
+4 -6
View File
@@ -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)
]
+46 -15
View File
@@ -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))
+35 -20
View File
@@ -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):
+1 -1
View File
@@ -199,7 +199,7 @@ def main() -> int:
"name": None,
}
],
"connectors": [],
"public_connectors": [],
"constraints": [],
"grounded_component_ids": ["component_a"],
"kind": "assembly",
@@ -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,
),
]
+8 -23
View File
@@ -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
@@ -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",
+10 -27
View File
@@ -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"
@@ -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(