f3d2solidcraft 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- f3d2solidcraft/__init__.py +3 -0
- f3d2solidcraft/__main__.py +3 -0
- f3d2solidcraft/_vendor/__init__.py +0 -0
- f3d2solidcraft/_vendor/ezf3d/LICENSE +21 -0
- f3d2solidcraft/_vendor/ezf3d/__init__.py +1 -0
- f3d2solidcraft/_vendor/ezf3d/container/__init__.py +1 -0
- f3d2solidcraft/_vendor/ezf3d/container/archive.py +204 -0
- f3d2solidcraft/_vendor/ezf3d/model/__init__.py +1 -0
- f3d2solidcraft/_vendor/ezf3d/model/parameters.py +365 -0
- f3d2solidcraft/_vendor/ezf3d/model/sketch.py +645 -0
- f3d2solidcraft/_vendor/ezf3d/model/timeline.py +493 -0
- f3d2solidcraft/_vendor/ezf3d/streams/__init__.py +1 -0
- f3d2solidcraft/_vendor/ezf3d/streams/manifest.py +262 -0
- f3d2solidcraft/_vendor/ezf3d/streams/primitives.py +191 -0
- f3d2solidcraft/_vendor/ezf3d/streams/segment.py +521 -0
- f3d2solidcraft/cli.py +574 -0
- f3d2solidcraft/engine.py +458 -0
- f3d2solidcraft/fallback.py +250 -0
- f3d2solidcraft/geometry.py +397 -0
- f3d2solidcraft/mappers/__init__.py +141 -0
- f3d2solidcraft/mappers/bodies.py +99 -0
- f3d2solidcraft/mappers/combine.py +73 -0
- f3d2solidcraft/mappers/components.py +542 -0
- f3d2solidcraft/mappers/edges.py +449 -0
- f3d2solidcraft/mappers/extrude.py +1501 -0
- f3d2solidcraft/mappers/faces.py +50 -0
- f3d2solidcraft/mappers/loft.py +149 -0
- f3d2solidcraft/mappers/outputs.py +73 -0
- f3d2solidcraft/mappers/params.py +134 -0
- f3d2solidcraft/mappers/pattern.py +68 -0
- f3d2solidcraft/mappers/planes.py +222 -0
- f3d2solidcraft/mappers/primitives.py +144 -0
- f3d2solidcraft/mappers/records.py +51 -0
- f3d2solidcraft/mappers/revolve.py +134 -0
- f3d2solidcraft/mappers/sheet.py +95 -0
- f3d2solidcraft/mappers/shell.py +180 -0
- f3d2solidcraft/mappers/sketch.py +455 -0
- f3d2solidcraft/mcp.py +218 -0
- f3d2solidcraft/model.py +503 -0
- f3d2solidcraft/oracle.py +905 -0
- f3d2solidcraft/pairing.py +105 -0
- f3d2solidcraft/reader/__init__.py +77 -0
- f3d2solidcraft/reader/cadir.py +832 -0
- f3d2solidcraft/reader/fusion.py +218 -0
- f3d2solidcraft/reader/locale.py +115 -0
- f3d2solidcraft/replay.py +322 -0
- f3d2solidcraft/report.py +107 -0
- f3d2solidcraft/tools.py +219 -0
- f3d2solidcraft/verify.py +186 -0
- f3d2solidcraft/visibility.py +95 -0
- f3d2solidcraft-0.3.0.dist-info/METADATA +189 -0
- f3d2solidcraft-0.3.0.dist-info/RECORD +74 -0
- f3d2solidcraft-0.3.0.dist-info/WHEEL +4 -0
- f3d2solidcraft-0.3.0.dist-info/entry_points.txt +5 -0
- f3d2solidcraft-0.3.0.dist-info/licenses/LICENSE +21 -0
- f3d2solidcraft-0.3.0.dist-info/licenses/src/f3d2solidcraft/_vendor/ezf3d/LICENSE +21 -0
- f3d2solidcraft_app/__init__.py +5 -0
- f3d2solidcraft_app/__main__.py +40 -0
- f3d2solidcraft_app/engines.py +158 -0
- f3d2solidcraft_app/events.py +35 -0
- f3d2solidcraft_app/opener.py +22 -0
- f3d2solidcraft_app/outcome.py +54 -0
- f3d2solidcraft_app/resources/icon-128.png +0 -0
- f3d2solidcraft_app/resources/icon-16.png +0 -0
- f3d2solidcraft_app/resources/icon-256.png +0 -0
- f3d2solidcraft_app/resources/icon-32.png +0 -0
- f3d2solidcraft_app/resources/icon-512.png +0 -0
- f3d2solidcraft_app/resources/icon-64.png +0 -0
- f3d2solidcraft_app/resources/icon.icns +0 -0
- f3d2solidcraft_app/resources/icon.ico +0 -0
- f3d2solidcraft_app/resources/icon.svg +26 -0
- f3d2solidcraft_app/runner.py +91 -0
- f3d2solidcraft_app/texts.py +98 -0
- f3d2solidcraft_app/window.py +677 -0
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Bodies that could not be rebuilt come back from the original B-rep."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from f3d2solidcraft.engine import CommandRefused
|
|
9
|
+
from f3d2solidcraft.mappers import Context
|
|
10
|
+
from f3d2solidcraft.pairing import declared_name
|
|
11
|
+
from f3d2solidcraft.replay import ReplayResult
|
|
12
|
+
from f3d2solidcraft.tools import ToolFailed, run_tool
|
|
13
|
+
|
|
14
|
+
_CHECK_ERROR = re.compile(r"^\s*\[error/(\w+)\] (.*?)(?: \([^()]*\))?$", re.MULTILINE)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def original_step(cadmpeg: Path, source: Path, out: Path) -> tuple[Path, list[str]]:
|
|
18
|
+
"""The design's bodies as STEP, hidden ones included; internal only (fallback and verification).
|
|
19
|
+
|
|
20
|
+
source may be the .f3d or the CADIR JSON already dumped from it, which skips a second decode.
|
|
21
|
+
When cadmpeg's own check refuses the export, it is redone with --allow-errors and the check
|
|
22
|
+
errors come back as warnings: an imperfect B-rep beats a missing body.
|
|
23
|
+
"""
|
|
24
|
+
args = [str(cadmpeg), "convert", str(source), "-o", str(out), "--force"]
|
|
25
|
+
try:
|
|
26
|
+
run_tool(args, 600)
|
|
27
|
+
except ToolFailed as exc:
|
|
28
|
+
if "refusing to export" not in str(exc):
|
|
29
|
+
raise
|
|
30
|
+
run_tool([*args, "--allow-errors"], 600)
|
|
31
|
+
return out, check_warnings(str(exc))
|
|
32
|
+
return out, []
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def check_warnings(text: str) -> list[str]:
|
|
36
|
+
"""One warning per kind of cadmpeg check error, with its count (and worst deviation if geometric)."""
|
|
37
|
+
kinds: dict[str, list[str]] = {}
|
|
38
|
+
for kind, message in _CHECK_ERROR.findall(text):
|
|
39
|
+
kinds.setdefault(kind, []).append(message)
|
|
40
|
+
warnings = []
|
|
41
|
+
for kind, messages in kinds.items():
|
|
42
|
+
head = f"cadmpeg check: {len(messages)}\u00d7 {kind}"
|
|
43
|
+
deviations = [float(m) for m in re.findall(r"\bby ([0-9.]+)", " ".join(messages))]
|
|
44
|
+
if deviations:
|
|
45
|
+
warnings.append(
|
|
46
|
+
f"{head} (max deviation {max(deviations):.3g}) \u2014 imported geometry may be inexact"
|
|
47
|
+
)
|
|
48
|
+
else:
|
|
49
|
+
warnings.append(f"{head} ({messages[0].removeprefix('Fusion ')})")
|
|
50
|
+
return warnings
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def same_body(
|
|
54
|
+
a: dict,
|
|
55
|
+
b: dict,
|
|
56
|
+
vol_rel: float = 1e-3,
|
|
57
|
+
bbox_abs: float = 0.01,
|
|
58
|
+
faces: bool = True,
|
|
59
|
+
com_abs: float = 0.01,
|
|
60
|
+
) -> bool:
|
|
61
|
+
"""Whether these two measurements are of the same solid.
|
|
62
|
+
|
|
63
|
+
Volume, box and face count do not determine a shape, and for a while those three were the whole
|
|
64
|
+
check. Measured on the engine: a 10 mm cube notched 4 × 4 at corner (0, 0) and the same cube
|
|
65
|
+
notched at (6, 6) agree on every one of them — 840.000 mm³, the same 0..10 box, 8 faces, 18
|
|
66
|
+
edges, 12 vertices, 568.000 mm² — and are not the same solid. A conversion that built one where
|
|
67
|
+
the original has the other verified.
|
|
68
|
+
|
|
69
|
+
So the centre of mass is read too, to the same 0.01 mm as the box: it is where the shape's mass
|
|
70
|
+
actually sits, and on that pair it differs by 1.14 mm on two axes.
|
|
71
|
+
"""
|
|
72
|
+
if faces and a["faces"] != b["faces"]:
|
|
73
|
+
return False
|
|
74
|
+
# The engine reports a volume and a centre of mass only for a closed, consistently oriented
|
|
75
|
+
# body, so an open one — a surface — carries neither. Reading the volume straight **crashed** the
|
|
76
|
+
# whole conversion on a real package of the user's, `corpus-09.f3z`: `unsupported
|
|
77
|
+
# operand type(s) for -: 'NoneType' and 'float'` (spec section 89).
|
|
78
|
+
va, vb = a.get("volume_mm3"), b.get("volume_mm3")
|
|
79
|
+
if (va is None) != (vb is None):
|
|
80
|
+
return False # one is a closed solid and the other is not: not the same body
|
|
81
|
+
if va is None:
|
|
82
|
+
# Neither is closed, so there is no volume and no centre of mass to read. The surface area
|
|
83
|
+
# takes volume's place, to the same relative band: without it this pair would be judged on
|
|
84
|
+
# the box and the face count alone, which the measurement above shows do not determine a
|
|
85
|
+
# shape.
|
|
86
|
+
aa, ab = a.get("area_mm2"), b.get("area_mm2")
|
|
87
|
+
if aa is None or ab is None:
|
|
88
|
+
return False
|
|
89
|
+
if abs(aa - ab) > vol_rel * max(abs(aa), abs(ab), 1e-9):
|
|
90
|
+
return False
|
|
91
|
+
elif abs(va - vb) > vol_rel * max(abs(va), abs(vb), 1e-9):
|
|
92
|
+
return False
|
|
93
|
+
corners = zip(a["bbox"]["min"] + a["bbox"]["max"], b["bbox"]["min"] + b["bbox"]["max"])
|
|
94
|
+
if not all(abs(x - y) <= bbox_abs for x, y in corners):
|
|
95
|
+
return False
|
|
96
|
+
here, there = a.get("center_of_mass"), b.get("center_of_mass")
|
|
97
|
+
if here is None or there is None:
|
|
98
|
+
return True # an older measurement without it: judged on the three as before
|
|
99
|
+
return all(abs(x - y) <= com_abs for x, y in zip(here, there))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def apply_fallback(ctx: Context, result: ReplayResult, step: Path) -> list[str]:
|
|
103
|
+
"""Swap the bodies the replay could not finish for the original B-rep; record what was imported.
|
|
104
|
+
|
|
105
|
+
The names of the imported bodies that stay land in ``result.imported_bodies``; returns warnings.
|
|
106
|
+
"""
|
|
107
|
+
if not result.fallback_bodies:
|
|
108
|
+
return []
|
|
109
|
+
engine = ctx.engine
|
|
110
|
+
# Nothing is warned about a hidden body: `cadmpeg convert` exports every one of them, so the
|
|
111
|
+
# import brings it back like any other. This said the opposite and was simply false.
|
|
112
|
+
warnings: list[str] = []
|
|
113
|
+
present = set(engine.body_names())
|
|
114
|
+
partial = sorted({ctx.body_names[b] for b in result.fallback_bodies if b in ctx.body_names} & present)
|
|
115
|
+
if partial:
|
|
116
|
+
engine.execute("solid.remove", {"bodies": partial})
|
|
117
|
+
kept = engine.body_readings()
|
|
118
|
+
kept_names = {b["name"] for b in kept}
|
|
119
|
+
try:
|
|
120
|
+
engine.execute("file.insert_step", {"path": str(step), "name": "Fusion fallback"})
|
|
121
|
+
except CommandRefused as exc:
|
|
122
|
+
# This one call *is* the safety net, and it was the only unprotected one in the path, so a
|
|
123
|
+
# refusal here ended the whole conversion with the engine's error and no report at all.
|
|
124
|
+
# Measured on `corpus-07` under solidcraft 0.40.0-rc.3, whose STEP
|
|
125
|
+
# importer refuses the file because 3 of one solid's 242 faces fail their pcurves: the file
|
|
126
|
+
# produced nothing, where under 0.30.1 it converts and verifies (spec section 124).
|
|
127
|
+
#
|
|
128
|
+
# The partial bodies are already removed above, and they should stay removed: a body the
|
|
129
|
+
# replay began and no feature finished is geometry the original never had, so shipping it
|
|
130
|
+
# would read as `extra` where the truth is `missing`. So the design keeps what the replay
|
|
131
|
+
# really built, says what it could not recover in the engine's own words, and goes on to be
|
|
132
|
+
# verified on what it has. `imported_bodies` stays empty, which is what it is.
|
|
133
|
+
warnings.append(
|
|
134
|
+
f"the original could not be imported, so {len(result.fallback_bodies)} body(ies) the "
|
|
135
|
+
f"replay could not finish are missing from the design: {exc.message}"
|
|
136
|
+
)
|
|
137
|
+
return warnings
|
|
138
|
+
bodies = engine.body_readings()
|
|
139
|
+
# What the import left is the difference against what was measured before it, and nothing else
|
|
140
|
+
# happens between those two readings. This used to prefer the import's own `created_bodies` when
|
|
141
|
+
# it answered, and that list is short where the STEP carries nested occurrences: on a real
|
|
142
|
+
# package of the user's, `corpus-09.f3z`, it named 462 of the 494 bodies the design then
|
|
143
|
+
# held, so 32 imported placements were counted as native in the report (spec section 90).
|
|
144
|
+
imported = [b for b in bodies if b["name"] not in kept_names]
|
|
145
|
+
# Two sides of one question, asked against the whole import before anything is removed: the
|
|
146
|
+
# import holds every body of the original, so for each body now in the design there either is a
|
|
147
|
+
# counterpart or there is not.
|
|
148
|
+
#
|
|
149
|
+
# An imported body with a native counterpart is the duplicate — the replay already built that
|
|
150
|
+
# one, so the import goes and the native body stays. A **native** body with no counterpart
|
|
151
|
+
# anywhere in the import is the other case, and it used to stay: it is a body the replay began
|
|
152
|
+
# and no later feature finished, because the features that would have were the ones that fell
|
|
153
|
+
# back. Measured on `corpus-02` under cadmpeg 0.6.7, where the replay left `Body1` at
|
|
154
|
+
# 384.802 mm³ with 3 faces and `Body2` at 10240.000 mm³ with 6 against originals of 22133.318
|
|
155
|
+
# mm³ / 79 faces and 6654.503 / 14 — nothing either one stands for. Shipping them says the
|
|
156
|
+
# design rebuilt to something the original never had, and the verification reported them as
|
|
157
|
+
# `extra`.
|
|
158
|
+
#
|
|
159
|
+
# Condemning the feature's own bodies does not catch these: no failing feature names them. They
|
|
160
|
+
# are only knowable here, by what the import did and did not match.
|
|
161
|
+
duplicates = [b["name"] for b in imported if any(same_body(b, k) for k in kept)]
|
|
162
|
+
surplus = [k["name"] for k in kept if not any(same_body(b, k) for b in imported)]
|
|
163
|
+
if duplicates or surplus:
|
|
164
|
+
try:
|
|
165
|
+
engine.execute("solid.remove", {"bodies": duplicates + surplus})
|
|
166
|
+
except CommandRefused as exc:
|
|
167
|
+
names = ", ".join(duplicates + surplus)
|
|
168
|
+
warnings.append(f"bodies the import superseded not removed ({names}): {exc.message}")
|
|
169
|
+
# What is still standing, counted the way the import was: `body_names` lists a body per
|
|
170
|
+
# definition and `measure` one per placement, and on this package those are 462 against 494, so
|
|
171
|
+
# asking `body_names` here threw away the 32 placements it had just imported. The reading in
|
|
172
|
+
# hand answers it without measuring again — nothing has happened since but the removals above.
|
|
173
|
+
removed = set(duplicates + surplus)
|
|
174
|
+
present = {b["name"] for b in bodies if b["name"] not in removed} | {
|
|
175
|
+
b["name"] for b in kept if b["name"] not in removed
|
|
176
|
+
}
|
|
177
|
+
if surplus_left := [n for n in surplus if n in present]:
|
|
178
|
+
warnings.append(
|
|
179
|
+
f"{len(surplus_left)} body the replay began and no feature finished stayed in the "
|
|
180
|
+
f"design ({', '.join(surplus_left)}): the original has no counterpart for it"
|
|
181
|
+
)
|
|
182
|
+
result.imported_bodies = [b["name"] for b in imported if b["name"] in present]
|
|
183
|
+
return warnings
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def name_bodies(ctx: Context, result: ReplayResult) -> list[str]:
|
|
187
|
+
"""Give a body the name the designer gave it in Fusion, built or imported; returns warnings.
|
|
188
|
+
|
|
189
|
+
A body the replay built carries the engine's own numbering and an imported one carries the STEP
|
|
190
|
+
export's name — `Body1`, `cadmpeg_model (2)` — and neither is the design's. Where the file says
|
|
191
|
+
what the designer called the body, that is what the file the user opens should show.
|
|
192
|
+
|
|
193
|
+
Measured over the corpus's 90 bodies, **two** carry a name: `corpus-03`'s `corpus-03
|
|
194
|
+
(dont print)` and `corpus-03 (dont print)`. A real design of the user's,
|
|
195
|
+
`corpus-06.f3d`, carries a third — `RielArriba` — and it is the one that
|
|
196
|
+
made this cover built bodies too: that body is the output of a primitive the mapper now rebuilds
|
|
197
|
+
natively, so a step that only renamed imports would hand it back the engine's `Body1` and lose
|
|
198
|
+
the name it had just been given (spec section 85).
|
|
199
|
+
|
|
200
|
+
The other bodies are left exactly as they were named rather than renumbered: the file offers
|
|
201
|
+
nothing to call them, and an invented label would be this converter's word presented as the
|
|
202
|
+
design's (spec section 84).
|
|
203
|
+
|
|
204
|
+
Which body is which is not guessed. A body the replay built is in `ctx.body_names` by its own
|
|
205
|
+
Fusion id; an imported one goes through `pairing.declared_name`, the one rule for that question
|
|
206
|
+
and the same one `visibility` asks, which answers `None` wherever the import's block does not
|
|
207
|
+
line up with the file's bodies. A name the engine refuses, or one another body already has, is
|
|
208
|
+
reported and left alone.
|
|
209
|
+
"""
|
|
210
|
+
wanted = {b.id: b.name for b in ctx.design.bodies if b.name}
|
|
211
|
+
if not wanted:
|
|
212
|
+
return []
|
|
213
|
+
warnings: list[str] = []
|
|
214
|
+
taken = set(ctx.engine.body_names())
|
|
215
|
+
renamed: dict[str, str] = {}
|
|
216
|
+
for body_id, name in sorted(wanted.items()):
|
|
217
|
+
# The replay's own name for it first, but only while that body is still standing: a body the
|
|
218
|
+
# replay began and the import superseded leaves a stale entry in `body_names`, and taking it
|
|
219
|
+
# would skip the import's counterpart without ever asking the pairing. Measured on `corpus-03`, where exactly that lost `corpus-03 (dont print)` while the body beside it,
|
|
220
|
+
# which the replay never touched, was renamed.
|
|
221
|
+
built = ctx.body_names.get(body_id)
|
|
222
|
+
current = built if built in taken else declared_name(ctx.design, body_id, result.imported_bodies)
|
|
223
|
+
if current is None or current not in taken:
|
|
224
|
+
continue # nothing standing is this body, or the pairing cannot say which one is
|
|
225
|
+
if current == name:
|
|
226
|
+
continue # it already carries the name the file gives it: nothing to do and nothing to say
|
|
227
|
+
if name in taken:
|
|
228
|
+
# Another body holds it. Measured on `corpus-12.f3z`, this used to fire for
|
|
229
|
+
# `Lenovo`, `Caja1`, `Tapa` and `Fuente` where the body **already had** the name, because
|
|
230
|
+
# `name in taken` is true of a name a body holds itself — 16 warnings that read as
|
|
231
|
+
# failures and were not (spec section 93).
|
|
232
|
+
warnings.append(
|
|
233
|
+
f"the body Fusion calls {name!r} keeps the name {current!r}: another body holds {name!r}"
|
|
234
|
+
)
|
|
235
|
+
continue
|
|
236
|
+
try:
|
|
237
|
+
ctx.engine.execute("body.rename", {"body": current, "name": name})
|
|
238
|
+
except CommandRefused as exc:
|
|
239
|
+
warnings.append(f"the body Fusion calls {name!r} could not be renamed: {exc.message}")
|
|
240
|
+
continue
|
|
241
|
+
taken.discard(current)
|
|
242
|
+
taken.add(name)
|
|
243
|
+
renamed[current] = name
|
|
244
|
+
# Everything downstream reads these names: the rebuild check, the component reconciliation, the
|
|
245
|
+
# visibility replay and the report's native/imported count.
|
|
246
|
+
result.imported_bodies = [renamed.get(n, n) for n in result.imported_bodies]
|
|
247
|
+
for key, value in list(ctx.body_names.items()):
|
|
248
|
+
if value in renamed:
|
|
249
|
+
ctx.body_names[key] = renamed[value]
|
|
250
|
+
return warnings
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""Plane frames and 2D sketch geometry helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
from f3d2solidcraft.model import Frame, Sketch, SketchEntity, TrimmedSegment
|
|
8
|
+
|
|
9
|
+
Point2 = tuple[float, float]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class UnsupportedGeometry(ValueError):
|
|
13
|
+
"""A sketch entity kind this version cannot turn into points."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _cross(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]:
|
|
17
|
+
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def plane_spec(frame: Frame) -> dict:
|
|
21
|
+
"""SolidCraft sketch.create plane: x along Fusion's u axis, y = normal x u."""
|
|
22
|
+
y = _cross(frame.normal, frame.u_axis)
|
|
23
|
+
clean = [0.0 if abs(c) < 1e-12 else c for c in y]
|
|
24
|
+
return {"origin": list(frame.origin), "x_dir": list(frame.u_axis), "y_dir": clean}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _uv(p: dict) -> Point2:
|
|
28
|
+
return (float(p["u"]), float(p["v"]))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def entity_points(entity: SketchEntity, reversed: bool = False, segments: int = 48) -> list[Point2]:
|
|
32
|
+
g = entity.geometry
|
|
33
|
+
if entity.kind == "line":
|
|
34
|
+
pts = [_uv(g["start"]), _uv(g["end"])]
|
|
35
|
+
elif entity.kind == "circle":
|
|
36
|
+
cx, cy = _uv(g["center"])
|
|
37
|
+
r = float(g["radius"])
|
|
38
|
+
pts = [
|
|
39
|
+
(cx + r * math.cos(2 * math.pi * i / segments), cy + r * math.sin(2 * math.pi * i / segments))
|
|
40
|
+
for i in range(segments)
|
|
41
|
+
]
|
|
42
|
+
elif entity.kind == "arc":
|
|
43
|
+
cx, cy = _uv(g["center"])
|
|
44
|
+
r = float(g["radius"])
|
|
45
|
+
a0, a1 = float(g["start_angle"]), float(g["end_angle"])
|
|
46
|
+
if a1 <= a0:
|
|
47
|
+
a1 += 2 * math.pi
|
|
48
|
+
pts = [
|
|
49
|
+
(
|
|
50
|
+
cx + r * math.cos(a0 + (a1 - a0) * i / segments),
|
|
51
|
+
cy + r * math.sin(a0 + (a1 - a0) * i / segments),
|
|
52
|
+
)
|
|
53
|
+
for i in range(segments + 1)
|
|
54
|
+
]
|
|
55
|
+
elif entity.kind == "nurbs":
|
|
56
|
+
pts = nurbs_points(*nurbs_curve(g), segments=segments)
|
|
57
|
+
else:
|
|
58
|
+
raise UnsupportedGeometry(f"sketch entity kind {entity.kind}")
|
|
59
|
+
return pts[::-1] if reversed else pts
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def segment_points(
|
|
63
|
+
entity: SketchEntity, start: float, end: float, reversed: bool = False, segments: int = 48
|
|
64
|
+
) -> list[Point2]:
|
|
65
|
+
"""The part of one entity a trimmed boundary names, as points.
|
|
66
|
+
|
|
67
|
+
The parameter is the entity's own, and what it measures depends on the kind — so only the kinds
|
|
68
|
+
the corpus settles are translated and the rest are refused. Measured on `test weird box`'s one
|
|
69
|
+
trimmed region (spec section 112):
|
|
70
|
+
|
|
71
|
+
- **line**: 0 to 1 along start -> end. The file's start of `0.009148867715291616` on a 100 mm
|
|
72
|
+
edge is 0.9148867715 mm, and the chord the circle cuts off that edge is 0.914886771 mm. (Its
|
|
73
|
+
end is `0.9999999999999986`, which is the file's way of writing the far end.)
|
|
74
|
+
- **circle**: the angle in radians from the +u axis. The file's
|
|
75
|
+
`[1.5524975701750943, 1.5890950834146989]` is pi/2 +/- 0.0182987, and the half-angle of that
|
|
76
|
+
same chord is asin(0.457443/25) = 0.01829873.
|
|
77
|
+
|
|
78
|
+
- **arc**: the same quantity as a circle, the angle in radians from the +u axis — measured on
|
|
79
|
+
cadmpeg 0.6.11, which declares trimmed boundaries over arcs where 0.6.8 declared none
|
|
80
|
+
(spec section 137). Two independent readings say so. Where a boundary uses the whole arc, its
|
|
81
|
+
`start` and `end` are the arc's own `start_angle` and `end_angle` **to the last digit**: the
|
|
82
|
+
corpus-05's four arcs give `[1.5707963267948966, 4.71238898038469]` against an arc whose
|
|
83
|
+
angles are exactly those. Where it trims one, the values fall strictly inside that span:
|
|
84
|
+
`corpus-01`'s `[-2.3317388986423015, -0.809853754947492]` inside `[-2.3412531376361687,
|
|
85
|
+
-0.8003395159536246]`.
|
|
86
|
+
|
|
87
|
+
And the check that decides it rather than suggesting it: read as absolute angles, all four of
|
|
88
|
+
the corpus's arc boundaries **close to 0.000000 mm** between consecutive endpoints. Read as a
|
|
89
|
+
normalized 0..1 of the arc's own sweep they leave gaps of 2.34 to 21.25 mm, and read as an
|
|
90
|
+
angle measured from `start_angle`, 2.12 to 19.89 mm. The right reading is not close to the
|
|
91
|
+
others; it is exact.
|
|
92
|
+
|
|
93
|
+
A nurbs has a parameter too and the corpus holds no trimmed segment of one, so which quantity it
|
|
94
|
+
is there is not measured — and a wrong guess would not fail loudly, it would quietly bound a
|
|
95
|
+
different region. Refused.
|
|
96
|
+
"""
|
|
97
|
+
# `start` to `end` in the order the file gives them, with no sorting: the direction a boundary
|
|
98
|
+
# runs is part of what it says, and `reversed` is the file's own word for flipping it. Sorting
|
|
99
|
+
# the pair would quietly turn a segment that runs backwards into one that runs forwards.
|
|
100
|
+
g = entity.geometry
|
|
101
|
+
if entity.kind == "line":
|
|
102
|
+
(x0, y0), (x1, y1) = _uv(g["start"]), _uv(g["end"])
|
|
103
|
+
pts = [(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t) for t in (start, end)]
|
|
104
|
+
elif entity.kind in ("circle", "arc"):
|
|
105
|
+
# One branch for both, because the parameter is the same quantity: the angle in radians
|
|
106
|
+
# from the +u axis. An arc's `start_angle` and `end_angle` are not read here on purpose —
|
|
107
|
+
# the boundary's own range is what it uses, and where it uses the whole arc that range IS
|
|
108
|
+
# those two angles.
|
|
109
|
+
cx, cy = _uv(g["center"])
|
|
110
|
+
r = float(g["radius"])
|
|
111
|
+
pts = [
|
|
112
|
+
(
|
|
113
|
+
cx + r * math.cos(start + (end - start) * i / segments),
|
|
114
|
+
cy + r * math.sin(start + (end - start) * i / segments),
|
|
115
|
+
)
|
|
116
|
+
for i in range(segments + 1)
|
|
117
|
+
]
|
|
118
|
+
else:
|
|
119
|
+
raise UnsupportedGeometry(
|
|
120
|
+
f"a parameter range on a sketch entity of kind {entity.kind}: what its parameter "
|
|
121
|
+
"measures is not settled by anything in the corpus"
|
|
122
|
+
)
|
|
123
|
+
return pts[::-1] if reversed else pts
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def boundary_polygon(sketch: Sketch, boundary: tuple[TrimmedSegment, ...]) -> list[Point2]:
|
|
127
|
+
"""A trimmed region's boundary as one closed polygon, in the order the file lists it."""
|
|
128
|
+
by_id = {e.id: e for e in sketch.entities}
|
|
129
|
+
poly: list[Point2] = []
|
|
130
|
+
for segment in boundary:
|
|
131
|
+
entity = by_id.get(segment.entity)
|
|
132
|
+
if entity is None:
|
|
133
|
+
raise UnsupportedGeometry("a trimmed boundary names an entity that is not in the sketch")
|
|
134
|
+
poly.extend(segment_points(entity, segment.start, segment.end, segment.reversed))
|
|
135
|
+
return poly
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def profile_polygon(sketch: Sketch, index: int) -> list[Point2]:
|
|
139
|
+
by_id = {e.id: e for e in sketch.entities}
|
|
140
|
+
poly: list[Point2] = []
|
|
141
|
+
for edge in sketch.profiles[index]:
|
|
142
|
+
poly.extend(entity_points(by_id[edge.entity], edge.reversed))
|
|
143
|
+
return poly
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def point_in_polygon(pt: Point2, poly: list[Point2]) -> bool:
|
|
147
|
+
x, y = pt
|
|
148
|
+
inside = False
|
|
149
|
+
j = len(poly) - 1
|
|
150
|
+
for i in range(len(poly)):
|
|
151
|
+
xi, yi = poly[i]
|
|
152
|
+
xj, yj = poly[j]
|
|
153
|
+
if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
|
|
154
|
+
inside = not inside
|
|
155
|
+
j = i
|
|
156
|
+
return inside
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _pole(point: dict) -> dict:
|
|
160
|
+
"""The u/v of one pole, whichever of the two shapes cadmpeg wrote it in."""
|
|
161
|
+
inner = point.get("point")
|
|
162
|
+
return inner if isinstance(inner, dict) else point
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def nurbs_curve(geometry: dict) -> tuple[int, list[float], list[Point2], list[float]]:
|
|
166
|
+
"""degree, knots, poles and weights of a cadmpeg nurbs curve, in sketch u/v."""
|
|
167
|
+
curve = geometry.get("curve") or {}
|
|
168
|
+
points = (curve.get("poles") or {}).get("points") or []
|
|
169
|
+
try:
|
|
170
|
+
degree = int(curve["degree"])
|
|
171
|
+
knots = [float(k) for k in curve["knots"]]
|
|
172
|
+
# A rational curve's poles come as {point: {u, v}, weight}; a polynomial one's as bare
|
|
173
|
+
# {u, v} with no weight around them (measured on `mango para lima`'s two degree 3 curves).
|
|
174
|
+
poles = [(float(_pole(p)["u"]), float(_pole(p)["v"])) for p in points]
|
|
175
|
+
weights = [float(p.get("weight", 1.0)) for p in points]
|
|
176
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
177
|
+
raise UnsupportedGeometry(f"a nurbs curve this reader cannot read: {exc}") from None
|
|
178
|
+
if degree < 1 or not poles:
|
|
179
|
+
raise UnsupportedGeometry(f"a nurbs curve of degree {degree} with {len(poles)} poles")
|
|
180
|
+
return degree, knots, poles, weights
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _insert_knot(
|
|
184
|
+
degree: int, knots: list[float], poles: list[Point2], u: float
|
|
185
|
+
) -> tuple[list[float], list[Point2]]:
|
|
186
|
+
"""Böhm's knot insertion: the same curve, with `u` once more in its knot vector.
|
|
187
|
+
|
|
188
|
+
Exact, and that is the whole point: inserting a knot rewrites the poles so the curve does not
|
|
189
|
+
move at all. Only the poles that carry the span around `u` change, each to a point on the
|
|
190
|
+
segment between two of the old ones.
|
|
191
|
+
"""
|
|
192
|
+
# The last span whose start is at or before u: with u already present, that is its last
|
|
193
|
+
# occurrence, which is what keeps the denominators below away from zero.
|
|
194
|
+
k = max(i for i in range(degree, len(knots) - degree - 1) if knots[i] <= u)
|
|
195
|
+
out: list[Point2] = []
|
|
196
|
+
for i in range(len(poles) + 1):
|
|
197
|
+
if i <= k - degree:
|
|
198
|
+
out.append(poles[i])
|
|
199
|
+
elif i <= k:
|
|
200
|
+
lo, hi = knots[i], knots[i + degree]
|
|
201
|
+
a = (u - lo) / (hi - lo)
|
|
202
|
+
before, now = poles[i - 1], poles[i]
|
|
203
|
+
out.append(((1 - a) * before[0] + a * now[0], (1 - a) * before[1] + a * now[1]))
|
|
204
|
+
else:
|
|
205
|
+
out.append(poles[i - 1])
|
|
206
|
+
return sorted([*knots, u]), out
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def bezier_spans(degree: int, knots: list[float], poles: list[Point2]) -> list[list[Point2]]:
|
|
210
|
+
"""The same curve as a chain of Bézier segments of the same degree, exactly.
|
|
211
|
+
|
|
212
|
+
A clamped B-spline becomes a chain of Bézier curves by raising every interior knot to
|
|
213
|
+
multiplicity `degree`: the poles then fall into groups of `degree + 1` that share an end, and
|
|
214
|
+
each group is a Bézier of that degree over its own span. Nothing is approximated — knot
|
|
215
|
+
insertion is an exact rewrite of the poles (`_insert_knot`), so the chain *is* the curve.
|
|
216
|
+
|
|
217
|
+
What it buys: SolidCraft's control point splines are clamped and uniform, so a curve whose
|
|
218
|
+
interior knots are unevenly spaced cannot be handed over as it stands. Each Bézier segment has
|
|
219
|
+
no interior knots at all, which makes it both — so every segment is drawable as it is. Measured
|
|
220
|
+
on the corpus's four such curves (spec section 76), all degree 3 with every interior knot
|
|
221
|
+
doubled: 5 to 8 segments each.
|
|
222
|
+
|
|
223
|
+
The caller must have checked that the curve is clamped and non-rational; this only needs the
|
|
224
|
+
knot vector to be the right length for the poles.
|
|
225
|
+
"""
|
|
226
|
+
knots, poles = list(knots), list(poles)
|
|
227
|
+
if len(knots) != len(poles) + degree + 1:
|
|
228
|
+
raise UnsupportedGeometry(
|
|
229
|
+
f"a degree {degree} spline with {len(poles)} poles needs {len(poles) + degree + 1} knots, "
|
|
230
|
+
f"got {len(knots)}"
|
|
231
|
+
)
|
|
232
|
+
while True:
|
|
233
|
+
interior = knots[degree + 1 : len(knots) - degree - 1]
|
|
234
|
+
short = next((u for u in sorted(set(interior)) if interior.count(u) < degree), None)
|
|
235
|
+
if short is None:
|
|
236
|
+
break
|
|
237
|
+
knots, poles = _insert_knot(degree, knots, poles, short)
|
|
238
|
+
return [poles[j : j + degree + 1] for j in range(0, len(poles) - 1, degree)]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _span(degree: int, knots: list[float], t: float) -> int:
|
|
242
|
+
"""The knot span t falls in, clamped so the last span owns the end of the curve."""
|
|
243
|
+
last = len(knots) - degree - 2
|
|
244
|
+
for index in range(degree, last + 1):
|
|
245
|
+
if t < knots[index + 1]:
|
|
246
|
+
return index
|
|
247
|
+
return last
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def nurbs_points(
|
|
251
|
+
degree: int, knots: list[float], poles: list[Point2], weights: list[float], segments: int = 48
|
|
252
|
+
) -> list[Point2]:
|
|
253
|
+
"""A NURBS curve sampled into `segments` straight pieces, by de Boor's algorithm.
|
|
254
|
+
|
|
255
|
+
Rational all through — the weights are carried in homogeneous coordinates and divided out at the
|
|
256
|
+
end — so a curve with weights other than 1 samples correctly even where it cannot be rebuilt
|
|
257
|
+
exactly. Sampling is uniform in the parameter, not in arc length: it is for area and
|
|
258
|
+
point-in-profile work, where what matters is that the polygon follows the curve closely.
|
|
259
|
+
"""
|
|
260
|
+
if len(poles) != len(weights) or len(knots) != len(poles) + degree + 1:
|
|
261
|
+
raise UnsupportedGeometry(
|
|
262
|
+
f"a degree {degree} spline with {len(poles)} poles needs {len(poles) + degree + 1} knots, "
|
|
263
|
+
f"got {len(knots)}"
|
|
264
|
+
)
|
|
265
|
+
start, end = knots[degree], knots[len(knots) - degree - 1]
|
|
266
|
+
out: list[Point2] = []
|
|
267
|
+
for step in range(segments + 1):
|
|
268
|
+
t = start + (end - start) * step / segments
|
|
269
|
+
span = _span(degree, knots, t)
|
|
270
|
+
# de Boor on (x·w, y·w, w), so the division at the end is the rational part
|
|
271
|
+
working = [
|
|
272
|
+
(poles[span - degree + i][0] * w, poles[span - degree + i][1] * w, w)
|
|
273
|
+
for i, w in enumerate(weights[span - degree : span + 1])
|
|
274
|
+
]
|
|
275
|
+
for level in range(1, degree + 1):
|
|
276
|
+
for i in range(degree, level - 1, -1):
|
|
277
|
+
lo = knots[span - degree + i]
|
|
278
|
+
hi = knots[span + i - level + 1]
|
|
279
|
+
alpha = 0.0 if hi == lo else (t - lo) / (hi - lo)
|
|
280
|
+
before, now = working[i - 1], working[i]
|
|
281
|
+
working[i] = tuple(b * (1.0 - alpha) + n * alpha for b, n in zip(before, now))
|
|
282
|
+
x, y, w = working[degree]
|
|
283
|
+
out.append((x / w, y / w) if w else (x, y))
|
|
284
|
+
return out
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def polygon_area(poly: list[Point2]) -> float:
|
|
288
|
+
"""Unsigned area of a closed polygon, whichever way it winds."""
|
|
289
|
+
total = 0.0
|
|
290
|
+
for i, (x1, y1) in enumerate(poly):
|
|
291
|
+
x2, y2 = poly[(i + 1) % len(poly)]
|
|
292
|
+
total += x1 * y2 - x2 * y1
|
|
293
|
+
return abs(total) / 2.0
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _encloses(outer: list[Point2], inner: list[Point2]) -> bool:
|
|
297
|
+
"""Whether every point of inner lies in outer.
|
|
298
|
+
|
|
299
|
+
Strictly every one, because a loop that merely overlaps another is not inside it and its area is
|
|
300
|
+
not a hole in it. Read as a majority, `corpus-04`'s first sketch had one loop's overlapping
|
|
301
|
+
neighbours taken off it as holes and the profile came out at -32.166 mm², a negative area.
|
|
302
|
+
"""
|
|
303
|
+
return all(point_in_polygon(p, outer) for p in inner)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def direct_children(loops: list[list[Point2]], outer: int) -> list[int]:
|
|
307
|
+
"""The loops directly inside `loops[outer]`: the ones whose area is not part of its profile.
|
|
308
|
+
|
|
309
|
+
A loop two levels down is material again — the island in the middle of a hole belongs to the
|
|
310
|
+
plate — so only direct children count.
|
|
311
|
+
|
|
312
|
+
Shared by the two things that have to agree about one profile: the area it covers
|
|
313
|
+
(`profile_area`) and a point inside it (`interior_point`'s `excluded`). They disagreed, and
|
|
314
|
+
`corpus-03`'s `Extrude 8` is what that cost — spec section 78.
|
|
315
|
+
"""
|
|
316
|
+
return [
|
|
317
|
+
j
|
|
318
|
+
for j in range(len(loops))
|
|
319
|
+
if j != outer
|
|
320
|
+
and _encloses(loops[outer], loops[j])
|
|
321
|
+
and not any(
|
|
322
|
+
k not in (outer, j) and _encloses(loops[outer], loops[k]) and _encloses(loops[k], loops[j])
|
|
323
|
+
for k in range(len(loops))
|
|
324
|
+
)
|
|
325
|
+
]
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def profile_area(loops: list[list[Point2]], outer: int, holes: tuple[int, ...]) -> float:
|
|
329
|
+
"""The area the profile at `outer` covers: its loop, less the loops directly inside it.
|
|
330
|
+
|
|
331
|
+
`holes` are the ones the file named; they are direct children already, and naming them cannot
|
|
332
|
+
take the same area off twice.
|
|
333
|
+
"""
|
|
334
|
+
taken = set(direct_children(loops, outer)) | {h for h in holes if h != outer}
|
|
335
|
+
return polygon_area(loops[outer]) - sum(polygon_area(loops[j]) for j in taken)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _inside_the_edges(target: list[Point2]) -> list[Point2]:
|
|
339
|
+
"""Points a little way in from each edge of `target`, for a band a grid steps over.
|
|
340
|
+
|
|
341
|
+
A grid finds a point in the middle of an area, and that is the right answer whenever there is a
|
|
342
|
+
middle. What it cannot find is a thin band — a profile that is one loop less the loop nested
|
|
343
|
+
just inside it. Measured on `corpus-03`'s `Extrude 8`: a 463 mm² ring around a 12165 mm²
|
|
344
|
+
island, barely over a millimetre wide, where the 25-step grid over a 115 mm extent lands no
|
|
345
|
+
point at all (spec section 78).
|
|
346
|
+
|
|
347
|
+
These candidates come off the loop's own edges, so a band has them wherever it is: the midpoint
|
|
348
|
+
of each edge, stepped in along its normal by a ladder of distances. Both signs of the normal are
|
|
349
|
+
offered rather than working out the winding — the caller tests every candidate against the
|
|
350
|
+
target anyway, so the one that points outwards is simply rejected.
|
|
351
|
+
"""
|
|
352
|
+
xs = [p[0] for p in target]
|
|
353
|
+
ys = [p[1] for p in target]
|
|
354
|
+
diagonal = math.dist((min(xs), min(ys)), (max(xs), max(ys)))
|
|
355
|
+
out: list[Point2] = []
|
|
356
|
+
for a, b in zip(target, [*target[1:], target[0]]):
|
|
357
|
+
length = math.dist(a, b)
|
|
358
|
+
if not length:
|
|
359
|
+
continue
|
|
360
|
+
nx, ny = -(b[1] - a[1]) / length, (b[0] - a[0]) / length
|
|
361
|
+
mx, my = (a[0] + b[0]) / 2, (a[1] + b[1]) / 2
|
|
362
|
+
for scale in (1e-1, 1e-2, 1e-3, 1e-4):
|
|
363
|
+
step = diagonal * scale
|
|
364
|
+
out.append((mx + nx * step, my + ny * step))
|
|
365
|
+
out.append((mx - nx * step, my - ny * step))
|
|
366
|
+
return out
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def interior_point(
|
|
370
|
+
target: list[Point2], others: list[list[Point2]], grid: int = 25, excluded: list[list[Point2]] = ()
|
|
371
|
+
) -> Point2 | None:
|
|
372
|
+
"""A point inside target and outside every excluded loop, in as few others as possible, nearest the centre.
|
|
373
|
+
|
|
374
|
+
Candidates are a grid over the loop's box plus points just inside its edges
|
|
375
|
+
(`_inside_the_edges`), which is what makes a thin band reachable. The scoring is unchanged, so a
|
|
376
|
+
grid point still wins any tie: an edge candidate only comes out on top when it lies in strictly
|
|
377
|
+
fewer of the other loops, which is precisely the band case.
|
|
378
|
+
"""
|
|
379
|
+
xs = [p[0] for p in target]
|
|
380
|
+
ys = [p[1] for p in target]
|
|
381
|
+
cx, cy = sum(xs) / len(xs), sum(ys) / len(ys)
|
|
382
|
+
candidates = [
|
|
383
|
+
(
|
|
384
|
+
min(xs) + (max(xs) - min(xs)) * i / grid,
|
|
385
|
+
min(ys) + (max(ys) - min(ys)) * j / grid,
|
|
386
|
+
)
|
|
387
|
+
for i in range(1, grid)
|
|
388
|
+
for j in range(1, grid)
|
|
389
|
+
]
|
|
390
|
+
best: tuple[int, float, Point2] | None = None
|
|
391
|
+
for pt in [*candidates, *_inside_the_edges(target)]:
|
|
392
|
+
if not point_in_polygon(pt, target) or any(point_in_polygon(pt, e) for e in excluded):
|
|
393
|
+
continue
|
|
394
|
+
score = (sum(point_in_polygon(pt, o) for o in others), math.dist(pt, (cx, cy)), pt)
|
|
395
|
+
if best is None or score[:2] < best[:2]:
|
|
396
|
+
best = score
|
|
397
|
+
return best[2] if best else None
|