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,3 @@
1
+ """Convert Autodesk Fusion .f3d designs into editable SolidCraft designs."""
2
+
3
+ __version__ = "0.3.0"
@@ -0,0 +1,3 @@
1
+ from f3d2solidcraft.cli import main
2
+
3
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ezf3d contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ """Vendored from ezf3d 97fe90ab8c39c3978fa6354f4a21c5ebdbc38c6e (MIT). Generated: do not edit."""
@@ -0,0 +1 @@
1
+ """Vendored from ezf3d 97fe90ab8c39c3978fa6354f4a21c5ebdbc38c6e (MIT). Generated: do not edit."""
@@ -0,0 +1,204 @@
1
+ """Zstandard-aware ZIP reader for Fusion 360 archives.
2
+
3
+ Fusion writes ``.f3d``/``.f3z`` as ZIP files whose entries use compression
4
+ method 93 (Zstandard, APPNOTE 6.3.7). The stdlib :mod:`zipfile` parses the
5
+ central directory of such an archive without complaint and only raises from
6
+ ``ZipFile.open()``, so we let it own directory parsing and take over just the
7
+ byte-fetch: seek to the local header, skip it, read ``compress_size`` bytes,
8
+ and inflate them ourselves.
9
+
10
+ That keeps us off monkeypatching ``zipfile.decompressor``-internals, and it
11
+ means a future method (LZMA, whatever Fusion picks next) is a two-line change
12
+ in :func:`_decompress`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import struct
18
+ import zipfile
19
+ import zlib
20
+ from collections.abc import Iterator
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import IO, BinaryIO
24
+
25
+ import zstandard
26
+
27
+ #: ZIP compression method numbers we know how to undo.
28
+ ZIP_STORED = 0
29
+ ZIP_DEFLATED = 8
30
+ ZIP_ZSTANDARD = 93
31
+
32
+ _LOCAL_HEADER = struct.Struct("<IHHHHHIIIHH")
33
+ _LOCAL_HEADER_SIG = 0x04034B50
34
+
35
+
36
+ class UnsupportedCompressionError(NotImplementedError):
37
+ """Raised for a ZIP entry compressed with a method ezf3d cannot undo."""
38
+
39
+
40
+ class BadArchiveError(ValueError):
41
+ """Raised when an archive is not a readable Fusion container."""
42
+
43
+
44
+ @dataclass(frozen=True, slots=True)
45
+ class Entry:
46
+ """One file inside an :class:`F3DArchive`."""
47
+
48
+ name: str
49
+ size: int
50
+ compressed_size: int
51
+ method: int
52
+ crc: int
53
+
54
+ @property
55
+ def method_name(self) -> str:
56
+ return {
57
+ ZIP_STORED: "stored",
58
+ ZIP_DEFLATED: "deflate",
59
+ ZIP_ZSTANDARD: "zstd",
60
+ }.get(self.method, f"method-{self.method}")
61
+
62
+
63
+ def _decompress(raw: bytes, method: int, expected_size: int, name: str) -> bytes:
64
+ if method == ZIP_STORED:
65
+ return raw
66
+ if method == ZIP_DEFLATED:
67
+ return zlib.decompress(raw, -zlib.MAX_WBITS, max(expected_size, 1))
68
+ if method == ZIP_ZSTANDARD:
69
+ # read_across_frames because Fusion occasionally splits a large entry
70
+ # into several zstd frames; a plain decompress() would stop at the first.
71
+ return zstandard.ZstdDecompressor().stream_reader(raw, read_across_frames=True).read()
72
+ raise UnsupportedCompressionError(
73
+ f"{name!r} uses ZIP compression method {method}, which ezf3d cannot decode"
74
+ )
75
+
76
+
77
+ class F3DArchive:
78
+ """Random-access reader over a Fusion ``.f3d`` / ``.f3z`` archive.
79
+
80
+ Accepts a path or any seekable binary stream, so a ``.f3d`` nested inside a
81
+ ``.f3z`` can be opened straight from memory::
82
+
83
+ with F3DArchive(path) as pkg:
84
+ inner = F3DArchive(io.BytesIO(pkg.read("root.f3d")))
85
+ """
86
+
87
+ def __init__(self, source: str | Path | IO[bytes]) -> None:
88
+ self.source = source
89
+ self._owns_stream = isinstance(source, (str, Path))
90
+ self._stream: BinaryIO
91
+ if self._owns_stream:
92
+ self.path: Path | None = Path(source) # type: ignore[arg-type]
93
+ self._stream = self.path.open("rb")
94
+ else:
95
+ self.path = None
96
+ self._stream = source # type: ignore[assignment]
97
+ try:
98
+ self._zf = zipfile.ZipFile(self._stream)
99
+ except zipfile.BadZipFile as exc: # pragma: no cover - defensive
100
+ if self._owns_stream:
101
+ self._stream.close()
102
+ raise BadArchiveError(f"not a ZIP container: {source}") from exc
103
+
104
+ # -- lifecycle ---------------------------------------------------------
105
+
106
+ def close(self) -> None:
107
+ self._zf.close()
108
+ if self._owns_stream:
109
+ self._stream.close()
110
+
111
+ def __enter__(self) -> F3DArchive:
112
+ return self
113
+
114
+ def __exit__(self, *exc_info: object) -> None:
115
+ self.close()
116
+
117
+ # -- directory ---------------------------------------------------------
118
+
119
+ def entries(self) -> Iterator[Entry]:
120
+ """Yield every non-directory entry, in central-directory order."""
121
+ for info in self._zf.infolist():
122
+ if info.is_dir():
123
+ continue
124
+ yield Entry(
125
+ name=info.filename,
126
+ size=info.file_size,
127
+ compressed_size=info.compress_size,
128
+ method=info.compress_type,
129
+ crc=info.CRC,
130
+ )
131
+
132
+ def namelist(self) -> list[str]:
133
+ return [e.name for e in self.entries()]
134
+
135
+ def directories(self) -> list[str]:
136
+ """Directory entries, which carry no payload but shape the layout."""
137
+ return [i.filename for i in self._zf.infolist() if i.is_dir()]
138
+
139
+ def __contains__(self, name: str) -> bool:
140
+ try:
141
+ self._zf.getinfo(name)
142
+ except KeyError:
143
+ return False
144
+ return True
145
+
146
+ # -- payload -----------------------------------------------------------
147
+
148
+ def read(self, name: str, *, verify: bool = True) -> bytes:
149
+ """Return the decompressed bytes of *name*.
150
+
151
+ Raises :class:`KeyError` if absent, :class:`UnsupportedCompressionError` if
152
+ the method is unknown, and :class:`BadArchiveError` if *verify* is set and
153
+ the CRC-32 does not match the central directory.
154
+ """
155
+ info = self._zf.getinfo(name)
156
+ if info.compress_type in (ZIP_STORED, ZIP_DEFLATED):
157
+ # Let the stdlib handle what the stdlib handles well.
158
+ data = self._zf.read(name)
159
+ else:
160
+ data = _decompress(
161
+ self._read_raw(info), info.compress_type, info.file_size, info.filename
162
+ )
163
+ if verify and info.CRC and zlib.crc32(data) != info.CRC:
164
+ raise BadArchiveError(f"CRC mismatch for {name!r}")
165
+ if info.file_size and len(data) != info.file_size:
166
+ raise BadArchiveError(
167
+ f"{name!r} decompressed to {len(data)} bytes, expected {info.file_size}"
168
+ )
169
+ return data
170
+
171
+ def read_prefix(self, name: str, size: int) -> bytes:
172
+ """Return up to *size* leading bytes of *name* without inflating the rest.
173
+
174
+ A single body can be 25 MB of ASM, and reading only its header is
175
+ enough to report the kernel version -- so ``ezf3d info`` costs
176
+ kilobytes regardless of design size.
177
+ """
178
+ info = self._zf.getinfo(name)
179
+ if info.compress_type == ZIP_STORED:
180
+ self._stream.seek(info.header_offset)
181
+ return self._read_raw(info)[:size]
182
+ if info.compress_type == ZIP_DEFLATED:
183
+ with self._zf.open(name) as stream:
184
+ return stream.read(size)
185
+ if info.compress_type == ZIP_ZSTANDARD:
186
+ reader = zstandard.ZstdDecompressor().stream_reader(
187
+ self._read_raw(info), read_across_frames=True
188
+ )
189
+ return reader.read(size)
190
+ raise UnsupportedCompressionError(
191
+ f"{name!r} uses ZIP compression method {info.compress_type}, which ezf3d cannot decode"
192
+ )
193
+
194
+ def _read_raw(self, info: zipfile.ZipInfo) -> bytes:
195
+ """Read an entry's compressed bytes, bypassing zipfile's decompressors."""
196
+ self._stream.seek(info.header_offset)
197
+ header = self._stream.read(_LOCAL_HEADER.size)
198
+ sig, *_, name_len, extra_len = _LOCAL_HEADER.unpack(header)
199
+ if sig != _LOCAL_HEADER_SIG:
200
+ raise BadArchiveError(f"no local header for {info.filename!r} at {info.header_offset}")
201
+ # The local header's sizes are unreliable when a data descriptor is in
202
+ # play (general-purpose bit 3), so always trust the central directory.
203
+ self._stream.seek(name_len + extra_len, 1)
204
+ return self._stream.read(info.compress_size)
@@ -0,0 +1 @@
1
+ """Vendored from ezf3d 97fe90ab8c39c3978fa6354f4a21c5ebdbc38c6e (MIT). Generated: do not edit."""
@@ -0,0 +1,365 @@
1
+ """Design parameters: the names, roles, units, expressions and values.
2
+
3
+ Every dimension a designer types goes into one of these. ``ezf3d bodies`` can
4
+ say a face is a cylinder of radius 1.5 cm; this module is what says the radius
5
+ came from ``d27``, whose expression is ``1 mm``, and which feature slot it
6
+ fills.
7
+
8
+ A design keeps them in two objects that sit next to each other in the bulk
9
+ stream:
10
+
11
+ **The manager** holds a reference to the table, then one reference per
12
+ parameter in id order.
13
+
14
+ **The table** maps name to object: ``u32 count``, then that many entries of
15
+ ``wstr name, 0x01, u64 object id, u16 0``. It is the authoritative list --
16
+ every name a design has, including any the user typed.
17
+
18
+ **Each parameter is its own object**, and its layout is fixed after a 31-byte
19
+ preamble::
20
+
21
+ u32 number (at +16, the N in the auto name dN)
22
+ ...
23
+ wstr expression (at +31, e.g. "300 mm")
24
+ <padding> (nine bytes, ten before revision 489)
25
+ wstr role, wstr comment, wstr unit, wstr name
26
+ f64 value
27
+ 0x00, 0x01, u64 manager, 0x00, 0x00
28
+ str8 revision (of the record, not the stream)
29
+
30
+ Three redundancies make the reading checkable rather than merely plausible.
31
+ The name in the record equals the name the table filed it under; the ``u32``
32
+ at +16 equals the digits of that name; and the back-reference after the value
33
+ is the same manager object for every parameter of a document. All three hold
34
+ for **1,193 of 1,193** parameters across the four samples.
35
+
36
+ **Values are in Fusion's internal units** -- centimetres and radians -- and the
37
+ expression carries the unit the designer typed. That is checkable too: where
38
+ an expression is a literal, converting it by :data:`UNIT_FACTORS` must give the
39
+ stored value, and it does for every literal in the samples. A parameter whose
40
+ expression is a *formula* is reported as written; ezf3d does not evaluate it.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import math
46
+ import re
47
+ import struct
48
+ from dataclasses import dataclass, field
49
+
50
+ from f3d2solidcraft._vendor.ezf3d.streams.primitives import scan_strings
51
+ from f3d2solidcraft._vendor.ezf3d.streams.segment import BulkObject, Segment
52
+
53
+ #: Bytes before a parameter record's expression. Constant across the four
54
+ #: bulk-stream revisions on hand (299, 373, 397, 489) and the five record
55
+ #: revisions inside them (301, 312, 327, 369, 387).
56
+ PREAMBLE = 31
57
+
58
+ #: Offset of the ``u32`` that repeats the number in an auto-generated name.
59
+ NUMBER_AT = 16
60
+
61
+ #: Most padding tolerated between the expression and the role. Nine bytes in
62
+ #: revision 489, ten in the others; the search is bounded rather than fixed so
63
+ #: a further revision does not need new code to be *read* -- only to be
64
+ #: trusted, which the name check decides.
65
+ _MAX_PADDING = 16
66
+
67
+ #: A reference: the byte ``0x01`` followed by a little-endian object id.
68
+ _REFERENCE = 0x01
69
+
70
+ #: Longest string treated as a name or a unit while walking the table.
71
+ _MAX_STRING = 512
72
+
73
+ #: How Fusion names a parameter it generated itself. The ``_1`` suffix appears
74
+ #: on parameters that arrived with an XREF'd component.
75
+ AUTO_NAME_RE = re.compile(r"d(\d+)(?:_\d+)?$")
76
+
77
+ #: An expression that is a plain number with an optional unit, which is the
78
+ #: case :func:`Parameters.literal_check` can verify against the stored value.
79
+ LITERAL_RE = re.compile(r"\s*(-?\d+(?:\.\d+)?)\s*([A-Za-z]*)\s*$")
80
+
81
+ #: How many of a unit make one internal unit. Lengths are stored in
82
+ #: centimetres and angles in radians, so ``mm`` is 10 and ``deg`` is 180/pi.
83
+ #:
84
+ #: ``mm``, ``deg`` and the empty unit are the ones the samples exercise -- 1,185
85
+ #: literal expressions between them -- and ``in`` is pinned by a single formula,
86
+ #: ``1.5 in / 2``, stored as 1.905. The rest follow from the same two internal
87
+ #: units and are offered untested; an unknown unit converts to ``None`` rather
88
+ #: than to a guess.
89
+ UNIT_FACTORS: dict[str, float] = {
90
+ "": 1.0,
91
+ "cm": 1.0,
92
+ "mm": 10.0,
93
+ "m": 0.01,
94
+ "km": 1e-5,
95
+ "in": 1.0 / 2.54,
96
+ "ft": 1.0 / 30.48,
97
+ "rad": 1.0,
98
+ "deg": 180.0 / math.pi,
99
+ "grad": 200.0 / math.pi,
100
+ }
101
+
102
+ #: Relative tolerance for the literal check. Fusion writes the value as a
103
+ #: ``f64`` computed from the same literal, so agreement is near-exact.
104
+ LITERAL_TOLERANCE = 1e-9
105
+
106
+
107
+ @dataclass(frozen=True, slots=True)
108
+ class Parameter:
109
+ """One parameter of a design."""
110
+
111
+ #: Object id -- also its position in creation order.
112
+ oid: int
113
+ #: What the Parameters dialog calls it: ``d27``, or whatever the user typed.
114
+ name: str
115
+ #: The ``u32`` at :data:`NUMBER_AT`, which repeats the digits of an auto name.
116
+ number: int
117
+ #: The slot it fills in the feature that owns it -- ``AlongDistance``,
118
+ #: ``TaperAngle``, ``Radius`` -- or the sketch dimension's own name.
119
+ role: str
120
+ #: Unit as the designer sees it; empty for a count or a ratio.
121
+ unit: str
122
+ #: What the designer typed. May be a formula naming other parameters.
123
+ expression: str
124
+ #: **Internal units**: centimetres for lengths, radians for angles.
125
+ value: float
126
+ comment: str = ""
127
+ #: Schema revision Fusion stamped on this record.
128
+ revision: str = ""
129
+
130
+ @property
131
+ def is_auto(self) -> bool:
132
+ """True when Fusion generated the name rather than the user typing one."""
133
+ return AUTO_NAME_RE.fullmatch(self.name) is not None
134
+
135
+ @property
136
+ def display(self) -> float | None:
137
+ """:attr:`value` in :attr:`unit`, or ``None`` for a unit ezf3d has no factor for."""
138
+ factor = UNIT_FACTORS.get(self.unit)
139
+ return None if factor is None else self.value * factor
140
+
141
+
142
+ @dataclass(slots=True)
143
+ class Parameters:
144
+ """Every parameter a design segment declares."""
145
+
146
+ #: Object id of the name table.
147
+ table: int = 0
148
+ #: Object id of the manager, which every parameter points back to.
149
+ manager: int = 0
150
+ #: Entries the table declares.
151
+ declared: int = 0
152
+ #: The parameters, in creation order.
153
+ values: list[Parameter] = field(default_factory=list)
154
+ #: Names the table declares whose record did not read. Empty in every
155
+ #: sample; named rather than dropped when it is not.
156
+ unreadable: tuple[str, ...] = ()
157
+
158
+ def __len__(self) -> int:
159
+ return len(self.values)
160
+
161
+ def __iter__(self):
162
+ return iter(self.values)
163
+
164
+ def by_name(self) -> dict[str, Parameter]:
165
+ return {parameter.name: parameter for parameter in self.values}
166
+
167
+ def literal_check(self) -> tuple[int, tuple[str, ...]]:
168
+ """``(checked, disagreeing names)`` over parameters with literal expressions.
169
+
170
+ Converts each literal expression by :data:`UNIT_FACTORS` and compares it
171
+ with the stored value. This is what pins the claim that values are
172
+ centimetres and radians: it is derived from two fields Fusion wrote
173
+ independently, so agreement is evidence and not a restatement.
174
+ """
175
+ checked = 0
176
+ wrong: list[str] = []
177
+ for parameter in self.values:
178
+ match = LITERAL_RE.fullmatch(parameter.expression)
179
+ if match is None:
180
+ continue
181
+ factor = UNIT_FACTORS.get(match.group(2) or parameter.unit)
182
+ if factor is None:
183
+ continue
184
+ checked += 1
185
+ expected = float(match.group(1)) / factor
186
+ if abs(parameter.value - expected) > LITERAL_TOLERANCE * max(1.0, abs(expected)):
187
+ wrong.append(parameter.name)
188
+ return checked, tuple(wrong)
189
+
190
+
191
+ def _wstr_at(body: bytes, pos: int, limit: int) -> tuple[str, int] | None:
192
+ """A ``wstr`` at *pos* and the offset past it, or ``None``.
193
+
194
+ Empty is a legitimate value -- most parameters carry no comment and a count
195
+ carries no unit -- so a zero length reads as the empty string.
196
+ """
197
+ if pos < 0 or pos + 4 > limit:
198
+ return None
199
+ count = struct.unpack_from("<I", body, pos)[0]
200
+ if count > _MAX_STRING or pos + 4 + 2 * count > limit:
201
+ return None
202
+ raw = body[pos + 4 : pos + 4 + 2 * count]
203
+ if any(raw[2 * i + 1] for i in range(count)):
204
+ return None
205
+ return raw.decode("utf-16-le"), pos + 4 + 2 * count
206
+
207
+
208
+ def _is_label(text: str) -> bool:
209
+ return bool(text) and all(char >= " " for char in text)
210
+
211
+
212
+ def _walk_table(body: bytes, item: BulkObject, first: int) -> list[tuple[str, int]] | None:
213
+ """The ``name -> object id`` entries of a table whose first name is at *first*.
214
+
215
+ ``None`` when the walk does not complete, which is what disqualifies every
216
+ object that is not the parameter table.
217
+ """
218
+ if first - 4 < item.offset:
219
+ return None
220
+ count = struct.unpack_from("<I", body, first - 4)[0]
221
+ if not 1 <= count <= (item.size // 12):
222
+ return None
223
+ entries: list[tuple[str, int]] = []
224
+ pos = first
225
+ for _ in range(count):
226
+ found = _wstr_at(body, pos, item.end)
227
+ if found is None or not _is_label(found[0]):
228
+ return None
229
+ name, after = found
230
+ if after + 11 > item.end or body[after] != _REFERENCE:
231
+ return None
232
+ entries.append((name, struct.unpack_from("<Q", body, after + 1)[0]))
233
+ pos = after + 11
234
+ return entries
235
+
236
+
237
+ def find_table(segment: Segment) -> tuple[BulkObject, list[tuple[str, int]]] | None:
238
+ """The parameter name table, or ``None`` for a design that has none.
239
+
240
+ Found by shape rather than by position: the table is the object whose first
241
+ wide string is preceded by a count that walks cleanly to that many
242
+ ``name, reference`` entries. Two of the ``.f3z`` package's members hold no
243
+ such object and no parameters either, which is the honest answer for a
244
+ document assembled out of imported bodies.
245
+ """
246
+ body = segment.bulk.body
247
+ items = segment.objects()
248
+ if not items:
249
+ return None
250
+
251
+ # One linear pass: the bulk stream is megabytes and per-object scanning is
252
+ # what would make this command expensive.
253
+ starts = [item.offset for item in items]
254
+ first_wide: dict[int, int] = {}
255
+ index = 0
256
+ for found in scan_strings(body, min_len=1):
257
+ while index + 1 < len(items) and starts[index + 1] <= found.offset:
258
+ index += 1
259
+ if found.kind == "wstr":
260
+ first_wide.setdefault(items[index].oid, found.offset)
261
+
262
+ best: tuple[BulkObject, list[tuple[str, int]]] | None = None
263
+ for item in items:
264
+ start = first_wide.get(item.oid)
265
+ if start is None:
266
+ continue
267
+ entries = _walk_table(body, item, start)
268
+ if entries and (best is None or len(entries) > len(best[1])):
269
+ best = (item, entries)
270
+ return best
271
+
272
+
273
+ def _read_record(body: bytes, item: BulkObject) -> dict | None:
274
+ """Fields of one parameter record, or ``None`` if it does not read."""
275
+ found = _wstr_at(body, item.offset + PREAMBLE, item.end)
276
+ if found is None:
277
+ return None
278
+ expression, pos = found
279
+
280
+ role = ""
281
+ after = pos
282
+ for padding in range(_MAX_PADDING + 1):
283
+ candidate = _wstr_at(body, pos + padding, item.end)
284
+ if candidate is not None and _is_label(candidate[0]):
285
+ role, after = candidate
286
+ break
287
+ if not role:
288
+ return None
289
+
290
+ fields: list[str] = []
291
+ for _ in range(3):
292
+ candidate = _wstr_at(body, after, item.end)
293
+ if candidate is None:
294
+ return None
295
+ fields.append(candidate[0])
296
+ after = candidate[1]
297
+ comment, unit, name = fields
298
+
299
+ if after + 8 > item.end:
300
+ return None
301
+ value = struct.unpack_from("<d", body, after)[0]
302
+ after += 8
303
+
304
+ if after + 10 > item.end or body[after + 1] != _REFERENCE:
305
+ return None
306
+ manager = struct.unpack_from("<Q", body, after + 2)[0]
307
+
308
+ revision = next(
309
+ (
310
+ found.value
311
+ for found in scan_strings(body, start=after + 10, end=item.end, min_len=1)
312
+ if found.kind == "str8" and found.value.isdigit()
313
+ ),
314
+ "",
315
+ )
316
+ return {
317
+ "name": name,
318
+ "number": struct.unpack_from("<I", body, item.offset + NUMBER_AT)[0],
319
+ "role": role,
320
+ "unit": unit,
321
+ "expression": expression,
322
+ "value": value,
323
+ "comment": comment,
324
+ "revision": revision,
325
+ "manager": manager,
326
+ }
327
+
328
+
329
+ def read_parameters(segment: Segment) -> Parameters:
330
+ """Read a design segment's parameters, in creation order.
331
+
332
+ A record is kept only when the name it carries is the name the table filed
333
+ it under. That check is what makes the bounded padding search above safe:
334
+ a misread lands on the wrong string and is reported in
335
+ :attr:`Parameters.unreadable` rather than published as a parameter.
336
+ """
337
+ found = find_table(segment)
338
+ if found is None:
339
+ return Parameters()
340
+ table, entries = found
341
+
342
+ body = segment.bulk.body
343
+ by_id = {item.oid: item for item in segment.objects()}
344
+ values: list[Parameter] = []
345
+ unreadable: list[str] = []
346
+ managers: set[int] = set()
347
+
348
+ for name, oid in sorted(entries, key=lambda entry: entry[1]):
349
+ item = by_id.get(oid)
350
+ record = _read_record(body, item) if item is not None else None
351
+ if record is None or record["name"] != name:
352
+ unreadable.append(name)
353
+ continue
354
+ managers.add(record.pop("manager"))
355
+ values.append(Parameter(oid=oid, **record))
356
+
357
+ return Parameters(
358
+ table=table.oid,
359
+ # One manager per document in every sample; ambiguity would mean the
360
+ # table gathered records that are not all one design's, so say nothing.
361
+ manager=managers.pop() if len(managers) == 1 else 0,
362
+ declared=len(entries),
363
+ values=values,
364
+ unreadable=tuple(unreadable),
365
+ )