replicator-workshop 0.1.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 (118) hide show
  1. replicator/__init__.py +6 -0
  2. replicator/app.py +204 -0
  3. replicator/config.py +48 -0
  4. replicator/core/__init__.py +0 -0
  5. replicator/core/assembly.py +117 -0
  6. replicator/core/blender_link.py +161 -0
  7. replicator/core/critique.py +594 -0
  8. replicator/core/drawing.py +389 -0
  9. replicator/core/dxf.py +120 -0
  10. replicator/core/evaluate.py +439 -0
  11. replicator/core/explain.py +139 -0
  12. replicator/core/export.py +96 -0
  13. replicator/core/fit.py +170 -0
  14. replicator/core/importers.py +185 -0
  15. replicator/core/materials.py +104 -0
  16. replicator/core/ops_advanced.py +496 -0
  17. replicator/core/ops_engineering.py +223 -0
  18. replicator/core/physics.py +147 -0
  19. replicator/core/printers.py +100 -0
  20. replicator/core/program.py +298 -0
  21. replicator/core/render.py +145 -0
  22. replicator/core/reverse.py +350 -0
  23. replicator/core/robot.py +153 -0
  24. replicator/core/step.py +245 -0
  25. replicator/fixtures/gaming_pc_liquid.json +2259 -0
  26. replicator/fixtures/gas_generator_rocket.json +876 -0
  27. replicator/fixtures/gas_generator_rocket_aero.json +861 -0
  28. replicator/fixtures/house_two_bed.json +979 -0
  29. replicator/fixtures/quadcopter_drone.json +687 -0
  30. replicator/fixtures/raspberry_pi_5.json +884 -0
  31. replicator/fixtures/rocket_engine.json +652 -0
  32. replicator/fixtures/turbofan.json +931 -0
  33. replicator/fixtures/vector_engine.json +314 -0
  34. replicator/gpu.py +81 -0
  35. replicator/image3d/__init__.py +0 -0
  36. replicator/image3d/comfy.py +181 -0
  37. replicator/image3d/pipeline.py +208 -0
  38. replicator/image3d/sheet.py +154 -0
  39. replicator/knowledge/__init__.py +61 -0
  40. replicator/knowledge/car_wheel_corner.md +21 -0
  41. replicator/knowledge/desk_lamp.md +21 -0
  42. replicator/knowledge/desktop_pc.md +20 -0
  43. replicator/knowledge/electronics_board.md +21 -0
  44. replicator/knowledge/exoskeleton.md +21 -0
  45. replicator/knowledge/house.md +22 -0
  46. replicator/knowledge/light_aircraft.md +22 -0
  47. replicator/knowledge/multirotor_drone.md +25 -0
  48. replicator/knowledge/print_replica.md +13 -0
  49. replicator/knowledge/rocket_engine.md +27 -0
  50. replicator/knowledge/turbofan.md +23 -0
  51. replicator/llm/__init__.py +0 -0
  52. replicator/llm/client.py +424 -0
  53. replicator/llm/prompts/blueprint.md +28 -0
  54. replicator/llm/prompts/edit.md +15 -0
  55. replicator/llm/prompts/explain.md +37 -0
  56. replicator/llm/prompts/name_parts.md +13 -0
  57. replicator/llm/prompts/program.md +72 -0
  58. replicator/llm/prompts/research_queries.md +8 -0
  59. replicator/mcp_server.py +307 -0
  60. replicator/qml/Main.qml +874 -0
  61. replicator/qml/Replicator/UI/Chip.qml +17 -0
  62. replicator/qml/Replicator/UI/DockHeader.qml +27 -0
  63. replicator/qml/Replicator/UI/Icon.qml +118 -0
  64. replicator/qml/Replicator/UI/IconButton.qml +31 -0
  65. replicator/qml/Replicator/UI/Kbd.qml +18 -0
  66. replicator/qml/Replicator/UI/NumField.qml +69 -0
  67. replicator/qml/Replicator/UI/Pill.qml +28 -0
  68. replicator/qml/Replicator/UI/RCombo.qml +51 -0
  69. replicator/qml/Replicator/UI/RMenu.qml +42 -0
  70. replicator/qml/Replicator/UI/RSlider.qml +23 -0
  71. replicator/qml/Replicator/UI/Segmented.qml +63 -0
  72. replicator/qml/Replicator/UI/Swatch.qml +47 -0
  73. replicator/qml/Replicator/UI/Theme.qml +149 -0
  74. replicator/qml/Replicator/UI/qmldir +14 -0
  75. replicator/qml/panels/AgentPrompt.qml +53 -0
  76. replicator/qml/panels/AttributeManager.qml +171 -0
  77. replicator/qml/panels/Commander.qml +136 -0
  78. replicator/qml/panels/HolodeckPanel.qml +117 -0
  79. replicator/qml/panels/IssuesCard.qml +78 -0
  80. replicator/qml/panels/LedgerPanel.qml +110 -0
  81. replicator/qml/panels/MaterialShelf.qml +97 -0
  82. replicator/qml/panels/ObjectManager.qml +107 -0
  83. replicator/qml/panels/Preferences.qml +211 -0
  84. replicator/qml/panels/Presenter.qml +316 -0
  85. replicator/qml/panels/StatusBar.qml +77 -0
  86. replicator/qml/panels/Timeline.qml +149 -0
  87. replicator/qml/panels/Welcome.qml +126 -0
  88. replicator/qml/viewport/Callouts.qml +87 -0
  89. replicator/qml/viewport/EdgeMaterial.qml +16 -0
  90. replicator/qml/viewport/GridMaterial.qml +16 -0
  91. replicator/qml/viewport/HoloMaterial.qml +23 -0
  92. replicator/qml/viewport/NavGizmo.qml +72 -0
  93. replicator/qml/viewport/ReferenceMaterial.qml +17 -0
  94. replicator/qml/viewport/Viewport.qml +583 -0
  95. replicator/qt/__init__.py +0 -0
  96. replicator/qt/bridge.py +1427 -0
  97. replicator/qt/drawing_sheet.py +33 -0
  98. replicator/qt/envmap.py +40 -0
  99. replicator/qt/library.py +68 -0
  100. replicator/qt/mesh_geometry.py +167 -0
  101. replicator/qt/svg.py +41 -0
  102. replicator/research/__init__.py +0 -0
  103. replicator/research/lane.py +281 -0
  104. replicator/shaders/edge.frag +9 -0
  105. replicator/shaders/edge.vert +7 -0
  106. replicator/shaders/grid.frag +52 -0
  107. replicator/shaders/grid.vert +6 -0
  108. replicator/shaders/holo.frag +41 -0
  109. replicator/shaders/reference.frag +15 -0
  110. replicator/shaders/reference.vert +6 -0
  111. replicator/voice.py +120 -0
  112. replicator_workshop-0.1.0.dist-info/METADATA +410 -0
  113. replicator_workshop-0.1.0.dist-info/RECORD +118 -0
  114. replicator_workshop-0.1.0.dist-info/WHEEL +5 -0
  115. replicator_workshop-0.1.0.dist-info/entry_points.txt +3 -0
  116. replicator_workshop-0.1.0.dist-info/licenses/LICENSE +21 -0
  117. replicator_workshop-0.1.0.dist-info/licenses/vendor/mcp-for-blender/LICENSE +21 -0
  118. replicator_workshop-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,496 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import Any, Callable
5
+
6
+ import numpy as np
7
+ from manifold3d import Manifold, OpType
8
+
9
+ Builder = Callable[..., Manifold]
10
+
11
+
12
+ def _eval_error() -> type[ValueError]:
13
+ from .evaluate import EvalError
14
+
15
+ return EvalError
16
+
17
+
18
+ def _need_keys(params: dict, required: set[str], name: str) -> None:
19
+ missing = sorted(required - set(params))
20
+ if missing:
21
+ raise _eval_error()(f"{name} needs params {', '.join(missing)}")
22
+
23
+
24
+ def _optional_int(params: dict, key: str, default: int, lo: int, hi: int, name: str) -> int:
25
+ value = int(params.get(key, default))
26
+ if not lo <= value <= hi:
27
+ raise _eval_error()(f"{name} {key} must be {lo}..{hi}")
28
+ return value
29
+
30
+
31
+ def _positive_float(params: dict, key: str, name: str, default: float | None = None) -> float:
32
+ value = float(params[key] if key in params else default)
33
+ if not math.isfinite(value) or value <= 0:
34
+ raise _eval_error()(f"{name} {key} must be a positive finite number")
35
+ return value
36
+
37
+
38
+ def _finite_float(params: dict, key: str, name: str, default: float | None = None) -> float:
39
+ value = float(params[key] if key in params else default)
40
+ if not math.isfinite(value):
41
+ raise _eval_error()(f"{name} {key} must be finite")
42
+ return value
43
+
44
+
45
+ def _make_mesh(V: np.ndarray, F: np.ndarray):
46
+ from manifold3d import Mesh
47
+
48
+ return Mesh(vert_properties=V, tri_verts=F)
49
+
50
+
51
+ def _resample_polyline(points: np.ndarray, n: int) -> np.ndarray:
52
+ """n points evenly spaced by arc length around a closed ring (a repeated last point is dropped)."""
53
+ if n < 3:
54
+ raise _eval_error_("resample needs at least 3 points")
55
+ ring = np.asarray(points, np.float64).reshape(-1, 3)
56
+ if len(ring) > 1 and np.allclose(ring[0], ring[-1]):
57
+ ring = ring[:-1]
58
+ if len(ring) < 3:
59
+ raise _eval_error_("a section needs at least 3 distinct points")
60
+ closed = np.vstack([ring, ring[:1]])
61
+ seg = np.linalg.norm(np.diff(closed, axis=0), axis=1)
62
+ cum = np.r_[0.0, np.cumsum(seg)]
63
+ if cum[-1] <= 0:
64
+ raise _eval_error_("a section has zero length")
65
+ t = np.linspace(0.0, cum[-1], n, endpoint=False)
66
+ return np.column_stack([np.interp(t, cum, closed[:, k]) for k in range(3)])
67
+
68
+
69
+ def _eval_error_(msg: str):
70
+ raise _eval_error()(msg)
71
+
72
+
73
+ def _section_points(sec: dict, name: str) -> np.ndarray:
74
+ if not isinstance(sec, dict):
75
+ raise _eval_error_(f"{name} sections must be dicts")
76
+ if "y" not in sec:
77
+ raise _eval_error_(f"{name} sections need y")
78
+ if "radius" in sec:
79
+ r = float(sec["radius"])
80
+ if not math.isfinite(r) or r <= 0:
81
+ raise _eval_error_(f"{name} radius must be a positive finite number, got {sec['radius']}")
82
+ theta = np.linspace(0.0, 2.0 * math.pi, 256, endpoint=False)
83
+ return np.column_stack([r * np.cos(theta), np.zeros_like(theta), r * np.sin(theta)])
84
+ if "rx" in sec or "rz" in sec:
85
+ rx = float(sec.get("rx", sec.get("rz", 1.0)))
86
+ rz = float(sec.get("rz", sec.get("rx", 1.0)))
87
+ if not (math.isfinite(rx) and math.isfinite(rz) and rx > 0 and rz > 0):
88
+ raise _eval_error_(f"{name} rx and rz must be positive finite numbers")
89
+ theta = np.linspace(0.0, 2.0 * math.pi, 256, endpoint=False)
90
+ return np.column_stack([rx * np.cos(theta), np.zeros_like(theta), rz * np.sin(theta)])
91
+ pts = sec.get("points")
92
+ if not isinstance(pts, (list, tuple)) or len(pts) < 3:
93
+ raise _eval_error_(f"{name} polygon sections need at least 3 points")
94
+ arr = []
95
+ for p in pts:
96
+ if not (isinstance(p, (list, tuple)) and len(p) == 2):
97
+ raise _eval_error_(f"{name} polygon points must be [x, z]")
98
+ arr.append([float(p[0]), float(p[1])])
99
+ arr = np.asarray(arr, dtype=np.float64)
100
+ if not np.isfinite(arr).all():
101
+ raise _eval_error_(f"{name} polygon points must be finite")
102
+ if np.allclose(arr[0], arr[-1], rtol=1e-8, atol=1e-9):
103
+ arr = arr[:-1]
104
+ if len(arr) < 3:
105
+ raise _eval_error_(f"{name} polygon sections need at least 3 distinct points")
106
+ return np.column_stack([arr[:, 0], np.zeros_like(arr[:, 0]), arr[:, 1]])
107
+
108
+
109
+ def _section_signed_area_z(pts3: np.ndarray) -> float:
110
+ x = pts3[:, 0]
111
+ z = pts3[:, 2]
112
+ xn = np.roll(x, -1)
113
+ zn = np.roll(z, -1)
114
+ return float(np.sum(x * zn - xn * z))
115
+
116
+
117
+ def _rotate_section_to_start_max_x(pts3: np.ndarray) -> np.ndarray:
118
+ if len(pts3) == 0:
119
+ return pts3
120
+ idx = int(np.argmax(pts3[:, 0]))
121
+ return np.roll(pts3, -idx, axis=0)
122
+
123
+
124
+ def _orient_for_loft(pts3: np.ndarray, want_positive_z: bool) -> np.ndarray:
125
+ # A polygon ordered as angle increasing in (x,z) gives -Y planar normal.
126
+ # For +Y caps we need the reverse order; for -Y caps we keep it.
127
+ area = _section_signed_area_z(pts3)
128
+ if area == 0:
129
+ return pts3
130
+ positive_standard = area > 0
131
+ if want_positive_z and positive_standard:
132
+ return pts3[::-1]
133
+ if not want_positive_z and not positive_standard:
134
+ return pts3[::-1]
135
+ return pts3
136
+
137
+
138
+ def _build_loft(params: dict) -> Manifold:
139
+ """Skin closed sections stacked along +Y into a solid. Every section is resampled to the same point count,
140
+ starting at its max-x point, so the rings line up; caps are triangulated."""
141
+ _need_keys(params, {"sections"}, "loft")
142
+ sections = params["sections"]
143
+ if not isinstance(sections, (list, tuple)) or len(sections) < 2:
144
+ raise _eval_error_("loft sections must be a list with at least 2 entries")
145
+ n = _optional_int(params, "segments", 48, 3, 512, "loft")
146
+ rings, ys = [], []
147
+ for i, sec in enumerate(sections):
148
+ if not isinstance(sec, dict) or "y" not in sec:
149
+ raise _eval_error_(f"loft sections[{i}] needs a y")
150
+ p = _rotate_section_to_start_max_x(_resample_polyline(_section_points(sec, f"loft sections[{i}]"), n))
151
+ xz = np.column_stack([p[:, 0], p[:, 2]])
152
+ area = 0.5 * np.sum(xz[:, 0] * np.roll(xz[:, 1], -1) - np.roll(xz[:, 0], -1) * xz[:, 1])
153
+ if area < 0: # one winding for every ring, keeping the max-x start
154
+ xz = np.vstack([xz[:1], xz[1:][::-1]])
155
+ y = float(sec["y"])
156
+ if not math.isfinite(y):
157
+ raise _eval_error_(f"loft sections[{i}] y must be finite")
158
+ if abs(area) <= 1e-9 * max(float(np.ptp(xz[:, 0])), float(np.ptp(xz[:, 1])), 1e-12) ** 2:
159
+ raise _eval_error_(f"loft sections[{i}] has no area (its points are collinear, repeated or cross themselves): give "
160
+ "[x, z] points that enclose a shape")
161
+ ys.append(y)
162
+ rings.append(np.column_stack([xz[:, 0], np.full(n, y), xz[:, 1]]))
163
+ if np.any(np.diff(ys) <= 0):
164
+ raise _eval_error_(f"loft section y values must be strictly increasing, got {ys}; sort the sections "
165
+ "from bottom to top")
166
+ from manifold3d import triangulate
167
+ V = np.vstack(rings)
168
+ side = []
169
+ for r in range(len(rings) - 1):
170
+ for i in range(n):
171
+ j = (i + 1) % n
172
+ b0, b1, t0, t1 = r * n + i, r * n + j, (r + 1) * n + i, (r + 1) * n + j
173
+ side += [[b0, t0, b1], [t0, t1, b1]]
174
+ cap = np.asarray(triangulate([rings[0][:, [0, 2]].tolist()]), np.int64)
175
+ bottom = cap.tolist()
176
+ top = (cap[:, ::-1] + (len(rings) - 1) * n).tolist()
177
+ side = np.asarray(side, np.int64)
178
+ for flip_side in (False, True): # pick the consistent orientation with positive volume
179
+ for flip_caps in (False, True):
180
+ S = side[:, ::-1] if flip_side else side
181
+ B = np.asarray(bottom)[:, ::-1] if flip_caps else np.asarray(bottom)
182
+ T = np.asarray(top)[:, ::-1] if flip_caps else np.asarray(top)
183
+ try:
184
+ m = Manifold(_make_mesh(V, np.vstack([S, B, T])))
185
+ except Exception: # noqa: BLE001
186
+ continue
187
+ if not m.is_empty() and m.status().name == "NoError" and float(m.volume()) > 0:
188
+ return m
189
+ raise _eval_error_("loft sections do not form a closed solid (self-crossing or degenerate sections?)")
190
+
191
+
192
+ def _catmull_rom(points: np.ndarray, points_per_span: int) -> np.ndarray:
193
+ pts = points.reshape(-1, 3)
194
+ if len(pts) < 2:
195
+ raise _eval_error_("pipe path must have at least 2 points")
196
+ if points_per_span < 1:
197
+ raise _eval_error_("pipe smooth must be positive")
198
+ if len(pts) == 2:
199
+ t = np.linspace(0.0, 1.0, max(points_per_span, 2))
200
+ return pts[0] + t[:, None] * (pts[1] - pts[0])
201
+ padded = np.vstack([pts[0:1], pts, pts[-1:]])
202
+ out = []
203
+ for i in range(1, len(padded) - 2):
204
+ p0, p1, p2, p3 = padded[i - 1], padded[i], padded[i + 1], padded[i + 2]
205
+ for j in range(points_per_span):
206
+ t = j / points_per_span
207
+ t2 = t * t
208
+ t3 = t2 * t
209
+ out.append(
210
+ 0.5
211
+ * (
212
+ 2.0 * p1
213
+ + (p2 - p0) * t
214
+ + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2
215
+ + (3.0 * (p1 - p2) + p3 - p0) * t3
216
+ )
217
+ )
218
+ out.append(pts[-1].copy())
219
+ return np.asarray(out, dtype=np.float64)
220
+
221
+
222
+ def _build_pipe(params: dict) -> Manifold:
223
+ _need_keys(params, {"path", "radius"}, "pipe")
224
+ path = params["path"]
225
+ if not isinstance(path, (list, tuple)) or len(path) < 2:
226
+ raise _eval_error_("pipe path must be a list of at least 2 [x, y, z] points")
227
+ arr = []
228
+ for p in path:
229
+ if not (isinstance(p, (list, tuple)) and len(p) == 3):
230
+ raise _eval_error_("pipe path points must be [x, y, z]")
231
+ arr.append([float(p[0]), float(p[1]), float(p[2])])
232
+ arr = np.asarray(arr, dtype=np.float64)
233
+ if np.any(~np.isfinite(arr)):
234
+ raise _eval_error_("pipe path points must be finite")
235
+ keep = np.r_[True, np.any(np.diff(arr, axis=0) != 0, axis=1)] # a repeated point makes a kink or a dead segment
236
+ arr = arr[keep]
237
+
238
+ r = _positive_float(params, "radius", "pipe")
239
+ smooth = _optional_int(params, "smooth", 0, 0, 64, "pipe")
240
+ segs = _optional_int(params, "segments", 16, 3, 256, "pipe")
241
+
242
+ if len(arr) < 2:
243
+ raise _eval_error_("pipe path points are all the same; give at least two different [x, y, z] points "
244
+ "(use sphere for a ball)")
245
+ if smooth > 0:
246
+ path_pts = _catmull_rom(arr, smooth)
247
+ else:
248
+ path_pts = arr
249
+ if len(path_pts) > 6000:
250
+ raise _eval_error_("pipe path is too long (over 6000 segments): fewer points or less smooth")
251
+
252
+ parts = []
253
+ for i in range(len(path_pts) - 1):
254
+ s0 = Manifold.sphere(r, segs).translate(path_pts[i].tolist())
255
+ s1 = Manifold.sphere(r, segs).translate(path_pts[i + 1].tolist())
256
+ parts.append(Manifold.batch_hull([s0, s1]))
257
+ if len(parts) == 1:
258
+ m = parts[0]
259
+ else:
260
+ m = Manifold.batch_boolean(parts, OpType.Add)
261
+ if m.is_empty() or float(m.volume()) <= 0:
262
+ raise _eval_error_("pipe did not produce a valid non-empty manifold")
263
+ return m
264
+
265
+
266
+ def _build_helix(params: dict) -> Manifold:
267
+ _need_keys(params, {"radius", "pitch", "turns", "wire_radius"}, "helix")
268
+ radius = _positive_float(params, "radius", "helix")
269
+ pitch = _finite_float(params, "pitch", "helix")
270
+ if pitch == 0:
271
+ raise _eval_error_("helix pitch must be non-zero")
272
+ turns = _finite_float(params, "turns", "helix")
273
+ if not 1e-9 < abs(turns) <= 200:
274
+ raise _eval_error_("helix turns must be non-zero and at most 200")
275
+ wire = _positive_float(params, "wire_radius", "helix")
276
+ segs = _optional_int(params, "segments", 16, 3, 256, "helix")
277
+ pts_per_turn = max(24, segs)
278
+ total_pts = max(48, int(math.ceil(abs(turns) * pts_per_turn)) + 1)
279
+ if total_pts > 6000:
280
+ raise _eval_error_(f"helix would need {total_pts} path points (limit 6000): fewer turns or segments")
281
+ t = np.linspace(0.0, turns * 2.0 * math.pi, total_pts)
282
+ path = np.column_stack([radius * np.cos(t), pitch * t / (2.0 * math.pi), radius * np.sin(t)])
283
+ return _build_pipe({"path": path.tolist(), "radius": wire, "segments": segs})
284
+
285
+
286
+ def _gear_teeth(params: dict) -> int:
287
+ try:
288
+ v = float(params["teeth"])
289
+ except (TypeError, ValueError):
290
+ v = math.nan
291
+ if not math.isfinite(v) or v != int(v) or not 6 <= v <= 200:
292
+ raise _eval_error_(f"gear teeth must be a whole number from 6 to 200, got {params['teeth']}")
293
+ return int(v)
294
+
295
+
296
+ def _involute_gear_profile(params: dict) -> np.ndarray:
297
+ """Closed CCW polygon [(x, z)] of a standard spur gear: involute flanks from the base (or root) circle to the
298
+ tip circle, tip arcs and root arcs. Pitch r = m*z/2, addendum m, dedendum 1.25 m."""
299
+ teeth = _gear_teeth(params)
300
+ m = _positive_float(params, "module", "gear")
301
+ pa = float(params.get("pressure_angle", 20.0))
302
+ if not math.isfinite(pa) or not (5.0 <= pa <= 35.0):
303
+ raise _eval_error_("gear pressure_angle must be 5..35 degrees")
304
+ n = 8 # points per flank (segments is the bore circle's resolution)
305
+ alpha = math.radians(pa)
306
+ rp = m * teeth / 2.0
307
+ rb = rp * math.cos(alpha)
308
+ ra = rp + m
309
+ rf = max(rp - 1.25 * m, 0.3 * rp)
310
+ inv = lambda a: math.tan(a) - a # noqa: E731
311
+ # half the tooth's angular thickness at the pitch circle is pi/(2z); shift to the base-circle involute origin
312
+ half_pitch = math.pi / (2 * teeth)
313
+ origin = half_pitch + inv(alpha) # angle of the involute start (on the base circle) from tooth centre
314
+ r_start = max(rb, rf)
315
+
316
+ def flank(sign: int) -> list[tuple[float, float]]:
317
+ pts = []
318
+ for k in range(n + 1):
319
+ r = r_start + (ra - r_start) * k / n
320
+ a_r = math.acos(min(1.0, rb / r))
321
+ theta = origin - inv(a_r) # half-angle of the tooth at radius r
322
+ pts.append((r, sign * theta))
323
+ return pts
324
+
325
+ poly: list[tuple[float, float]] = []
326
+ step = 2 * math.pi / teeth
327
+ for t in range(teeth):
328
+ c = t * step
329
+ right = flank(-1) # from root up the trailing side
330
+ left = flank(+1)[::-1] # down the leading side
331
+ tooth = [(r, c + a) for r, a in right] + [(r, c + a) for r, a in left]
332
+ if rf < rb: # radial line from the root circle to the base circle
333
+ tooth = [(rf, tooth[0][1])] + tooth + [(rf, tooth[-1][1])]
334
+ poly.extend(tooth)
335
+ # root arc to the next tooth
336
+ a0, a1 = tooth[-1][1], c + step + (tooth[0][1] - c)
337
+ for k in range(1, 4):
338
+ poly.append((rf, a0 + (a1 - a0) * k / 4))
339
+ pts = np.array([[r * math.cos(a), r * math.sin(a)] for r, a in poly])
340
+ area = 0.5 * np.sum(pts[:, 0] * np.roll(pts[:, 1], -1) - np.roll(pts[:, 0], -1) * pts[:, 1])
341
+ return pts if area > 0 else pts[::-1]
342
+
343
+
344
+ def _build_gear(params: dict) -> Manifold:
345
+ _need_keys(params, {"teeth", "module", "thickness"}, "gear")
346
+ _gear_teeth(params)
347
+ module = _positive_float(params, "module", "gear")
348
+ thickness = _positive_float(params, "thickness", "gear")
349
+ bore = float(params.get("bore", 0.0))
350
+ if not math.isfinite(bore) or bore < 0:
351
+ raise _eval_error_("gear bore must be a finite number >= 0")
352
+
353
+ prof = _involute_gear_profile(params)
354
+ xs, zs = prof[:, 0], prof[:, 1]
355
+ root_r = float(np.hypot(xs, zs).min())
356
+ if bore >= root_r:
357
+ raise _eval_error_(f"gear bore {bore:g} must be smaller than the root radius {root_r:.4g} "
358
+ "(pitch radius is module x teeth / 2, root is 1.25 modules below it)")
359
+
360
+ # Extrude in Z then rotate to Y. CrossSection expects XY; our profile is XZ, so map x->x, z->y.
361
+ from manifold3d import CrossSection
362
+
363
+ poly = [[float(x), float(z)] for x, z in prof]
364
+ holes = []
365
+ if bore > 0:
366
+ m = _optional_int(params, "segments", 64, 12, 512, "gear")
367
+ theta = np.linspace(0.0, 2.0 * math.pi, m, endpoint=False)
368
+ holes.append([[bore * math.cos(t), bore * math.sin(t)] for t in theta[::-1]]) # clockwise, or it fills in
369
+
370
+ m = Manifold.extrude(CrossSection([poly] + holes), thickness, n_divisions=0, twist_degrees=0.0, scale_top=[1.0, 1.0])
371
+ m = m.translate((0.0, 0.0, -thickness / 2.0))
372
+ m = m.rotate((-90.0, 0.0, 0.0))
373
+ if m.is_empty() or float(m.volume()) <= 0:
374
+ raise _eval_error_("gear did not produce a valid non-empty manifold")
375
+ return m
376
+
377
+
378
+ def _axis_index(axis, name: str) -> int:
379
+ if isinstance(axis, str):
380
+ a = axis.strip().lower().lstrip("+-")
381
+ if a in ("x", "y", "z"):
382
+ return "xyz".index(a)
383
+ raise _eval_error_("deform axis must be x, y or z")
384
+ if isinstance(axis, (list, tuple)) and len(axis) == 3:
385
+ vals = [abs(float(v)) for v in axis]
386
+ if sorted(vals)[:2] == [0.0, 0.0] and max(vals) > 0:
387
+ return vals.index(max(vals))
388
+ raise _eval_error_("deform axis must be axis-aligned")
389
+ raise _eval_error_("deform axis must be x, y or z")
390
+
391
+
392
+ def _build_deform(params: dict, m: Manifold) -> Manifold:
393
+ _need_keys(params, {"mode", "amount"}, "deform")
394
+ mode = str(params["mode"]).lower()
395
+ if mode not in ("taper", "twist", "bend"):
396
+ raise _eval_error_("deform mode must be taper, twist or bend")
397
+ amount = float(params["amount"])
398
+ if not math.isfinite(amount):
399
+ raise _eval_error_("deform amount must be finite")
400
+ if mode == "taper" and (amount <= 0):
401
+ raise _eval_error_("deform taper amount is the end scale and must be > 0 (1 = no change, 0.5 = half size)")
402
+ if mode == "twist" and abs(amount) > 3600:
403
+ raise _eval_error_("deform twist amount is in degrees, within +-3600")
404
+ if mode == "bend" and not -360 <= amount <= 360:
405
+ raise _eval_error_("deform bend amount is in degrees, within +-360")
406
+ idx = _axis_index(params.get("axis", "y"), "deform")
407
+
408
+ bb = np.asarray(m.bounding_box(), dtype=np.float64)
409
+ lo, hi = bb[:3], bb[3:]
410
+ size = hi - lo
411
+ extent = float(size[idx])
412
+ if extent <= 0:
413
+ raise _eval_error_("deform input has zero extent along the deformation axis")
414
+ res = params.get("resolution")
415
+ if res is None:
416
+ res = extent / 48.0
417
+ else:
418
+ res = float(res)
419
+ if not res >= extent / 400.0:
420
+ raise _eval_error_(f"deform resolution must be at least {extent / 400.0:.3g} (1/400 of the part)")
421
+ refined = m.refine_to_length(res)
422
+
423
+ center = (lo + hi) / 2.0
424
+ min_end = lo[idx]
425
+ max_end = hi[idx]
426
+
427
+ others = [j for j in range(3) if j != idx]
428
+ if mode == "taper":
429
+ def warp(P: np.ndarray) -> np.ndarray:
430
+ P = P.copy()
431
+ t = np.clip((P[:, idx] - min_end) / extent, 0.0, 1.0)
432
+ scale = 1.0 + (amount - 1.0) * t
433
+ for j in others:
434
+ P[:, j] = center[j] + scale * (P[:, j] - center[j])
435
+ return P
436
+ elif mode == "twist":
437
+ def warp(P: np.ndarray) -> np.ndarray:
438
+ P = P.copy()
439
+ t = np.clip((P[:, idx] - min_end) / extent, 0.0, 1.0)
440
+ th = np.radians(amount * t)
441
+ a, b = others
442
+ x, z = P[:, a] - center[a], P[:, b] - center[b]
443
+ P[:, a] = center[a] + np.cos(th) * x - np.sin(th) * z
444
+ P[:, b] = center[b] + np.sin(th) * x + np.cos(th) * z
445
+ return P
446
+ else:
447
+ # Bend the axis into an arc of `amount` degrees. The neutral axis passes through the centre; a point at
448
+ # offset d from it (along the bend direction) lands on radius R - d, so volume is kept to first order.
449
+ if abs(amount) < 1e-6:
450
+ return m
451
+ theta_total = math.radians(amount)
452
+ R = extent / theta_total
453
+ bend_dir = max(others, key=lambda j: float(size[j])) # bend in the plane of the wider cross-section side
454
+ if abs(R) <= size[bend_dir] / 2:
455
+ raise _eval_error_(f"deform bend of {amount:g} degrees over {extent:g} is too tight for a part "
456
+ f"{size[bend_dir]:g} wide (the inside folds through itself): bend less, or bend a "
457
+ "longer part")
458
+ def warp(P: np.ndarray) -> np.ndarray:
459
+ P = P.copy()
460
+ th = (P[:, idx] - min_end) / R
461
+ d = P[:, bend_dir] - center[bend_dir]
462
+ P[:, idx] = min_end + (R - d) * np.sin(th)
463
+ P[:, bend_dir] = center[bend_dir] + R - (R - d) * np.cos(th)
464
+ return P
465
+ warped = refined.warp_batch(warp)
466
+ if warped.is_empty() or float(warped.volume()) <= 0:
467
+ raise _eval_error_("deform did not produce a valid non-empty manifold")
468
+ return warped
469
+
470
+
471
+ def _wrap_builder(builder: Builder) -> Builder:
472
+ def wrapped(*args, **kwargs):
473
+ try:
474
+ return builder(*args, **kwargs)
475
+ except Exception as e:
476
+ if isinstance(e, _eval_error()):
477
+ raise
478
+ if isinstance(e, KeyError):
479
+ raise _eval_error_(f"missing param {e}")
480
+ if isinstance(e, (ValueError, TypeError)):
481
+ raise _eval_error_(f"a param has the wrong type or value ({e}); numbers must be numbers, "
482
+ "lists must be lists")
483
+ raise _eval_error_(str(e))
484
+ return wrapped
485
+
486
+
487
+ PRIMITIVES: dict[str, tuple[set[str], set[str], Builder]] = {
488
+ "loft": ({"sections"}, {"segments", "closed_caps"}, _wrap_builder(_build_loft)),
489
+ "pipe": ({"path", "radius"}, {"segments", "smooth"}, _wrap_builder(_build_pipe)),
490
+ "helix": ({"radius", "pitch", "turns", "wire_radius"}, {"segments"}, _wrap_builder(_build_helix)),
491
+ "gear": ({"teeth", "module", "thickness"}, {"bore", "pressure_angle", "segments"}, _wrap_builder(_build_gear)),
492
+ }
493
+
494
+ MODIFIERS: dict[str, tuple[set[str], set[str], Builder]] = {
495
+ "deform": ({"mode", "amount"}, {"axis", "resolution"}, _wrap_builder(_build_deform)),
496
+ }