feat(core)!: QL-only topology enumeration — remove bare getter list form

Plural topology getters (get_edges/get_faces/get_wires/get_vertices/
get_solids/get_inner_wires/get_edge_occurrences and the Compound
variants) now accept ONLY an index. The no-argument list form raises a
SimpleCADError with migration guidance (enumerate via
ql.<kind>().resolve(shape), pick via get_X(index)). This closes the
selection channel that escapes the graph: Python loops over bare lists
lose the predicate, capture kernel artifacts (the periodic-face seam
edges that broke FCStd translation), and leave no cardinality contract.

- each shape class keeps its enumeration logic as private _iter_<kind>();
  indexed picks record geo-select nodes as before (contract test added);
  Compound getters gain the same indexed recording they lacked
- _TopologySelectionList (the __getitem__ recording vehicle, which also
  made get_X()[i] a silent escape hatch) is retired
- all 109 internal call sites, 165 test call sites, and 31 example call
  sites migrated: SDK/tests use the private channel, user-facing
  examples use ql.<kind>().resolve(...)
- QL _resolve_scope_items switches to the private channel; scene
  contract profile descriptions synced; error strings recommending
  bracket indexing rewritten
- skill docs: strict prohibition added to SKILL.md global rules (new
  rule 6), core README contract statement rewritten, solid/wire/face/
  shell/tagged_mixin pages re-exemplified with QL, geometric-validation
  anti-pattern section updated; mirrors rebuilt via tools/skillbuild.py

Gates: full suite 1418 passed / 5 skipped; translator suites 133 passed;
u_link stage verifiers + render check ALL PASS; scadpkg->FCStd
retranslation verified (5 visible deliverables, 167-object editable
tree).
This commit is contained in:
NiJingzhe
2026-09-01 02:09:29 +08:00
parent 14f3fe952e
commit a5e6bf8eb6
78 changed files with 718 additions and 558 deletions
+16 -7
View File
@@ -93,21 +93,30 @@ it and stop that route; never invent an alternative route.
5. Build and validate incrementally: each major step prints small
QL-derived facts; grounding uses QL wherever possible; never
print whole solids or full model objects.
6. Tags: attach with `apply_tag(shape=..., tag=...)` (LOCAL scope —
6. Topology enumeration is QL-only and strictly enforced: plural
getters (`get_edges`, `get_faces`, `get_wires`, `get_vertices`,
`get_solids`, `get_inner_wires`) accept ONLY an index — the
no-argument list form raises. Enumerate, count, and measure via
`ql.<kind>().resolve(shape)`; filter with QL predicates plus
`take`/`exactly` cardinality; never build selections by looping
over an enumerated list and indexing it. Indexed picks
(`get_edges(index)`) are reserved for intentional, named choices
and are recorded as graph selection nodes.
7. Tags: attach with `apply_tag(shape=..., tag=...)` (LOCAL scope —
it never propagates downward); inspect with
`list_tags(shape=...)`; keep numeric facts in metadata, never in
tags.
7. `@scad.part` for one physical single-solid product;
8. `@scad.part` for one physical single-solid product;
`@scad.assemble` for assemblies with explicit definitions.
Neither nests inside an active `GraphSession`. Durable delivery
is `capture(result, "out/product.scadpkg")` in one call.
8. `simplecadapi.inspect.brep` is diagnostic-only and rejected
9. `simplecadapi.inspect.brep` is diagnostic-only and rejected
inside `GraphSession`; obtain/export geometry first, inspect
outside.
9. Standard parts first: before hand-modeling a gear, ring gear,
rack, cycloidal disc, or bearing, check `scad.std.gear` /
`scad.std.bearing`.
10. Read `references/docs/guides/cache-build-workflow.md` in full
10. Standard parts first: before hand-modeling a gear, ring gear,
rack, cycloidal disc, or bearing, check `scad.std.gear` /
`scad.std.bearing`.
11. Read `references/docs/guides/cache-build-workflow.md` in full
before configuring persistent cache, durable builds, or cache
maintenance; cache mutation requires explicit confirmation.
@@ -41,8 +41,10 @@ review.
- Select by tags, axes, normals, positions, or QL predicates — not arbitrary
topology indexes, which booleans and fillets renumber.
- Indexed getters (`get_faces(index)`, `get_edges(index)`, ...) are for
intentional picks; they are preserved as graph geo-select nodes.
- Plural getters (`get_faces(index)`, `get_edges(index)`, ...) accept ONLY an
index; enumeration, counting, and measurement go through QL selectors
(`ql.faces().resolve(shape)`, `len(ql.edges().resolve(shape))`). Indexed
picks are preserved as graph geo-select nodes.
- `apply_tag(shape=..., tag=...)` attaches a tag to exactly the given shape
with LOCAL scope — it never propagates downward; `list_tags(shape=...)`
reads effective tags. Downward/topology-scoped propagation is only exposed
@@ -68,8 +70,11 @@ returns a valid solid. Before every `fillet_rsolid`/`chamfer_rsolid`:
view used. Seeing the selected edges is the check.
Anti-patterns, each a documented silent-wrong-part delivery:
- Index picks (`get_edges()[i]`) for edges you did not create and name
in this step — booleans and fillets renumber topology.
- Bare enumeration of topology with Python loops or post-filtered lists —
the no-argument getter list form is removed; every read goes through QL,
and picks use `get_edges(index)` only for edges you can name and intend.
Booleans and fillets renumber topology; a predicate survives, an index
guess does not.
- Enumerating candidate edge sets x radii with `except: pass`; a hit
confirms the selection is uncontrolled, it does not solve it.
- Counting generated `face.*` tag faces as proof the blend landed on
+6 -5
View File
@@ -68,7 +68,11 @@ SimpleWorkplane ← local modeling context
- **OCP-native runtime**: geometry construction, topology traversal, properties, booleans, transforms, and export use OCP/OpenCascade helpers.
- **Replayable graph workflows**: an explicit `GraphSession` records operations, `session.capture_result()` selects canonical output nodes, and `export_model_json()` plus `replay_model_json()` provide interchange and replay.
- **Tags and metadata**: tags are useful for lightweight semantics; structured numeric facts should be stored in metadata such as `metadata["geo"]`.
- **Indexed topology access**: use plural methods such as `get_edges()` and `get_faces()` for enumeration, and pass an index to the same getter, such as `get_edges(index)` or `get_faces(index)`, for intentional indexed picks that should become graph selection nodes.
- **QL-only topology enumeration**: plural getters such as `get_edges(index)` and
`get_faces(index)` accept ONLY an index — the no-argument list form is forbidden
and raises. Enumerate, count, or measure topology through QL selectors
(`ql.edges().resolve(shape)`); an intentional single pick uses the indexed form,
which is recorded as a graph selection node.
## Basic Usage
@@ -82,10 +86,7 @@ scad.apply_tag(shape=box, tag="role.bracket")
box.set_metadata("material", "6061-T6")
box.auto_tag_faces("box")
top_faces = [
face for face in box.get_faces()
if "face.top" in scad.list_tags(shape=face)
]
top_faces = scad.ql.faces().where(scad.ql.tag("face.top")).resolve(box)
print(len(top_faces))
```
+6 -6
View File
@@ -103,7 +103,7 @@ Get the normal vector of the face at the specified parameter position.
**Example:**
```python
from simplecadapi import make_rectangle_rface
from simplecadapi import make_rectangle_rface, ql
rectangle = make_rectangle_rface(width=5, height=3)
normal = rectangle.get_normal_at()
@@ -126,7 +126,7 @@ from simplecadapi import make_rectangle_rface
rectangle = make_rectangle_rface(width=5, height=3)
outer_wire = rectangle.get_outer_wire()
edges = outer_wire.get_edges()
edges = ql.edges().resolve(outer_wire)
print(f"The outer boundary consists of {len(edges)} edges")
```
@@ -171,7 +171,7 @@ for face in faces:
area = face.get_area()
normal = face.get_normal_at()
outer_wire = face.get_outer_wire()
edges = outer_wire.get_edges()
edges = ql.edges().resolve(outer_wire)
tags = list_tags(face)
print(f"Face type: {tags}")
@@ -208,7 +208,7 @@ def analyze_face_geometry():
for i, rect in enumerate(rectangles):
area = rect.get_area()
outer_wire = rect.get_outer_wire()
edges = outer_wire.get_edges()
edges = ql.edges().resolve(outer_wire)
# Compute perimeter
perimeter = sum(edge.get_length() for edge in edges)
@@ -234,7 +234,7 @@ def analyze_face_geometry():
for i, circle in enumerate(circles):
area = circle.get_area()
outer_wire = circle.get_outer_wire()
edges = outer_wire.get_edges()
edges = ql.edges().resolve(outer_wire)
# Compute circumference
perimeter = sum(edge.get_length() for edge in edges)
@@ -361,7 +361,7 @@ def transform_faces():
area = face.get_area()
normal = face.get_normal_at()
outer_wire = face.get_outer_wire()
edges = outer_wire.get_edges()
edges = ql.edges().resolve(outer_wire)
# Compute bounding box
all_coords = []
+4 -4
View File
@@ -6,9 +6,9 @@
## Topology and Properties
- `get_faces(index=None)` returns all faces or one indexed face.
- `get_wires(index=None)` returns the Shell's free boundary wires.
- `get_edges(index=None)` returns unique edges across the shell faces.
- `get_faces(index)` — enumeration is QL-only; the no-argument list form is forbidden returns all faces or one indexed face.
- `get_wires(index)` — free boundary wires; indexed picks only returns the Shell's free boundary wires.
- `get_edges(index)` — indexed picks only returns unique edges across the shell faces.
- `get_area()` returns total face area.
- `is_closed()` reports whether the shell has no free boundary.
- `free_boundaries_rwirelist(shell)` returns the open boundary loops.
@@ -36,7 +36,7 @@ open_shell = scad.loft_rshell(
side_faces_tag="group.skin",
)
assert not open_shell.is_closed()
assert len(open_shell.get_wires()) == 2
assert len(ql.wires().resolve(open_shell)) == 2
assert len(scad.ql.wires().where(scad.ql.tag("anchor.inlet")).resolve(open_shell)) == 1
closed_shell = scad.fill_holes_rshell(open_shell)
+28 -69
View File
@@ -91,22 +91,22 @@ expected_volume = (4/3) * math.pi * 1.5**3
print(f"Sphere volume: {sphere_volume:.3f}, expected: {expected_volume:.3f}")
```
### `get_faces()`
### `get_faces(index)` — enumeration is QL-only
Get all faces that make up the solid.
There is no no-argument list form: bare topology enumeration is forbidden
(calling `get_faces()` raises with guidance). Enumerate, count, or filter
faces through QL selectors; use this method only for an intentional indexed
pick, which is recorded as a graph selection node.
**Returns:**
- `List[Face]`: List of face objects
**Raises:**
- `ValueError`: When face list retrieval fails
- `Face`: The selected face object
**Example:**
```python
from simplecadapi import make_box_rsolid
from simplecadapi import make_box_rsolid, ql
box = make_box_rsolid(width=4, height=3, depth=2)
faces = box.get_faces()
faces = ql.faces().resolve(box)
print(f"The box has {len(faces)} faces")
for i, face in enumerate(faces):
@@ -114,39 +114,15 @@ for i, face in enumerate(faces):
print(f"Face {i}: area {area:.3f}")
```
### `get_faces(index)`
### `get_edges(index)` — enumeration is QL-only
Get one face by explicit index. In an active `GraphSession`, this intentional
indexed pick is preserved as a graph geo select node.
There is no no-argument list form. Enumerate or measure edges through QL:
**Returns:**
- `Face`: The selected face object
**Example:**
```python
from simplecadapi import make_box_rsolid
from simplecadapi import make_box_rsolid, ql
box = make_box_rsolid(width=4, height=3, depth=2)
first_face = box.get_faces(0)
print(first_face.get_area())
```
### `get_edges()`
Get all edges that make up the solid.
**Returns:**
- `List[Edge]`: List of edge objects
**Raises:**
- `ValueError`: When edge list retrieval fails
**Example:**
```python
from simplecadapi import make_box_rsolid
box = make_box_rsolid(width=4, height=3, depth=2)
edges = box.get_edges()
edges = ql.edges().resolve(box)
print(f"The box has {len(edges)} edges")
for i, edge in enumerate(edges):
@@ -154,23 +130,6 @@ for i, edge in enumerate(edges):
print(f"Edge {i}: length {length:.3f}")
```
### `get_edges(index)`
Get one edge by explicit index. In an active `GraphSession`, this intentional
indexed pick is preserved as a graph geo select node.
**Returns:**
- `Edge`: The selected edge object
**Example:**
```python
from simplecadapi import make_box_rsolid
box = make_box_rsolid(width=4, height=3, depth=2)
first_edge = box.get_edges(0)
print(first_edge.get_length())
```
### `auto_tag_faces(geometry_type)`
Automatically add tags to faces.
@@ -186,7 +145,7 @@ from simplecadapi import make_box_rsolid, make_cylinder_rsolid
box = make_box_rsolid(width=4, height=3, depth=2)
box.auto_tag_faces("box")
faces = box.get_faces()
faces = ql.faces().resolve(box)
for face in faces:
print(f"Face tags: {list_tags(face)}")
@@ -194,7 +153,7 @@ for face in faces:
cylinder = make_cylinder_rsolid(center=(0, 0, 0), radius=2, height=4)
cylinder.auto_tag_faces("cylinder")
faces = cylinder.get_faces()
faces = ql.faces().resolve(cylinder)
for face in faces:
print(f"Face tags: {list_tags(face)}")
```
@@ -234,8 +193,8 @@ def create_basic_solids():
# Get geometric properties
volume = solid.get_volume()
faces = solid.get_faces()
edges = solid.get_edges()
faces = ql.faces().resolve(solid)
edges = ql.edges().resolve(solid)
# Compute surface area
total_surface_area = sum(face.get_area() for face in faces)
@@ -318,7 +277,7 @@ def boolean_operations_example():
for name, solid in operations:
volume = solid.get_volume()
faces = solid.get_faces()
faces = ql.faces().resolve(solid)
surface_area = sum(face.get_area() for face in faces)
solid.set_metadata("operation_type", name)
@@ -355,8 +314,8 @@ def feature_operations_example():
# Analyze the original geometry
original_volume = base_box.get_volume()
original_faces = base_box.get_faces()
original_edges = base_box.get_edges()
original_faces = ql.faces().resolve(base_box)
original_edges = ql.edges().resolve(base_box)
print(f"Original geometry:")
print(f" Volume: {original_volume:.3f}")
@@ -371,8 +330,8 @@ def feature_operations_example():
apply_tag(filleted_box, "rounded_edges")
filleted_volume = filleted_box.get_volume()
filleted_faces = filleted_box.get_faces()
filleted_edges = filleted_box.get_edges()
filleted_faces = ql.faces().resolve(filleted_box)
filleted_edges = ql.edges().resolve(filleted_box)
filleted_box.set_metadata("original_volume", original_volume)
filleted_box.set_metadata("volume_change", filleted_volume - original_volume)
@@ -396,8 +355,8 @@ def feature_operations_example():
apply_tag(chamfered_box, "beveled_edges")
chamfered_volume = chamfered_box.get_volume()
chamfered_faces = chamfered_box.get_faces()
chamfered_edges = chamfered_box.get_edges()
chamfered_faces = ql.faces().resolve(chamfered_box)
chamfered_edges = ql.edges().resolve(chamfered_box)
chamfered_box.set_metadata("original_volume", original_volume)
chamfered_box.set_metadata("volume_change", chamfered_volume - original_volume)
@@ -424,7 +383,7 @@ def feature_operations_example():
print("Feature operation comparison:")
for name, solid in results:
volume = solid.get_volume()
faces = solid.get_faces()
faces = ql.faces().resolve(solid)
tags = list_tags(solid)
print(f" {name}: volume={volume:.3f}, face count={len(faces)}, tags={tags}")
@@ -487,8 +446,8 @@ def create_complex_geometry():
# Analyze the complex solid
volume = complex_solid.get_volume()
faces = complex_solid.get_faces()
edges = complex_solid.get_edges()
faces = ql.faces().resolve(complex_solid)
edges = ql.edges().resolve(complex_solid)
# Compute geometric complexity
face_count = len(faces)
@@ -559,8 +518,8 @@ def analyze_solid_quality():
# Basic geometric properties
volume = solid.get_volume()
faces = solid.get_faces()
edges = solid.get_edges()
faces = ql.faces().resolve(solid)
edges = ql.edges().resolve(solid)
# Compute quality metrics
surface_area = sum(face.get_area() for face in faces)
@@ -33,7 +33,7 @@ scad.apply_tag(box, "role.bracket")
box.auto_tag_faces("box")
print(scad.list_tags(box))
top_faces = [face for face in box.get_faces() if "face.top" in scad.list_tags(face)]
top_faces = [face for face in ql.faces().resolve(box) if "face.top" in scad.list_tags(face)]
print(len(top_faces))
```
@@ -105,8 +105,8 @@ body = scad.make_box_rsolid(10, 10, 2)
scad.apply_tag(body, "role.mounting_plate")
body.auto_tag_faces("box")
top_faces = Q.select(body.get_faces()).where(Q.tag("face.top")).all()
role_faces = Q.select(body.get_faces()).where(Q.tag("role.*", scope="effective")).all()
top_faces = Q.select(ql.faces().resolve(body)).where(Q.tag("face.top")).all()
role_faces = Q.select(ql.faces().resolve(body)).where(Q.tag("role.*", scope="effective")).all()
print(len(top_faces), len(role_faces))
```
+12 -12
View File
@@ -56,22 +56,22 @@ polyline = make_polyline_rwire(points=[(0, 0, 0), (1, 1, 0), (2, 0, 0)])
## Common Methods
### `get_edges()`
### `get_edges(index)` — enumeration is QL-only
Get all edges that make up the wire.
There is no no-argument list form: bare topology enumeration is forbidden
(calling `get_edges()` raises with guidance). Enumerate or measure a wire's
edges through QL; use the indexed form only for an intentional pick, which
is recorded as a graph selection node.
**Returns:**
- `List[Edge]`: List of edge objects
**Raises:**
- `ValueError`: When edge list retrieval fails
- `Edge`: The selected edge object
**Example:**
```python
from simplecadapi import make_rectangle_rwire
from simplecadapi import make_rectangle_rwire, ql
rectangle = make_rectangle_rwire(width=4, height=3)
edges = rectangle.get_edges()
edges = ql.edges().resolve(rectangle)
print(f"The rectangle consists of {len(edges)} edges")
for i, edge in enumerate(edges):
@@ -144,7 +144,7 @@ apply_tag(spline, "smooth")
# Analyze wire properties
wires = [rectangle, circle, polyline, spline]
for wire in wires:
edges = wire.get_edges()
edges = ql.edges().resolve(wire)
closed = wire.is_closed()
tags = list_tags(wire)
@@ -181,7 +181,7 @@ def create_complex_profile():
apply_tag(profile, "symmetric")
# Add geometric info
edges = profile.get_edges()
edges = ql.edges().resolve(profile)
total_length = sum(edge.get_length() for edge in edges)
profile.set_metadata("total_length", total_length)
@@ -212,7 +212,7 @@ def analyze_wire_properties():
for i, wire in enumerate(wires):
# Basic properties
edges = wire.get_edges()
edges = ql.edges().resolve(wire)
is_closed = wire.is_closed()
# Compute total length
@@ -282,7 +282,7 @@ def transform_wires():
# Analyze transform results
for wire in all_wires:
edges = wire.get_edges()
edges = ql.edges().resolve(wire)
total_length = sum(edge.get_length() for edge in edges)
# Compute bounding box (simplified)
@@ -112,9 +112,10 @@ Gotchas this recipe absorbs:
- `incident_to` on a cylindrical wall returns seam edges too (the
vertical seam of the cylinder surface sits mid-wall); filter rims by
an axial coordinate window.
- Tagging a bare sub-shape taken from `get_faces()` fails graph
- Tagging a bare sub-shape resolved from QL fails graph
ownership ("assignment scope is not produced by the active
GraphSession"). Tag through the scope with `apply_tag_rselection`.
(The bare getter list form no longer exists — enumeration is QL-only.)
- Objects live in one `GraphSession`; passing a solid into operations
under another session fails loudly. Keep the whole build in one.
+1 -1
View File
@@ -609,7 +609,7 @@ def _build_model_body():
def _profile_entity_tags(profile: scad.Face) -> list[str]:
return sorted(
tag
for edge in scad.ql.select(items=profile.get_edges())
for edge in scad.ql.edges().resolve(profile)
.where(scad.ql.tag(pattern="sketch_entity.*"))
.all()
for tag in scad.list_tags(shape=edge)
+2 -2
View File
@@ -80,7 +80,7 @@ def _build_hydraulic_rod_assembly_body():
def _require_complete_face_naming(solid, prefix: str) -> None:
unnamed = [
index
for index, face in enumerate(solid.get_faces())
for index, face in enumerate(ql.faces().resolve(solid))
if not any(
tag.startswith(prefix)
for tag in scad.list_tags(face, scope="local")
@@ -527,7 +527,7 @@ def main() -> None:
face_count = len(ql.faces().resolve(preview))
print("assembly", assembly.assembly_id)
print("components", assembly.component_ids())
print("preview_solids", len(preview.get_solids()))
print("preview_solids", len(ql.solids().resolve(preview)))
print("preview_faces", face_count)
print("preview_volume", round(preview.get_volume(), 3))
print("graph_nodes", len(payload["graph"]["nodes"]))
+2 -2
View File
@@ -34,7 +34,7 @@ def _tag_closest_face(
"""Tag one final face while preserving the active graph source binding."""
candidates: list[tuple[float, scad.Face]] = []
for face in body.get_faces():
for face in scad.ql.faces().resolve(body):
actual_center = face.get_center()
if normal is not None:
actual_normal = face.get_normal_at()
@@ -173,7 +173,7 @@ def main() -> None:
result = build_bracket()
scad.capture(result, PACKAGE_PATH)
print("product_package", PACKAGE_PATH)
print("faces", len(result.part.body.get_faces()))
print("faces", len(scad.ql.faces().resolve(result.part.body)))
print("volume", f"{result.part.body.get_volume():.3f}")
@@ -39,8 +39,8 @@ tag_prefix: str,) -> scad.Assembly:
f"od={spec.outer_diameter:.2f} bore={spec.bore_diameter:.2f} width={spec.width:.2f}"
)
print(
f"bearing_{bearing_id}_rings: outer_faces={len(outer_ring.get_faces())} "
f"inner_faces={len(inner_ring.get_faces())}"
f"bearing_{bearing_id}_rings: outer_faces={len(scad.ql.faces().resolve(outer_ring))} "
f"inner_faces={len(scad.ql.faces().resolve(inner_ring))}"
)
return bearing
@@ -249,7 +249,7 @@ tag_prefix: str,) -> scad.Solid:
f"{stage.stage_id}_carrier_geometry: center_radius={stage.planet_center_radius:.3f} "
f"arm_length={arm_length:.3f} arm_hub_embed={hub_radius - arm_inner_radius:.3f} "
f"pin_height={pin_height:.3f} shaft_top={central_shaft_top_z:.3f} "
f"faces={len(carrier.get_faces())} volume={carrier.get_volume():.3f}"
f"faces={len(scad.ql.faces().resolve(carrier))} volume={carrier.get_volume():.3f}"
)
return carrier
@@ -143,7 +143,7 @@ def _axis_face(
normal_z: float,
) -> scad.Face:
candidates = []
for face in ql.select(items=solid.get_faces()).all():
for face in ql.faces().resolve(solid):
normal = face.get_normal_at()
if normal_z > 0.0 and normal.z < 0.65:
continue
@@ -166,7 +166,7 @@ def _axis_face(
def _ground_solid(*, label: str, solid: scad.Solid) -> None:
faces = ql.select(items=solid.get_faces()).all()
faces = ql.faces().resolve(solid)
local_roles = [
tag
for tag in scad.list_tags(shape=solid, scope="local")
@@ -181,7 +181,7 @@ def _ground_solid(*, label: str, solid: scad.Solid) -> None:
def _ground_compound(*, label: str, compound: scad.Compound) -> None:
"""Print a compact QL-backed summary of an assembly preview compound."""
solids = ql.select(items=compound.get_solids()).all()
face_count = sum(len(ql.select(items=solid.get_faces()).all()) for solid in solids)
solids = ql.solids().resolve(compound)
face_count = sum(len(ql.faces().resolve(solid)) for solid in solids)
volume = sum(solid.get_volume() for solid in solids)
print(f"{label}: solids={len(solids)} faces={face_count} volume={volume:.3f}")
@@ -73,7 +73,7 @@ def make_input_flange_rpart(*, material: scad.Material) -> scad.Part:
)
print(
f"input_flange: outer_diameter={INPUT_FLANGE_OUTER_DIAMETER:.1f} "
f"top_z={INPUT_FLANGE_TOP_Z:.3f} faces={len(flange.get_faces())}"
f"top_z={INPUT_FLANGE_TOP_Z:.3f} faces={len(scad.ql.faces().resolve(flange))}"
)
return make_axis_part_rpart(
part_id="input_flange",
@@ -106,7 +106,7 @@ def make_output_flange_rpart(*, material: scad.Material) -> scad.Part:
print(
f"output_flange: outer_diameter={OUTPUT_FLANGE_OUTER_DIAMETER:.1f} "
f"holes={OUTPUT_FLANGE_HOLE_COUNT} top_z={OUTPUT_FLANGE_TOP_Z:.3f} "
f"faces={len(flange.get_faces())}"
f"faces={len(scad.ql.faces().resolve(flange))}"
)
return make_axis_part_rpart(
part_id="output_flange",
@@ -303,7 +303,7 @@ def _make_output_flange_solid_rsolid(*, tag_prefix: str) -> scad.Solid:
print(
f"output_flange_core: od={OUTPUT_FLANGE_OUTER_DIAMETER:.1f} "
f"register_pads={OUTPUT_FLANGE_REGISTER_PAD_COUNT} link_holes={len(output_hole_angles)} "
f"cap_holes={OUTPUT_FLANGE_CENTER_FASTENER_COUNT} faces={len(flange.get_faces())} "
f"cap_holes={OUTPUT_FLANGE_CENTER_FASTENER_COUNT} faces={len(scad.ql.faces().resolve(flange))} "
f"volume={flange.get_volume():.3f}"
)
return flange
@@ -389,7 +389,7 @@ tag_prefix: str,) -> scad.Solid:
flange = scad.cut_rsolid(flange, cutters, skip_non_intersecting=False)
print(
f"flange_core: od={flange_outer_diameter:.1f} id={flange_inner_diameter:.1f} "
f"holes={hole_count} hole_d={hole_diameter:.1f} faces={len(flange.get_faces())} "
f"holes={hole_count} hole_d={hole_diameter:.1f} faces={len(scad.ql.faces().resolve(flange))} "
f"volume={flange.get_volume():.3f}"
)
return flange
@@ -247,8 +247,8 @@ tag_prefix: str,) -> scad.Solid:
def _ground_gear(*, label: str, solid: scad.Solid) -> None:
faces = ql.select(items=solid.get_faces()).all()
edges = ql.select(items=solid.get_edges()).all()
faces = ql.faces().resolve(solid)
edges = ql.edges().resolve(solid)
print(
f"gear_{label}: faces={len(faces)} edges={len(edges)} "
f"volume={solid.get_volume():.3f} tags={','.join(scad.list_tags(shape=solid))}"
@@ -121,7 +121,7 @@ def make_reducer_housing_rpart(*, material: scad.Material) -> scad.Part:
)
print(
f"housing_envelope: diameter={HOUSING_OUTER_RADIUS * 2.0:.1f} "
f"height={HOUSING_HEIGHT:.1f} datum_count={len(datum_zs)} faces={len(housing.get_faces())}"
f"height={HOUSING_HEIGHT:.1f} datum_count={len(datum_zs)} faces={len(scad.ql.faces().resolve(housing))}"
)
part = scad.make_part_rpart(
part_id="reducer_housing",
@@ -104,7 +104,7 @@ def main() -> None:
fcstd_status = f"{fcstd_path} ({fcstd_path.stat().st_size} bytes)"
solids = preview.get_solids()
solids = scad.ql.solids().resolve(preview)
print(f"envelope_diameter={HOUSING_OUTER_RADIUS * 2.0:.1f}")
print(f"envelope_height={HOUSING_HEIGHT:.1f}")
print(f"total_reduction={TOTAL_REDUCTION:.1f}")
@@ -49,8 +49,8 @@ def make_main_bearing_rassembly(*, bearing_id: str, spec: BearingSpec, material:
print(
f"bearing_{bearing_id}: stdlib=fused rollers={meta['ball_count']} "
f"bore={spec.bore_diameter:.1f} od={spec.outer_diameter:.1f} "
f"width={spec.width:.1f} outer_faces={len(outer.get_faces())} "
f"inner_faces={len(inner.get_faces())} material={material.material_id}"
f"width={spec.width:.1f} outer_faces={len(scad.ql.faces().resolve(outer))} "
f"inner_faces={len(scad.ql.faces().resolve(inner))} material={material.material_id}"
)
return bearing
@@ -147,7 +147,7 @@ angle_offset: float = 0.0,) -> list[scad.Solid]:
def ground_solid(*, label: str, solid: scad.Solid) -> None:
"""Print a concise QL-backed solid summary."""
faces = ql.select(items=solid.get_faces()).all()
faces = ql.faces().resolve(solid)
local_roles = [
tag
for tag in scad.list_tags(shape=solid, scope="local")
@@ -162,8 +162,8 @@ def ground_solid(*, label: str, solid: scad.Solid) -> None:
def ground_compound(*, label: str, compound: scad.Compound) -> None:
"""Print a concise QL-backed assembly projection summary."""
solids = ql.select(items=compound.get_solids()).all()
faces = sum(len(ql.select(items=solid.get_faces()).all()) for solid in solids)
solids = ql.solids().resolve(compound)
faces = sum(len(ql.faces().resolve(solid)) for solid in solids)
volume = sum(solid.get_volume() for solid in solids)
print(f"{label}: solids={len(solids)} faces={faces} volume={volume:.3f}")
+1 -1
View File
@@ -142,4 +142,4 @@ def make_link_part(
def link_faces_and_volume(body: scad.Solid) -> tuple[int, float]:
"""QL grounding facts for one finished link body."""
return len(body.get_faces()), body.get_volume()
return len(scad.ql.faces().resolve(body)), body.get_volume()
+2 -2
View File
@@ -47,8 +47,8 @@ def _validate_dimensions(*, span: float, sag: float, left_diameter: float, right
def _print_stage(label: str, solid: scad.Solid) -> None:
faces = cast(list[scad.Face], solid.get_faces())
edges = cast(list[scad.Edge], solid.get_edges())
faces = ql.faces().resolve(solid)
edges = ql.edges().resolve(solid)
print(f"{label}: faces={len(faces)} edges={len(edges)} volume={solid.get_volume():.3f}")
+2 -2
View File
@@ -85,7 +85,7 @@ def build_shell_body() -> scad.Solid:
ql.prop("geom.area", ">=", 500.0),
)).resolve(shell)
assert len(bottom_face) == 1, f"平底面识别异常 n={len(bottom_face)}"
rim_edges = list(bottom_face[0].get_outer_wire().get_edges())
rim_edges = ql.edges().resolve(bottom_face[0].get_outer_wire())
assert len(rim_edges) >= 4, f"平底外缘边识别异常 n={len(rim_edges)}"
shell = scad.fillet_rsolid(solid=shell, edges=rim_edges, radius=p["safe_fillet_r"])
@@ -152,4 +152,4 @@ def build_shell_part() -> scad.Part:
if __name__ == "__main__":
result = build_shell_part()
body = result.value.body
print(f"shell volume={body.get_volume():.3f} faces={len(body.get_faces())}")
print(f"shell volume={body.get_volume():.3f} faces={len(ql.faces().resolve(body))}")
+1 -1
View File
@@ -484,4 +484,4 @@ def build_flat_bottom() -> scad.Solid:
if __name__ == "__main__":
result = build_u_link_part()
body = result.value.body
print(f"part volume={body.get_volume():.3f} faces={len(body.get_faces())}")
print(f"part volume={body.get_volume():.3f} faces={len(scad.ql.faces().resolve(body))}")
@@ -90,7 +90,7 @@ with GraphSession(graph_id="s7_hyp") as session:
n_after_cut = len(ql.faces().where(ql.tag("feature.back_face")).resolve(body))
print(f"H3 back tag after S3 pocket cut: n={n_after_cut}")
body = u_link.scad.fillet_rsolid(solid=body, edges=list(body.get_edges()),
body = u_link.scad.fillet_rsolid(solid=body, edges=ql.edges().resolve(body),
radius=P["fillet_r"], generated_faces_tag="fillet.global_patch")
n_after_fillet = len(ql.faces().where(ql.tag("feature.back_face")).resolve(body))
backs4 = ql.faces().where(ql.and_(
@@ -79,7 +79,7 @@ with scad.GraphSession(graph_id=f"s9_diag_{label}") as session:
counts = {}
picked = []
for e in body.get_edges():
for e in scad.ql.edges().resolve(body):
g = group_of(e)
counts[g] = counts.get(g, 0) + 1
if g in want:
+1 -1
View File
@@ -102,7 +102,7 @@ def build_solid_trimesh(
all_corner_normals: list[tuple[tuple[float, float, float], ...]] = []
face_ranges: list[FaceTriangleRange] = []
for face_index, face in enumerate(solid.get_faces()):
for face_index, face in enumerate(solid._iter_faces()):
start = len(all_triangles)
vertices, triangles, corner_normals = tessellate_face_with_normals(
face.wrapped,
+226 -136
View File
@@ -21,7 +21,7 @@ from OCP.TopAbs import (
from OCP.TopoDS import TopoDS, TopoDS_Shape
from ._internal.vendor_warning_filters import suppress_vendor_deprecation_warnings
from .errors import raise_harness_error
from .errors import SimpleCADError, raise_harness_error
from .kernel.ocp_cast import (
as_compound,
as_edge,
@@ -958,23 +958,49 @@ def _record_indexed_topology_selection(source: Any, selected_shapes: Iterable[An
return
class _TopologySelectionList(list):
def __init__(self, source: Any, target_kind: str, items: Iterable[Any]) -> None:
super().__init__(items)
self._source = source
self._target_kind = target_kind
def _topology_enumeration_error(method: str, kind: str) -> SimpleCADError:
"""Bare topology enumeration is forbidden: reads go through QL selectors."""
from .errors import ErrorGuidance
def __getitem__(self, index: Any) -> Any:
selected = super().__getitem__(index)
if isinstance(index, slice):
_record_indexed_topology_selection(self._source, selected)
return selected
_record_indexed_topology_selection(self._source, [selected])
return selected
return SimpleCADError(
f"{method} (no index)",
ErrorGuidance(
what_happened=(
f"{method}() without an index no longer returns a list — "
"bare topology enumeration is not part of the public API."
),
possible_causes=(
"Calling a plural topology getter (get_edges/get_faces/...) with no argument.",
"Porting code that enumerated topology with Python loops or len().",
),
how_to_fix=(
"Enumerate or measure via QL: ql.edges().resolve(shape) / len(ql.faces().resolve(shape)).",
"Pick intentionally with the indexed form get_edges(index) — indexed picks "
"are recorded as graph selection nodes.",
"Filter with QL predicates and cardinality (take/exactly) instead of "
"post-filtering an enumerated list.",
),
signature=f"{method}(index: int) -> {kind.capitalize()}",
technical_details=(
"Enumeration escapes the graph: selections made by indexing a bare list "
"carry no predicate and capture kernel artifacts (e.g. periodic-face seams)."
),
),
)
def _selection_list(source: Any, target_kind: str, items: Iterable[Any]) -> List[Any]:
return cast(List[Any], _TopologySelectionList(source, target_kind, items))
def _indexed_topology_pick(
source: Any,
kind: str,
items: List[Any],
index: Optional[int],
method: str,
) -> Any:
if index is None:
raise _topology_enumeration_error(method, kind)
selected = items[index]
_record_indexed_topology_selection(source, [selected])
return selected
class Vertex(TaggedMixin, TopoMixein):
@@ -1070,15 +1096,17 @@ class Edge(TaggedMixin, TopoMixein):
break
return faces
def get_vertices(self, index: Optional[int] = None) -> Union[List[Vertex], Vertex]:
def _iter_vertices(self) -> List[Vertex]:
return [child for child in self.get_children() if isinstance(child, Vertex)]
def get_vertices(self, index: Optional[int] = None) -> Vertex:
try:
vertices = [
child for child in self.get_children() if isinstance(child, Vertex)
]
result = cast(List[Vertex], _selection_list(self, "vertex", vertices))
if index is None:
return result
return result[index]
return cast(
Vertex,
_indexed_topology_pick(self, "vertex", self._iter_vertices(), index, "get_vertices"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取顶点失败: {e}")
@@ -1123,12 +1151,17 @@ class Wire(TaggedMixin, TopoMixein):
except Exception as e:
raise ValueError(f"初始化线失败: {e}. 请检查输入的线对象是否有效。")
def get_edges(self, index: Optional[int] = None) -> Union[List[Edge], Edge]:
def _iter_edges(self) -> List[Edge]:
return cast(List[Edge], self.get_children())
def get_edges(self, index: Optional[int] = None) -> Edge:
try:
result = cast(List[Edge], _selection_list(self, "edge", self.get_children()))
if index is None:
return result
return result[index]
return cast(
Edge,
_indexed_topology_pick(self, "edge", self._iter_edges(), index, "get_edges"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取边失败: {e}")
@@ -1139,7 +1172,7 @@ class Wire(TaggedMixin, TopoMixein):
raise ValueError(f"检查线闭合性失败: {e}")
def _tag_edges(self) -> None:
for i, edge in enumerate(self.get_edges()):
for i, edge in enumerate(self._iter_edges()):
edge._apply_tag("edge.boundary", propagate=False)
geo = dict(edge.get_metadata("geo", {}))
geo["edge_index"] = i
@@ -1149,11 +1182,11 @@ class Wire(TaggedMixin, TopoMixein):
return self._format_string(indent=0)
def __repr__(self) -> str:
return f"Wire(edge_count={len(self.get_edges())}, closed={self.is_closed()}, tags={self._list_tags()})"
return f"Wire(edge_count={len(self._iter_edges())}, closed={self.is_closed()}, tags={self._list_tags()})"
def _format_string(self, indent: int = 0, show_coordinate_system: bool = False) -> str:
spaces = " " * indent
edges = self.get_edges()
edges = self._iter_edges()
result = [f"{spaces}Wire:", f"{spaces} edge_count: {len(edges)}", f"{spaces} closed: {self.is_closed()}"]
if edges:
result.append(f"{spaces} edges:")
@@ -1179,14 +1212,14 @@ class Face(TaggedMixin, TopoMixein):
outer_wire._apply_tag("wire.outer", propagate=False)
self.add_child(outer_wire)
outer_wire._entity.incident_face_ids.add(self.topo_id)
for edge in outer_wire.get_edges():
for edge in outer_wire._iter_edges():
edge._entity.incident_face_ids.add(self.topo_id)
for wire in inner_wires_of(self.wrapped):
inner = Wire(wire, cache=self._topology_cache)
inner._apply_tag("wire.inner", propagate=False)
self.add_child(inner)
inner._entity.incident_face_ids.add(self.topo_id)
for edge in inner.get_edges():
for edge in inner._iter_edges():
edge._entity.incident_face_ids.add(self.topo_id)
except Exception as e:
raise ValueError(f"初始化面失败: {e}. 请检查输入的面对象是否有效。")
@@ -1207,7 +1240,7 @@ class Face(TaggedMixin, TopoMixein):
outer_wire = self.get_outer_wire()
outer_wire._apply_tag("wire.outer", propagate=False)
outer_wire._tag_edges()
for i, inner in enumerate(self.get_inner_wires()):
for i, inner in enumerate(self._iter_inner_wires()):
inner._apply_tag("wire.inner", propagate=False)
geo = dict(inner.get_metadata("geo", {}))
geo["inner_wire_index"] = i
@@ -1220,46 +1253,64 @@ class Face(TaggedMixin, TopoMixein):
except Exception as e:
raise ValueError(f"获取外边界线失败: {e}")
def get_wires(self, index: Optional[int] = None) -> Union[List[Wire], Wire]:
def _iter_wires(self) -> List[Wire]:
return [child for child in self.get_children() if isinstance(child, Wire)]
def get_wires(self, index: Optional[int] = None) -> Wire:
try:
wires = [child for child in self.get_children() if isinstance(child, Wire)]
result = cast(List[Wire], _selection_list(self, "wire", wires))
if index is None:
return result
return result[index]
return cast(
Wire,
_indexed_topology_pick(self, "wire", self._iter_wires(), index, "get_wires"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取边界线失败: {e}")
def get_inner_wires(self, index: Optional[int] = None) -> Union[List[Wire], Wire]:
def _iter_inner_wires(self) -> List[Wire]:
return [
w
for w in cast(List[Wire], self.get_children())
if w.is_closed() and w._has_tag("wire.inner")
]
def get_inner_wires(self, index: Optional[int] = None) -> Wire:
try:
wires = [
w
for w in cast(List[Wire], self.get_children())
if w.is_closed() and w._has_tag("wire.inner")
]
result = cast(List[Wire], _selection_list(self, "wire", wires))
if index is None:
return result
return result[index]
return cast(
Wire,
_indexed_topology_pick(
self, "wire", self._iter_inner_wires(), index, "get_inner_wires"
),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取内边界线失败: {e}")
def get_center(self) -> Vec3:
return center_of_mass(self.wrapped)
def get_edges(self, index: Optional[int] = None) -> Union[List[Edge], Edge]:
def _iter_edges(self) -> List[Edge]:
edges: List[Edge] = []
edges.extend(self.get_outer_wire().get_edges())
for inner in self.get_inner_wires():
edges.extend(inner.get_edges())
result = cast(List[Edge], _selection_list(self, "edge", edges))
if index is None:
return result
return result[index]
edges.extend(self.get_outer_wire()._iter_edges())
for inner in self._iter_inner_wires():
edges.extend(inner._iter_edges())
return edges
def get_edges(self, index: Optional[int] = None) -> Edge:
try:
return cast(
Edge,
_indexed_topology_pick(self, "edge", self._iter_edges(), index, "get_edges"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取边失败: {e}")
def get_adjacent_faces(self) -> List["Face"]:
adjacent: Dict[str, Face] = {}
for edge in self.get_edges():
for edge in self._iter_edges():
for face in edge.get_incident_faces():
if face.topo_id != self.topo_id:
adjacent.setdefault(face.topo_id, face)
@@ -1285,7 +1336,7 @@ class Face(TaggedMixin, TopoMixein):
except Exception:
result.append(f"{spaces} outer_wire: [unable to retrieve]")
try:
for inner in self.get_inner_wires():
for inner in self._iter_inner_wires():
result.append(f"{spaces} inner_wire:")
result.append(inner._format_string(indent + 2, False))
except Exception:
@@ -1326,41 +1377,48 @@ class Shell(TaggedMixin, TopoMixein):
return shell_is_closed(self.wrapped)
def get_faces(self, index: Optional[int] = None) -> Union[List[Face], Face]:
faces = [
def _iter_faces(self) -> List[Face]:
return [
face for face in cast(List[Face], self.get_children()) if isinstance(face, Face)
]
result = cast(List[Face], _selection_list(self, "face", faces))
if index is None:
return result
return result[index]
def get_wires(self, index: Optional[int] = None) -> Union[List[Wire], Wire]:
"""Return the Shell's free boundary wires."""
def get_faces(self, index: Optional[int] = None) -> Face:
return cast(
Face,
_indexed_topology_pick(self, "face", self._iter_faces(), index, "get_faces"),
)
wires = [
def _iter_wires(self) -> List[Wire]:
"""The Shell's free boundary wires."""
return [
wire
for wire in cast(List[Wire], self.get_children())
if isinstance(wire, Wire)
]
result = cast(List[Wire], _selection_list(self, "wire", wires))
if index is None:
return result
return result[index]
def get_edges(self, index: Optional[int] = None) -> Union[List[Edge], Edge]:
def get_wires(self, index: Optional[int] = None) -> Wire:
return cast(
Wire,
_indexed_topology_pick(self, "wire", self._iter_wires(), index, "get_wires"),
)
def _iter_edges(self) -> List[Edge]:
unique: Dict[str, Edge] = {}
for face in self.get_faces():
for edge in face.get_edges():
for face in self._iter_faces():
for edge in face._iter_edges():
unique.setdefault(edge.topo_id, edge)
result = cast(List[Edge], _selection_list(self, "edge", unique.values()))
if index is None:
return result
return result[index]
return list(unique.values())
def get_edges(self, index: Optional[int] = None) -> Edge:
return cast(
Edge,
_indexed_topology_pick(self, "edge", self._iter_edges(), index, "get_edges"),
)
def __repr__(self) -> str:
return (
f"Shell(faces={len(self.get_faces())}, area={self.get_area():.3f}, "
f"Shell(faces={len(self._iter_faces())}, area={self.get_area():.3f}, "
f"closed={self.is_closed()}, tags={self._list_tags()})"
)
@@ -1391,46 +1449,62 @@ class Solid(TaggedMixin, TopoMixein):
except Exception as e:
raise ValueError(f"获取体积失败: {e}")
def get_faces(self, index: Optional[int] = None) -> Union[List[Face], Face]:
def _iter_faces(self) -> List[Face]:
return [
f for f in cast(List[Face], self.get_children()) if isinstance(f, Face)
]
def get_faces(self, index: Optional[int] = None) -> Face:
try:
faces = [
f for f in cast(List[Face], self.get_children()) if isinstance(f, Face)
]
result = cast(List[Face], _selection_list(self, "face", faces))
if index is None:
return result
return result[index]
return cast(
Face,
_indexed_topology_pick(self, "face", self._iter_faces(), index, "get_faces"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取面失败: {e}")
def get_edges(self, index: Optional[int] = None) -> Union[List[Edge], Edge]:
def _iter_edges(self) -> List[Edge]:
unique: Dict[str, Edge] = {}
for face in self._iter_faces():
for edge in face._iter_edges():
unique.setdefault(edge.topo_id, edge)
return list(unique.values())
def get_edges(self, index: Optional[int] = None) -> Edge:
try:
unique: Dict[str, Edge] = {}
for face in self.get_faces():
for edge in face.get_edges():
unique.setdefault(edge.topo_id, edge)
result = cast(List[Edge], _selection_list(self, "edge", unique.values()))
if index is None:
return result
return result[index]
return cast(
Edge,
_indexed_topology_pick(self, "edge", self._iter_edges(), index, "get_edges"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取边失败: {e}")
def get_edge_occurrences(self, index: Optional[int] = None) -> Union[List[Edge], Edge]:
def _iter_edge_occurrences(self) -> List[Edge]:
edges: List[Edge] = []
for face in self._iter_faces():
edges.extend(face._iter_edges())
return edges
def get_edge_occurrences(self, index: Optional[int] = None) -> Edge:
try:
edges: List[Edge] = []
for face in self.get_faces():
edges.extend(face.get_edges())
result = cast(List[Edge], _selection_list(self, "edge", edges))
if index is None:
return result
return result[index]
return cast(
Edge,
_indexed_topology_pick(
self, "edge", self._iter_edge_occurrences(), index, "get_edge_occurrences"
),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取边实例列表失败: {e}")
def auto_tag_faces(self, geometry_type: str = "unknown") -> None:
try:
faces = self.get_faces()
faces = self._iter_faces()
if geometry_type == "box" and len(faces) == 6:
self._auto_tag_box_faces(faces)
elif geometry_type == "cylinder" and len(faces) == 3:
@@ -1504,12 +1578,12 @@ class Solid(TaggedMixin, TopoMixein):
return self._format_string(indent=0)
def __repr__(self) -> str:
return f"Solid(volume={self.get_volume():.3f}, faces={len(self.get_faces())}, tags={self._list_tags()})"
return f"Solid(volume={self.get_volume():.3f}, faces={len(self._iter_faces())}, tags={self._list_tags()})"
def _format_string(self, indent: int = 0, show_coordinate_system: bool = True) -> str:
spaces = " " * indent
faces = self.get_faces()
edges = self.get_edges()
faces = self._iter_faces()
edges = self._iter_edges()
result = [f"{spaces}Solid:", f"{spaces} volume: {self.get_volume():.3f}", f"{spaces} face_count: {len(faces)}", f"{spaces} edge_count: {len(edges)}"]
if show_coordinate_system:
current_cs = get_current_cs()
@@ -1541,53 +1615,69 @@ class Compound(TaggedMixin, TopoMixein):
except Exception as e:
raise ValueError(f"初始化组合体失败: {e}. 请检查输入的组合体对象是否有效。")
def get_solids(self, index: Optional[int] = None) -> Union[List[Solid], Solid]:
def _iter_solids(self) -> List[Solid]:
return [
child for child in self.get_children() if isinstance(child, Solid)
]
def get_solids(self, index: Optional[int] = None) -> Solid:
try:
solids = [
child for child in self.get_children() if isinstance(child, Solid)
]
if index is None:
return solids
return solids[index]
return cast(
Solid,
_indexed_topology_pick(self, "solid", self._iter_solids(), index, "get_solids"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取实体列表失败: {e}")
def get_faces(self, index: Optional[int] = None) -> Union[List[Face], Face]:
def _iter_faces(self) -> List[Face]:
faces: List[Face] = []
for solid in self._iter_solids():
faces.extend(solid._iter_faces())
return faces
def get_faces(self, index: Optional[int] = None) -> Face:
try:
faces: List[Face] = []
for solid in self.get_solids():
faces.extend(cast(Solid, solid).get_faces())
if index is None:
return faces
return faces[index]
return cast(
Face,
_indexed_topology_pick(self, "face", self._iter_faces(), index, "get_faces"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取面失败: {e}")
def get_edges(self, index: Optional[int] = None) -> Union[List[Edge], Edge]:
def _iter_edges(self) -> List[Edge]:
unique: Dict[str, Edge] = {}
for face in self._iter_faces():
for edge in face._iter_edges():
unique.setdefault(edge.topo_id, edge)
return list(unique.values())
def get_edges(self, index: Optional[int] = None) -> Edge:
try:
unique: Dict[str, Edge] = {}
for face in self.get_faces():
for edge in face.get_edges():
unique.setdefault(edge.topo_id, edge)
edges = list(unique.values())
if index is None:
return edges
return edges[index]
return cast(
Edge,
_indexed_topology_pick(self, "edge", self._iter_edges(), index, "get_edges"),
)
except SimpleCADError:
raise
except Exception as e:
raise ValueError(f"获取边失败: {e}")
def get_volume(self) -> float:
return sum(float(solid.get_volume()) for solid in self.get_solids())
return sum(float(solid.get_volume()) for solid in self._iter_solids())
def __str__(self) -> str:
return self._format_string(indent=0)
def __repr__(self) -> str:
return f"Compound(solids={len(self.get_solids())}, volume={self.get_volume():.3f}, tags={self._list_tags()})"
return f"Compound(solids={len(self._iter_solids())}, volume={self.get_volume():.3f}, tags={self._list_tags()})"
def _format_string(self, indent: int = 0, show_coordinate_system: bool = True) -> str:
spaces = " " * indent
solids = cast(List[Solid], self.get_solids())
solids = cast(List[Solid], self._iter_solids())
result = [
f"{spaces}Compound:",
f"{spaces} solid_count: {len(solids)}",
+1 -1
View File
@@ -722,7 +722,7 @@ def _render_sdk_screenshot_rpath(
(bounds[2] + bounds[3]) * 0.5,
(bounds[4] + bounds[5]) * 0.5,
)
for face in solid.get_faces():
for face in solid._iter_faces():
face_tag = next((tag for tag in tags if face._has_tag(tag)), None)
selected_tag = face_tag or solid_tag
grouped_faces.setdefault(selected_tag, []).append(face.wrapped)
+17 -17
View File
@@ -911,12 +911,12 @@ def _make_selector_hint(shape: AnyShape) -> Dict[str, object]:
if normal_tuple is not None:
hint["normal"] = normal_tuple
elif isinstance(shape, Wire):
hint["edge_count"] = len(shape.get_edges())
hint["edge_count"] = len(shape._iter_edges())
hint["closed"] = bool(shape.is_closed())
elif isinstance(shape, Vertex):
hint["coordinates"] = tuple(float(v) for v in shape.get_coordinates())
elif isinstance(shape, Shell):
hint["face_count"] = len(shape.get_faces())
hint["face_count"] = len(shape._iter_faces())
bb = bounding_box(shape.wrapped)
hint["bbox"] = {
"min": (float(bb.xmin), float(bb.ymin), float(bb.zmin)),
@@ -931,7 +931,7 @@ def _make_selector_hint(shape: AnyShape) -> Dict[str, object]:
}
elif isinstance(shape, Compound):
hint["volume"] = float(shape.get_volume())
hint["solid_count"] = len(shape.get_solids())
hint["solid_count"] = len(shape._iter_solids())
bb = bounding_box(shape.wrapped)
hint["bbox"] = {
"min": (float(bb.xmin), float(bb.ymin), float(bb.zmin)),
@@ -1058,15 +1058,15 @@ def _selection_op_for_shape(shape: AnyShape) -> Optional[str]:
def _candidate_shapes_for_selection(source: AnyShape, kind: str) -> List[AnyShape]:
if kind == "edge":
if hasattr(source, "get_edges"):
return list(source.get_edges())
return list(source._iter_edges())
return [source] if isinstance(source, Edge) else []
if kind == "face":
if isinstance(source, (Shell, Solid, Compound)):
return list(source.get_faces())
return list(source._iter_faces())
return [source] if isinstance(source, Face) else []
if kind == "wire":
if isinstance(source, Face):
return [source.get_outer_wire(), *source.get_inner_wires()]
return [source.get_outer_wire(), *source._iter_inner_wires()]
if hasattr(source, "get_children"):
return [
cast(AnyShape, child)
@@ -1094,7 +1094,7 @@ def _candidate_shapes_for_selection(source: AnyShape, kind: str) -> List[AnyShap
return [source] if isinstance(source, Shell) else []
if kind == "solid":
if isinstance(source, Compound):
return cast(List[AnyShape], source.get_solids())
return cast(List[AnyShape], source._iter_solids())
return [source] if isinstance(source, Solid) else []
if kind == "compound":
return [source] if isinstance(source, Compound) else []
@@ -1160,7 +1160,7 @@ def _make_geo_selector(
except Exception:
pass
elif isinstance(shape, Wire):
selector["edge_count"] = len(shape.get_edges())
selector["edge_count"] = len(shape._iter_edges())
selector["closed"] = bool(shape.is_closed())
elif isinstance(shape, Face):
selector["area"] = float(shape.get_area())
@@ -1168,10 +1168,10 @@ def _make_geo_selector(
normal = shape.get_normal_at()
selector["center"] = [float(center.x), float(center.y), float(center.z)]
selector["normal"] = [float(normal.x), float(normal.y), float(normal.z)]
selector["edge_count"] = len(shape.get_edges())
selector["inner_wire_count"] = len(shape.get_inner_wires())
selector["edge_count"] = len(shape._iter_edges())
selector["inner_wire_count"] = len(shape._iter_inner_wires())
elif isinstance(shape, Shell):
selector["face_count"] = len(shape.get_faces())
selector["face_count"] = len(shape._iter_faces())
elif isinstance(shape, Solid):
selector["volume"] = float(shape.get_volume())
center = shape.get_center() if hasattr(shape, "get_center") else None
@@ -1179,7 +1179,7 @@ def _make_geo_selector(
selector["center"] = [float(center.x), float(center.y), float(center.z)]
elif isinstance(shape, Compound):
selector["volume"] = float(shape.get_volume())
selector["solid_count"] = len(shape.get_solids())
selector["solid_count"] = len(shape._iter_solids())
return selector
def _record_geo_selection_nodes(
@@ -1580,10 +1580,10 @@ def _copy_exact_topology_identity_tags(
source_members = [
member
for source in sources
for member in (source.get_edges() if hasattr(source, "get_edges") else [source])
for member in (source._iter_edges() if hasattr(source, "get_edges") else [source])
if isinstance(member, Edge)
]
target_members = target.get_edges() if hasattr(target, "get_edges") else [target]
target_members = target._iter_edges() if hasattr(target, "get_edges") else [target]
result = target
for target_member in target_members:
if not isinstance(target_member, Edge):
@@ -1679,7 +1679,7 @@ def _apply_profile_tag_prefix(
if prefix is not None
else shape
)
edges = list(shape.get_edges())
edges = list(shape._iter_edges())
local_names = (
[str(value) for value in edge_tags]
if edge_tags is not None
@@ -1980,13 +1980,13 @@ def _apply_feature_tag_prefix(
_topo_id(edge.wrapped): edge
for source in source_shapes
for edge in (
source.get_edges()
source._iter_edges()
if hasattr(source, "get_edges")
else ([source] if isinstance(source, Edge) else [])
)
}
result_faces = {
_topo_id(face.wrapped): face for face in cast(Solid, result).get_faces()
_topo_id(face.wrapped): face for face in cast(Solid, result)._iter_faces()
}
if side_role is not None:
# A side Face may have multiple source profile Edges (for example, a
+3 -3
View File
@@ -349,7 +349,7 @@ def fillet_rsolid(
selection_params["selected_edge_node_ids"] = selected_edge_node_ids
else:
selection_params["selected_edge_indices"] = _serialize_selection_indices(
selected_edges, solid.get_edges()
selected_edges, solid._iter_edges()
)
target_kinds = _validate_operation_output_roles(tracked.delta, assignments)
@@ -431,7 +431,7 @@ def chamfer_rsolid(
selection_params["selected_edge_node_ids"] = selected_edge_node_ids
else:
selection_params["selected_edge_indices"] = _serialize_selection_indices(
selected_edges, solid.get_edges()
selected_edges, solid._iter_edges()
)
target_kinds = _validate_operation_output_roles(tracked.delta, assignments)
@@ -523,7 +523,7 @@ def shell_rsolid(
selection_params["selected_face_node_ids"] = selected_face_node_ids
else:
selection_params["selected_face_indices"] = _serialize_selection_indices(
selected_faces, solid.get_faces()
selected_faces, solid._iter_faces()
)
target_kinds = _validate_operation_output_roles(tracked.delta, assignments)
+11 -11
View File
@@ -582,15 +582,15 @@ def _pending_loft_role(shape: AnyShape, role: str, method: str) -> TopoRoleEntry
)
def _matching_shell_boundary(shell: Shell, profile: Wire) -> Wire:
profile_edges = list(profile.get_edges())
profile_edges = list(profile._iter_edges())
matches = [
boundary
for boundary in shell.get_wires()
if len(boundary.get_edges()) == len(profile_edges)
for boundary in shell._iter_wires()
if len(boundary._iter_edges()) == len(profile_edges)
and all(
any(
edge.wrapped.IsSame(profile_edge.wrapped)
for edge in boundary.get_edges()
for edge in boundary._iter_edges()
)
for profile_edge in profile_edges
)
@@ -606,8 +606,8 @@ def _apply_loft_role_metadata(
) -> AnyShape:
candidates: Dict[Tuple[TopoKind, str], AnyShape] = {}
for kind, members in (
(TopoKind.FACE, shape.get_faces() if hasattr(shape, "get_faces") else []),
(TopoKind.WIRE, shape.get_wires() if hasattr(shape, "get_wires") else []),
(TopoKind.FACE, shape._iter_faces() if hasattr(shape, "get_faces") else []),
(TopoKind.WIRE, shape._iter_wires() if hasattr(shape, "get_wires") else []),
):
for member in members:
candidates[(kind, _topo_id(member.wrapped))] = member
@@ -783,7 +783,7 @@ def loft_rshell(
)
roles = [
_pending_loft_role(face, "loft.side", "ResultSideFace")
for face in result.get_faces()
for face in result._iter_faces()
]
if start_is_wire:
roles.append(
@@ -936,7 +936,7 @@ def make_solid_from_shell_rsolid(
)
_carry_face_provenance(
result,
shell.get_faces(),
shell._iter_faces(),
allow_orientation_change=True,
replace_local_bindings=False,
)
@@ -1882,7 +1882,7 @@ def _carry_face_provenance(
allow_orientation_change: bool = False,
replace_local_bindings: bool = True,
) -> None:
result_faces = list(shape.get_faces())
result_faces = list(shape._iter_faces())
if result_face_indices is None:
mapped_indices = []
for source in source_faces:
@@ -2056,7 +2056,7 @@ def _attach_brep_region_provenance(
)
shape._add_tag_binding(root_binding)
source_face_ids = tuple(region.get("source_face_ids") or ())
for index, face in enumerate(shape.get_faces()):
for index, face in enumerate(shape._iter_faces()):
face_evidence = {
**evidence,
"source_face_id": (
@@ -3290,7 +3290,7 @@ def make_helix_redge(
x_direction=global_x_direction,
)
wire = Wire(wire_shape)
edges = wire.get_edges()
edges = wire._iter_edges()
if not edges:
raise ValueError("无法从螺旋线中提取边")
helix_edge = edges[0]
+3 -3
View File
@@ -411,7 +411,7 @@ def make_face_connector_rconnector(
],
how_to_fix=[
"Use a stable connector_id such as 'mount_face'.",
"Select a face via ql.faces().resolve(solid) or solid.get_faces()[i].",
"Select a face via ql.faces().where(...).resolve(solid), or an indexed pick solid.get_faces(index).",
],
error=e,
)
@@ -448,7 +448,7 @@ def make_edge_connector_rconnector(
],
how_to_fix=[
"Use a stable connector_id such as 'hinge_axis'.",
"Select an edge via ql.edges().resolve(solid) or solid.get_edges()[i].",
"Select an edge via ql.edges().where(...).resolve(solid), or an indexed pick solid.get_edges(index).",
],
error=e,
)
@@ -485,7 +485,7 @@ def make_vertex_connector_rconnector(
],
how_to_fix=[
"Use a stable connector_id such as 'pivot_point'.",
"Select a vertex via ql.vertices().resolve(solid) or solid.get_vertices()[i].",
"Select a vertex via ql.vertices().where(...).resolve(solid), or an indexed pick solid.get_vertices(index).",
],
error=e,
)
+3 -3
View File
@@ -123,7 +123,7 @@ def select_faces_by_tag(
try:
normalized = normalize_tag(tag, strict=True)
resolved_scope = normalize_tag_scope(scope)
faces = solid.get_faces()
faces = solid._iter_faces()
return [face for face in faces if face._has_tag(normalized, resolved_scope)]
except Exception as e:
_wrap_public_api_error(
@@ -150,9 +150,9 @@ def select_edges_by_tag(
normalized = normalize_tag(tag, strict=True)
resolved_scope = normalize_tag_scope(scope)
if isinstance(shape, Face):
edges = shape.get_edges()
edges = shape._iter_edges()
elif isinstance(shape, Solid):
edges = shape.get_edges()
edges = shape._iter_edges()
else:
raise ValueError("只能从面或实体中选择边")
+4 -4
View File
@@ -996,7 +996,7 @@ def _apply_sketch_promotion_metadata(
if isinstance(shape, Wire):
wires = [shape]
elif isinstance(shape, Face):
wires = cast(List[Wire], shape.get_wires())
wires = cast(List[Wire], shape._iter_wires())
for wire in wires:
matches = [
@@ -1025,7 +1025,7 @@ def _apply_sketch_promotion_metadata(
"sketch.entity_edges", []
)
]
for edge in cast(List[Edge], shape.get_edges()):
for edge in cast(List[Edge], shape._iter_edges()):
matches = [source for source in source_edges if source[4].IsSame(edge.wrapped)]
if len(matches) != 1:
raise ValueError(
@@ -1145,7 +1145,7 @@ def _apply_sketch_promotion_identity_tags(
)
if isinstance(shape, Face):
for wire in cast(List[Wire], shape.get_wires()):
for wire in cast(List[Wire], shape._iter_wires()):
matches = [
source
for source in source_wires
@@ -1178,7 +1178,7 @@ def _apply_sketch_promotion_identity_tags(
"sketch.entity_edges", []
)
]
for edge in cast(List[Edge], shape.get_edges()):
for edge in cast(List[Edge], shape._iter_edges()):
matches = [source for source in source_edges if source[2].IsSame(edge.wrapped)]
if len(matches) != 1:
raise ValueError(
+10 -10
View File
@@ -1107,7 +1107,7 @@ def _boundary_items(scope: Any, target_kind: str) -> List[Any]:
if target_kind == "face":
if hasattr(scope, "get_faces"):
return list(scope.get_faces())
return list(scope._iter_faces())
return []
if target_kind == "wire":
@@ -1116,11 +1116,11 @@ def _boundary_items(scope: Any, target_kind: str) -> List[Any]:
if hasattr(scope, "get_outer_wire"):
wires.append(scope.get_outer_wire())
if hasattr(scope, "get_inner_wires"):
wires.extend(scope.get_inner_wires())
wires.extend(scope._iter_inner_wires())
return wires
if hasattr(scope, "get_faces"):
wires = []
for face in scope.get_faces():
for face in scope._iter_faces():
wires.extend(_boundary_items(face, "wire"))
return _dedupe_items(wires)
if hasattr(scope, "get_children"):
@@ -1136,13 +1136,13 @@ def _boundary_items(scope: Any, target_kind: str) -> List[Any]:
edges = []
for wire in _boundary_items(scope, "wire"):
if hasattr(wire, "get_edges"):
edges.extend(wire.get_edges())
edges.extend(wire._iter_edges())
return _dedupe_items(edges)
if hasattr(scope, "get_edges"):
return _dedupe_items(scope.get_edges())
return _dedupe_items(scope._iter_edges())
if hasattr(scope, "get_faces"):
edges = []
for face in scope.get_faces():
for face in scope._iter_faces():
edges.extend(_boundary_items(face, "edge"))
return _dedupe_items(edges)
return []
@@ -1163,7 +1163,7 @@ def _boundary_items(scope: Any, target_kind: str) -> List[Any]:
if target_kind == "solid":
if cls_name == "Compound" and hasattr(scope, "get_solids"):
return list(scope.get_solids())
return list(scope._iter_solids())
return [scope] if cls_name == "Solid" else []
if target_kind == "shell":
@@ -1198,10 +1198,10 @@ def _resolve_scope_items(scope: Any, target_kind: str) -> List[Any]:
return [scope]
if target_kind == "edge":
if hasattr(scope, "get_edges"):
return list(scope.get_edges())
return list(scope._iter_edges())
if target_kind == "face":
if hasattr(scope, "get_faces"):
return list(scope.get_faces())
return list(scope._iter_faces())
if target_kind == "shell":
if hasattr(scope, "get_children"):
shells = [
@@ -1216,7 +1216,7 @@ def _resolve_scope_items(scope: Any, target_kind: str) -> List[Any]:
if target_kind == "solid":
if hasattr(scope, "get_solids"):
return list(scope.get_solids())
return list(scope._iter_solids())
if scope.__class__.__name__ == "Solid":
return [scope]
if target_kind == "wire":
+23 -23
View File
@@ -1441,21 +1441,21 @@ def _candidate_shapes_for_geo_selection(source: AnyShape, kind: str) -> List[Any
return [source] if isinstance(source, Shell) else []
if kind == "face":
if isinstance(source, (Shell, Solid)):
return list(source.get_faces())
return list(source._iter_faces())
return [source] if isinstance(source, Face) else []
if kind == "edge":
if hasattr(source, "get_edges"):
return _dedupe_shapes(cast(Sequence[AnyShape], source.get_edges()))
return _dedupe_shapes(cast(Sequence[AnyShape], source._iter_edges()))
return [source] if isinstance(source, Edge) else []
if kind == "wire":
wires: List[AnyShape] = []
if isinstance(source, Face):
wires.append(source.get_outer_wire())
wires.extend(source.get_inner_wires())
wires.extend(source._iter_inner_wires())
elif isinstance(source, Solid):
for face in source.get_faces():
for face in source._iter_faces():
wires.append(face.get_outer_wire())
wires.extend(face.get_inner_wires())
wires.extend(face._iter_inner_wires())
elif hasattr(source, "get_children"):
wires.extend(
cast(AnyShape, child)
@@ -1470,7 +1470,7 @@ def _candidate_shapes_for_geo_selection(source: AnyShape, kind: str) -> List[Any
if isinstance(source, Edge):
vertices.extend(cast(Sequence[AnyShape], source.get_children()))
elif hasattr(source, "get_edges"):
for edge in source.get_edges():
for edge in source._iter_edges():
vertices.extend(cast(Sequence[AnyShape], edge.get_children()))
elif hasattr(source, "get_children"):
vertices.extend(
@@ -1612,7 +1612,7 @@ def _geo_selector_score(
pass
elif isinstance(shape, Wire):
if "edge_count" in selector:
score += abs(len(shape.get_edges()) - int(selector["edge_count"])) * 10.0
score += abs(len(shape._iter_edges()) - int(selector["edge_count"])) * 10.0
if "closed" in selector and bool(shape.is_closed()) != bool(selector["closed"]):
score += 10.0
elif isinstance(shape, Face):
@@ -1635,15 +1635,15 @@ def _geo_selector_score(
* 5.0
)
if "edge_count" in selector:
score += abs(len(shape.get_edges()) - int(selector["edge_count"])) * 10.0
score += abs(len(shape._iter_edges()) - int(selector["edge_count"])) * 10.0
if "inner_wire_count" in selector:
score += (
abs(len(shape.get_inner_wires()) - int(selector["inner_wire_count"]))
abs(len(shape._iter_inner_wires()) - int(selector["inner_wire_count"]))
* 10.0
)
elif isinstance(shape, Shell):
if "face_count" in selector:
score += abs(len(shape.get_faces()) - int(selector["face_count"])) * 10.0
score += abs(len(shape._iter_faces()) - int(selector["face_count"])) * 10.0
elif isinstance(shape, Solid):
if "volume" in selector:
score += abs(float(shape.get_volume()) - float(selector["volume"]))
@@ -1768,7 +1768,7 @@ def _face_hint_score(face: Face, hint: Dict[str, Any]) -> float:
def _resolve_edges_from_selector_hints(
solid: Solid, refs: Sequence[Dict[str, Any]]
) -> List[Edge]:
edges = solid.get_edges()
edges = solid._iter_edges()
remaining = list(edges)
resolved: List[Edge] = []
for ref_dict in refs:
@@ -1787,7 +1787,7 @@ def _resolve_edges_from_selector_hints(
def _resolve_faces_from_selector_hints(
solid: Solid, refs: Sequence[Dict[str, Any]]
) -> List[Face]:
faces = solid.get_faces()
faces = solid._iter_faces()
remaining = list(faces)
resolved: List[Face] = []
for ref_dict in refs:
@@ -1810,7 +1810,7 @@ def _resolve_edges_from_refs(
return []
edge_map = {
_shape_topo_ref_dict(edge).get("topo_id"): edge
for edge in solid.get_edges()
for edge in solid._iter_edges()
if _shape_topo_ref_dict(edge)
}
resolved: List[Edge] = []
@@ -1829,7 +1829,7 @@ def _resolve_faces_from_refs(
return []
face_map = {
_shape_topo_ref_dict(face).get("topo_id"): face
for face in solid.get_faces()
for face in solid._iter_faces()
if _shape_topo_ref_dict(face)
}
resolved: List[Face] = []
@@ -1842,12 +1842,12 @@ def _resolve_faces_from_refs(
def _resolve_edges_from_indices(solid: Solid, indices: Sequence[int]) -> List[Edge]:
edges = solid.get_edges()
edges = solid._iter_edges()
return [edges[idx] for idx in indices if 0 <= idx < len(edges)]
def _resolve_faces_from_indices(solid: Solid, indices: Sequence[int]) -> List[Face]:
faces = solid.get_faces()
faces = solid._iter_faces()
return [faces[idx] for idx in indices if 0 <= idx < len(faces)]
@@ -2280,11 +2280,11 @@ def _validate_replayed_topology_roles(
continue
candidates: List[AnyShape] = []
if hasattr(output, "get_faces"):
candidates.extend(output.get_faces())
candidates.extend(output._iter_faces())
if hasattr(output, "get_edges"):
candidates.extend(output.get_edges())
candidates.extend(output._iter_edges())
if hasattr(output, "get_wires"):
candidates.extend(output.get_wires())
candidates.extend(output._iter_wires())
for candidate in candidates:
track = candidate.get_metadata("track")
if not isinstance(track, dict):
@@ -2362,13 +2362,13 @@ def _validate_operation_output_evidence(
source = cast(AnyShape, source_outputs[source_output_slot])
target_kind = next(iter(serialized_kinds))
if target_kind == "face":
runtime_items = source.get_faces()
runtime_items = source._iter_faces()
elif target_kind == "edge":
runtime_items = source.get_edges()
runtime_items = source._iter_edges()
elif target_kind == "wire":
runtime_items = source.get_wires()
runtime_items = source._iter_wires()
elif target_kind == "vertex":
runtime_items = source.get_vertices()
runtime_items = source._iter_vertices()
else:
raise ValueError(
f"operation output role '{role}' uses unsupported topology kind '{target_kind}'"
+13 -13
View File
@@ -380,8 +380,8 @@ def _compile_assembly(root_id: str, assembly: Assembly, transform: Placement, so
def _make_renderable(definition_id: str, solid: Solid, options: SceneCompileOptions, appearances: dict[str, dict[str, Any]], *, appearance_id: str | None = None) -> _Renderable:
face_ids = [f"entity/face/{index}" for index in range(len(solid.get_faces()))]
edge_ids = [f"entity/edge/{index}" for index in range(len(solid.get_edges()))]
face_ids = [f"entity/face/{index}" for index in range(len(solid._iter_faces()))]
edge_ids = [f"entity/edge/{index}" for index in range(len(solid._iter_edges()))]
render_mesh = build_render_mesh(solid, face_entity_ids=face_ids, linear_tolerance=options.linear_tolerance, angular_tolerance=options.angular_tolerance)
edge_mesh = build_edge_mesh(
solid,
@@ -393,12 +393,12 @@ def _make_renderable(definition_id: str, solid: Solid, options: SceneCompileOpti
def _entity_asset(*, definition_id: str, definition_kind: str, geometry_asset_id: str, edge_asset_id: str, solid: Solid, render_mesh: RenderMesh, edge_mesh: RenderEdgeMesh, source: SceneSource, definition_source: Mapping[str, Any], ocp_version: str) -> dict[str, Any]:
faces = solid.get_faces()
edges = solid.get_edges()
faces = solid._iter_faces()
edges = solid._iter_edges()
vertices = []
seen_vertices: dict[str, Vertex] = {}
for edge in edges:
for vertex in edge.get_vertices():
for vertex in edge._iter_vertices():
seen_vertices.setdefault(vertex.topo_id, vertex)
face_id = {face.topo_id: f"entity/face/{index}" for index, face in enumerate(faces)}
edge_id = {edge.topo_id: f"entity/edge/{index}" for index, edge in enumerate(edges)}
@@ -414,13 +414,13 @@ def _entity_asset(*, definition_id: str, definition_kind: str, geometry_asset_id
center = _vec(face.get_center())
geometry = _surface_geometry(face)
connector_frame = _frame(center, normal)
entities.append({"entity_id": entity_id, "kind": "face", "parent_entity_ids": ["entity/solid/0"], "child_entity_ids": sorted({edge_id[edge.topo_id] for edge in face.get_edges()}, key=lambda item: item.encode("utf-8")), "source": entity_source, "geometry": geometry, "properties": {"quality": "kernel_evaluated", "bounds": _bounds(_shape_bounds(face)), "area": face.get_area(), "centroid": list(center), "orientation": _orientation(face.wrapped.Orientation())}, "sdk_connector_frame": _frame(center, normal), "render_status": "rendered", "connector_binding_status": "owner_not_part" if definition_kind != "part" else "source_not_model", "semantic_binding_ids": [], "evaluated_tags": sorted(face._list_tags(), key=lambda item: item.encode("utf-8")), "sdk_metadata": _metadata(face)})
entities.append({"entity_id": entity_id, "kind": "face", "parent_entity_ids": ["entity/solid/0"], "child_entity_ids": sorted({edge_id[edge.topo_id] for edge in face._iter_edges()}, key=lambda item: item.encode("utf-8")), "source": entity_source, "geometry": geometry, "properties": {"quality": "kernel_evaluated", "bounds": _bounds(_shape_bounds(face)), "area": face.get_area(), "centroid": list(center), "orientation": _orientation(face.wrapped.Orientation())}, "sdk_connector_frame": _frame(center, normal), "render_status": "rendered", "connector_binding_status": "owner_not_part" if definition_kind != "part" else "source_not_model", "semantic_binding_ids": [], "evaluated_tags": sorted(face._list_tags(), key=lambda item: item.encode("utf-8")), "sdk_metadata": _metadata(face)})
entities[-1]["sdk_connector_frame"] = connector_frame
entities[-1]["connector_binding_status"] = _binding_status(source, definition_kind, connector_frame)
for edge in edges:
entity_id = edge_id[edge.topo_id]
child_vertices = sorted(
{vertex_id[vertex.topo_id] for vertex in edge.get_vertices() if vertex.topo_id in vertex_id},
{vertex_id[vertex.topo_id] for vertex in edge._iter_vertices() if vertex.topo_id in vertex_id},
key=lambda item: item.encode("utf-8"),
)
start, end = _edge_endpoints(edge)
@@ -431,7 +431,7 @@ def _entity_asset(*, definition_id: str, definition_kind: str, geometry_asset_id
for vertex in vertex_items:
point = _vec(vertex.get_coordinates())
vertex_frame = {**_IDENTITY, "origin": list(point)}
entities.append({"entity_id": vertex_id[vertex.topo_id], "kind": "vertex", "parent_entity_ids": sorted({edge_id[edge.topo_id] for edge in edges if any(child.topo_id == vertex.topo_id for child in edge.get_vertices())}, key=lambda item: item.encode("utf-8")), "child_entity_ids": [], "source": entity_source, "geometry": {"type": "point", "position": list(point)}, "properties": {"quality": "kernel_evaluated", "bounds": {"min": list(point), "max": list(point)}, "position": list(point)}, "sdk_connector_frame": vertex_frame, "render_status": "rendered", "connector_binding_status": _binding_status(source, definition_kind, vertex_frame), "semantic_binding_ids": [], "evaluated_tags": sorted(vertex._list_tags(), key=lambda item: item.encode("utf-8")), "sdk_metadata": _metadata(vertex)})
entities.append({"entity_id": vertex_id[vertex.topo_id], "kind": "vertex", "parent_entity_ids": sorted({edge_id[edge.topo_id] for edge in edges if any(child.topo_id == vertex.topo_id for child in edge._iter_vertices())}, key=lambda item: item.encode("utf-8")), "child_entity_ids": [], "source": entity_source, "geometry": {"type": "point", "position": list(point)}, "properties": {"quality": "kernel_evaluated", "bounds": {"min": list(point), "max": list(point)}, "position": list(point)}, "sdk_connector_frame": vertex_frame, "render_status": "rendered", "connector_binding_status": _binding_status(source, definition_kind, vertex_frame), "semantic_binding_ids": [], "evaluated_tags": sorted(vertex._list_tags(), key=lambda item: item.encode("utf-8")), "sdk_metadata": _metadata(vertex)})
for entity in entities:
entity["parent_entity_ids"] = sorted(entity["parent_entity_ids"], key=lambda item: item.encode("utf-8"))
entity["child_entity_ids"] = sorted(entity["child_entity_ids"], key=lambda item: item.encode("utf-8"))
@@ -892,13 +892,13 @@ def _resolve_connector_target(solid: Solid, connector: Connector) -> Face | Edge
def _entity_id_for_shape(solid: Solid, shape: Face | Edge | Vertex) -> str:
kind = type(shape).__name__.lower()
if kind == "face":
values = solid.get_faces()
values = solid._iter_faces()
elif kind == "edge":
values = solid.get_edges()
values = solid._iter_edges()
else:
seen: dict[str, Vertex] = {}
for edge in solid.get_edges():
for vertex in edge.get_vertices():
for edge in solid._iter_edges():
for vertex in edge._iter_vertices():
seen.setdefault(vertex.topo_id, vertex)
values = list(seen.values())
try:
@@ -932,7 +932,7 @@ def _normalized_assembly(assembly: Assembly, root_id: str) -> dict[str, Any]:
def _compound_solid(compound: Compound) -> Solid:
solids = compound.get_solids()
solids = compound._iter_solids()
if len(solids) != 1:
raise ValueError("a standalone Compound must contain exactly one solid in the first compiler slice")
return solids[0]
@@ -138,7 +138,7 @@
"selector_solid_fields": ["volume", "center"],
"bbox_api": "BRepBndLib.AddOptimal_s(shape, box, False, False) after Bnd_Box.SetGap(0.0)",
"edge_payload_calls": ["Edge.get_length()", "Edge.get_center()", "Edge.get_start_vertex().get_coordinates()", "Edge.get_end_vertex().get_coordinates()"],
"face_payload_calls": ["Face.get_area()", "Face.get_center()", "Face.get_normal_at(0.5, 0.5)", "Face.get_edges()", "Face.get_inner_wires()"],
"face_payload_calls": ["Face.get_area()", "Face.get_center()", "Face.get_normal_at(0.5, 0.5)", "Face._iter_edges()", "Face._iter_inner_wires()"],
"face_normal_calls": ["BRepAdaptor_Surface(face, True)", "BRepAdaptor_Surface.FirstUParameter()", "BRepAdaptor_Surface.LastUParameter()", "BRepAdaptor_Surface.FirstVParameter()", "BRepAdaptor_Surface.LastVParameter()", "BRepLProp_SLProps(adaptor, midpoint_u, midpoint_v, 1, 1e-7)", "BRepLProp_SLProps.IsNormalDefined()", "BRepLProp_SLProps.Normal()"],
"face_normal_orientation": "reverse_when_face.Orientation() == TopAbs_REVERSED",
"vertex_payload_call": "Vertex.get_coordinates()",
@@ -142,7 +142,7 @@
"selector_solid_fields": ["volume", "center"],
"bbox_api": "BRepBndLib.AddOptimal_s(shape, box, False, False) after Bnd_Box.SetGap(0.0)",
"edge_payload_calls": ["Edge.get_length()", "Edge.get_center()", "Edge.get_start_vertex().get_coordinates()", "Edge.get_end_vertex().get_coordinates()"],
"face_payload_calls": ["Face.get_area()", "Face.get_center()", "Face.get_normal_at(0.5, 0.5)", "Face.get_edges()", "Face.get_inner_wires()"],
"face_payload_calls": ["Face.get_area()", "Face.get_center()", "Face.get_normal_at(0.5, 0.5)", "Face._iter_edges()", "Face._iter_inner_wires()"],
"face_normal_calls": ["BRepAdaptor_Surface(face, True)", "BRepAdaptor_Surface.FirstUParameter()", "BRepAdaptor_Surface.LastUParameter()", "BRepAdaptor_Surface.FirstVParameter()", "BRepAdaptor_Surface.LastVParameter()", "BRepLProp_SLProps(adaptor, midpoint_u, midpoint_v, 1, 1e-7)", "BRepLProp_SLProps.IsNormalDefined()", "BRepLProp_SLProps.Normal()"],
"face_normal_orientation": "reverse_when_face.Orientation() == TopAbs_REVERSED",
"vertex_payload_call": "Vertex.get_coordinates()",
+6 -6
View File
@@ -334,11 +334,11 @@ def _part_geometry(
for item in snapshot["entities"]
}
faces = body.get_faces()
edges = body.get_edges()
faces = body._iter_faces()
edges = body._iter_edges()
vertices_by_id: dict[str, Vertex] = {}
for edge in edges:
for vertex in edge.get_vertices():
for vertex in edge._iter_vertices():
vertices_by_id.setdefault(vertex.topo_id, vertex)
vertices = list(vertices_by_id.values())
face_ids = {
@@ -406,7 +406,7 @@ def _part_geometry(
"topo_id": face.topo_id,
"parent_entity_ids": [solid_id],
"child_entity_ids": sorted(
edge_ids[item.topo_id] for item in face.get_edges()
edge_ids[item.topo_id] for item in face._iter_edges()
),
"source": source_by_key[("face", face.topo_id)],
"geometry": _surface_geometry(face),
@@ -439,7 +439,7 @@ def _part_geometry(
if item.topo_id in face_ids
),
"child_entity_ids": sorted(
vertex_ids[item.topo_id] for item in edge.get_vertices()
vertex_ids[item.topo_id] for item in edge._iter_vertices()
),
"source": source_by_key[("edge", edge.topo_id)],
"geometry": _curve_geometry(edge),
@@ -464,7 +464,7 @@ def _part_geometry(
for edge in edges
if any(
child.topo_id == vertex.topo_id
for child in edge.get_vertices()
for child in edge._iter_vertices()
)
),
"child_entity_ids": [],
+2 -2
View File
@@ -93,7 +93,7 @@ def build_render_mesh(
linear_tolerance: float,
angular_tolerance: float,
) -> RenderMesh:
faces = solid.get_faces()
faces = solid._iter_faces()
if len(faces) != len(face_entity_ids):
raise ValueError("face entity count does not match the solid topology")
mesh = cached_mesh(
@@ -146,7 +146,7 @@ def build_edge_mesh(
linear_tolerance: float,
angular_tolerance: float = DEFAULT_ANGULAR_TOLERANCE,
) -> RenderEdgeMesh:
edges = solid.get_edges()
edges = solid._iter_edges()
if len(edges) != len(edge_entity_ids):
raise ValueError("edge entity count does not match the solid topology")
blocks = tuple(
+2 -2
View File
@@ -675,7 +675,7 @@ class Sketch(TaggedMixin, TopoMixein):
list(
zip(
profile_payload["entity_ids"],
[edge.wrapped for edge in wire.get_edges()],
[edge.wrapped for edge in wire._iter_edges()],
)
),
)
@@ -764,7 +764,7 @@ class Sketch(TaggedMixin, TopoMixein):
edges.append(edge)
entity_edges.append((str(eid), edge.wrapped))
wire = make_wire_from_edges_rwire(edges)
wire_edges = list(wire.get_edges())
wire_edges = list(wire._iter_edges())
if len(wire_edges) != len(entity_edges):
raise ValueError(
"Sketch profile wire edge count changed during kernel construction"
+2 -2
View File
@@ -91,7 +91,7 @@ def _validate_ball_count(
def _candidate_chamfer_edges(solid: Solid, bearing_width: float) -> List[object]:
circular_min_length = max(1e-6, bearing_width * 1.1)
return [edge for edge in solid.get_edges() if edge.get_length() > circular_min_length]
return [edge for edge in solid._iter_edges() if edge.get_length() > circular_min_length]
def _apply_edge_chamfer(solid: Solid, edge_chamfer: float, bearing_width: float) -> Solid:
@@ -201,7 +201,7 @@ def _make_race_ring_solid(
def _axis_face(solid: Solid, target_z: float) -> Face:
candidates = []
for face in solid.get_faces():
for face in solid._iter_faces():
normal = face.get_normal_at()
if normal.z < 0.7:
continue
+1 -1
View File
@@ -389,7 +389,7 @@ def _default_head_dimensions(diameter: float, head_style: str) -> Tuple[float, f
def _underhead_edge(solid: Solid, shank_radius: float) -> Edge:
circumference = 2.0 * math.pi * shank_radius
edges = cast(List[Edge], solid.get_edges())
edges = cast(List[Edge], solid._iter_edges())
candidates = [
edge
for edge in edges
+4 -4
View File
@@ -468,7 +468,7 @@ def apply_tracking_tags(
_topo_id(face.wrapped): face
for source in all_sources
for face in (
source.get_faces()
source._iter_faces()
if hasattr(source, "get_faces")
else ([source] if source.__class__.__name__ == "Face" else [])
)
@@ -477,7 +477,7 @@ def apply_tracking_tags(
_topo_id(edge.wrapped): edge
for source in all_sources
for edge in (
source.get_edges()
source._iter_edges()
if hasattr(source, "get_edges")
else ([source] if source.__class__.__name__ == "Edge" else [])
)
@@ -498,7 +498,7 @@ def apply_tracking_tags(
str(witness["input_topo_id"]), set()
).add(str(target_id))
for face in solid.get_faces():
for face in solid._iter_faces():
topo_id = _topo_id(face.wrapped)
entry = _matching_entry(entries, topo_id, TopoKind.FACE)
if entry is None:
@@ -545,7 +545,7 @@ def apply_tracking_tags(
section_ids = {
ref.topo_id for ref in delta.section_edges if ref.kind == TopoKind.EDGE
}
for edge in solid.get_edges():
for edge in solid._iter_edges():
topo_id = _topo_id(edge.wrapped)
entry = _matching_entry(entries, topo_id, TopoKind.EDGE)
if entry is None:
+3 -3
View File
@@ -1764,7 +1764,7 @@ def tracked_loft(profiles: List[Wire | Vertex], ruled: bool = False) -> TrackedR
}
cap_faces = [
face
for face in result_solid.get_faces()
for face in result_solid._iter_faces()
if _topo_id(face.wrapped) not in side_face_ids
]
wire_endpoint_roles = [
@@ -1817,7 +1817,7 @@ def tracked_sweep(profile: Face, path: Wire, is_frenet: bool = False) -> Tracked
graph_id = _make_id("g")
node_id = _make_id("n")
if profile.get_inner_wires():
if profile._iter_inner_wires():
raise ValueError(
"Sweep profiles with inner wires are unsupported because PipeShell only receives the outer profile wire"
)
@@ -2008,7 +2008,7 @@ def tracked_twisted_sweep(
raise ValueError(f"Twisted sweep failed: {sweep_op.GetStatus().name}")
return sweep_op
profile_wires = [profile.get_outer_wire(), *profile.get_inner_wires()]
profile_wires = [profile.get_outer_wire(), *profile._iter_inner_wires()]
sweep_ops = [_pipe_shell(wire) for wire in profile_wires]
approximation_error = max(float(op.ErrorOnSurface()) for op in sweep_ops)
@@ -568,7 +568,7 @@ def _canonical_detail_edge_catalog(
sources: Dict[str, Dict[str, Any]] = {}
for source_id, source_shape in source_shapes.items():
try:
source_edges = list(source_shape.get_edges())
source_edges = list(source_shape._iter_edges())
except Exception:
continue
edges = []
@@ -594,7 +594,7 @@ def _canonical_detail_edge_catalog(
if source_shape is None or source_entry is None:
continue
try:
source_edges = list(source_shape.get_edges())
source_edges = list(source_shape._iter_edges())
selected_indices = []
for selector_node_id in (
detail_node.params.get("selected_edge_node_ids") or []
+7 -7
View File
@@ -303,7 +303,7 @@ class TestBooleanOperations(unittest.TestCase):
with redirect_stdout(stdout_buffer):
result = scad.union_rsolid(box_left, box_right)
self.assertAlmostEqual(result.get_volume(), 2.0, places=6)
self.assertEqual(len(result.get_faces()), 6)
self.assertEqual(len(result._iter_faces()), 6)
self.assertEqual(stdout_buffer.getvalue(), "")
def test_union_bridges_small_explicit_gap_only_with_tolerance(self):
@@ -406,7 +406,7 @@ class TestAdvancedFeatures(unittest.TestCase):
def test_fillet(self):
"""Test fillet."""
# 获取所有边
edges = self.box.get_edges()
edges = self.box._iter_edges()
# 选择前4条边进行圆角
selected_edges = edges[:4]
@@ -421,7 +421,7 @@ class TestAdvancedFeatures(unittest.TestCase):
def test_chamfer(self):
"""Test chamfer."""
# 获取所有边
edges = self.box.get_edges()
edges = self.box._iter_edges()
# 选择前4条边进行倒角
selected_edges = edges[:4]
@@ -436,7 +436,7 @@ class TestAdvancedFeatures(unittest.TestCase):
def test_shell(self):
"""Test shell."""
# 获取顶面
faces = self.box.get_faces()
faces = self.box._iter_faces()
top_faces = [face for face in faces if "face.top" in scad.list_tags(face)]
try:
@@ -519,7 +519,7 @@ class TestTagging(unittest.TestCase):
def test_auto_tag_faces_box(self):
"""Test auto tag faces box."""
self.box.auto_tag_faces("box")
faces = self.box.get_faces()
faces = self.box._iter_faces()
# 检查是否有标记的面
tagged_faces = [face for face in faces if len(scad.list_tags(face)) > 0]
@@ -529,7 +529,7 @@ class TestTagging(unittest.TestCase):
"""Test auto tag faces cylinder."""
cylinder = scad.create_cylinder(1.0, 2.0)
cylinder.auto_tag_faces("cylinder")
faces = cylinder.get_faces()
faces = cylinder._iter_faces()
# 检查是否有标记的面
tagged_faces = [face for face in faces if len(scad.list_tags(face)) > 0]
@@ -539,7 +539,7 @@ class TestTagging(unittest.TestCase):
"""Test auto tag faces sphere."""
sphere = scad.create_sphere(1.0)
sphere.auto_tag_faces("sphere")
faces = sphere.get_faces()
faces = sphere._iter_faces()
# 球体应该只有一个面,且被标记为surface
self.assertEqual(len(faces), 1)
+22 -22
View File
@@ -162,19 +162,19 @@ def test_face_region_loads_as_one_replayable_shell(tmp_path: Path) -> None:
os.chdir(previous_cwd)
assert isinstance(loaded, scad.Shell)
assert len(loaded.get_faces()) == 1
assert len(loaded._iter_faces()) == 1
assert not loaded.is_closed()
assert "kettle.copied.shell" in scad.list_tags(loaded, scope="local")
assert "provenance.exact_transcription" in scad.list_tags(loaded)
assert all(
face.get_metadata("provenance")["construction"] == "exact_transcription"
for face in loaded.get_faces()
for face in loaded._iter_faces()
)
assert loaded.get_faces()[0].get_metadata("provenance")["source_face_id"] == (
assert loaded.get_faces(0).get_metadata("provenance")["source_face_id"] == (
f"face:{top_face_id}"
)
explanation = scad.explain_tag(
loaded.get_faces()[0],
loaded.get_faces(0),
"provenance.exact_transcription",
scope="local",
)
@@ -199,7 +199,7 @@ def test_face_region_loads_as_one_replayable_shell(tmp_path: Path) -> None:
finally:
os.chdir(previous_cwd)
assert isinstance(replayed[0], scad.Shell)
assert len(replayed[0].get_faces()) == 1
assert len(replayed[0]._iter_faces()) == 1
def test_face_region_rejects_duplicate_face_ids(tmp_path: Path) -> None:
@@ -459,11 +459,11 @@ def test_copied_face_provenance_survives_downstream_boolean(
descendants = [
face
for face in cut.get_faces()
for face in cut._iter_faces()
if "provenance.exact_transcription" in scad.list_tags(face, scope="lineage")
]
assert descendants
assert len(descendants) < len(cut.get_faces())
assert len(descendants) < len(cut._iter_faces())
def test_copied_face_provenance_survives_sewing(tmp_path: Path) -> None:
@@ -485,10 +485,10 @@ def test_copied_face_provenance_survives_sewing(tmp_path: Path) -> None:
digest = hashlib.sha256(snapshot.read_bytes()).hexdigest()
copied = scad.load_brep_region_rshell(path=snapshot, sha256=digest)
sewn = scad.sew_faces_rshell(faces=copied.get_faces(), tolerance=1.0e-7)
sewn = scad.sew_faces_rshell(faces=copied._iter_faces(), tolerance=1.0e-7)
assert "provenance.exact_transcription" in scad.list_tags(sewn.get_faces()[0])
assert sewn.get_faces()[0].get_metadata("provenance")["source_face_id"] == (
assert "provenance.exact_transcription" in scad.list_tags(sewn.get_faces(0))
assert sewn.get_faces(0).get_metadata("provenance")["source_face_id"] == (
f"face:{top}"
)
@@ -512,13 +512,13 @@ def test_shell_faces_sew_and_solid_conversion_replay(tmp_path: Path) -> None:
copied = scad.load_brep_region_rshell(
path=Path(snapshot.name), sha256=digest
)
sewn = scad.sew_faces_rshell(copied.get_faces(), tolerance=1.0e-7)
sewn = scad.sew_faces_rshell(copied._iter_faces(), tolerance=1.0e-7)
solid = scad.make_solid_from_shell_rsolid(sewn, tag_prefix="hybrid")
authored_bindings = {
face.get_metadata("provenance")["source_face_id"]: scad.explain_tag(
face, "provenance.exact_transcription", scope="local"
)[0]["binding_id"]
for face in solid.get_faces()
for face in solid._iter_faces()
}
session.capture_result(value=solid)
payload = scad.export_model_json(session)
@@ -531,21 +531,21 @@ def test_shell_faces_sew_and_solid_conversion_replay(tmp_path: Path) -> None:
assert "hybrid.solid" in scad.list_tags(replayed)
assert all(
face.get_metadata("provenance")["construction"] == "exact_transcription"
for face in replayed.get_faces()
for face in replayed._iter_faces()
)
assert len(
{
scad.explain_tag(face, "provenance.exact_transcription", scope="local")[0][
"binding_id"
]
for face in replayed.get_faces()
for face in replayed._iter_faces()
}
) == len(replayed.get_faces())
) == len(replayed._iter_faces())
assert {
face.get_metadata("provenance")["source_face_id"]: scad.explain_tag(
face, "provenance.exact_transcription", scope="local"
)[0]["binding_id"]
for face in replayed.get_faces()
for face in replayed._iter_faces()
} == authored_bindings
payload_data = json.loads(payload)
@@ -554,7 +554,7 @@ def test_shell_faces_sew_and_solid_conversion_replay(tmp_path: Path) -> None:
for node in payload_data["graph"]["nodes"]
if node["op"] == "make_select_rface"
]
assert len(face_selectors) == len(source.get_faces())
assert len(face_selectors) == len(source._iter_faces())
assert {
selector["brep_region_ref"]["source_face_id"] for selector in face_selectors
} == set(authored_bindings)
@@ -583,7 +583,7 @@ def test_semantically_tagged_face_replays_as_sewing_input(tmp_path: Path) -> Non
feature_face = scad.apply_tag(
feature_face, "provenance.feature_constructed"
)
sewn = scad.sew_faces_rshell([*copied.get_faces(), feature_face])
sewn = scad.sew_faces_rshell([*copied._iter_faces(), feature_face])
solid = scad.make_solid_from_shell_rsolid(sewn)
session.capture_result(value=solid)
replayed = scad.replay_model_json(scad.export_model_json(session))[0]
@@ -594,7 +594,7 @@ def test_semantically_tagged_face_replays_as_sewing_input(tmp_path: Path) -> Non
assert (
sum(
"provenance.feature_constructed" in scad.list_tags(face)
for face in replayed.get_faces()
for face in replayed._iter_faces()
)
== 1
)
@@ -647,10 +647,10 @@ def test_kettle_bspline_regions_roundtrip_as_two_exact_shells(tmp_path: Path) ->
digest = hashlib.sha256(snapshot.read_bytes()).hexdigest()
loaded_shells.append(scad.load_brep_region_rshell(path=snapshot, sha256=digest))
assert sorted(len(shell.get_faces()) for shell in loaded_shells) == [53, 70]
assert sum(len(shell.get_faces()) for shell in loaded_shells) == 123
assert sorted(len(shell._iter_faces()) for shell in loaded_shells) == [53, 70]
assert sum(len(shell._iter_faces()) for shell in loaded_shells) == 123
assert all(
face.get_metadata("provenance")["construction"] == "exact_transcription"
for shell in loaded_shells
for face in shell.get_faces()
for face in shell._iter_faces()
)
+4 -4
View File
@@ -40,7 +40,7 @@ def _build_freecad_nested_package(tmp_path: Path):
@scad.part(id="linked", cache=cache)
def build_part() -> scad.Part:
body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0)
named_face = scad.apply_tag(body.get_faces()[0], "interface.mount_face")
named_face = scad.apply_tag(body.get_faces(0), "interface.mount_face")
part = scad.make_part_rpart("linked", body, name="Part linked")
connector = scad.make_face_connector_rconnector("mount", named_face)
return scad.add_connector_rpart(part, connector)
@@ -1336,7 +1336,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh:
gear_height=8.0,
)
top_face = max(
ql.select(gear.get_faces()).all(), key=lambda face: face.get_center().z
ql.select(gear._iter_faces()).all(), key=lambda face: face.get_center().z
)
connector = scad.make_face_connector_rconnector("axis", top_face)
part = scad.add_connector_rpart(
@@ -3241,7 +3241,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh:
self.assertEqual(inspected["type_id"], "Part::Cut")
self.assertTrue(inspected["valid"])
self.assertEqual(inspected["solid_count"], 1)
self.assertEqual(inspected["face_count"], len(result_solid.get_faces()))
self.assertEqual(inspected["face_count"], len(result_solid._iter_faces()))
self.assertAlmostEqual(inspected["volume"], result_solid.get_volume(), places=7)
self.assertEqual(inspected["base_type"], "Part::Box")
self.assertEqual(inspected["tool_type"], "Part::Extrusion")
@@ -3310,7 +3310,7 @@ with open(OUT_PATH, 'w', encoding='utf-8') as fh:
self.assertEqual(inspected["type_id"], "Part::Cut")
self.assertTrue(inspected["valid"])
self.assertEqual(inspected["solid_count"], 1)
self.assertEqual(inspected["face_count"], len(result_solid.get_faces()))
self.assertEqual(inspected["face_count"], len(result_solid._iter_faces()))
self.assertAlmostEqual(
inspected["volume"], result_solid.get_volume(), delta=1.0e-3
)
+2 -2
View File
@@ -97,7 +97,7 @@ class TestQLSugar(unittest.TestCase):
tagged = apply_tracking_tags_to_delta(
result.solid, result.delta, result.delta_entries, op="cut"
)
modified = Q.select(tagged.get_faces()).where(Q.op("cut", "modified")).all()
modified = Q.select(tagged._iter_faces()).where(Q.op("cut", "modified")).all()
self.assertGreater(len(modified), 0)
def test_select_faces_by_origin(self):
@@ -107,7 +107,7 @@ class TestQLSugar(unittest.TestCase):
tagged = apply_tracking_tags_to_delta(
result.solid, result.delta, result.delta_entries, op="cut"
)
tool_faces = Q.select(tagged.get_faces()).where(Q.origin("tool")).all()
tool_faces = Q.select(tagged._iter_faces()).where(Q.origin("tool")).all()
self.assertGreater(len(tool_faces), 0)
+1 -1
View File
@@ -38,7 +38,7 @@ def test_internal_mesh_preserves_face_triangle_ranges():
assert mesh is not None
ranges = mesh.face_triangle_ranges
assert len(ranges) == len(solid.get_faces())
assert len(ranges) == len(solid._iter_faces())
assert sum(item.count for item in ranges) == mesh.triangle_count
assert [item.face_index for item in ranges] == list(range(len(ranges)))
assert all(item.source_topo_id for item in ranges)
+11 -11
View File
@@ -9,7 +9,7 @@ from simplecadapi import ql as Q
def _role_count(shape, role):
candidates = shape.get_edges() if role == "shell.wall" else shape.get_faces()
candidates = shape._iter_edges() if role == "shell.wall" else shape._iter_faces()
return sum(Q.output_role(role)(item) for item in candidates)
@@ -69,7 +69,7 @@ class TestOperationOutputRoles(unittest.TestCase):
self.assertEqual(
{
tag
for face in revolved.get_faces()
for face in revolved._iter_faces()
for tag in scad.list_tags(face, scope="local")
if tag.startswith("revolved.face.side.")
},
@@ -89,7 +89,7 @@ class TestOperationOutputRoles(unittest.TestCase):
self.assertEqual(
{
tag
for face in swept.get_faces()
for face in swept._iter_faces()
for tag in scad.list_tags(face, scope="local")
if tag.startswith("swept.face.side.")
},
@@ -117,7 +117,7 @@ class TestOperationOutputRoles(unittest.TestCase):
side_tags = {
tag
for face in lofted.get_faces()
for face in lofted._iter_faces()
for tag in scad.list_tags(face, scope="local")
if tag == "lofted.face.side" or tag.startswith("lofted.face.side.")
}
@@ -127,7 +127,7 @@ class TestOperationOutputRoles(unittest.TestCase):
cylinder = scad.make_cylinder_rsolid(2.0, 5.0, tag_prefix="shaft")
for role in ("cylinder.start", "cylinder.end", "cylinder.side"):
self.assertEqual(
sum(Q.output_role(role)(face) for face in cylinder.get_faces()), 1
sum(Q.output_role(role)(face) for face in cylinder._iter_faces()), 1
)
for role in (
"cylinder.start_boundary",
@@ -135,7 +135,7 @@ class TestOperationOutputRoles(unittest.TestCase):
"cylinder.seam",
):
self.assertEqual(
sum(Q.output_role(role)(edge) for edge in cylinder.get_edges()), 1
sum(Q.output_role(role)(edge) for edge in cylinder._iter_edges()), 1
)
self.assertEqual(
len(Q.faces().where(Q.tag("shaft.face.start")).resolve(cylinder)), 1
@@ -155,7 +155,7 @@ class TestOperationOutputRoles(unittest.TestCase):
"box.right",
):
self.assertEqual(
sum(Q.output_role(role)(face) for face in box.get_faces()), 1
sum(Q.output_role(role)(face) for face in box._iter_faces()), 1
)
top = Q.faces().where(Q.tag("housing.face.top"))
@@ -208,7 +208,7 @@ class TestOperationOutputRoles(unittest.TestCase):
self.assertEqual(
sum(
Q.output_role("box.right")(face)
for face in shape.get_faces()
for face in shape._iter_faces()
),
1,
)
@@ -254,7 +254,7 @@ class TestOperationOutputRoles(unittest.TestCase):
"cone.seam",
):
self.assertEqual(
sum(Q.output_role(role)(edge) for edge in shape.get_edges()), 1
sum(Q.output_role(role)(edge) for edge in shape._iter_edges()), 1
)
self.assertEqual(
@@ -307,7 +307,7 @@ class TestOperationOutputRoles(unittest.TestCase):
self.assertEqual(
sum(
Q.output_role("cone.end_boundary")(edge)
for edge in shape.get_edges()
for edge in shape._iter_edges()
),
1,
)
@@ -361,7 +361,7 @@ class TestOperationOutputRoles(unittest.TestCase):
self.assertEqual(
sum(
Q.output_role("cylinder.seam")(edge)
for edge in shape.get_edges()
for edge in shape._iter_edges()
),
1,
)
+7 -7
View File
@@ -17,7 +17,7 @@ class TestOriginalBooleanApiIntegration(unittest.TestCase):
result = scad.cut_rsolid(body, tool)
self.assertIsInstance(result, scad.Solid)
faces = result.get_faces()
faces = result._iter_faces()
modified = Q.select(faces).where(Q.op("cut", "modified")).all()
preserved = Q.select(faces).where(Q.op("cut", "preserved")).all()
tool_faces = Q.select(faces).where(Q.origin("tool")).all()
@@ -33,7 +33,7 @@ class TestOriginalBooleanApiIntegration(unittest.TestCase):
result = scad.intersect_rsolid(a, b)
self.assertIsInstance(result, scad.Solid)
faces = result.get_faces()
faces = result._iter_faces()
tagged = Q.select(faces).where(Q.op("intersect")).all()
self.assertGreaterEqual(len(tagged), 0)
self.assertEqual(
@@ -47,7 +47,7 @@ class TestOriginalBooleanApiIntegration(unittest.TestCase):
result = scad.union_rsolid(a, b)
self.assertIsInstance(result, scad.Solid)
faces = result.get_faces()
faces = result._iter_faces()
tagged = Q.select(faces).where(Q.op("union")).all()
self.assertGreaterEqual(len(tagged), 0)
self.assertEqual(result.get_metadata("track")["op"], "make_union_rsolid")
@@ -84,7 +84,7 @@ class TestOriginalTransformApiIntegration(unittest.TestCase):
self.assertIsInstance(moved, scad.Solid)
self.assertEqual(moved.get_metadata("track")["op"], "make_translate_rshape")
faces = moved.get_faces()
faces = moved._iter_faces()
self.assertGreater(
len(
Q.select(faces).where(Q.op("make_translate_rshape", "modified")).all()
@@ -98,7 +98,7 @@ class TestOriginalTransformApiIntegration(unittest.TestCase):
self.assertIsInstance(moved, scad.Solid)
self.assertEqual(moved.get_metadata("track")["op"], "make_rotate_rshape")
faces = moved.get_faces()
faces = moved._iter_faces()
self.assertGreater(
len(Q.select(faces).where(Q.op("make_rotate_rshape", "modified")).all()),
0,
@@ -111,7 +111,7 @@ class TestOriginalFeatureApiIntegration(unittest.TestCase):
extruded = scad.extrude_rsolid(profile, (0, 0, 1), 2.0)
self.assertEqual(extruded.get_metadata("track")["op"], "make_extrude_rsolid")
faces = extruded.get_faces()
faces = extruded._iter_faces()
self.assertEqual(
len(Q.select(faces).where(Q.output_role("extrusion.start")).all()), 1
)
@@ -128,7 +128,7 @@ class TestOriginalFeatureApiIntegration(unittest.TestCase):
filleted = scad.fillet_rsolid(box, edges, 0.2)
self.assertEqual(filleted.get_metadata("track")["op"], "make_fillet_rsolid")
faces = filleted.get_faces()
faces = filleted._iter_faces()
tagged = Q.select(faces).where(Q.op("make_fillet_rsolid")).all()
self.assertGreater(len(tagged), 0)
+1 -1
View File
@@ -29,7 +29,7 @@ def test_periodic_interpolated_wire_is_closed_and_passes_through_points():
wire = scad.make_periodic_spline_rwire(points=points + [points[0]])
assert wire.is_closed()
assert len(wire.get_edges()) == 1
assert len(wire._iter_edges()) == 1
edge = wire.get_edges(0)
for point in points:
distance = BRepExtrema_DistShapeShape(
+2 -2
View File
@@ -118,7 +118,7 @@ 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 len(compound._iter_solids()) == 2
assert math.isclose(
compound.get_volume(), 2.0 * bolt_body.get_volume(), rel_tol=1e-7
)
@@ -153,7 +153,7 @@ def test_nested_assembly_projection_composes_component_placements():
round(face.get_center().x, 1) for face in ql.faces().resolve(compound)
)
assert len(compound.get_solids()) == 1
assert len(compound._iter_solids()) == 1
assert face_centers_x[0] >= 11.5
assert face_centers_x[-1] <= 12.5
+1 -1
View File
@@ -85,7 +85,7 @@ def _build_nested_package(root: Path):
@scad.part(id="linked", cache=cache, project_root=Path(__file__).parent)
def build_part() -> scad.Part:
body = scad.make_box_rsolid(1.0, 2.0, 3.0)
face = scad.apply_tag(body.get_faces()[0], "interface.mount_face")
face = scad.apply_tag(body.get_faces(0), "interface.mount_face")
part = scad.make_part_rpart("linked", body, name="Part linked")
return scad.add_connector_rpart(
part,
+2 -2
View File
@@ -27,7 +27,7 @@ def _build_named_part(tmp_path: Path, part_id: str = "box") -> scad.PartBuildRes
@scad.part(id=part_id, cache=_policy(tmp_path / "cache"))
def build() -> scad.Part:
body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0)
named_face = body.get_faces()[0]
named_face = body.get_faces(0)
named_face = scad.apply_tag(named_face, "interface.mount_face")
part = scad.make_part_rpart(
part_id=part_id,
@@ -148,7 +148,7 @@ def test_cache_off_part_package_is_byte_deterministic(tmp_path: Path) -> None:
def build() -> scad.Part:
body = scad.make_box_rsolid(width=1.0, height=2.0, depth=3.0)
tagged_face = scad.apply_tag(
shape=body.get_faces()[0],
shape=body.get_faces(0),
tag="interface.mount_face",
)
part = scad.make_part_rpart(part_id="deterministic_part", body=body)
+2 -2
View File
@@ -17,7 +17,7 @@ class TestQLTagPredicates(unittest.TestCase):
def test_tag_face_prefix(self):
box = scad.make_box_rsolid(1.0, 1.0, 1.0)
box.auto_tag_faces("box")
top_faces = [face for face in box.get_faces() if "face.top" in scad.list_tags(face)]
top_faces = [face for face in box._iter_faces() if "face.top" in scad.list_tags(face)]
self.assertTrue(top_faces)
top_face = top_faces[0]
@@ -299,7 +299,7 @@ class TestSerializableGeometrySelectors(unittest.TestCase):
.where(Q.tag("first.solid"))
.shared_boundary(Q.solids().where(Q.tag("first.solid")))
.resolve(first),
first.get_edges(),
first._iter_edges(),
)
self.assertEqual(
len(
+4 -4
View File
@@ -311,12 +311,12 @@ class TestRearchitecture20CoreOps(unittest.TestCase):
if item.op == "make_twisted_sweep_rsolid"
)
self.assertIsNotNone(node.topo_delta)
self.assertEqual(len(solid.get_faces()), 6)
self.assertEqual(len(solid._iter_faces()), 6)
replayed = scad.replay_model_json(
scad.export_model_json(session), strict=True
)[0]
self.assertEqual(len(replayed.get_faces()), 6)
self.assertEqual(len(replayed._iter_faces()), 6)
self.assertAlmostEqual(replayed.get_volume(), solid.get_volume(), places=8)
def test_twisted_sweep_supports_expression_parameters_and_arbitrary_axis(self):
@@ -342,7 +342,7 @@ class TestRearchitecture20CoreOps(unittest.TestCase):
if item.op == "make_twisted_sweep_rsolid"
)
self.assertEqual(set(node.param_exprs), {"distance", "twist_angle"})
self.assertEqual(len(solid.get_faces()), 6)
self.assertEqual(len(solid._iter_faces()), 6)
replayed = scad.replay_model_json(
scad.export_model_json(session), strict=True
@@ -364,7 +364,7 @@ class TestRearchitecture20CoreOps(unittest.TestCase):
expected = math.pi * (2.0**2 - 1.0**2) * 2.0
self.assertAlmostEqual(swept.get_volume() / expected, 1.0, places=6)
self.assertEqual(len(swept.get_faces()), 4)
self.assertEqual(len(swept._iter_faces()), 4)
def test_twisted_sweep_rejects_invalid_axis(self):
outer = scad.make_circle_rface(center=(0.0, 0.0, 0.0), radius=2.0)
+4 -4
View File
@@ -134,7 +134,7 @@ def test_manual_face_connector_is_exported_with_entity_target():
solid = scad.make_box_rsolid(width=4.0, height=5.0, depth=6.0)
connector = scad.make_face_connector_rconnector(
connector_id="mount",
face=solid.get_faces()[0],
face=solid.get_faces(0),
)
part = scad.make_part_rpart(part_id="block", body=solid)
part = scad.add_connector_rpart(part=part, connector=connector)
@@ -159,7 +159,7 @@ def test_render_and_collision_use_the_same_default_mesh_object():
render = scene.build_render_mesh(
solid,
face_entity_ids=[f"entity/face/{index}" for index in range(len(solid.get_faces()))],
face_entity_ids=[f"entity/face/{index}" for index in range(len(solid._iter_faces()))],
linear_tolerance=0.35,
angular_tolerance=0.22,
)
@@ -170,7 +170,7 @@ def test_render_and_collision_use_the_same_default_mesh_object():
def test_edge_mesh_uses_angular_tolerance_for_curved_edges():
solid = scad.make_cylinder_rsolid(radius=2.0, height=5.0)
edge_ids = [f"edge-{index}" for index, _edge in enumerate(solid.get_edges())]
edge_ids = [f"edge-{index}" for index, _edge in enumerate(solid._iter_edges())]
default = scene.build_edge_mesh(
solid,
@@ -193,7 +193,7 @@ def test_edge_mesh_uses_angular_tolerance_for_curved_edges():
def test_edge_mesh_default_angular_tolerance_preserves_public_call_shape():
solid = scad.make_cylinder_rsolid(radius=2.0, height=5.0)
edge_ids = [f"edge-{index}" for index, _edge in enumerate(solid.get_edges())]
edge_ids = [f"edge-{index}" for index, _edge in enumerate(solid._iter_edges())]
mesh = scene.build_edge_mesh(
solid,
+8 -8
View File
@@ -131,7 +131,7 @@ def test_model_schema_2_topology_witnesses_and_roles_survive_clean_replay():
assert len(replayed) == 1
solid = replayed[0]
assert {
role: sum(scad.ql.output_role(role)(face) for face in solid.get_faces())
role: sum(scad.ql.output_role(role)(face) for face in solid._iter_faces())
for role in ("extrusion.start", "extrusion.end", "extrusion.side")
} == {
"extrusion.start": 1,
@@ -178,8 +178,8 @@ def test_reversed_kernel_traversal_preserves_normalized_evaluated_properties():
reversed_root = Compound(
make_compound_always([second.wrapped, first.wrapped])
)
forward_solids = forward_root.get_solids()
reversed_solids = reversed_root.get_solids()
forward_solids = forward_root._iter_solids()
reversed_solids = reversed_root._iter_solids()
assert len(forward_solids) == len(reversed_solids) == 2
assert forward_solids[0].wrapped.IsSame(first.wrapped)
@@ -189,7 +189,7 @@ def test_reversed_kernel_traversal_preserves_normalized_evaluated_properties():
def evaluated_property_records(root: Compound) -> list[bytes]:
records = []
for solid in root.get_solids():
for solid in root._iter_solids():
selector = _make_geo_selector(solid)
records.append(
canonical_json_bytes(
@@ -217,7 +217,7 @@ def test_symmetric_entities_are_selector_ambiguous_even_if_legacy_resolver_picks
first = scad.make_box_rsolid(width=2, height=2, depth=2)
second = scad.make_box_rsolid(width=2, height=2, depth=2)
compound = Compound(make_compound_always([first.wrapped, second.wrapped]))
selector = _make_geo_selector(compound.get_edges()[0])
selector = _make_geo_selector(compound.get_edges(0))
candidates = _candidate_shapes_for_geo_selection(compound, "edge")
passing = [
candidate
@@ -328,11 +328,11 @@ def test_shared_shape_compound_violates_disjoint_solid_ownership_target():
solid = scad.make_box_rsolid(width=2, height=2, depth=2)
compound = Compound(make_compound_always([solid.wrapped, solid.wrapped]))
solids = compound.get_solids()
solids = compound._iter_solids()
assert len(solids) == 2
assert solids[0].wrapped.IsSame(solids[1].wrapped)
assert len(compound.get_faces()) == 12
assert len({face.topo_id for face in compound.get_faces()}) == 6
assert len(compound._iter_faces()) == 12
assert len({face.topo_id for face in compound._iter_faces()}) == 6
def test_symmetric_graph_canonicalization_has_a_hard_failure_budget():
+1 -1
View File
@@ -98,7 +98,7 @@ if path.name == "10_part_assembly.py":
for item in nodes
if not isinstance(item, Assembly) and item.part_id == part_id
)
faces = part.body.get_faces()
faces = part.body._iter_faces()
face_naming[part_id] = {
"face_count": len(faces),
"unnamed_indices": [
+2 -2
View File
@@ -493,7 +493,7 @@ class TestReplay(unittest.TestCase):
tag = "role.explicit_target"
with scad.GraphSession() as session:
box = scad.make_box_rsolid(2.0, 3.0, 4.0)
top_face = max(box.get_faces(), key=lambda face: face.get_center().z)
top_face = max(box._iter_faces(), key=lambda face: face.get_center().z)
expected_ref = top_face.get_metadata("topo_ref")
scad.apply_tag_rselection(box, [top_face], tag)
@@ -1261,7 +1261,7 @@ class TestReplay(unittest.TestCase):
results = replay_graph(import_graph_json(json.dumps(payload)), strict=True)
self.assertEqual(len(results), 1)
self.assertEqual(len(results[0].get_faces()), 6)
self.assertEqual(len(results[0]._iter_faces()), 6)
self.assertAlmostEqual(results[0].get_volume(), swept.get_volume(), places=8)
def test_replay_sweep_records_ql_selected_extrude_end_face_profile(self):
+11 -11
View File
@@ -69,7 +69,7 @@ class TestSketchApi(unittest.TestCase):
self.assertEqual(face.get_metadata("source_sketch")["name"], "rect")
edge_tags = set()
for edge in face.get_edges():
for edge in face._iter_edges():
edge_tags.update(scad.list_tags(edge))
self.assertIn("sketch.rect", scad.list_tags(face))
self.assertIn("sketch_entity.bottom", edge_tags)
@@ -148,7 +148,7 @@ class TestSketchApi(unittest.TestCase):
self.assertEqual(
{
tag
for face in body.get_faces()
for face in body._iter_faces()
for tag in scad.list_tags(face, scope="local")
if tag.startswith("body.face.side.")
},
@@ -178,7 +178,7 @@ class TestSketchApi(unittest.TestCase):
self.assertEqual(
{
tag
for face in rebuilt.get_faces()
for face in rebuilt._iter_faces()
for tag in scad.list_tags(face, scope="local")
if tag.startswith("body.face.side.")
},
@@ -353,7 +353,7 @@ class TestSketchApi(unittest.TestCase):
self.assertAlmostEqual(normal.x, 1.0, places=6)
self.assertAlmostEqual(normal.y, 0.0, places=6)
self.assertAlmostEqual(normal.z, 0.0, places=6)
for vertex in face.get_edges()[0].get_vertices():
for vertex in face.get_edges(0)._iter_vertices():
self.assertAlmostEqual(vertex.get_coordinates()[0], 10.0, places=6)
self.assertEqual(
sketch.entities["lower"].data["control_points"][0],
@@ -397,11 +397,11 @@ class TestSketchApi(unittest.TestCase):
inner_profiles=("left_hole", "right_hole"),
)
self.assertEqual(len(face.get_inner_wires()), 2)
self.assertEqual(len(face._iter_inner_wires()), 2)
self.assertAlmostEqual(face.get_area(), 23.0 * 3.141592653589793, places=5)
edge_tags = {
tag
for edge in face.get_edges()
for edge in face._iter_edges()
for tag in scad.list_tags(edge, scope="local")
}
self.assertIn("sketch.plate.entity.outer", edge_tags)
@@ -798,9 +798,9 @@ class TestSketchChainPromotion(unittest.TestCase):
wire = scad.make_wire_from_sketch_rwire(sketch, require_fully_constrained=True)
self.assertFalse(wire.is_closed())
self.assertEqual(len(wire.get_edges()), 2)
self.assertEqual(len(wire._iter_edges()), 2)
self.assertAlmostEqual(
sum(edge.get_length() for edge in wire.get_edges()), 18.0, places=6
sum(edge.get_length() for edge in wire._iter_edges()), 18.0, places=6
)
def test_extrude_rejects_open_chain_wire(self):
@@ -829,14 +829,14 @@ class TestSketchChainPromotion(unittest.TestCase):
path = scad.make_wire_from_sketch_rwire(sketch, require_fully_constrained=True)
self.assertFalse(path.is_closed())
self.assertEqual(len(path.get_edges()), 5)
self.assertEqual(len(path._iter_edges()), 5)
expected = (
2.0 * (height - radius)
+ (length - 2.0 * radius)
+ 2.0 * (math.pi * radius / 2.0)
)
self.assertAlmostEqual(
sum(edge.get_length() for edge in path.get_edges()), expected, places=4
sum(edge.get_length() for edge in path._iter_edges()), expected, places=4
)
profile = scad.make_circle_rface(
@@ -879,7 +879,7 @@ class TestSketchChainPromotion(unittest.TestCase):
chain_wire = scad.make_wire_from_sketch_rwire(sketch, profile="tail")
self.assertFalse(chain_wire.is_closed())
self.assertEqual(len(chain_wire.get_edges()), 1)
self.assertEqual(len(chain_wire._iter_edges()), 1)
loop_face = scad.make_face_from_sketch_rface(sketch)
self.assertAlmostEqual(loop_face.get_area(), 12.0, places=6)
+6 -6
View File
@@ -128,23 +128,23 @@ class TestBallBearingAssembly(unittest.TestCase):
self.assertTrue(
any(
BRepAdaptor_Surface(face.wrapped).GetType() == GeomAbs_Torus
for face in outer_part.body.get_faces()
for face in outer_part.body._iter_faces()
)
)
self.assertTrue(
any(
BRepAdaptor_Surface(face.wrapped).GetType() == GeomAbs_Torus
for face in inner_part.body.get_faces()
for face in inner_part.body._iter_faces()
)
)
self.assertTrue(
all(
BRepAdaptor_Surface(face.wrapped).GetType() == GeomAbs_Sphere
for face in ball_part.body.get_faces()
for face in ball_part.body._iter_faces()
)
)
self.assertEqual(len(preview.get_solids()), 9)
self.assertEqual(len(preview._iter_solids()), 9)
self.assertGreater(preview.get_volume(), 0.0)
self.assertTrue(
scad.measure_constraint_residual_rconstraintresidual(
@@ -200,7 +200,7 @@ class TestBallBearingAssembly(unittest.TestCase):
)
shaft_part = scad.make_part_rpart("shaft", shaft)
top_face = max(
shaft.get_faces(),
shaft._iter_faces(),
key=lambda face: (
face.get_center().z if face.get_normal_at().z > 0.7 else -999.0
),
@@ -252,7 +252,7 @@ class TestBallBearingAssembly(unittest.TestCase):
)
shaft_part = scad.make_part_rpart("parent_bind_shaft", shaft)
top_face = max(
shaft.get_faces(),
shaft._iter_faces(),
key=lambda face: (
face.get_center().z if face.get_normal_at().z > 0.7 else -999.0
),
+2 -2
View File
@@ -163,7 +163,7 @@ class TestBoltSolid(unittest.TestCase):
self.assertAlmostEqual(replayed[0].get_volume(), bolt.get_volume(), places=5)
print(
"modeled_bolt: "
f"volume={bolt.get_volume():.3f} faces={len(bolt.get_faces())}"
f"volume={bolt.get_volume():.3f} faces={len(bolt._iter_faces())}"
)
def test_external_thread_stabilization_records_only_selected_phase(self):
@@ -295,7 +295,7 @@ class TestNutSolid(unittest.TestCase):
self.assertAlmostEqual(replayed[0].get_volume(), modeled.get_volume(), places=5)
print(
"modeled_nut: "
f"volume={modeled.get_volume():.3f} faces={len(modeled.get_faces())}"
f"volume={modeled.get_volume():.3f} faces={len(modeled._iter_faces())}"
)
def test_internal_thread_stabilization_records_only_selected_phase(self):
+13 -13
View File
@@ -103,10 +103,10 @@ class TestSpurGear(unittest.TestCase):
)
expected_tip = module * n_teeth / 2.0 + module
max_r = 0.0
for face in solid.get_faces():
for wire in face.get_wires():
for edge in wire.get_edges():
for vertex in edge.get_vertices():
for face in solid._iter_faces():
for wire in face._iter_wires():
for edge in wire._iter_edges():
for vertex in edge._iter_vertices():
x, y, _ = vertex.get_coordinates()
max_r = max(max_r, math.sqrt(x * x + y * y))
self.assertLess(max_r, expected_tip * 1.05)
@@ -412,12 +412,12 @@ class TestHelicalGear(unittest.TestCase):
self.assertFalse(
any(node["op"] == "make_loft_rsolid" for node in payload["graph"]["nodes"])
)
self.assertEqual(len(solid.get_faces()), 74)
self.assertEqual(len(solid._iter_faces()), 74)
replayed = scad.replay_model_json(
json_str=json.dumps(payload), strict=True
)[0]
self.assertEqual(len(replayed.get_faces()), 74)
self.assertEqual(len(replayed._iter_faces()), 74)
self.assertAlmostEqual(replayed.get_volume(), solid.get_volume(), places=6)
@@ -467,12 +467,12 @@ class TestHerringboneGear(unittest.TestCase):
if node["op"] == "make_twisted_sweep_rsolid"
)
)
self.assertEqual(len(solid.get_faces()), 146)
self.assertEqual(len(solid._iter_faces()), 146)
replayed = scad.replay_model_json(
json_str=json.dumps(payload), strict=True
)[0]
self.assertEqual(len(replayed.get_faces()), 146)
self.assertEqual(len(replayed._iter_faces()), 146)
self.assertAlmostEqual(replayed.get_volume(), solid.get_volume(), places=6)
def test_stdlib_graph_tracking_scope_does_not_leak(self):
@@ -545,12 +545,12 @@ class TestSpurRingGear(unittest.TestCase):
pressure_angle=pressure_angle,
rim_thickness=4.0,
)
inner_wire = face.get_inner_wires()[0]
inner_wire = face.get_inner_wires(0)
vertex_radii = [
math.hypot(x, y)
for edge in inner_wire.get_edges()
for vertex in edge.get_vertices()
for edge in inner_wire._iter_edges()
for vertex in edge._iter_vertices()
for x, y, _z in [vertex.get_coordinates()]
]
pitch_radius = module * n_teeth / 2.0
@@ -943,7 +943,7 @@ class Test2DFaceBoolean(unittest.TestCase):
math.pi * (100 - 16),
places=1,
)
self.assertEqual(len(ring.get_inner_wires()), 1)
self.assertEqual(len(ring._iter_inner_wires()), 1)
def test_make_face_from_wires_rface_creates_hole(self):
outer = scad.make_circle_rwire(center=(0, 0, 0), radius=10.0)
@@ -954,7 +954,7 @@ class Test2DFaceBoolean(unittest.TestCase):
math.pi * (100 - 16),
places=1,
)
self.assertEqual(len(ring.get_inner_wires()), 1)
self.assertEqual(len(ring._iter_inner_wires()), 1)
def test_make_2d_union_rface(self):
a = scad.make_circle_rface(center=(0, 0, 0), radius=5.0)
+19 -19
View File
@@ -210,13 +210,13 @@ class TestSurfaceApi(unittest.TestCase):
def test_solid_from_closed_shell_replays(self):
with scad.GraphSession() as session:
box = scad.make_box_rsolid(1.0, 2.0, 3.0)
shell = scad.sew_faces_rshell(box.get_faces())
shell = scad.sew_faces_rshell(box._iter_faces())
shell = scad.apply_tag_rselection(
shell,
scad.ql.faces(),
"role.preserved_face",
)
source_face_tags = {face.topo_id for face in shell.get_faces()}
source_face_tags = {face.topo_id for face in shell._iter_faces()}
solid = scad.make_solid_from_shell_rsolid(shell, tag_prefix="body")
replayed = scad.replay_model_json(scad.export_model_json(session))[0]
@@ -229,13 +229,13 @@ class TestSurfaceApi(unittest.TestCase):
all(
face.topo_id in source_face_tags
and "role.preserved_face" in scad.list_tags(face)
for face in solid.get_faces()
for face in solid._iter_faces()
)
)
self.assertTrue(
all(
"role.preserved_face" in scad.list_tags(face)
for face in replayed.get_faces()
for face in replayed._iter_faces()
)
)
@@ -275,7 +275,7 @@ class TestSurfaceApi(unittest.TestCase):
def test_shell_scoped_face_tag_replays(self):
with scad.GraphSession() as session:
box = scad.make_box_rsolid(1.0, 2.0, 3.0)
shell = scad.sew_faces_rshell(box.get_faces())
shell = scad.sew_faces_rshell(box._iter_faces())
tagged_face = scad.apply_tag(
shell.get_faces(0),
"role.shell_face",
@@ -350,7 +350,7 @@ class TestSurfaceApi(unittest.TestCase):
self.assertEqual(len(replayed), 2)
self.assertAlmostEqual(replayed[0].get_area(), gordon.get_area(), places=7)
self.assertAlmostEqual(replayed[1].get_area(), patch.get_area(), places=7)
self.assertEqual(len(replayed[1].get_edges()), 4)
self.assertEqual(len(replayed[1]._iter_edges()), 4)
self.assertIn("patch.face", scad.list_tags(replayed[1]))
def test_trim_surface_with_hole_and_replay(self):
@@ -371,7 +371,7 @@ class TestSurfaceApi(unittest.TestCase):
self.assertIsInstance(trimmed, scad.Face)
self.assertAlmostEqual(trimmed.get_area(), 15.0, places=6)
self.assertAlmostEqual(replayed.get_area(), trimmed.get_area(), places=7)
self.assertEqual(len(trimmed.get_wires()), 2)
self.assertEqual(len(trimmed._iter_wires()), 2)
self.assertIn("trimmed.face", scad.list_tags(replayed))
def test_trim_preserves_existing_carrier_holes(self):
@@ -390,7 +390,7 @@ class TestSurfaceApi(unittest.TestCase):
)
self.assertAlmostEqual(trimmed.get_area(), 5.0, places=6)
self.assertEqual(len(trimmed.get_inner_wires()), 1)
self.assertEqual(len(trimmed._iter_inner_wires()), 1)
def test_trim_intersects_partially_overlapping_planar_loop(self):
backing = scad.make_bezier_surface_rface(
@@ -450,7 +450,7 @@ class TestSurfaceApi(unittest.TestCase):
trimmed = scad.trim_surface_rface(carrier, outer, tolerance=tolerance)
self.assertIsInstance(trimmed, scad.Face)
self.assertEqual(len(trimmed.get_wires()), 1)
self.assertEqual(len(trimmed._iter_wires()), 1)
def test_trim_rejects_closed_oscillating_curve_between_coarse_samples(self):
carrier = scad.make_bezier_surface_rface(
@@ -520,7 +520,7 @@ class TestSurfaceApi(unittest.TestCase):
]
self.assertIsInstance(replayed, scad.Shell)
self.assertFalse(replayed.is_closed())
self.assertEqual(len(replayed.get_wires()), 2)
self.assertEqual(len(replayed._iter_wires()), 2)
self.assertEqual(
len(scad.ql.wires().where(scad.ql.tag("anchor.inlet")).resolve(replayed)),
1,
@@ -538,7 +538,7 @@ class TestSurfaceApi(unittest.TestCase):
point = scad.make_point_rvertex(0, 0, 4)
pointed = scad.loft_rshell([upper, point], start_wire_tag="anchor.base")
self.assertEqual(len(pointed.get_wires()), 1)
self.assertEqual(len(pointed._iter_wires()), 1)
self.assertEqual(
len(scad.ql.wires().where(scad.ql.tag("anchor.base")).resolve(pointed)),
1,
@@ -556,8 +556,8 @@ class TestSurfaceApi(unittest.TestCase):
replayed = scad.replay_model_json(scad.export_model_json(session))
self.assertEqual(len(boundaries), 1)
self.assertEqual(len(replayed), 1)
original_length = sum(edge.get_length() for edge in boundaries[0].get_edges())
replayed_length = sum(edge.get_length() for edge in replayed[0].get_edges())
original_length = sum(edge.get_length() for edge in boundaries[0]._iter_edges())
replayed_length = sum(edge.get_length() for edge in replayed[0]._iter_edges())
self.assertAlmostEqual(replayed_length, original_length, places=8)
def test_sew_shell_faces_replays_selected_face_inputs(self):
@@ -565,7 +565,7 @@ class TestSurfaceApi(unittest.TestCase):
lower = scad.make_circle_rwire((0, 0, 0), 1.0)
upper = scad.make_circle_rwire((0, 0, 2), 1.0)
lofted = scad.loft_rshell([lower, upper])
resewn = scad.sew_faces_rshell(lofted.get_faces())
resewn = scad.sew_faces_rshell(lofted._iter_faces())
session.capture_result(value=resewn)
payload = scad.export_model_json(session)
@@ -579,13 +579,13 @@ class TestSurfaceApi(unittest.TestCase):
replayed = scad.replay_model_json(payload, strict=True)
self.assertEqual(len(replayed), 1)
self.assertIsInstance(replayed[0], scad.Shell)
self.assertEqual(len(replayed[0].get_faces()), len(resewn.get_faces()))
self.assertEqual(len(replayed[0]._iter_faces()), len(resewn._iter_faces()))
self.assertAlmostEqual(replayed[0].get_area(), resewn.get_area(), places=8)
def test_solidification_does_not_overwrite_existing_shell_face_refs(self):
with scad.GraphSession() as session:
box = scad.make_box_rsolid(1.0, 2.0, 3.0)
shell = scad.sew_faces_rshell(box.get_faces())
shell = scad.sew_faces_rshell(box._iter_faces())
retained_face = shell.get_faces(0)
retained_ref = retained_face._get_runtime("topo.ref")
scad.make_solid_from_shell_rsolid(shell)
@@ -599,7 +599,7 @@ class TestSurfaceApi(unittest.TestCase):
def test_solidification_isolates_cache_and_preserves_subshape_state(self):
box = scad.make_box_rsolid(1.0, 2.0, 3.0)
shell = scad.sew_faces_rshell(box.get_faces())
shell = scad.sew_faces_rshell(box._iter_faces())
source_face = shell.get_faces(0)
scad.apply_tag(source_face, "role.shell_face_state")
source_face.set_metadata("audit", {"value": 1})
@@ -608,7 +608,7 @@ class TestSurfaceApi(unittest.TestCase):
solid = scad.make_solid_from_shell_rsolid(shell)
matches = [
face
for face in solid.get_faces()
for face in solid._iter_faces()
if face.wrapped.IsSame(source_face.wrapped)
]
@@ -621,7 +621,7 @@ class TestSurfaceApi(unittest.TestCase):
def test_solid_subshape_uses_fresh_graph_references(self):
with scad.GraphSession() as session:
box = scad.make_box_rsolid(1.0, 2.0, 3.0)
shell = scad.sew_faces_rshell(box.get_faces())
shell = scad.sew_faces_rshell(box._iter_faces())
solid = scad.make_solid_from_shell_rsolid(shell)
moved = scad.translate_shape(solid.get_faces(0), (1.0, 0.0, 0.0))
session.capture_result(value=moved)
+6 -6
View File
@@ -20,7 +20,7 @@ class TestTaggingRefactor(unittest.TestCase):
self.assertFalse(
any(
"role.mounting_surface" in face._list_tags("effective")
for face in box.get_faces()
for face in box._iter_faces()
)
)
@@ -278,7 +278,7 @@ class TestTaggingRefactor(unittest.TestCase):
lineage_policy=scad.LineagePolicy.CONTINUATION_FRAGMENT,
)
tagged_face = next(
face for face in tagged.get_faces() if face.topo_id == source_face.topo_id
face for face in tagged._iter_faces() if face.topo_id == source_face.topo_id
)
self.assertIn(
@@ -311,7 +311,7 @@ class TestTaggingRefactor(unittest.TestCase):
def test_wire_edge_indices_live_in_geo_metadata_not_tags(self):
wire = scad.make_rectangle_rwire(1.0, 1.0)
edges = wire.get_edges()
edges = wire._iter_edges()
self.assertTrue(edges)
self.assertFalse(any(tag.isdigit() for edge in edges for tag in scad.list_tags(edge)))
@@ -328,14 +328,14 @@ class TestAutoTagFacesNamespaces(unittest.TestCase):
def test_box_faces_have_new_tags(self):
box = scad.make_box_rsolid(1.0, 1.0, 1.0)
box.auto_tag_faces("box")
faces = box.get_faces()
faces = box._iter_faces()
self.assertTrue(any("face.top" in scad.list_tags(face) for face in faces))
self.assertTrue(any("face.bottom" in scad.list_tags(face) for face in faces))
def test_cylinder_faces_have_new_tags(self):
cylinder = scad.make_cylinder_rsolid(1.0, 2.0)
cylinder.auto_tag_faces("cylinder")
faces = cylinder.get_faces()
faces = cylinder._iter_faces()
self.assertTrue(any("face.top" in scad.list_tags(face) for face in faces))
self.assertTrue(any("face.bottom" in scad.list_tags(face) for face in faces))
self.assertTrue(any("face.side" in scad.list_tags(face) for face in faces))
@@ -343,7 +343,7 @@ class TestAutoTagFacesNamespaces(unittest.TestCase):
def test_sphere_faces_have_new_tags(self):
sphere = scad.make_sphere_rsolid(1.0)
sphere.auto_tag_faces("sphere")
faces = sphere.get_faces()
faces = sphere._iter_faces()
self.assertEqual(len(faces), 1)
self.assertIn("face.surface", scad.list_tags(faces[0]))
+95
View File
@@ -0,0 +1,95 @@
"""Contract tests: bare topology enumeration is forbidden; reads go through QL.
Plural topology getters accept only an index. The no-argument form raises a
guidance error pointing at QL selectors; indexed picks remain recorded as
graph selection nodes.
"""
from __future__ import annotations
import json
import unittest
import simplecadapi as scad
from simplecadapi import ql
from simplecadapi.core import Compound
from simplecadapi.kernel.ocp_export import make_compound_always
class TestTopologyGetterContract(unittest.TestCase):
def setUp(self):
self.box = scad.make_box_rsolid(3.0, 2.0, 1.0)
self.face = ql.faces().resolve(self.box)[0]
self.wire = self.face.get_outer_wire()
self.edge = ql.edges().resolve(self.wire)[0]
self.shell = scad.sew_faces_rshell(self.box._iter_faces())
self.compound = Compound(
make_compound_always([self.box.wrapped, self.box.wrapped])
)
def _assert_enumeration_forbidden(self, owner, method_name):
with self.assertRaises(scad.SimpleCADError) as ctx:
getattr(owner, method_name)()
message = str(ctx.exception)
self.assertIn("ql.", message)
self.assertIn("index", message)
def test_every_plural_getter_forbids_bare_enumeration(self):
cases = [
(self.edge, "get_vertices"),
(self.wire, "get_edges"),
(self.face, "get_wires"),
(self.face, "get_inner_wires"),
(self.face, "get_edges"),
(self.shell, "get_faces"),
(self.shell, "get_wires"),
(self.shell, "get_edges"),
(self.box, "get_faces"),
(self.box, "get_edges"),
(self.box, "get_edge_occurrences"),
(self.compound, "get_solids"),
(self.compound, "get_faces"),
(self.compound, "get_edges"),
]
for owner, method_name in cases:
with self.subTest(shape=type(owner).__name__, method=method_name):
self._assert_enumeration_forbidden(owner, method_name)
def test_indexed_pick_returns_shape_and_records_select_node(self):
# The source shape must itself be a recorded graph node, so build it
# inside the session the pick is recorded against.
with scad.GraphSession() as session:
box = scad.make_box_rsolid(3.0, 2.0, 1.0)
picked = box.get_edges(0)
self.assertEqual(
picked.get_length(), ql.edges().resolve(box)[0].get_length()
)
scad.chamfer_rsolid(solid=box, edges=[picked], distance=0.1)
payload = json.loads(scad.export_model_json(session))
select_ops = [
node["op"]
for node in payload["graph"]["nodes"]
if node["op"] == "make_select_redge"
]
self.assertGreaterEqual(len(select_ops), 1)
def test_ql_bare_enumeration_replaces_list_getters(self):
self.assertEqual(len(ql.faces().resolve(self.box)), 6)
self.assertEqual(len(ql.edges().resolve(self.box)), 12)
self.assertEqual(len(ql.edges().resolve(self.wire)), 4)
self.assertEqual(len(ql.solids().resolve(self.compound)), 2)
def test_ql_predicate_and_cardinality_contract(self):
bottom = (
ql.faces()
.where(ql.prop("geom.normal.z", "<=", -0.999))
.take(1)
.exactly(1)
.resolve(self.box)
)
self.assertAlmostEqual(bottom[0].get_area(), 6.0, places=6)
if __name__ == "__main__":
unittest.main()
+11 -11
View File
@@ -63,8 +63,8 @@ class TestTrackedCut(unittest.TestCase):
def test_tracked_cut_total_faces_increased(self):
"""A cylinder cut through a box adds the cylindrical hole face."""
result = tracked_cut(self.body, self.tool)
original_faces = len(self.body.get_faces())
result_faces = len(result.solid.get_faces())
original_faces = len(self.body._iter_faces())
result_faces = len(result.solid._iter_faces())
# Cylinder through box: at least 1 new face (cylindrical hole)
self.assertGreaterEqual(result_faces, original_faces)
@@ -136,9 +136,9 @@ class TestTrackedUnion(unittest.TestCase):
]
result = scad.union_rsolid(*solids, glue=False)
tracks = [face.get_metadata("track") for face in result.get_faces()]
tracks = [face.get_metadata("track") for face in result._iter_faces()]
self.assertEqual(len(result.get_faces()), 6)
self.assertEqual(len(result._iter_faces()), 6)
self.assertTrue(all(track["status"] == "proven" for track in tracks))
self.assertEqual(
{role for track in tracks for role in track["origin_roles"]},
@@ -165,13 +165,13 @@ class TestTrackedUnion(unittest.TestCase):
bottom_face_center=(58.0, 0.0, 0.0),
axis=(1.0, 0.0, 0.0),
)
source_face = max(flange.get_faces(), key=lambda face: face.get_center().x)
source_face = max(flange._iter_faces(), key=lambda face: face.get_center().x)
scad.apply_tag(source_face, "cap.face.end")
result = scad.union_rsolid(barrel, flange, nose, glue=False)
descendants = [
face
for face in result.get_faces()
for face in result._iter_faces()
if "cap.face.end" in scad.list_tags(face, scope="lineage")
]
@@ -200,7 +200,7 @@ class TestTrackedUnion(unittest.TestCase):
bottom_face_center=(58.0, 0.0, 0.0),
axis=(1.0, 0.0, 0.0),
)
source_face = max(flange.get_faces(), key=lambda face: face.get_center().x)
source_face = max(flange._iter_faces(), key=lambda face: face.get_center().x)
flange = scad.apply_tag_rselection(
flange,
[source_face],
@@ -211,7 +211,7 @@ class TestTrackedUnion(unittest.TestCase):
result = scad.union_rsolid(barrel, flange, nose, glue=False)
self.assertFalse(
any("cap.face.end" in scad.list_tags(face) for face in result.get_faces())
any("cap.face.end" in scad.list_tags(face) for face in result._iter_faces())
)
def test_nary_union_face_binding_stays_directly_queryable_after_cut(self):
@@ -278,11 +278,11 @@ class TestTrackedUnion(unittest.TestCase):
result = scad.union_rsolid(*solids, clean=False, glue=False)
self.assertEqual(len(result.get_faces()), 14)
self.assertEqual(len(result._iter_faces()), 14)
self.assertTrue(
all(
face.get_metadata("track")["status"] == "proven"
for face in result.get_faces()
for face in result._iter_faces()
)
)
@@ -349,7 +349,7 @@ class TestSolidMapping(unittest.TestCase):
def test_result_has_faces(self):
result = tracked_cut(self.body, self.tool)
faces = result.solid.get_faces()
faces = result.solid._iter_faces()
self.assertGreater(len(faces), 0)
def test_result_has_valid_volume(self):
+2 -2
View File
@@ -33,7 +33,7 @@ class TestTrackedTranslate(unittest.TestCase):
def test_translate_all_faces_modified(self):
result = tracked_translate(self.box, (5, 0, 0))
modified = [r for r in result.delta.modified if r.kind == TopoKind.FACE]
original_faces = len(self.box.get_faces())
original_faces = len(self.box._iter_faces())
self.assertEqual(len(modified), original_faces)
def test_translate_no_generated(self):
@@ -64,7 +64,7 @@ class TestTrackedRotate(unittest.TestCase):
def test_rotate_all_faces_modified(self):
result = tracked_rotate(self.box, 45.0, (0, 0, 1))
modified = [r for r in result.delta.modified if r.kind == TopoKind.FACE]
original_faces = len(self.box.get_faces())
original_faces = len(self.box._iter_faces())
self.assertEqual(len(modified), original_faces)
def test_rotate_no_generated(self):
+10 -10
View File
@@ -28,7 +28,7 @@ class TestAutoTagCut(unittest.TestCase):
tagged_solid = apply_tracking_tags_to_delta(
result.solid, result.delta, result.delta_entries, op="cut"
)
faces = tagged_solid.get_faces()
faces = tagged_solid._iter_faces()
has_change = any(
proven_event("cut", "modified")(face)
or proven_event("cut", "generated")(face)
@@ -41,7 +41,7 @@ class TestAutoTagCut(unittest.TestCase):
tagged_solid = apply_tracking_tags_to_delta(
result.solid, result.delta, result.delta_entries, op="cut"
)
faces = tagged_solid.get_faces()
faces = tagged_solid._iter_faces()
preserved = [face for face in faces if proven_event("cut", "preserved")(face)]
self.assertGreater(len(preserved), 0)
@@ -50,7 +50,7 @@ class TestAutoTagCut(unittest.TestCase):
tagged_solid = apply_tracking_tags_to_delta(
result.solid, result.delta, result.delta_entries, op="cut"
)
faces = tagged_solid.get_faces()
faces = tagged_solid._iter_faces()
for face in faces:
track = face.get_metadata("track")
self.assertEqual(track["schema_version"], "1.0")
@@ -71,7 +71,7 @@ class TestAutoTagCut(unittest.TestCase):
tagged_solid = apply_tracking_tags_to_delta(
result.solid, result.delta, result.delta_entries, op="cut"
)
faces = tagged_solid.get_faces()
faces = tagged_solid._iter_faces()
proven = Q.meta("track.status", "==", "proven")
has_body = any(Q.origin_role("body")(face) and proven(face) for face in faces)
has_tool = any(Q.origin_role("tool")(face) and proven(face) for face in faces)
@@ -82,7 +82,7 @@ class TestAutoTagCut(unittest.TestCase):
solid = scad.make_box_rsolid(1.0, 1.0, 1.0)
tagged = apply_tracking_tags_to_delta(solid, TopoDelta(), op="cut")
for face in tagged.get_faces():
for face in tagged._iter_faces():
track = face.get_metadata("track")
self.assertEqual(track["coverage"], "partial")
self.assertEqual(track["status"], "unknown")
@@ -102,7 +102,7 @@ class TestAutoTagUnion(unittest.TestCase):
tagged_solid = apply_tracking_tags_to_delta(
result.solid, result.delta, result.delta_entries, op="union"
)
faces = tagged_solid.get_faces()
faces = tagged_solid._iter_faces()
has_union_evidence = any(
proven_event("union", "modified")(face)
or proven_event("union", "preserved")(face)
@@ -112,7 +112,7 @@ class TestAutoTagUnion(unittest.TestCase):
section_tracks = [
edge.get_metadata("track")
for edge in tagged_solid.get_edges()
for edge in tagged_solid._iter_edges()
if edge.get_metadata("track").get("section")
]
self.assertTrue(section_tracks)
@@ -134,7 +134,7 @@ class TestAutoTagExtrude(unittest.TestCase):
tagged_solid = apply_tracking_tags_to_delta(
result.shape, result.delta, result.delta_entries, op="extrude"
)
faces = tagged_solid.get_faces()
faces = tagged_solid._iter_faces()
self.assertTrue(faces)
roles = [
role
@@ -150,7 +150,7 @@ class TestAutoTagExtrude(unittest.TestCase):
class TestAutoTagPreservesExisting(unittest.TestCase):
def test_user_semantics_are_available_only_through_proven_lineage(self):
body = scad.make_box_rsolid(10, 10, 10)
for face in body.get_faces():
for face in body._iter_faces():
scad.apply_tag(face, "role.source_face")
tool = scad.make_cylinder_rsolid(2.0, 15.0, bottom_face_center=(3, 3, -2.5))
result = tracked_cut(body, tool)
@@ -163,7 +163,7 @@ class TestAutoTagPreservesExisting(unittest.TestCase):
)
body_descendants = [
face
for face in tagged_solid.get_faces()
for face in tagged_solid._iter_faces()
if Q.origin_role("body")(face)
and face.get_metadata("track")["status"] == "proven"
]
+1 -1
View File
@@ -29,7 +29,7 @@ def test_ocp_native_basic_properties():
box = make_box_rsolid(1, 2, 3)
assert isinstance(box, Solid)
assert box.get_volume() == pytest.approx(6.0)
assert len(box.get_faces()) == 6
assert len(box._iter_faces()) == 6
def test_ocp_native_face_wire_topology_and_extrude():
+3 -3
View File
@@ -10,8 +10,8 @@ from simplecadapi.sketch import Sketch, SketchRef, SketchSolveResult
def _box_edge_occurrences():
box = scad.make_box_rsolid(1.0, 1.0, 1.0)
occurrences = []
for face in box.get_faces():
occurrences.extend(face.get_outer_wire().get_edges())
for face in box._iter_faces():
occurrences.extend(face.get_outer_wire()._iter_edges())
return box, occurrences
@@ -132,7 +132,7 @@ def test_semantic_shape_clone_keeps_independent_entity_state():
def test_solid_get_edges_returns_unique_topological_edges():
box, _ = _box_edge_occurrences()
edges = box.get_edges()
edges = box._iter_edges()
assert len(edges) == 12
assert len({edge.topo_id for edge in edges}) == 12