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.
Files changed (74) hide show
  1. f3d2solidcraft/__init__.py +3 -0
  2. f3d2solidcraft/__main__.py +3 -0
  3. f3d2solidcraft/_vendor/__init__.py +0 -0
  4. f3d2solidcraft/_vendor/ezf3d/LICENSE +21 -0
  5. f3d2solidcraft/_vendor/ezf3d/__init__.py +1 -0
  6. f3d2solidcraft/_vendor/ezf3d/container/__init__.py +1 -0
  7. f3d2solidcraft/_vendor/ezf3d/container/archive.py +204 -0
  8. f3d2solidcraft/_vendor/ezf3d/model/__init__.py +1 -0
  9. f3d2solidcraft/_vendor/ezf3d/model/parameters.py +365 -0
  10. f3d2solidcraft/_vendor/ezf3d/model/sketch.py +645 -0
  11. f3d2solidcraft/_vendor/ezf3d/model/timeline.py +493 -0
  12. f3d2solidcraft/_vendor/ezf3d/streams/__init__.py +1 -0
  13. f3d2solidcraft/_vendor/ezf3d/streams/manifest.py +262 -0
  14. f3d2solidcraft/_vendor/ezf3d/streams/primitives.py +191 -0
  15. f3d2solidcraft/_vendor/ezf3d/streams/segment.py +521 -0
  16. f3d2solidcraft/cli.py +574 -0
  17. f3d2solidcraft/engine.py +458 -0
  18. f3d2solidcraft/fallback.py +250 -0
  19. f3d2solidcraft/geometry.py +397 -0
  20. f3d2solidcraft/mappers/__init__.py +141 -0
  21. f3d2solidcraft/mappers/bodies.py +99 -0
  22. f3d2solidcraft/mappers/combine.py +73 -0
  23. f3d2solidcraft/mappers/components.py +542 -0
  24. f3d2solidcraft/mappers/edges.py +449 -0
  25. f3d2solidcraft/mappers/extrude.py +1501 -0
  26. f3d2solidcraft/mappers/faces.py +50 -0
  27. f3d2solidcraft/mappers/loft.py +149 -0
  28. f3d2solidcraft/mappers/outputs.py +73 -0
  29. f3d2solidcraft/mappers/params.py +134 -0
  30. f3d2solidcraft/mappers/pattern.py +68 -0
  31. f3d2solidcraft/mappers/planes.py +222 -0
  32. f3d2solidcraft/mappers/primitives.py +144 -0
  33. f3d2solidcraft/mappers/records.py +51 -0
  34. f3d2solidcraft/mappers/revolve.py +134 -0
  35. f3d2solidcraft/mappers/sheet.py +95 -0
  36. f3d2solidcraft/mappers/shell.py +180 -0
  37. f3d2solidcraft/mappers/sketch.py +455 -0
  38. f3d2solidcraft/mcp.py +218 -0
  39. f3d2solidcraft/model.py +503 -0
  40. f3d2solidcraft/oracle.py +905 -0
  41. f3d2solidcraft/pairing.py +105 -0
  42. f3d2solidcraft/reader/__init__.py +77 -0
  43. f3d2solidcraft/reader/cadir.py +832 -0
  44. f3d2solidcraft/reader/fusion.py +218 -0
  45. f3d2solidcraft/reader/locale.py +115 -0
  46. f3d2solidcraft/replay.py +322 -0
  47. f3d2solidcraft/report.py +107 -0
  48. f3d2solidcraft/tools.py +219 -0
  49. f3d2solidcraft/verify.py +186 -0
  50. f3d2solidcraft/visibility.py +95 -0
  51. f3d2solidcraft-0.3.0.dist-info/METADATA +189 -0
  52. f3d2solidcraft-0.3.0.dist-info/RECORD +74 -0
  53. f3d2solidcraft-0.3.0.dist-info/WHEEL +4 -0
  54. f3d2solidcraft-0.3.0.dist-info/entry_points.txt +5 -0
  55. f3d2solidcraft-0.3.0.dist-info/licenses/LICENSE +21 -0
  56. f3d2solidcraft-0.3.0.dist-info/licenses/src/f3d2solidcraft/_vendor/ezf3d/LICENSE +21 -0
  57. f3d2solidcraft_app/__init__.py +5 -0
  58. f3d2solidcraft_app/__main__.py +40 -0
  59. f3d2solidcraft_app/engines.py +158 -0
  60. f3d2solidcraft_app/events.py +35 -0
  61. f3d2solidcraft_app/opener.py +22 -0
  62. f3d2solidcraft_app/outcome.py +54 -0
  63. f3d2solidcraft_app/resources/icon-128.png +0 -0
  64. f3d2solidcraft_app/resources/icon-16.png +0 -0
  65. f3d2solidcraft_app/resources/icon-256.png +0 -0
  66. f3d2solidcraft_app/resources/icon-32.png +0 -0
  67. f3d2solidcraft_app/resources/icon-512.png +0 -0
  68. f3d2solidcraft_app/resources/icon-64.png +0 -0
  69. f3d2solidcraft_app/resources/icon.icns +0 -0
  70. f3d2solidcraft_app/resources/icon.ico +0 -0
  71. f3d2solidcraft_app/resources/icon.svg +26 -0
  72. f3d2solidcraft_app/runner.py +91 -0
  73. f3d2solidcraft_app/texts.py +98 -0
  74. f3d2solidcraft_app/window.py +677 -0
@@ -0,0 +1,645 @@
1
+ """Sketches: the points and curves a design draws before it extrudes them.
2
+
3
+ Phase 3 could say that timeline entry #4 is an extrude that cuts 50 mm on one
4
+ side. What it could not say is *what shape* -- the profile. That was recorded
5
+ as unreachable because an extrude's ``inputs`` list never names its sketch, and
6
+ it does not: **0 of 88** extrudes across the samples reach one that way.
7
+
8
+ The reference simply runs the other way. Each entity names its sketch::
9
+
10
+ str8 EntityGenesis
11
+ str8 IntrinsicMetaTypeuint64
12
+ str8 pt_tag | crv_primary_id what this record is
13
+ str8 IntrinsicMetaTypeuint64
14
+ ...
15
+ f64 x, f64 y, f64 z at +27 past the anchor, for a point
16
+ ...
17
+ 0x01 u64 owner, 0x00 0x00 the sketch's geometry container
18
+ str8 revision
19
+
20
+ Unlike a feature's operation code, these records **say what they are**: the
21
+ ``str8`` key is on the wire. There is no enum to guess.
22
+
23
+ **The owner reference is read, not inferred.** It sits immediately before a
24
+ record's trailing revision string, and the sketch feature follows the container
25
+ it names by three ids in almost every case and four in the rest. Over the four
26
+ samples it resolves **3,217 of 3,221** entities with no record reaching two
27
+ sketches, and it reaches *every* sketch each design has -- 8 of 8, 82 of 82 and
28
+ 39 of 39. Positional attribution was tried first, the way
29
+ :func:`~ezf3d.model.timeline.attribute` does it for parameters, and topped out
30
+ at 95%; this is better and it is a reading rather than a rule.
31
+
32
+ A record may nest a second ``EntityGenesis`` block -- a spline carrying its own
33
+ dimension does -- so every revision-shaped string is tried and the first whose
34
+ preceding reference lands on a sketch wins. Anchoring on the last one instead
35
+ loses exactly those splines, which is the same trap the extrude settings
36
+ sprang in 3.6b.
37
+
38
+ **Coordinates are two-dimensional**, in the sketch's own frame: ``z`` is zero
39
+ for 1,876 of 1,912 points and never larger than 1.8e-15 in the rest, which is
40
+ rounding rather than depth. The frame itself is *not* in the design stream --
41
+ see :doc:`unknowns </format/unknowns>`.
42
+
43
+ What checks the reading is the design's own parameters. A sketch's ``Linear
44
+ Dimension-N`` must be the distance between two of that sketch's points, and it
45
+ is for **155 of 179** of them to within 1e-7 cm. The parameter record and the
46
+ point records are different objects reached by different scans, so their
47
+ agreement is not self-consistency. The 24 that miss are dimensions measuring a
48
+ point against a *line* rather than against another point, which this module
49
+ does not yet resolve.
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import math
55
+ import struct
56
+ from bisect import bisect_left
57
+ from collections import Counter
58
+ from collections.abc import Iterable
59
+ from dataclasses import dataclass, field
60
+ from itertools import combinations
61
+
62
+ from f3d2solidcraft._vendor.ezf3d.model.parameters import Parameter, read_parameters
63
+ from f3d2solidcraft._vendor.ezf3d.model.timeline import Timeline, read_timeline
64
+ from f3d2solidcraft._vendor.ezf3d.streams.primitives import scan_strings
65
+ from f3d2solidcraft._vendor.ezf3d.streams.segment import BulkObject, Segment
66
+
67
+
68
+ def _key(name: str) -> bytes:
69
+ """A ``str8`` on the wire: a ``u32`` byte count and the ASCII."""
70
+ return struct.pack("<I", len(name)) + name.encode("ascii")
71
+
72
+
73
+ #: The ``str8`` that says a record is a sketch point.
74
+ POINT_KEY = "pt_tag"
75
+
76
+ #: And a sketch curve. ``crv_secondary_id`` follows it in the same record.
77
+ CURVE_KEY = "crv_primary_id"
78
+
79
+ #: The type word each key is followed by; the coordinates are measured from
80
+ #: the end of the one that follows the key, not from the record's start,
81
+ #: because the three record shapes in the samples begin differently.
82
+ _ANCHOR = "IntrinsicMetaTypeuint64"
83
+
84
+ #: Bytes between that anchor and the ``f64`` triple. One offset for all three
85
+ #: point shapes -- ``(169, 221, 225)`` bytes over four subsystem revisions --
86
+ #: which is what says it is a field rather than an alignment.
87
+ COORDINATE_GAP = 27
88
+
89
+ #: A reference: ``0x01``, a ``u64`` object id, two spare bytes.
90
+ _REFERENCE = 0x01
91
+ _STRIDE = 11
92
+
93
+ #: Most ids between the container an entity names and the sketch feature
94
+ #: itself. Three for all but 22 of the entities resolved across the samples,
95
+ #: four for those; the margin is deliberate slack, and a wider one would start
96
+ #: matching the *next* sketch, so it is bounded rather than open.
97
+ OWNER_REACH = 8
98
+
99
+ #: Record sizes considered. A point is 169 to 225 bytes and a curve 295 to
100
+ #: 815; the bounds keep the scan off the megabyte-scale objects without
101
+ #: deciding anything about what is inside them.
102
+ _MIN_RECORD = 40
103
+ _MAX_RECORD = 2000
104
+
105
+ #: How close a dimension has to come to a point-pair distance to count as
106
+ #: re-derived. Coordinates are stored to full double precision, so this is
107
+ #: far tighter than any modelling tolerance.
108
+ DIMENSION_TOLERANCE = 1e-7
109
+
110
+ #: The second key in a curve record; the endpoint block is measured from the
111
+ #: type word that follows *it*. Both keys are also the curve's *identity*: the
112
+ #: ``u64`` after each one's type word is what an ASM ``sketch_attrib_def``
113
+ #: names the curve by, which is how body topology reaches back to the sketch
114
+ #: that drew it.
115
+ _CURVE_TAIL = "crv_secondary_id"
116
+
117
+ #: Bytes between that type word and the block of point references. 104 in all
118
+ #: four documents, where the block's absolute offset is 266 in three of them
119
+ #: and 214 in Focuser Mk1 -- which is what makes it a field and not an offset
120
+ #: that happens to work.
121
+ ENDPOINT_GAP = 104
122
+
123
+ #: Offsets past the same anchor for the two numbers a curve carries. The
124
+ #: radius is checkable: for an arc it must equal the distance from the centre
125
+ #: it names to the endpoint it names, and it does for all 282 to 2.2e-07 cm.
126
+ RADIUS_AT = 80
127
+ SPAN_AT = ENDPOINT_GAP - 8
128
+
129
+ #: How many points a curve references, and therefore what it is. Not a size
130
+ #: rule: 3.6b established that record size classifies nothing across
131
+ #: documents, and these sizes do move with the revision. The count does not.
132
+ CURVE_KINDS = {1: "Circle", 2: "Line", 3: "Arc"}
133
+
134
+ #: A circle's span is a full turn. Pinned because it is what separates a
135
+ #: one-reference circle from a misread record.
136
+ FULL_TURN = 2.0 * math.pi
137
+
138
+ #: Agreement asked of a curve's stored radius and span against the geometry
139
+ #: its own points describe -- centimetres and radians.
140
+ CURVE_TOLERANCE = 1e-6
141
+
142
+ _POINT_MARK = _key(POINT_KEY)
143
+ _CURVE_MARK = _key(CURVE_KEY)
144
+ _CURVE_TAIL_MARK = _key(_CURVE_TAIL)
145
+ _ANCHOR_MARK = _key(_ANCHOR)
146
+
147
+
148
+ @dataclass(frozen=True, slots=True)
149
+ class Point:
150
+ """A sketch point, in the sketch's own two-dimensional frame."""
151
+
152
+ oid: int
153
+ #: Centimetres, Fusion's internal unit.
154
+ x: float
155
+ y: float
156
+
157
+ def distance(self, other: Point) -> float:
158
+ return math.dist((self.x, self.y), (other.x, other.y))
159
+
160
+
161
+ @dataclass(frozen=True, slots=True)
162
+ class Curve:
163
+ """A sketch curve: what kind it is, and which of its sketch's points it uses.
164
+
165
+ The kind is **how many points the curve references**, not how large its
166
+ record is. Size does separate the kinds inside one document -- 347, 356
167
+ and 367 bytes in SUCKER -- but 3.6b established that record size classifies
168
+ nothing across documents, and these sizes move with the revision. The
169
+ reference count does not: 1, 2 or 3 in every document, and every reference
170
+ is a point of the curve's own sketch, for all 1,334 curves in the samples.
171
+ """
172
+
173
+ oid: int
174
+ #: Bytes in the record, carried for the record it is rather than used.
175
+ size: int
176
+ #: ``Circle``, ``Line`` or ``Arc``; ``""`` when the block did not read.
177
+ kind: str = ""
178
+ #: The points it names. A line's two endpoints; an arc's **centre first**,
179
+ #: then its two endpoints; a circle's centre alone.
180
+ points: tuple[int, ...] = ()
181
+ #: Centimetres. Zero for a line, which has none.
182
+ radius: float = 0.0
183
+ #: The parameter range the record stores: a full turn for a circle, the
184
+ #: angle its endpoints subtend for an arc, and +/-1 for a line -- the sign
185
+ #: is carried rather than interpreted, as the extrude's third code is.
186
+ span: float = 0.0
187
+ #: ``(crv_primary_id, crv_secondary_id)`` -- the curve's own identity, and
188
+ #: the key an ASM ``sketch_attrib_def`` names it by. See
189
+ #: :mod:`ezf3d.model.placement`.
190
+ key: tuple[int, int] = (0, 0)
191
+
192
+ @property
193
+ def centre(self) -> int | None:
194
+ """The point a circle or arc turns about, or ``None`` for a line."""
195
+ return self.points[0] if self.kind in ("Circle", "Arc") else None
196
+
197
+ @property
198
+ def ends(self) -> tuple[int, int] | None:
199
+ """The two points a line or arc runs between; ``None`` for a circle."""
200
+ if self.kind == "Line":
201
+ return (self.points[0], self.points[1])
202
+ if self.kind == "Arc":
203
+ return (self.points[1], self.points[2])
204
+ return None
205
+
206
+ @property
207
+ def is_closed(self) -> bool:
208
+ return self.kind == "Circle"
209
+
210
+
211
+ @dataclass(frozen=True, slots=True)
212
+ class Loop:
213
+ """A closed chain of curves -- the thing an extrude sweeps.
214
+
215
+ A sketch is a *graph*, not a single outline: construction lines and open
216
+ chains are ordinary, and 245 of the samples' 1,255 curve endpoints have
217
+ only one curve on them. So the loops a sketch yields are the components
218
+ every one of whose points carries exactly two curves, plus each circle,
219
+ which is a loop by itself. What is left over is reported rather than
220
+ forced into a shape it does not have.
221
+ """
222
+
223
+ #: Curve ids, in the order they chain.
224
+ curves: tuple[int, ...]
225
+ #: Point ids, in the same order; empty for a circle.
226
+ points: tuple[int, ...] = ()
227
+
228
+ def __len__(self) -> int:
229
+ return len(self.curves)
230
+
231
+
232
+ @dataclass(frozen=True, slots=True)
233
+ class Sketch:
234
+ """One sketch, its geometry, and the dimensions that drive it."""
235
+
236
+ oid: int
237
+ #: Position in the timeline, or ``-1`` for a sketch the list does not hold.
238
+ index: int
239
+ #: The label Fusion shows, or the name the user gave it.
240
+ name: str
241
+ points: tuple[Point, ...] = ()
242
+ curves: tuple[Curve, ...] = ()
243
+ #: The sketch's own dimensions, as attributed by
244
+ #: :func:`~ezf3d.model.timeline.attribute`.
245
+ parameters: tuple[Parameter, ...] = ()
246
+
247
+ @property
248
+ def in_timeline(self) -> bool:
249
+ return self.index >= 0
250
+
251
+ def extent(self) -> tuple[float, float, float, float]:
252
+ """``(xmin, ymin, xmax, ymax)`` in centimetres; zeros when empty."""
253
+ if not self.points:
254
+ return (0.0, 0.0, 0.0, 0.0)
255
+ xs = [point.x for point in self.points]
256
+ ys = [point.y for point in self.points]
257
+ return (min(xs), min(ys), max(xs), max(ys))
258
+
259
+ def distances(self) -> set[float]:
260
+ """Every distance between two of this sketch's points."""
261
+ return {a.distance(b) for a, b in combinations(self.points, 2)}
262
+
263
+ def kinds(self) -> Counter[str]:
264
+ """How many circles, lines and arcs."""
265
+ return Counter(curve.kind for curve in self.curves if curve.kind)
266
+
267
+ def loops(self) -> tuple[Loop, ...]:
268
+ """The closed chains this sketch's curves form.
269
+
270
+ Each circle is a loop of its own. The rest are walked as a graph on
271
+ point ids, and a component counts only when every one of its points
272
+ carries exactly two curves -- anything else is an open chain or a
273
+ junction, which :meth:`loose` counts.
274
+ """
275
+ found = [Loop(curves=(c.oid,)) for c in self.curves if c.kind == "Circle"]
276
+ adjacency: dict[int, list[tuple[int, int]]] = {}
277
+ for curve in self.curves:
278
+ ends = curve.ends
279
+ if ends is None:
280
+ continue
281
+ adjacency.setdefault(ends[0], []).append((curve.oid, ends[1]))
282
+ adjacency.setdefault(ends[1], []).append((curve.oid, ends[0]))
283
+
284
+ seen: set[int] = set()
285
+ for start in adjacency:
286
+ if start in seen:
287
+ continue
288
+ component = _component(adjacency, start)
289
+ seen |= component
290
+ if any(len(adjacency[point]) != 2 for point in component):
291
+ continue
292
+ found.append(_walk(adjacency, start))
293
+ return tuple(found)
294
+
295
+ def loose(self) -> int:
296
+ """Curves that no closed loop uses -- open chains and junctions."""
297
+ used = {oid for loop in self.loops() for oid in loop.curves}
298
+ return sum(1 for curve in self.curves if curve.oid not in used)
299
+
300
+ def curve_check(self) -> tuple[int, tuple[int, ...]]:
301
+ """``(curves whose numbers match their own geometry, those that do not)``.
302
+
303
+ The check that says the kinds are read rather than guessed. An arc
304
+ names a centre and two endpoints, so its stored radius must be the
305
+ distance from that centre to those endpoints and its stored span the
306
+ angle they subtend -- neither of which the record's *size* could
307
+ predict. A circle must store a full turn. Lines carry no geometry to
308
+ check, and are not counted either way.
309
+ """
310
+ at = {point.oid: point for point in self.points}
311
+ good = 0
312
+ bad: list[int] = []
313
+ for curve in self.curves:
314
+ if curve.kind == "Circle":
315
+ ok = abs(curve.span - FULL_TURN) < CURVE_TOLERANCE and curve.radius > 0.0
316
+ elif curve.kind == "Arc":
317
+ ok = _arc_agrees(curve, at)
318
+ else:
319
+ continue
320
+ good += ok
321
+ if not ok:
322
+ bad.append(curve.oid)
323
+ return good, tuple(bad)
324
+
325
+ def dimension_check(self) -> tuple[int, tuple[str, ...]]:
326
+ """``(linear dimensions re-derived, those that were not)``.
327
+
328
+ The cross-check this module rests on: a ``Linear Dimension-N`` the
329
+ parameter table holds must be a distance between two points the
330
+ geometry records hold. A miss is reported rather than tolerated --
331
+ a dimension can legitimately measure a point against a line, which
332
+ this does not resolve, so misses are expected and named.
333
+ """
334
+ spans = self.distances()
335
+ hit = 0
336
+ missed: list[str] = []
337
+ for parameter in self.parameters:
338
+ if not parameter.role.startswith("Linear Dimension"):
339
+ continue
340
+ if any(abs(span - abs(parameter.value)) < DIMENSION_TOLERANCE for span in spans):
341
+ hit += 1
342
+ else:
343
+ missed.append(parameter.role)
344
+ return hit, tuple(missed)
345
+
346
+
347
+ @dataclass(slots=True)
348
+ class Sketches:
349
+ """Every sketch a design has, and what the scan could not place."""
350
+
351
+ sketches: list[Sketch] = field(default_factory=list)
352
+ #: Entity records whose owner reference reached no sketch. Counted rather
353
+ #: than dropped: 4 across the four samples, all of them curves.
354
+ unowned: int = 0
355
+
356
+ def __len__(self) -> int:
357
+ return len(self.sketches)
358
+
359
+ def __iter__(self):
360
+ return iter(self.sketches)
361
+
362
+ def by_id(self) -> dict[int, Sketch]:
363
+ return {sketch.oid: sketch for sketch in self.sketches}
364
+
365
+ def points(self) -> int:
366
+ return sum(len(sketch.points) for sketch in self.sketches)
367
+
368
+ def curves(self) -> int:
369
+ return sum(len(sketch.curves) for sketch in self.sketches)
370
+
371
+ def kinds(self) -> Counter[str]:
372
+ total: Counter[str] = Counter()
373
+ for sketch in self.sketches:
374
+ total += sketch.kinds()
375
+ return total
376
+
377
+ def loops(self) -> int:
378
+ return sum(len(sketch.loops()) for sketch in self.sketches)
379
+
380
+ def curve_check(self) -> tuple[int, tuple[int, ...]]:
381
+ """``(curves agreeing with their own geometry, those that do not)``."""
382
+ good = 0
383
+ bad: list[int] = []
384
+ for sketch in self.sketches:
385
+ found, gaps = sketch.curve_check()
386
+ good += found
387
+ bad.extend(gaps)
388
+ return good, tuple(bad)
389
+
390
+ def check(self) -> tuple[int, tuple[tuple[int, str], ...]]:
391
+ """``(dimensions re-derived, (sketch id, role) for those that were not)``."""
392
+ hit = 0
393
+ missed: list[tuple[int, str]] = []
394
+ for sketch in self.sketches:
395
+ found, gaps = sketch.dimension_check()
396
+ hit += found
397
+ missed.extend((sketch.oid, role) for role in gaps)
398
+ return hit, tuple(missed)
399
+
400
+
401
+ def _component(adjacency: dict[int, list[tuple[int, int]]], start: int) -> set[int]:
402
+ """Every point reachable from *start* along curves."""
403
+ stack, seen = [start], set()
404
+ while stack:
405
+ point = stack.pop()
406
+ if point in seen:
407
+ continue
408
+ seen.add(point)
409
+ stack.extend(other for _, other in adjacency[point] if other not in seen)
410
+ return seen
411
+
412
+
413
+ def _walk(adjacency: dict[int, list[tuple[int, int]]], start: int) -> Loop:
414
+ """Order a component's curves by following it round from *start*."""
415
+ curves: list[int] = []
416
+ points: list[int] = [start]
417
+ previous, point = None, start
418
+ while True:
419
+ step = next(
420
+ (edge for edge in adjacency[point] if edge[0] != previous),
421
+ adjacency[point][0],
422
+ )
423
+ previous, point = step
424
+ curves.append(previous)
425
+ if point == start:
426
+ break
427
+ points.append(point)
428
+ if len(curves) > len(adjacency):
429
+ break
430
+ return Loop(curves=tuple(curves), points=tuple(points))
431
+
432
+
433
+ def _arc_agrees(curve: Curve, at: dict[int, Point]) -> bool:
434
+ """An arc's stored radius and span against the points it names."""
435
+ if len(curve.points) != 3 or not all(oid in at for oid in curve.points):
436
+ return False
437
+ centre, first, last = (at[oid] for oid in curve.points)
438
+ if abs(centre.distance(first) - abs(curve.radius)) > CURVE_TOLERANCE:
439
+ return False
440
+ start = math.atan2(first.y - centre.y, first.x - centre.x)
441
+ end = math.atan2(last.y - centre.y, last.x - centre.x)
442
+ turn = (end - start) % FULL_TURN
443
+ return min(abs(turn - abs(curve.span)), abs(FULL_TURN - turn - abs(curve.span))) < (
444
+ CURVE_TOLERANCE
445
+ )
446
+
447
+
448
+ def read_curve(body: bytes, item: BulkObject, points: set[int]) -> Curve | None:
449
+ """Kind, points, radius and span of a curve record.
450
+
451
+ The endpoint block is found from the type word after ``crv_secondary_id``
452
+ rather than from the record's start, and every reference in it has to be a
453
+ point of the sketch being read -- which is what stops the walk running on
454
+ into whatever follows.
455
+ """
456
+ size = item.end - item.offset
457
+ tail = body.find(_CURVE_TAIL_MARK, item.offset, item.end)
458
+ if tail < 0:
459
+ return Curve(oid=item.oid, size=size)
460
+ anchor = body.find(_ANCHOR_MARK, tail, item.end)
461
+ if anchor < 0:
462
+ return Curve(oid=item.oid, size=size)
463
+ base = anchor + len(_ANCHOR_MARK)
464
+ at = base + ENDPOINT_GAP
465
+ if at + _STRIDE > item.end or base + ENDPOINT_GAP > item.end:
466
+ return Curve(oid=item.oid, size=size)
467
+
468
+ named: list[int] = []
469
+ while at + _STRIDE <= item.end and body[at] == _REFERENCE:
470
+ (oid,) = struct.unpack_from("<Q", body, at + 1)
471
+ if oid not in points:
472
+ break
473
+ named.append(oid)
474
+ at += _STRIDE
475
+ kind = CURVE_KINDS.get(len(named), "")
476
+ if not kind:
477
+ return Curve(oid=item.oid, size=size)
478
+ (radius,) = struct.unpack_from("<d", body, base + RADIUS_AT)
479
+ (span,) = struct.unpack_from("<d", body, base + SPAN_AT)
480
+ return Curve(
481
+ oid=item.oid,
482
+ size=size,
483
+ kind=kind,
484
+ points=tuple(named),
485
+ radius=0.0 if kind == "Line" else radius,
486
+ span=span,
487
+ key=curve_key(body, item),
488
+ )
489
+
490
+
491
+ def curve_key(body: bytes, item: BulkObject) -> tuple[int, int]:
492
+ """``(crv_primary_id, crv_secondary_id)`` -- the curve's own identity.
493
+
494
+ Each key string is followed by its type word and then a ``u64``. A
495
+ secondary of zero is ordinary; many curves carry only a primary.
496
+ """
497
+ found: list[int] = []
498
+ for mark in (_CURVE_MARK, _CURVE_TAIL_MARK):
499
+ at = body.find(mark, item.offset, item.end)
500
+ word = body.find(_ANCHOR_MARK, at, item.end) if at >= 0 else -1
501
+ start = word + len(_ANCHOR_MARK)
502
+ if word < 0 or start + 8 > item.end:
503
+ found.append(0)
504
+ continue
505
+ (value,) = struct.unpack_from("<Q", body, start)
506
+ found.append(int(value) if value < (1 << 32) else 0)
507
+ return (found[0], found[1])
508
+
509
+
510
+ def read_point(body: bytes, item: BulkObject) -> tuple[float, float] | None:
511
+ """The ``(x, y)`` of a point record, or ``None`` if it is not one."""
512
+ at = _coordinates(body, item, _POINT_MARK)
513
+ if at is None:
514
+ return None
515
+ x, y, _z = struct.unpack_from("<3d", body, at)
516
+ if not (math.isfinite(x) and math.isfinite(y)):
517
+ return None
518
+ return x, y
519
+
520
+
521
+ def _coordinates(body: bytes, item: BulkObject, mark: bytes) -> int | None:
522
+ """Offset of the ``f64`` triple, measured from the key's type word."""
523
+ key = body.find(mark, item.offset, item.end)
524
+ if key < 0:
525
+ return None
526
+ anchor = body.find(_ANCHOR_MARK, key + len(mark), item.end)
527
+ if anchor < 0:
528
+ return None
529
+ at = anchor + len(_ANCHOR_MARK) + COORDINATE_GAP
530
+ return at if at + 24 <= item.end else None
531
+
532
+
533
+ def owner_of(body: bytes, item: BulkObject, sketches: list[int]) -> int | None:
534
+ """The sketch an entity record names, or ``None``.
535
+
536
+ Every revision-shaped string in the record is tried and the reference
537
+ before it read; the first that lands within :data:`OWNER_REACH` of a
538
+ sketch wins. Trying only the last one loses the splines, which nest a
539
+ second ``EntityGenesis`` block of their own.
540
+ """
541
+ if not sketches:
542
+ return None
543
+ for found in scan_strings(body, start=item.offset, end=item.end, min_len=3):
544
+ if found.kind != "str8" or not found.value.isdigit():
545
+ continue
546
+ at = found.offset - _STRIDE
547
+ if at < item.offset or body[at] != _REFERENCE:
548
+ continue
549
+ (container,) = struct.unpack_from("<Q", body, at + 1)
550
+ position = bisect_left(sketches, container)
551
+ if position < len(sketches) and sketches[position] - container <= OWNER_REACH:
552
+ return sketches[position]
553
+ return None
554
+
555
+
556
+ def _count_entities(segment: Segment) -> int:
557
+ """Point and curve records in a segment, without attributing any."""
558
+ body = segment.bulk.body
559
+ total = 0
560
+ for item in segment.objects():
561
+ size = item.end - item.offset
562
+ if not (_MIN_RECORD < size < _MAX_RECORD):
563
+ continue
564
+ if (
565
+ body.find(_POINT_MARK, item.offset, item.end) >= 0
566
+ or body.find(_CURVE_MARK, item.offset, item.end) >= 0
567
+ ):
568
+ total += 1
569
+ return total
570
+
571
+
572
+ def read_sketches(
573
+ segment: Segment,
574
+ timeline: Timeline | None = None,
575
+ parameters: Iterable[Parameter] | None = None,
576
+ ) -> Sketches:
577
+ """Read a design segment's sketches, their points and their curves.
578
+
579
+ *timeline* supplies which objects are sketches and what they are called;
580
+ one is read if not given. It must be the **wider** set -- every named
581
+ feature-shaped object, which :attr:`~ezf3d.model.timeline.Timeline.named`
582
+ carries -- and not only the entries the list holds: Focuser Mk1 keeps 6 of
583
+ its 39 sketches outside the timeline, and their geometry is in the stream
584
+ either way.
585
+ """
586
+ if timeline is None:
587
+ timeline = read_timeline(segment, parameters or read_parameters(segment).values)
588
+ body = segment.bulk.body
589
+
590
+ order = {feature.oid: feature for feature in timeline if feature.kind == "Sketch"}
591
+ ids = sorted(oid for oid, name in timeline.named.items() if name == "Sketch")
592
+ ids = sorted(set(ids) | set(order))
593
+ if not ids:
594
+ # A design can hold entity records and no sketch to hang them on: the
595
+ # registry-less `.f3z` members have no feature objects at all, and
596
+ # Roundified Cray keeps 51 such records. Counted, so that "no
597
+ # sketches" does not read as "no sketch geometry".
598
+ return Sketches(unowned=_count_entities(segment))
599
+
600
+ points: dict[int, list[Point]] = {oid: [] for oid in ids}
601
+ pending: dict[int, list[BulkObject]] = {oid: [] for oid in ids}
602
+ unowned = 0
603
+ for item in segment.objects():
604
+ size = item.end - item.offset
605
+ if not (_MIN_RECORD < size < _MAX_RECORD):
606
+ continue
607
+ is_point = body.find(_POINT_MARK, item.offset, item.end) >= 0
608
+ if not is_point and body.find(_CURVE_MARK, item.offset, item.end) < 0:
609
+ continue
610
+ owner = owner_of(body, item, ids)
611
+ if owner is None:
612
+ unowned += 1
613
+ continue
614
+ if is_point:
615
+ found = read_point(body, item)
616
+ if found is None:
617
+ unowned += 1
618
+ continue
619
+ points[owner].append(Point(oid=item.oid, x=found[0], y=found[1]))
620
+ else:
621
+ pending[owner].append(item)
622
+
623
+ # Curves are read second because a curve's references are validated
624
+ # against its own sketch's points, which is what bounds the walk.
625
+ curves: dict[int, list[Curve]] = {}
626
+ for oid in ids:
627
+ owned = {point.oid for point in points[oid]}
628
+ curves[oid] = [
629
+ read_curve(body, item, owned) or Curve(oid=item.oid, size=0) for item in pending[oid]
630
+ ]
631
+
632
+ return Sketches(
633
+ sketches=[
634
+ Sketch(
635
+ oid=oid,
636
+ index=order[oid].index if oid in order else -1,
637
+ name=order[oid].name if oid in order else "Sketch",
638
+ points=tuple(points[oid]),
639
+ curves=tuple(curves[oid]),
640
+ parameters=order[oid].parameters if oid in order else (),
641
+ )
642
+ for oid in ids
643
+ ],
644
+ unowned=unowned,
645
+ )