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.
- replicator/__init__.py +6 -0
- replicator/app.py +204 -0
- replicator/config.py +48 -0
- replicator/core/__init__.py +0 -0
- replicator/core/assembly.py +117 -0
- replicator/core/blender_link.py +161 -0
- replicator/core/critique.py +594 -0
- replicator/core/drawing.py +389 -0
- replicator/core/dxf.py +120 -0
- replicator/core/evaluate.py +439 -0
- replicator/core/explain.py +139 -0
- replicator/core/export.py +96 -0
- replicator/core/fit.py +170 -0
- replicator/core/importers.py +185 -0
- replicator/core/materials.py +104 -0
- replicator/core/ops_advanced.py +496 -0
- replicator/core/ops_engineering.py +223 -0
- replicator/core/physics.py +147 -0
- replicator/core/printers.py +100 -0
- replicator/core/program.py +298 -0
- replicator/core/render.py +145 -0
- replicator/core/reverse.py +350 -0
- replicator/core/robot.py +153 -0
- replicator/core/step.py +245 -0
- replicator/fixtures/gaming_pc_liquid.json +2259 -0
- replicator/fixtures/gas_generator_rocket.json +876 -0
- replicator/fixtures/gas_generator_rocket_aero.json +861 -0
- replicator/fixtures/house_two_bed.json +979 -0
- replicator/fixtures/quadcopter_drone.json +687 -0
- replicator/fixtures/raspberry_pi_5.json +884 -0
- replicator/fixtures/rocket_engine.json +652 -0
- replicator/fixtures/turbofan.json +931 -0
- replicator/fixtures/vector_engine.json +314 -0
- replicator/gpu.py +81 -0
- replicator/image3d/__init__.py +0 -0
- replicator/image3d/comfy.py +181 -0
- replicator/image3d/pipeline.py +208 -0
- replicator/image3d/sheet.py +154 -0
- replicator/knowledge/__init__.py +61 -0
- replicator/knowledge/car_wheel_corner.md +21 -0
- replicator/knowledge/desk_lamp.md +21 -0
- replicator/knowledge/desktop_pc.md +20 -0
- replicator/knowledge/electronics_board.md +21 -0
- replicator/knowledge/exoskeleton.md +21 -0
- replicator/knowledge/house.md +22 -0
- replicator/knowledge/light_aircraft.md +22 -0
- replicator/knowledge/multirotor_drone.md +25 -0
- replicator/knowledge/print_replica.md +13 -0
- replicator/knowledge/rocket_engine.md +27 -0
- replicator/knowledge/turbofan.md +23 -0
- replicator/llm/__init__.py +0 -0
- replicator/llm/client.py +424 -0
- replicator/llm/prompts/blueprint.md +28 -0
- replicator/llm/prompts/edit.md +15 -0
- replicator/llm/prompts/explain.md +37 -0
- replicator/llm/prompts/name_parts.md +13 -0
- replicator/llm/prompts/program.md +72 -0
- replicator/llm/prompts/research_queries.md +8 -0
- replicator/mcp_server.py +307 -0
- replicator/qml/Main.qml +874 -0
- replicator/qml/Replicator/UI/Chip.qml +17 -0
- replicator/qml/Replicator/UI/DockHeader.qml +27 -0
- replicator/qml/Replicator/UI/Icon.qml +118 -0
- replicator/qml/Replicator/UI/IconButton.qml +31 -0
- replicator/qml/Replicator/UI/Kbd.qml +18 -0
- replicator/qml/Replicator/UI/NumField.qml +69 -0
- replicator/qml/Replicator/UI/Pill.qml +28 -0
- replicator/qml/Replicator/UI/RCombo.qml +51 -0
- replicator/qml/Replicator/UI/RMenu.qml +42 -0
- replicator/qml/Replicator/UI/RSlider.qml +23 -0
- replicator/qml/Replicator/UI/Segmented.qml +63 -0
- replicator/qml/Replicator/UI/Swatch.qml +47 -0
- replicator/qml/Replicator/UI/Theme.qml +149 -0
- replicator/qml/Replicator/UI/qmldir +14 -0
- replicator/qml/panels/AgentPrompt.qml +53 -0
- replicator/qml/panels/AttributeManager.qml +171 -0
- replicator/qml/panels/Commander.qml +136 -0
- replicator/qml/panels/HolodeckPanel.qml +117 -0
- replicator/qml/panels/IssuesCard.qml +78 -0
- replicator/qml/panels/LedgerPanel.qml +110 -0
- replicator/qml/panels/MaterialShelf.qml +97 -0
- replicator/qml/panels/ObjectManager.qml +107 -0
- replicator/qml/panels/Preferences.qml +211 -0
- replicator/qml/panels/Presenter.qml +316 -0
- replicator/qml/panels/StatusBar.qml +77 -0
- replicator/qml/panels/Timeline.qml +149 -0
- replicator/qml/panels/Welcome.qml +126 -0
- replicator/qml/viewport/Callouts.qml +87 -0
- replicator/qml/viewport/EdgeMaterial.qml +16 -0
- replicator/qml/viewport/GridMaterial.qml +16 -0
- replicator/qml/viewport/HoloMaterial.qml +23 -0
- replicator/qml/viewport/NavGizmo.qml +72 -0
- replicator/qml/viewport/ReferenceMaterial.qml +17 -0
- replicator/qml/viewport/Viewport.qml +583 -0
- replicator/qt/__init__.py +0 -0
- replicator/qt/bridge.py +1427 -0
- replicator/qt/drawing_sheet.py +33 -0
- replicator/qt/envmap.py +40 -0
- replicator/qt/library.py +68 -0
- replicator/qt/mesh_geometry.py +167 -0
- replicator/qt/svg.py +41 -0
- replicator/research/__init__.py +0 -0
- replicator/research/lane.py +281 -0
- replicator/shaders/edge.frag +9 -0
- replicator/shaders/edge.vert +7 -0
- replicator/shaders/grid.frag +52 -0
- replicator/shaders/grid.vert +6 -0
- replicator/shaders/holo.frag +41 -0
- replicator/shaders/reference.frag +15 -0
- replicator/shaders/reference.vert +6 -0
- replicator/voice.py +120 -0
- replicator_workshop-0.1.0.dist-info/METADATA +410 -0
- replicator_workshop-0.1.0.dist-info/RECORD +118 -0
- replicator_workshop-0.1.0.dist-info/WHEEL +5 -0
- replicator_workshop-0.1.0.dist-info/entry_points.txt +3 -0
- replicator_workshop-0.1.0.dist-info/licenses/LICENSE +21 -0
- replicator_workshop-0.1.0.dist-info/licenses/vendor/mcp-for-blender/LICENSE +21 -0
- replicator_workshop-0.1.0.dist-info/top_level.txt +1 -0
replicator/qt/bridge.py
ADDED
|
@@ -0,0 +1,1427 @@
|
|
|
1
|
+
"""Studio: the one QObject QML talks to. Owns the program, evaluator, timeline cursor, modes, components, the
|
|
2
|
+
reverse-engineering ledger, and the model / render jobs."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import json
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from PySide6.QtCore import Property, QCoreApplication, QObject, QFileSystemWatcher, QTimer, QUrl, Signal, Slot
|
|
12
|
+
|
|
13
|
+
from .. import config, voice
|
|
14
|
+
from ..core import assembly, critique, drawing, explain, importers, materials, physics, printers, reverse
|
|
15
|
+
from ..core import export as exporter
|
|
16
|
+
from ..core.evaluate import EvalError, Evaluator, RawMesh, bounds
|
|
17
|
+
from ..core.ops_engineering import HOLES
|
|
18
|
+
from ..core.program import (ProgramError, apply_patch, check, component_map, component_ops,
|
|
19
|
+
delete_component, duplicate_component, op_inputs, scale_program)
|
|
20
|
+
from ..image3d import pipeline, sheet
|
|
21
|
+
from ..llm import client
|
|
22
|
+
from . import library
|
|
23
|
+
from .envmap import EnvMap
|
|
24
|
+
from .mesh_geometry import MeshGeometry
|
|
25
|
+
|
|
26
|
+
OUT = Path.home() / "Replicator"
|
|
27
|
+
HISTORY_LIMIT = 200
|
|
28
|
+
GEO_CACHE_LIMIT = 600 # viewport meshes kept for instant undo and scrub
|
|
29
|
+
EVAL_CACHE_LIMIT = 4000 # kernel results kept (op hash -> solid)
|
|
30
|
+
MODES = ("build", "dissect", "reverse", "showcase", "present")
|
|
31
|
+
ENUMS = {"mode": {"boolean": ["union", "difference", "intersection"], "array": ["linear", "radial", "mirror"],
|
|
32
|
+
"deform": ["taper", "twist", "bend"]},
|
|
33
|
+
"axis": ["x", "y", "z"], "hole": list(HOLES)}
|
|
34
|
+
INT_PARAMS = {"count", "teeth", "turns", "segments", "levels", "blades", "smooth"}
|
|
35
|
+
MEASURE_DELAY_MS = 150 # critique and mass wait for edits to settle, then run off the GUI thread
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _local(path: str) -> Path:
|
|
39
|
+
return Path(QUrl(path).toLocalFile() if path.startswith("file:") else path).expanduser()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Studio(QObject):
|
|
43
|
+
shapesChanged = Signal()
|
|
44
|
+
programChanged = Signal()
|
|
45
|
+
stepChanged = Signal()
|
|
46
|
+
logChanged = Signal()
|
|
47
|
+
busyChanged = Signal()
|
|
48
|
+
selectionChanged = Signal()
|
|
49
|
+
modeChanged = Signal()
|
|
50
|
+
reportChanged = Signal()
|
|
51
|
+
renderChanged = Signal()
|
|
52
|
+
sheetChanged = Signal()
|
|
53
|
+
holodeckChanged = Signal()
|
|
54
|
+
engineChanged = Signal()
|
|
55
|
+
historyChanged = Signal()
|
|
56
|
+
libraryChanged = Signal()
|
|
57
|
+
explanationChanged = Signal()
|
|
58
|
+
issuesChanged = Signal()
|
|
59
|
+
factsChanged = Signal()
|
|
60
|
+
measuringChanged = Signal()
|
|
61
|
+
_measured = Signal(object, object, object)
|
|
62
|
+
servicesChanged = Signal()
|
|
63
|
+
voiceChanged = Signal()
|
|
64
|
+
dictated = Signal(str)
|
|
65
|
+
_voiceEvent = Signal(str, str)
|
|
66
|
+
_jobDone = Signal(object, str)
|
|
67
|
+
|
|
68
|
+
def __init__(self):
|
|
69
|
+
super().__init__()
|
|
70
|
+
self._ev = Evaluator()
|
|
71
|
+
self._program: dict | None = None
|
|
72
|
+
self._project: Path | None = None
|
|
73
|
+
self._history: list[dict] = []
|
|
74
|
+
self._future: list[dict] = []
|
|
75
|
+
self._stats: dict = {}
|
|
76
|
+
self._ops_rows: list | None = None
|
|
77
|
+
self._comp_rows: list | None = None
|
|
78
|
+
self._step = -1
|
|
79
|
+
self._shapes: list[MeshGeometry] = []
|
|
80
|
+
self._prev_shapes: list = []
|
|
81
|
+
self._geo_cache: dict[str, MeshGeometry] = {}
|
|
82
|
+
self._comps: list[assembly.Component] = []
|
|
83
|
+
self._log: list[str] = []
|
|
84
|
+
self._busy = ""
|
|
85
|
+
self._engine = client.default_engine()
|
|
86
|
+
self._selected = ""
|
|
87
|
+
self._mode = "build"
|
|
88
|
+
self._mode_after: str | None = None
|
|
89
|
+
self._report: dict = {}
|
|
90
|
+
self._render_path = ""
|
|
91
|
+
self._sheet: dict = {}
|
|
92
|
+
self._ground = 0.0
|
|
93
|
+
self._radius = 300.0
|
|
94
|
+
self._center = [0.0, 150.0, 0.0]
|
|
95
|
+
self._env = EnvMap()
|
|
96
|
+
self._holodeck_watcher = QFileSystemWatcher()
|
|
97
|
+
if sheet.CHARACTERS.is_dir():
|
|
98
|
+
self._holodeck_watcher.addPath(str(sheet.CHARACTERS))
|
|
99
|
+
self._holodeck_watcher.directoryChanged.connect(self.holodeckChanged.emit)
|
|
100
|
+
self._file: Path | None = None # the program file that is open; an agent (MCP) may edit it on disk
|
|
101
|
+
self._file_watcher = QFileSystemWatcher()
|
|
102
|
+
self._file_watcher.fileChanged.connect(lambda _: self._reload_timer.start())
|
|
103
|
+
self._reload_timer = QTimer(self)
|
|
104
|
+
self._reload_timer.setSingleShot(True)
|
|
105
|
+
self._reload_timer.setInterval(150) # a writer replaces the file in two steps; settle first
|
|
106
|
+
self._reload_timer.timeout.connect(self._reload_from_disk)
|
|
107
|
+
self._jobDone.connect(self._on_job)
|
|
108
|
+
self._measured.connect(self._on_measured)
|
|
109
|
+
self.selectionChanged.connect(self.factsChanged)
|
|
110
|
+
self.shapesChanged.connect(self.factsChanged)
|
|
111
|
+
self.issuesChanged.connect(self.factsChanged)
|
|
112
|
+
self._measure_timer = QTimer(self)
|
|
113
|
+
self._measure_timer.setSingleShot(True)
|
|
114
|
+
self._measure_timer.setInterval(MEASURE_DELAY_MS)
|
|
115
|
+
self._measure_timer.timeout.connect(self._start_measure)
|
|
116
|
+
self._measure_job = None
|
|
117
|
+
self._measure_thread: threading.Thread | None = None
|
|
118
|
+
self._measuring = False
|
|
119
|
+
self._cfg = config.load()
|
|
120
|
+
self._explanation: dict = {}
|
|
121
|
+
self._issues: list[dict] = []
|
|
122
|
+
self._issues_of: dict | None = None
|
|
123
|
+
self._epoch = 0
|
|
124
|
+
self._mass: physics.Mass | None = None
|
|
125
|
+
self._rest = "flush"
|
|
126
|
+
self._say_token = 0
|
|
127
|
+
self._player = None
|
|
128
|
+
self._speaking = False
|
|
129
|
+
self._rec = None
|
|
130
|
+
self._listening = False
|
|
131
|
+
self._voiceEvent.connect(self._on_voice)
|
|
132
|
+
|
|
133
|
+
# ------------------------------------------------------------------ properties
|
|
134
|
+
@Property("QVariantList", notify=shapesChanged)
|
|
135
|
+
def shapes(self):
|
|
136
|
+
return self._shapes
|
|
137
|
+
|
|
138
|
+
@Property("QVariantList", notify=shapesChanged)
|
|
139
|
+
def ops(self):
|
|
140
|
+
if not self._program:
|
|
141
|
+
return []
|
|
142
|
+
if self._ops_rows is not None:
|
|
143
|
+
return self._ops_rows
|
|
144
|
+
comp = component_map(self._program)
|
|
145
|
+
colors = {c.id: c.color for c in self._comps}
|
|
146
|
+
consumed_at: dict[str, int] = {}
|
|
147
|
+
for i, op in enumerate(self._program["ops"]):
|
|
148
|
+
for ref in op_inputs(op):
|
|
149
|
+
consumed_at.setdefault(ref, i)
|
|
150
|
+
self._ops_rows = [
|
|
151
|
+
{"id": op["id"], "op": op["op"], "label": op.get("label", op["id"]), "part": op.get("part", ""),
|
|
152
|
+
"component": comp[op["id"]], "color": colors.get(comp[op["id"]], "#8a8f98"), "index": i,
|
|
153
|
+
"consumedAt": consumed_at.get(op["id"], -1)}
|
|
154
|
+
for i, op in enumerate(self._program["ops"])]
|
|
155
|
+
return self._ops_rows
|
|
156
|
+
|
|
157
|
+
@Property("QVariantList", notify=shapesChanged)
|
|
158
|
+
def components(self):
|
|
159
|
+
if self._comp_rows is not None:
|
|
160
|
+
return self._comp_rows
|
|
161
|
+
g = self._ground
|
|
162
|
+
self._comp_rows = [{"id": c.id, "label": c.label, "role": c.role, "color": c.color, "count": len(c.shapes),
|
|
163
|
+
"order": c.order, "shapes": c.shapes,
|
|
164
|
+
"center": [float(c.center[0]), float(c.center[1]) + g, float(c.center[2])],
|
|
165
|
+
"offset": [float(x) for x in (c.offset if c.offset is not None else [0, 0, 0])],
|
|
166
|
+
"size": [float(x) for x in (c.hi - c.lo)]} for c in self._comps]
|
|
167
|
+
return self._comp_rows
|
|
168
|
+
|
|
169
|
+
@Property(str, notify=programChanged)
|
|
170
|
+
def title(self):
|
|
171
|
+
return (self._program or {}).get("name", "Untitled")
|
|
172
|
+
|
|
173
|
+
@Property(str, notify=programChanged)
|
|
174
|
+
def summary(self):
|
|
175
|
+
return ((self._program or {}).get("blueprint") or {}).get("summary", "")
|
|
176
|
+
|
|
177
|
+
@Property("QVariantList", notify=shapesChanged)
|
|
178
|
+
def dimensions(self):
|
|
179
|
+
return self._dims
|
|
180
|
+
|
|
181
|
+
@Property(int, notify=programChanged)
|
|
182
|
+
def stepCount(self):
|
|
183
|
+
return len(self._program["ops"]) if self._program else 0
|
|
184
|
+
|
|
185
|
+
@Property(int, notify=stepChanged)
|
|
186
|
+
def step(self):
|
|
187
|
+
return self._step
|
|
188
|
+
|
|
189
|
+
@Property(float, notify=shapesChanged)
|
|
190
|
+
def ground(self):
|
|
191
|
+
return self._ground
|
|
192
|
+
|
|
193
|
+
@Property(str, notify=programChanged)
|
|
194
|
+
def units(self):
|
|
195
|
+
return str(self._program.get("units", "mm")) if self._program else "mm"
|
|
196
|
+
|
|
197
|
+
@Property(float, notify=shapesChanged)
|
|
198
|
+
def radius(self):
|
|
199
|
+
return self._radius
|
|
200
|
+
|
|
201
|
+
@Property("QVariantList", notify=shapesChanged)
|
|
202
|
+
def center(self):
|
|
203
|
+
return self._center
|
|
204
|
+
|
|
205
|
+
@Property(QObject, constant=True)
|
|
206
|
+
def envMap(self):
|
|
207
|
+
return self._env
|
|
208
|
+
|
|
209
|
+
@Property(str, notify=logChanged)
|
|
210
|
+
def log(self):
|
|
211
|
+
return "\n".join(self._log[-300:])
|
|
212
|
+
|
|
213
|
+
@Property(str, notify=logChanged)
|
|
214
|
+
def lastLog(self):
|
|
215
|
+
return self._log[-1] if self._log else "Ready. Specify something, or import a model to take apart."
|
|
216
|
+
|
|
217
|
+
@Property(str, notify=busyChanged)
|
|
218
|
+
def busy(self):
|
|
219
|
+
return self._busy
|
|
220
|
+
|
|
221
|
+
@Property(str, notify=modeChanged)
|
|
222
|
+
def mode(self):
|
|
223
|
+
return self._mode
|
|
224
|
+
|
|
225
|
+
@Property(str, notify=selectionChanged)
|
|
226
|
+
def selected(self):
|
|
227
|
+
return self._selected
|
|
228
|
+
|
|
229
|
+
@Property(str, notify=selectionChanged)
|
|
230
|
+
def selectedComponent(self):
|
|
231
|
+
for g in self._shapes:
|
|
232
|
+
if g.shapeId == self._selected:
|
|
233
|
+
return g.component
|
|
234
|
+
return self._selected if any(c.id == self._selected for c in self._comps) else ""
|
|
235
|
+
|
|
236
|
+
@Property(str, notify=selectionChanged)
|
|
237
|
+
def selectedJson(self):
|
|
238
|
+
op = self._op(self._selected)
|
|
239
|
+
return json.dumps(op, indent=1) if op else ""
|
|
240
|
+
|
|
241
|
+
@Property(str, notify=selectionChanged)
|
|
242
|
+
def selectedOpKind(self):
|
|
243
|
+
op = self._op(self._selected)
|
|
244
|
+
return op["op"] if op else ""
|
|
245
|
+
|
|
246
|
+
@Property("QVariantList", notify=selectionChanged)
|
|
247
|
+
def selectedParams(self):
|
|
248
|
+
"""Typed rows for the Attribute Manager: number, vec3, enum, bool, text or json (point lists)."""
|
|
249
|
+
op = self._op(self._selected)
|
|
250
|
+
if not op:
|
|
251
|
+
return []
|
|
252
|
+
rows = [{"key": "label", "kind": "text", "value": op.get("label", "")},
|
|
253
|
+
{"key": "material", "kind": "enum", "value": op.get("material") or "",
|
|
254
|
+
"options": [""] + sorted((self._program or {}).get("materials", {}))}]
|
|
255
|
+
params = op.get("params", {})
|
|
256
|
+
for k, v in params.items():
|
|
257
|
+
if k in ("translate", "rotate", "scale"):
|
|
258
|
+
continue
|
|
259
|
+
if isinstance(v, bool):
|
|
260
|
+
rows.append({"key": k, "kind": "bool", "value": v})
|
|
261
|
+
elif isinstance(v, (int, float)):
|
|
262
|
+
whole = k in INT_PARAMS
|
|
263
|
+
rows.append({"key": k, "kind": "number", "value": float(v), "integer": whole,
|
|
264
|
+
"step": 1.0 if whole else max(abs(float(v)) * 0.01, 0.1)})
|
|
265
|
+
elif k in ENUMS and isinstance(v, str):
|
|
266
|
+
opts = ENUMS[k] if isinstance(ENUMS[k], list) else ENUMS[k].get(op["op"], [v])
|
|
267
|
+
rows.append({"key": k, "kind": "enum", "value": v, "options": opts})
|
|
268
|
+
elif isinstance(v, list) and len(v) == 3 and all(isinstance(x, (int, float)) for x in v):
|
|
269
|
+
rows.append({"key": k, "kind": "vec3", "value": [float(x) for x in v]})
|
|
270
|
+
else:
|
|
271
|
+
rows.append({"key": k, "kind": "json", "value": json.dumps(v)})
|
|
272
|
+
if op["op"] == "grille" and "hole" not in params:
|
|
273
|
+
rows.append({"key": "hole", "kind": "enum", "value": "hex", "options": list(HOLES)})
|
|
274
|
+
for k in ("translate", "rotate", "scale"):
|
|
275
|
+
v = params.get(k)
|
|
276
|
+
if isinstance(v, (int, float)):
|
|
277
|
+
v = [float(v)] * 3
|
|
278
|
+
rows.append({"key": k, "kind": "vec3", "group": "Coordinates",
|
|
279
|
+
"value": [float(x) for x in v] if v else ([1.0] * 3 if k == "scale" else [0.0] * 3)})
|
|
280
|
+
return rows
|
|
281
|
+
|
|
282
|
+
@Property("QVariantMap", notify=factsChanged)
|
|
283
|
+
def selectedFacts(self):
|
|
284
|
+
"""Measured facts for the selection: size (mm) of the part or component, and its component's mass (kg)."""
|
|
285
|
+
if not self._program or not self._selected:
|
|
286
|
+
return {}
|
|
287
|
+
comp = self.selectedComponent
|
|
288
|
+
try:
|
|
289
|
+
full = self._ev.step(self._program)
|
|
290
|
+
except EvalError:
|
|
291
|
+
return {}
|
|
292
|
+
parts = [s for s in full if s.id == self._selected] or [s for s in full if s.component == comp]
|
|
293
|
+
out: dict = {"component": comp}
|
|
294
|
+
if parts:
|
|
295
|
+
lo, hi = bounds(parts)
|
|
296
|
+
out["size"] = [round(float(hi[i] - lo[i]), 1) for i in range(3)]
|
|
297
|
+
kg = (self._mass.by_component.get(comp) if self._mass else None)
|
|
298
|
+
if kg is not None:
|
|
299
|
+
out["kg"] = float(kg)
|
|
300
|
+
return out
|
|
301
|
+
|
|
302
|
+
@Property(str, constant=True)
|
|
303
|
+
def drawsOn(self):
|
|
304
|
+
"""What the window renders with, from the policy replicator.gpu applied before Qt loaded."""
|
|
305
|
+
import os
|
|
306
|
+
if os.environ.get("LIBGL_ALWAYS_SOFTWARE") == "1":
|
|
307
|
+
return "CPU"
|
|
308
|
+
return "iGPU" if os.environ.get("__GLX_VENDOR_LIBRARY_NAME") == "mesa" else "GPU"
|
|
309
|
+
|
|
310
|
+
@Property(str, constant=True)
|
|
311
|
+
def importPatterns(self):
|
|
312
|
+
return importers.patterns()
|
|
313
|
+
|
|
314
|
+
@Property("QVariantList", notify=servicesChanged) # endpoints added in services.json join the list
|
|
315
|
+
def engines(self):
|
|
316
|
+
return list(client.engines())
|
|
317
|
+
|
|
318
|
+
@Property("QVariantList", notify=reportChanged)
|
|
319
|
+
def ledger(self):
|
|
320
|
+
return self._report.get("ledger", [])
|
|
321
|
+
|
|
322
|
+
@Property("QVariantList", notify=reportChanged)
|
|
323
|
+
def checklist(self):
|
|
324
|
+
return self._report.get("checklist", [])
|
|
325
|
+
|
|
326
|
+
@Property("QVariantMap", notify=reportChanged)
|
|
327
|
+
def reportInput(self):
|
|
328
|
+
return self._report.get("input", {})
|
|
329
|
+
|
|
330
|
+
@Property("QVariantMap", notify=sheetChanged)
|
|
331
|
+
def sheet(self):
|
|
332
|
+
"""The last blueprint sheet: {png, svg, seconds}; empty when none is open."""
|
|
333
|
+
return self._sheet
|
|
334
|
+
|
|
335
|
+
@Slot()
|
|
336
|
+
def closeSheet(self):
|
|
337
|
+
if self._sheet:
|
|
338
|
+
self._sheet = {}
|
|
339
|
+
self.sheetChanged.emit()
|
|
340
|
+
|
|
341
|
+
@Slot(str)
|
|
342
|
+
def makeSheet(self, style: str):
|
|
343
|
+
"""A dimensioned A3 blueprint sheet of the finished build (SVG plus PNG), drawn off the GUI thread."""
|
|
344
|
+
if not self._program:
|
|
345
|
+
return
|
|
346
|
+
if self._busy:
|
|
347
|
+
return self._say("busy: one job at a time (one GPU)")
|
|
348
|
+
from .svg import render_png
|
|
349
|
+
prog, shapes = self._program, self._ev.step(self._program)
|
|
350
|
+
comps = assembly.components(prog, shapes)
|
|
351
|
+
name = "".join(c if c.isalnum() else "-" for c in self.title.lower()).strip("-") or "build"
|
|
352
|
+
work = OUT / "sheets"
|
|
353
|
+
source = f"Replicator · {self._engine}"
|
|
354
|
+
|
|
355
|
+
def job(log):
|
|
356
|
+
t = time.time()
|
|
357
|
+
svg = drawing.sheet_svg(prog, shapes, comps, style if style in drawing.STYLES else "blueprint", source)
|
|
358
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
359
|
+
stem = work / f"{name}-{time.strftime('%Y%m%d-%H%M%S')}"
|
|
360
|
+
stem.with_suffix(".svg").write_text(svg)
|
|
361
|
+
png = render_png(svg, stem.with_suffix(".png"), drawing.SHEET, 150)
|
|
362
|
+
return {"sheet": {"png": str(png), "svg": str(stem.with_suffix(".svg")),
|
|
363
|
+
"seconds": round(time.time() - t, 1)}}
|
|
364
|
+
self._run_job("Drawing the blueprint sheet", job)
|
|
365
|
+
|
|
366
|
+
@Property(str, notify=renderChanged)
|
|
367
|
+
def renderPath(self):
|
|
368
|
+
return self._render_path
|
|
369
|
+
|
|
370
|
+
@Property("QVariantList", notify=holodeckChanged)
|
|
371
|
+
def holodeckSheets(self):
|
|
372
|
+
"""Character sheets in $REPLICATOR_SHEETS, newest first."""
|
|
373
|
+
rows = []
|
|
374
|
+
if sheet.CHARACTERS.is_dir():
|
|
375
|
+
for p in sheet.CHARACTERS.glob("*.png"):
|
|
376
|
+
rows.append({"path": str(p), "name": p.stem, "subject": sheet.subject(sheet.sidecar(p)),
|
|
377
|
+
"mtime": p.stat().st_mtime})
|
|
378
|
+
rows.sort(key=lambda r: -r["mtime"])
|
|
379
|
+
return rows
|
|
380
|
+
|
|
381
|
+
@Property("QVariantMap", notify=shapesChanged)
|
|
382
|
+
def stats(self):
|
|
383
|
+
"""Kernel read-outs for the status bar: triangles, parts, build time and cache use of the last rebuild."""
|
|
384
|
+
return self._stats
|
|
385
|
+
|
|
386
|
+
@Property(bool, notify=historyChanged)
|
|
387
|
+
def canUndo(self):
|
|
388
|
+
return bool(self._history)
|
|
389
|
+
|
|
390
|
+
@Property(bool, notify=historyChanged)
|
|
391
|
+
def canRedo(self):
|
|
392
|
+
return bool(self._future)
|
|
393
|
+
|
|
394
|
+
@Property("QVariantList", constant=True)
|
|
395
|
+
def materialLibrary(self):
|
|
396
|
+
return materials.rows()
|
|
397
|
+
|
|
398
|
+
@Property("QVariantList", notify=programChanged)
|
|
399
|
+
def programMaterials(self):
|
|
400
|
+
return materials.program_rows(self._program)
|
|
401
|
+
|
|
402
|
+
@Property(str, notify=selectionChanged)
|
|
403
|
+
def selectedMaterial(self):
|
|
404
|
+
if not self._program:
|
|
405
|
+
return ""
|
|
406
|
+
for g in self._shapes:
|
|
407
|
+
if g.shapeId == self._selected:
|
|
408
|
+
return g.materialName
|
|
409
|
+
op = self._op(self._selected)
|
|
410
|
+
return (op or {}).get("material") or ""
|
|
411
|
+
|
|
412
|
+
@Property(bool, notify=measuringChanged)
|
|
413
|
+
def measuring(self):
|
|
414
|
+
return self._measuring
|
|
415
|
+
|
|
416
|
+
@Property("QVariantList", notify=issuesChanged)
|
|
417
|
+
def issues(self):
|
|
418
|
+
return self._issues
|
|
419
|
+
|
|
420
|
+
@Property("QVariantMap", notify=issuesChanged)
|
|
421
|
+
def mass(self):
|
|
422
|
+
"""Computed mass properties: kg, centre of gravity, per component, and which parts use an assumed density."""
|
|
423
|
+
m = self._mass
|
|
424
|
+
if m is None:
|
|
425
|
+
return {}
|
|
426
|
+
return {"kg": m.kg, "cg": m.cg, "byComponent": m.by_component, "assumed": len(m.assumed), "stands": m.stands}
|
|
427
|
+
|
|
428
|
+
@Property("QVariantMap", notify=explanationChanged)
|
|
429
|
+
def explanation(self):
|
|
430
|
+
"""The checked explanation of the open object ({} until Explain has run): chapters, sources, notice."""
|
|
431
|
+
return self._explanation
|
|
432
|
+
|
|
433
|
+
@Property(str, notify=modeChanged)
|
|
434
|
+
def restPose(self):
|
|
435
|
+
"""'flush' or 'levitate': how Present shows the object (measured from its footprint)."""
|
|
436
|
+
return self._rest
|
|
437
|
+
|
|
438
|
+
@Property("QVariantMap", notify=servicesChanged)
|
|
439
|
+
def services(self):
|
|
440
|
+
"""Optional services (web research, voice) and what is usable right now."""
|
|
441
|
+
return {**self._cfg, "status": voice.status(self._cfg)}
|
|
442
|
+
|
|
443
|
+
@Property("QVariantMap", notify=servicesChanged)
|
|
444
|
+
def activePrinter(self):
|
|
445
|
+
"""The printer prints are gated on (id, name, usable build volume); empty when none is active
|
|
446
|
+
or the saved profiles are broken (a status bar must not take the window down)."""
|
|
447
|
+
try:
|
|
448
|
+
p = printers.active(self._cfg)
|
|
449
|
+
except ValueError:
|
|
450
|
+
p = None
|
|
451
|
+
return {} if p is None else {"id": p.id, "name": p.name, "usable": list(p.usable())}
|
|
452
|
+
|
|
453
|
+
@Property(bool, notify=voiceChanged)
|
|
454
|
+
def speaking(self):
|
|
455
|
+
return self._speaking
|
|
456
|
+
|
|
457
|
+
@Property(bool, notify=voiceChanged)
|
|
458
|
+
def listening(self):
|
|
459
|
+
return self._listening
|
|
460
|
+
|
|
461
|
+
@Property("QVariantList", notify=libraryChanged)
|
|
462
|
+
def examples(self):
|
|
463
|
+
return library.examples()
|
|
464
|
+
|
|
465
|
+
@Property("QVariantList", notify=libraryChanged)
|
|
466
|
+
def recents(self):
|
|
467
|
+
return library.recents(OUT)
|
|
468
|
+
|
|
469
|
+
@Property("QVariantList", notify=programChanged)
|
|
470
|
+
def reference(self):
|
|
471
|
+
"""Reference images of the open program (image to 3D keeps the views it was built from): key, label, path."""
|
|
472
|
+
ref = (self._program or {}).get("reference") or {}
|
|
473
|
+
out = []
|
|
474
|
+
for v in ref.get("views", []):
|
|
475
|
+
p = Path(v.get("image", ""))
|
|
476
|
+
if not p.is_absolute() and self._project:
|
|
477
|
+
p = self._project / p
|
|
478
|
+
p = p.resolve()
|
|
479
|
+
if p.is_file():
|
|
480
|
+
fill, cy = library.figure_extent(p)
|
|
481
|
+
out.append({"key": v.get("key", "front"), "label": v.get("label", v.get("key", "")), "path": str(p),
|
|
482
|
+
"fill": fill, "cy": cy})
|
|
483
|
+
return out
|
|
484
|
+
|
|
485
|
+
# ------------------------------------------------------------------ helpers
|
|
486
|
+
_dims: list = []
|
|
487
|
+
|
|
488
|
+
def _say(self, msg: str):
|
|
489
|
+
self._log.append(time.strftime("%H:%M:%S ") + msg)
|
|
490
|
+
self.logChanged.emit()
|
|
491
|
+
|
|
492
|
+
def _op(self, oid: str) -> dict | None:
|
|
493
|
+
for op in (self._program or {}).get("ops", []):
|
|
494
|
+
if op["id"] == oid:
|
|
495
|
+
return op
|
|
496
|
+
return None
|
|
497
|
+
|
|
498
|
+
def _watch(self, path: Path | None):
|
|
499
|
+
if self._file_watcher.files():
|
|
500
|
+
self._file_watcher.removePaths(self._file_watcher.files())
|
|
501
|
+
self._file = path
|
|
502
|
+
if path is not None and path.exists():
|
|
503
|
+
self._file_watcher.addPath(str(path))
|
|
504
|
+
|
|
505
|
+
def _reload_from_disk(self):
|
|
506
|
+
"""The open file changed under us (an agent patched it through the MCP server): show the new program at its
|
|
507
|
+
last step, as one undo step. Ignored while a job runs, or when the content is what we already show."""
|
|
508
|
+
p = self._file
|
|
509
|
+
if p is None:
|
|
510
|
+
return
|
|
511
|
+
if str(p) not in self._file_watcher.files() and p.exists():
|
|
512
|
+
self._file_watcher.addPath(str(p)) # an atomic replace drops the inotify watch; arm it again
|
|
513
|
+
if self._busy:
|
|
514
|
+
self._reload_timer.start()
|
|
515
|
+
return
|
|
516
|
+
try:
|
|
517
|
+
prog = json.loads(p.read_text())
|
|
518
|
+
if prog == self._program:
|
|
519
|
+
return
|
|
520
|
+
self._set_program(prog, f"{p.name} changed on disk; showing the new version (Ctrl+Z goes back)",
|
|
521
|
+
keep_step=True)
|
|
522
|
+
except (OSError, json.JSONDecodeError, ProgramError, EvalError) as e:
|
|
523
|
+
self._say(f"{p.name} changed on disk but does not build: {e}")
|
|
524
|
+
|
|
525
|
+
def _set_program(self, program: dict, note: str, keep_step: bool = False, push: bool = True):
|
|
526
|
+
check(program)
|
|
527
|
+
if push and self._program is not None:
|
|
528
|
+
self._history.append(self._program)
|
|
529
|
+
del self._history[:-HISTORY_LIMIT]
|
|
530
|
+
self._future.clear()
|
|
531
|
+
self._program = program
|
|
532
|
+
self._ops_rows = self._comp_rows = None
|
|
533
|
+
self.closeSheet()
|
|
534
|
+
self.historyChanged.emit()
|
|
535
|
+
self._prev_shapes = []
|
|
536
|
+
self._step = -1
|
|
537
|
+
self.programChanged.emit()
|
|
538
|
+
self._say(note)
|
|
539
|
+
self.setStep(self.stepCount - 1 if keep_step else 0)
|
|
540
|
+
if self._mode == "reverse":
|
|
541
|
+
self._refresh_report()
|
|
542
|
+
|
|
543
|
+
def _set_measuring(self, on: bool):
|
|
544
|
+
if on != self._measuring:
|
|
545
|
+
self._measuring = on
|
|
546
|
+
self.measuringChanged.emit()
|
|
547
|
+
|
|
548
|
+
def _start_measure(self):
|
|
549
|
+
job = self._measure_job
|
|
550
|
+
if job is None:
|
|
551
|
+
return
|
|
552
|
+
if self._measure_thread is not None and self._measure_thread.is_alive():
|
|
553
|
+
self._measure_timer.start() # one measurement at a time; try again when it is done
|
|
554
|
+
return
|
|
555
|
+
self._measure_job = None
|
|
556
|
+
self._measure_thread = threading.Thread(target=self._measure, args=job, daemon=True)
|
|
557
|
+
self._measure_thread.start()
|
|
558
|
+
|
|
559
|
+
def _measure(self, program, full, comps):
|
|
560
|
+
try:
|
|
561
|
+
issues = [i.as_dict() for i in critique.critique(program, full, comps)]
|
|
562
|
+
solids = [s for s in full if not isinstance(s.manifold, RawMesh)]
|
|
563
|
+
mass = physics.properties(program, solids) if solids else None
|
|
564
|
+
except Exception as e: # a measurement bug must not leave the card on "measuring" forever
|
|
565
|
+
issues, mass = [], None
|
|
566
|
+
self._measured.emit(program, None, f"measurement failed: {e}")
|
|
567
|
+
return
|
|
568
|
+
self._measured.emit(program, issues, mass)
|
|
569
|
+
|
|
570
|
+
def _on_measured(self, program, issues, mass):
|
|
571
|
+
if program is not self._program: # the program moved on while this was measured
|
|
572
|
+
return
|
|
573
|
+
if issues is None:
|
|
574
|
+
self._say(str(mass))
|
|
575
|
+
self._set_measuring(False)
|
|
576
|
+
return
|
|
577
|
+
self._issues, self._mass = issues, mass
|
|
578
|
+
self._set_measuring(self._measure_job is not None)
|
|
579
|
+
self.issuesChanged.emit()
|
|
580
|
+
|
|
581
|
+
def waitMeasured(self):
|
|
582
|
+
"""Block until the pending measurement has landed (tests, tools); the GUI never calls this."""
|
|
583
|
+
self._measure_timer.stop()
|
|
584
|
+
while self._measure_job is not None or (self._measure_thread and self._measure_thread.is_alive()):
|
|
585
|
+
if self._measure_job is not None and not (self._measure_thread and self._measure_thread.is_alive()):
|
|
586
|
+
self._start_measure()
|
|
587
|
+
if self._measure_thread:
|
|
588
|
+
self._measure_thread.join()
|
|
589
|
+
QCoreApplication.sendPostedEvents(self, 0)
|
|
590
|
+
|
|
591
|
+
def _rebuild(self, prev=None):
|
|
592
|
+
if not self._program:
|
|
593
|
+
self._shapes, self._comps = [], []
|
|
594
|
+
self.shapesChanged.emit()
|
|
595
|
+
return
|
|
596
|
+
t0 = time.perf_counter()
|
|
597
|
+
try:
|
|
598
|
+
shapes = self._ev.step(self._program, self._step)
|
|
599
|
+
hits, misses = self._ev.last_hits, self._ev.last_misses
|
|
600
|
+
full = self._ev.step(self._program)
|
|
601
|
+
except EvalError as e:
|
|
602
|
+
self._say(f"build error: {e}")
|
|
603
|
+
return
|
|
604
|
+
mats = self._program.get("materials", {})
|
|
605
|
+
lo, hi = bounds(full) # frame and explode on the finished build, not the partial one
|
|
606
|
+
self._ground = -lo[1]
|
|
607
|
+
ext = [hi[i] - lo[i] for i in range(3)]
|
|
608
|
+
self._dims = [round(e, 1) for e in ext]
|
|
609
|
+
self._radius = max(0.5 * (ext[0] ** 2 + ext[1] ** 2 + ext[2] ** 2) ** 0.5, 1.0)
|
|
610
|
+
self._center = [(lo[0] + hi[0]) / 2, ext[1] / 2, (lo[2] + hi[2]) / 2]
|
|
611
|
+
self._comps = assembly.components(self._program, full)
|
|
612
|
+
if self._issues_of is not self._program: # measured once per program version, not per scrub step
|
|
613
|
+
self._issues_of = self._program
|
|
614
|
+
self._measure_job = (self._program, full, self._comps)
|
|
615
|
+
self._set_measuring(True)
|
|
616
|
+
self._measure_timer.start()
|
|
617
|
+
offsets = assembly.explode(full, self._comps)
|
|
618
|
+
cinfo = {c.id: c for c in self._comps}
|
|
619
|
+
cur = {s.hash for s in shapes}
|
|
620
|
+
prev = prev or []
|
|
621
|
+
prev_hashes = {s.hash for s in prev}
|
|
622
|
+
first = not prev
|
|
623
|
+
|
|
624
|
+
used: set[str] = set()
|
|
625
|
+
|
|
626
|
+
def geo(s, phase):
|
|
627
|
+
key = s.hash + "|" + json.dumps(mats.get(s.material), sort_keys=True)
|
|
628
|
+
c = cinfo.get(s.component)
|
|
629
|
+
key += "|" + s.id + "|" + (c.color if c else "") + "|" + (c.label if c else "")
|
|
630
|
+
used.add(key)
|
|
631
|
+
g = self._geo_cache.get(key)
|
|
632
|
+
if g is None:
|
|
633
|
+
g = MeshGeometry(s, mats.get(s.material), phase, c.color if c else "#8a8f98",
|
|
634
|
+
c.label if c else s.component)
|
|
635
|
+
g.materialName = s.material or ""
|
|
636
|
+
self._geo_cache[key] = g
|
|
637
|
+
g = g.for_step(phase)
|
|
638
|
+
g.set_offset(offsets.get(s.id, [0, 0, 0]))
|
|
639
|
+
return g
|
|
640
|
+
out = [geo(s, 1 if (first and self._step == 0) or (not first and s.hash not in prev_hashes) else 0)
|
|
641
|
+
for s in shapes]
|
|
642
|
+
out += [geo(s, 2) for s in prev if s.hash not in cur] # leaving: dematerialize on reverse playback
|
|
643
|
+
self._prev_shapes = shapes
|
|
644
|
+
self._shapes = out
|
|
645
|
+
if len(self._geo_cache) > GEO_CACHE_LIMIT: # scrubbing a parameter leaves a trail of old meshes
|
|
646
|
+
self._geo_cache = {k: g for k, g in self._geo_cache.items() if k in used}
|
|
647
|
+
self._ev.trim(EVAL_CACHE_LIMIT)
|
|
648
|
+
self._ops_rows = self._comp_rows = None
|
|
649
|
+
live = [g for g, s in zip(out, shapes)]
|
|
650
|
+
self._stats = {"triangles": sum(g.triangles for g in live), "parts": len(live),
|
|
651
|
+
"components": len(self._comps), "buildMs": round((time.perf_counter() - t0) * 1000, 1),
|
|
652
|
+
"cacheHits": hits, "cacheMisses": misses, "cached": len(self._ev._cache)}
|
|
653
|
+
self.shapesChanged.emit()
|
|
654
|
+
|
|
655
|
+
def _load_explanation(self):
|
|
656
|
+
"""A new object: forget the old explanation, pick up a saved one from the project folder."""
|
|
657
|
+
self.stopSpeaking()
|
|
658
|
+
doc = {}
|
|
659
|
+
f = (self._project / "explanation.json") if self._project else None
|
|
660
|
+
if f and f.exists():
|
|
661
|
+
try:
|
|
662
|
+
doc = json.loads(f.read_text())
|
|
663
|
+
except ValueError:
|
|
664
|
+
doc = {}
|
|
665
|
+
self._explanation = doc
|
|
666
|
+
self.explanationChanged.emit()
|
|
667
|
+
|
|
668
|
+
def _refresh_report(self):
|
|
669
|
+
if not self._program:
|
|
670
|
+
return
|
|
671
|
+
rep = (self._project / "reverse_report.json") if self._project else None
|
|
672
|
+
if rep and rep.exists() and (self._program.get("name", "").startswith("Reverse:") or self._program.get("reference")):
|
|
673
|
+
try:
|
|
674
|
+
self._report = json.loads(rep.read_text())
|
|
675
|
+
except (OSError, json.JSONDecodeError) as e:
|
|
676
|
+
self._say(f"reverse report unreadable ({e}); showing the program's own report")
|
|
677
|
+
self._report = reverse.program_report(self._program, self._ev.step(self._program))
|
|
678
|
+
else:
|
|
679
|
+
self._report = reverse.program_report(self._program, self._ev.step(self._program))
|
|
680
|
+
self.reportChanged.emit()
|
|
681
|
+
|
|
682
|
+
# ------------------------------------------------------------------ timeline
|
|
683
|
+
@Slot(int)
|
|
684
|
+
def setStep(self, k: int):
|
|
685
|
+
if not self._program:
|
|
686
|
+
return
|
|
687
|
+
k = max(0, min(int(k), self.stepCount - 1))
|
|
688
|
+
if k == self._step:
|
|
689
|
+
return
|
|
690
|
+
prev = self._prev_shapes if self._step >= 0 else []
|
|
691
|
+
self._step = k
|
|
692
|
+
self.stepChanged.emit()
|
|
693
|
+
self._rebuild(prev)
|
|
694
|
+
|
|
695
|
+
# ------------------------------------------------------------------ modes and selection
|
|
696
|
+
@Slot(str)
|
|
697
|
+
def setMode(self, m: str):
|
|
698
|
+
if m not in MODES or m == self._mode:
|
|
699
|
+
return
|
|
700
|
+
if self._mode == "present":
|
|
701
|
+
self.stopSpeaking()
|
|
702
|
+
self._mode = m
|
|
703
|
+
if m == "present" and self._program:
|
|
704
|
+
self._rest = explain.rest_pose(self._ev.step(self._program))
|
|
705
|
+
self.modeChanged.emit()
|
|
706
|
+
if m == "reverse":
|
|
707
|
+
self._refresh_report()
|
|
708
|
+
|
|
709
|
+
@Slot(str)
|
|
710
|
+
def select(self, oid: str):
|
|
711
|
+
self._selected = oid
|
|
712
|
+
self.selectionChanged.emit()
|
|
713
|
+
|
|
714
|
+
@Slot(str)
|
|
715
|
+
def setEngine(self, name: str):
|
|
716
|
+
if name and name != self._engine:
|
|
717
|
+
self._engine = name
|
|
718
|
+
self.engineChanged.emit()
|
|
719
|
+
|
|
720
|
+
@Property(str, notify=engineChanged)
|
|
721
|
+
def engine(self):
|
|
722
|
+
"""The engine Specify, Edit, Name parts and Explain use now."""
|
|
723
|
+
return self._engine
|
|
724
|
+
|
|
725
|
+
# ------------------------------------------------------------------ files
|
|
726
|
+
@Slot(str)
|
|
727
|
+
def openFile(self, path: str):
|
|
728
|
+
p = _local(path)
|
|
729
|
+
if p.suffix.lower() in importers.ROUTES:
|
|
730
|
+
return self.importModel(str(p))
|
|
731
|
+
try:
|
|
732
|
+
prog = json.loads(p.read_text())
|
|
733
|
+
self._epoch += 1
|
|
734
|
+
self._project = p.parent
|
|
735
|
+
self._ev = Evaluator(self._project)
|
|
736
|
+
self._history.clear()
|
|
737
|
+
self._future.clear()
|
|
738
|
+
self._geo_cache.clear()
|
|
739
|
+
self._program = None
|
|
740
|
+
self._report = {}
|
|
741
|
+
self._set_program(prog, f"opened {p.name}")
|
|
742
|
+
self._load_explanation()
|
|
743
|
+
self._watch(p)
|
|
744
|
+
except (OSError, json.JSONDecodeError, ProgramError, EvalError) as e:
|
|
745
|
+
self._say(f"open failed: {e}")
|
|
746
|
+
|
|
747
|
+
@Slot(str)
|
|
748
|
+
def importModel(self, path: str):
|
|
749
|
+
self._watch(None)
|
|
750
|
+
"""Reverse engineering: any supported 3D file (mesh, CAD, Blender scene, gallery ZIP) into pieces and
|
|
751
|
+
components, with an evidence ledger."""
|
|
752
|
+
src = _local(path)
|
|
753
|
+
try:
|
|
754
|
+
kind = importers.route(src)
|
|
755
|
+
except ValueError as e:
|
|
756
|
+
return self._say(f"import refused: {e}")
|
|
757
|
+
proj = OUT / "reverse" / (src.stem + time.strftime("-%Y%m%d-%H%M%S"))
|
|
758
|
+
|
|
759
|
+
def job(log):
|
|
760
|
+
log(f"import: {src.name} ({kind.label})")
|
|
761
|
+
proj.mkdir(parents=True, exist_ok=True)
|
|
762
|
+
glb, what = importers.prepare(src, proj / "import", log=log)
|
|
763
|
+
prog, rep = reverse.analyze_mesh(glb, proj)
|
|
764
|
+
rep["input"].update(file=src.name, format=what)
|
|
765
|
+
(proj / "reverse_report.json").write_text(json.dumps(rep, indent=1))
|
|
766
|
+
log(f"reverse: {len(prog['ops'])} pieces, {len(prog['components'])} components, "
|
|
767
|
+
f"{len(rep['ledger'])} ledger entries")
|
|
768
|
+
return {"program": prog, "project": str(proj)}
|
|
769
|
+
self._run_job("Reverse engineering", job, mode_after="reverse")
|
|
770
|
+
|
|
771
|
+
@Slot(str, bool)
|
|
772
|
+
def imageTo3D(self, path: str, single: bool):
|
|
773
|
+
"""Image or character sheet -> a 3D model via Hunyuan3D in ComfyUI."""
|
|
774
|
+
src = _local(path)
|
|
775
|
+
|
|
776
|
+
def job(log):
|
|
777
|
+
log(f"image3d: {src.name}")
|
|
778
|
+
info = pipeline.image_to_mesh(src, single=single, log=log)
|
|
779
|
+
prog = json.loads(Path(info["program"]).read_text())
|
|
780
|
+
log(f"image3d: ready, {info['parts']} part(s), {info['triangles']:,} triangles "
|
|
781
|
+
f"({info['gpu_seconds']} s on the card)")
|
|
782
|
+
return {"program": prog, "project": str(Path(info["program"]).parent)}
|
|
783
|
+
self._run_job("Image to 3D", job, mode_after="reverse")
|
|
784
|
+
|
|
785
|
+
# ------------------------------------------------------------------ edits
|
|
786
|
+
def _commit_op(self, oid: str, mutate, note: str) -> bool:
|
|
787
|
+
try:
|
|
788
|
+
prog = copy.deepcopy(self._program)
|
|
789
|
+
op = next(o for o in prog["ops"] if o["id"] == oid)
|
|
790
|
+
mutate(op)
|
|
791
|
+
self._ev.step(prog) # validates on the shared cache: only the edited op is rebuilt
|
|
792
|
+
keep = self._step
|
|
793
|
+
self._set_program(prog, note, keep_step=True)
|
|
794
|
+
if keep < self.stepCount - 1:
|
|
795
|
+
self.setStep(keep)
|
|
796
|
+
self.select(op["id"])
|
|
797
|
+
return True
|
|
798
|
+
except (StopIteration, json.JSONDecodeError, ProgramError, EvalError, TypeError, ValueError) as e:
|
|
799
|
+
self._say(f"edit rejected: {e}")
|
|
800
|
+
self.selectionChanged.emit()
|
|
801
|
+
return False
|
|
802
|
+
|
|
803
|
+
@Slot(str, str, str, result=bool)
|
|
804
|
+
def setParam(self, oid: str, key: str, value_json: str) -> bool:
|
|
805
|
+
try:
|
|
806
|
+
value = json.loads(value_json)
|
|
807
|
+
except json.JSONDecodeError as e:
|
|
808
|
+
self._say(f"edit rejected: {e}")
|
|
809
|
+
return False
|
|
810
|
+
|
|
811
|
+
def mutate(op):
|
|
812
|
+
if key in ("label", "material"):
|
|
813
|
+
if value in ("", None):
|
|
814
|
+
op.pop(key, None)
|
|
815
|
+
else:
|
|
816
|
+
op[key] = value
|
|
817
|
+
else:
|
|
818
|
+
op.setdefault("params", {})[key] = value
|
|
819
|
+
return self._commit_op(oid, mutate, f"{oid}.{key} = {value_json[:60]}")
|
|
820
|
+
|
|
821
|
+
@Slot(str, float, float, float, result=bool)
|
|
822
|
+
def nudge(self, oid: str, dx: float, dy: float, dz: float) -> bool:
|
|
823
|
+
"""Gizmo move: add to the op's translate (applied last, so it moves the finished part)."""
|
|
824
|
+
def mutate(op):
|
|
825
|
+
t = op.setdefault("params", {}).get("translate", [0, 0, 0])
|
|
826
|
+
op["params"]["translate"] = [round(t[0] + dx, 3), round(t[1] + dy, 3), round(t[2] + dz, 3)]
|
|
827
|
+
return self._commit_op(oid, mutate, f"moved {oid} by ({dx:.1f}, {dy:.1f}, {dz:.1f})")
|
|
828
|
+
|
|
829
|
+
@Slot(str, result=bool)
|
|
830
|
+
def applyOpJson(self, text: str) -> bool:
|
|
831
|
+
try:
|
|
832
|
+
new_op = json.loads(text)
|
|
833
|
+
except json.JSONDecodeError as e:
|
|
834
|
+
self._say(f"edit rejected: {e}")
|
|
835
|
+
return False
|
|
836
|
+
return self._commit_op(self._selected, lambda op: (op.clear(), op.update(new_op)),
|
|
837
|
+
f"edited {new_op.get('id')}")
|
|
838
|
+
|
|
839
|
+
@Slot(str)
|
|
840
|
+
def addPrimitive(self, kind: str):
|
|
841
|
+
"""Tool palette: append a primitive at the origin (or start a new program with it)."""
|
|
842
|
+
defaults = {"box": {"size": [100, 100, 100]}, "cylinder": {"height": 120, "radius": 40},
|
|
843
|
+
"sphere": {"radius": 60}, "torus": {"major_radius": 60, "minor_radius": 15},
|
|
844
|
+
"capsule": {"height": 100, "radius": 30}, "gear": {"teeth": 24, "module": 4, "thickness": 20,
|
|
845
|
+
"bore": 12},
|
|
846
|
+
"helix": {"radius": 30, "pitch": 12, "turns": 6, "wire_radius": 3},
|
|
847
|
+
"loft": {"sections": [{"y": 0, "rx": 60, "rz": 35}, {"y": 80, "radius": 40},
|
|
848
|
+
{"y": 160, "rx": 20, "rz": 45}]},
|
|
849
|
+
"pipe": {"path": [[-80, 20, 0], [0, 120, 0], [80, 20, 0]], "radius": 10, "smooth": 8},
|
|
850
|
+
"tube": {"height": 160, "radius": 60, "wall": 4},
|
|
851
|
+
"nozzle": {"throat_radius": 20, "expansion_ratio": 16, "contraction_ratio": 4},
|
|
852
|
+
"rotor": {"hub_radius": 22, "tip_radius": 90, "chord": 32, "blades": 16},
|
|
853
|
+
"grille": {"size": [140, 3, 140], "hole_size": 8, "hole": "hex"}}
|
|
854
|
+
if kind not in defaults:
|
|
855
|
+
return
|
|
856
|
+
prog = copy.deepcopy(self._program) if self._program else {
|
|
857
|
+
"version": 1, "name": "Untitled build", "units": "mm", "materials": {
|
|
858
|
+
"steel": {"base_color": [0.62, 0.64, 0.68], "metalness": 1.0, "roughness": 0.3}}, "ops": []}
|
|
859
|
+
prog.setdefault("materials", {}).setdefault(
|
|
860
|
+
"steel", {"base_color": [0.62, 0.64, 0.68], "metalness": 1.0, "roughness": 0.3})
|
|
861
|
+
ids = {o["id"] for o in prog["ops"]}
|
|
862
|
+
n = 1
|
|
863
|
+
while f"{kind}_{n}" in ids:
|
|
864
|
+
n += 1
|
|
865
|
+
oid = f"{kind}_{n}"
|
|
866
|
+
prog["ops"].append({"id": oid, "op": kind, "label": f"{kind.title()} {n}", "component": oid,
|
|
867
|
+
"material": "steel", "params": defaults[kind]})
|
|
868
|
+
if "components" in prog:
|
|
869
|
+
prog["components"].append({"id": oid, "label": f"{kind.title()} {n}"})
|
|
870
|
+
self._set_program(prog, f"added {oid}", keep_step=True)
|
|
871
|
+
self.select(oid)
|
|
872
|
+
|
|
873
|
+
@Slot()
|
|
874
|
+
def undo(self):
|
|
875
|
+
if not self._history:
|
|
876
|
+
self._say("nothing to undo")
|
|
877
|
+
return
|
|
878
|
+
self._future.append(self._program)
|
|
879
|
+
self._set_program(self._history.pop(), "undo", keep_step=True, push=False)
|
|
880
|
+
|
|
881
|
+
@Slot()
|
|
882
|
+
def redo(self):
|
|
883
|
+
if not self._future:
|
|
884
|
+
self._say("nothing to redo")
|
|
885
|
+
return
|
|
886
|
+
self._history.append(self._program)
|
|
887
|
+
self._set_program(self._future.pop(), "redo", keep_step=True, push=False)
|
|
888
|
+
|
|
889
|
+
@Slot(str, result=bool)
|
|
890
|
+
def applyMaterial(self, name: str) -> bool:
|
|
891
|
+
"""Material shelf: paint the selected part, or every part of the selected component."""
|
|
892
|
+
if not self._program:
|
|
893
|
+
return False
|
|
894
|
+
ids = [g.shapeId for g in self._shapes
|
|
895
|
+
if g.shapeId == self._selected or g.component == self._selected]
|
|
896
|
+
if not ids and self._op(self._selected):
|
|
897
|
+
ids = [self._selected]
|
|
898
|
+
try:
|
|
899
|
+
prog = materials.apply(copy.deepcopy(self._program), ids, name)
|
|
900
|
+
keep, sel = self._step, self._selected
|
|
901
|
+
self._set_program(prog, f"material {name} on {len(ids)} part(s)", keep_step=True)
|
|
902
|
+
if keep < self.stepCount - 1:
|
|
903
|
+
self.setStep(keep)
|
|
904
|
+
self.select(sel)
|
|
905
|
+
return True
|
|
906
|
+
except (ValueError, ProgramError, EvalError) as e:
|
|
907
|
+
self._say(f"material rejected: {e}")
|
|
908
|
+
return False
|
|
909
|
+
|
|
910
|
+
@Slot(str, str, result=bool)
|
|
911
|
+
def swapMaterial(self, old: str, preset: str) -> bool:
|
|
912
|
+
"""Whole-build material variant: every part made of `old` becomes `preset`, as one undo step."""
|
|
913
|
+
if not self._program:
|
|
914
|
+
return False
|
|
915
|
+
try:
|
|
916
|
+
prog = materials.swap(copy.deepcopy(self._program), old, preset)
|
|
917
|
+
keep, sel = self._step, self._selected
|
|
918
|
+
self._set_program(prog, f"material variant: {old} -> {preset}", keep_step=True)
|
|
919
|
+
if keep < self.stepCount - 1:
|
|
920
|
+
self.setStep(keep)
|
|
921
|
+
self.select(sel)
|
|
922
|
+
return True
|
|
923
|
+
except (ValueError, ProgramError, EvalError) as e:
|
|
924
|
+
self._say(f"material swap rejected: {e}")
|
|
925
|
+
return False
|
|
926
|
+
|
|
927
|
+
@Slot(float)
|
|
928
|
+
def rescale(self, factor: float):
|
|
929
|
+
"""Scale the whole build about the origin, e.g. an import whose units were metres, as one undo step."""
|
|
930
|
+
if not self._program:
|
|
931
|
+
return
|
|
932
|
+
try:
|
|
933
|
+
prog = scale_program(self._program, factor)
|
|
934
|
+
self._ev.step(prog)
|
|
935
|
+
except (ProgramError, EvalError) as e:
|
|
936
|
+
return self._say(f"rescale refused: {e}")
|
|
937
|
+
self._set_program(prog, f"scaled the build by {factor:g}", keep_step=True)
|
|
938
|
+
|
|
939
|
+
@Slot()
|
|
940
|
+
def closeProgram(self):
|
|
941
|
+
"""Back to the start screen."""
|
|
942
|
+
self._epoch += 1
|
|
943
|
+
self._program = None
|
|
944
|
+
self._project = None
|
|
945
|
+
self._watch(None)
|
|
946
|
+
self._history.clear()
|
|
947
|
+
self._future.clear()
|
|
948
|
+
self._geo_cache.clear()
|
|
949
|
+
self._ev = Evaluator()
|
|
950
|
+
self._ops_rows = self._comp_rows = None
|
|
951
|
+
self._prev_shapes = []
|
|
952
|
+
self._step = -1
|
|
953
|
+
self._selected = ""
|
|
954
|
+
self._report = {}
|
|
955
|
+
self._stats = {}
|
|
956
|
+
self._dims = []
|
|
957
|
+
self._explanation = {}
|
|
958
|
+
self._issues, self._issues_of, self._mass, self._measure_job = [], None, None, None
|
|
959
|
+
self._measure_timer.stop()
|
|
960
|
+
self._set_measuring(False)
|
|
961
|
+
self.issuesChanged.emit()
|
|
962
|
+
self.explanationChanged.emit()
|
|
963
|
+
self.stopSpeaking()
|
|
964
|
+
self.programChanged.emit()
|
|
965
|
+
self.historyChanged.emit()
|
|
966
|
+
self.selectionChanged.emit()
|
|
967
|
+
self.stepChanged.emit()
|
|
968
|
+
self.reportChanged.emit()
|
|
969
|
+
self.libraryChanged.emit()
|
|
970
|
+
self._rebuild()
|
|
971
|
+
|
|
972
|
+
# ------------------------------------------------------------------ model jobs
|
|
973
|
+
@Slot(str)
|
|
974
|
+
def dream(self, text: str):
|
|
975
|
+
engine, cfg = self._engine, dict(self._cfg)
|
|
976
|
+
|
|
977
|
+
def job(log):
|
|
978
|
+
sources = None
|
|
979
|
+
if cfg["research"]: # ground the concept in real mechanisms before the blueprint is written
|
|
980
|
+
from ..research import lane
|
|
981
|
+
qs = client.research_queries(text, [], engine, log=log)
|
|
982
|
+
sources = lane.gather(qs, [text], cfg["search_url"], log=log) or None
|
|
983
|
+
return {"program": client.dream(text, engine, log=log, sources=sources)}
|
|
984
|
+
self._run_job("Specifying", job)
|
|
985
|
+
|
|
986
|
+
@Slot(str)
|
|
987
|
+
def edit(self, text: str):
|
|
988
|
+
if not self._program:
|
|
989
|
+
return self.dream(text)
|
|
990
|
+
self._agent_edit("Editing", text)
|
|
991
|
+
|
|
992
|
+
def _agent_edit(self, label: str, text: str, scope: set[str] | None = None):
|
|
993
|
+
base, engine, current = copy.deepcopy(self._program), self._engine, self._program
|
|
994
|
+
|
|
995
|
+
def job(log):
|
|
996
|
+
patch = client.edit(base, text, engine, log=log, scope=scope)
|
|
997
|
+
log(f"patch: {len(patch)} change(s)")
|
|
998
|
+
return {"program": apply_patch(base, patch), "keep": True, "base": current}
|
|
999
|
+
self._run_job(label, job)
|
|
1000
|
+
|
|
1001
|
+
@Slot()
|
|
1002
|
+
def fixIssues(self):
|
|
1003
|
+
"""Hand the critic's measured problems to the model as one scoped edit."""
|
|
1004
|
+
if self._measuring:
|
|
1005
|
+
return self._say("still measuring this version; try again in a moment")
|
|
1006
|
+
if not self._program or not self._issues:
|
|
1007
|
+
return self._say("no accuracy issues to fix")
|
|
1008
|
+
issues = [critique.Issue(**i) for i in self._issues]
|
|
1009
|
+
scope = {o for i in issues if i.subject for o in component_ops(self._program, i.subject)}
|
|
1010
|
+
self._agent_edit("Fixing", client.fix_instruction(issues), scope or None)
|
|
1011
|
+
|
|
1012
|
+
@Slot(str, str)
|
|
1013
|
+
def rework(self, cid: str, text: str):
|
|
1014
|
+
"""Agent edit limited to one component: every op outside it must come back unchanged."""
|
|
1015
|
+
if not self._program or not text.strip():
|
|
1016
|
+
return
|
|
1017
|
+
scope = set(component_ops(self._program, cid))
|
|
1018
|
+
if not scope:
|
|
1019
|
+
return self._say(f"rework: no component {cid}")
|
|
1020
|
+
label = next((c.label for c in self._comps if c.id == cid), cid)
|
|
1021
|
+
self._agent_edit(f"Reworking {label}", f"Rework the part {label!r}: {text.strip()}", scope)
|
|
1022
|
+
|
|
1023
|
+
@Slot(str)
|
|
1024
|
+
def deleteComponent(self, cid: str):
|
|
1025
|
+
try:
|
|
1026
|
+
prog = delete_component(self._program, cid)
|
|
1027
|
+
self._ev.step(prog)
|
|
1028
|
+
except (ProgramError, EvalError, TypeError) as e:
|
|
1029
|
+
return self._say(f"delete refused: {e}")
|
|
1030
|
+
self._selected = ""
|
|
1031
|
+
self._set_program(prog, f"deleted {cid}", keep_step=True)
|
|
1032
|
+
self.selectionChanged.emit()
|
|
1033
|
+
|
|
1034
|
+
@Slot(str)
|
|
1035
|
+
def duplicateComponent(self, cid: str):
|
|
1036
|
+
c = next((c for c in self._comps if c.id == cid), None)
|
|
1037
|
+
if c is None:
|
|
1038
|
+
return self._say(f"duplicate: no component {cid}")
|
|
1039
|
+
try:
|
|
1040
|
+
prog, new = duplicate_component(self._program, cid, [round(float(c.hi[0] - c.lo[0]) * 1.15, 1), 0, 0])
|
|
1041
|
+
self._ev.step(prog)
|
|
1042
|
+
except (ProgramError, EvalError, TypeError) as e:
|
|
1043
|
+
return self._say(f"duplicate refused: {e}")
|
|
1044
|
+
self._set_program(prog, f"duplicated {cid} as {new}", keep_step=True)
|
|
1045
|
+
self.select(new)
|
|
1046
|
+
|
|
1047
|
+
@Slot()
|
|
1048
|
+
def nameParts(self):
|
|
1049
|
+
"""Inferred names for components from their observed measurements (local model, tagged inferred)."""
|
|
1050
|
+
if not self._program:
|
|
1051
|
+
return
|
|
1052
|
+
prog, current = copy.deepcopy(self._program), self._program
|
|
1053
|
+
facts = [{"id": c.id, "current_label": c.label, "pieces": len(c.shapes),
|
|
1054
|
+
"extent": (c.hi - c.lo).round(1).tolist(), "center": c.center.round(1).tolist()}
|
|
1055
|
+
for c in self._comps]
|
|
1056
|
+
context = self.title
|
|
1057
|
+
|
|
1058
|
+
def job(log):
|
|
1059
|
+
names = client.name_components(facts, context, self._engine, log=log)
|
|
1060
|
+
comps = prog.setdefault("components", [{"id": f["id"], "label": f["current_label"]} for f in facts])
|
|
1061
|
+
for c in comps:
|
|
1062
|
+
if c["id"] in names:
|
|
1063
|
+
c["label"] = names[c["id"]].get("label", c.get("label", c["id"]))
|
|
1064
|
+
c["role"] = names[c["id"]].get("role", "")
|
|
1065
|
+
return {"program": prog, "keep": True, "names": names, "base": current}
|
|
1066
|
+
self._run_job("Naming parts", job)
|
|
1067
|
+
|
|
1068
|
+
def _run_job(self, label: str, fn, mode_after: str | None = None):
|
|
1069
|
+
if self._busy:
|
|
1070
|
+
self._say("busy: one job at a time (one GPU)")
|
|
1071
|
+
return
|
|
1072
|
+
local = label.startswith(("Reverse", "Render", "Opening", "Pulling", "Image to 3D", "Drawing"))
|
|
1073
|
+
self.stopSpeaking()
|
|
1074
|
+
self._busy = label if local else f"{label} on {self._engine}"
|
|
1075
|
+
self.busyChanged.emit()
|
|
1076
|
+
self._mode_after = mode_after
|
|
1077
|
+
|
|
1078
|
+
epoch = self._epoch
|
|
1079
|
+
|
|
1080
|
+
def run():
|
|
1081
|
+
try:
|
|
1082
|
+
res = fn(lambda m: self._jobDone.emit(None, "log:" + m))
|
|
1083
|
+
if isinstance(res, dict):
|
|
1084
|
+
res["epoch"] = epoch
|
|
1085
|
+
self._jobDone.emit(res, "done")
|
|
1086
|
+
except Exception as e: # noqa: BLE001 - every failure is reported in the console
|
|
1087
|
+
self._jobDone.emit(None, f"failed: {e}")
|
|
1088
|
+
threading.Thread(target=run, daemon=True).start()
|
|
1089
|
+
|
|
1090
|
+
def _on_job(self, res, msg: str):
|
|
1091
|
+
if msg.startswith("log:"):
|
|
1092
|
+
self._say(msg[4:])
|
|
1093
|
+
return
|
|
1094
|
+
self._busy = ""
|
|
1095
|
+
self.busyChanged.emit()
|
|
1096
|
+
if res is None:
|
|
1097
|
+
self._say(msg)
|
|
1098
|
+
return
|
|
1099
|
+
if res.get("epoch", self._epoch) != self._epoch:
|
|
1100
|
+
if "program" in res and "project" not in res and "base" not in res:
|
|
1101
|
+
OUT.mkdir(parents=True, exist_ok=True)
|
|
1102
|
+
saved = OUT / time.strftime("%Y%m%d-%H%M%S.json")
|
|
1103
|
+
saved.write_text(json.dumps(res["program"], indent=1))
|
|
1104
|
+
self.libraryChanged.emit()
|
|
1105
|
+
return self._say(f"finished after you switched builds; saved to {saved} (open it from Recents)")
|
|
1106
|
+
return self._say("a job finished for a build that is no longer open; its result was dropped")
|
|
1107
|
+
if "note" in res:
|
|
1108
|
+
self._say(res["note"])
|
|
1109
|
+
return
|
|
1110
|
+
if "explanation" in res:
|
|
1111
|
+
self._explanation = res["explanation"]
|
|
1112
|
+
self.explanationChanged.emit()
|
|
1113
|
+
c = self._explanation["counts"]
|
|
1114
|
+
self._say(f"explained: {len(self._explanation['chapters'])} chapters, {c['cited']} cited, "
|
|
1115
|
+
f"{c['measured']} measured, {c['concept']} concept, {self._explanation['dropped']} dropped")
|
|
1116
|
+
self.setMode("present")
|
|
1117
|
+
return
|
|
1118
|
+
if "sheet" in res:
|
|
1119
|
+
self._sheet = res["sheet"]
|
|
1120
|
+
self.sheetChanged.emit()
|
|
1121
|
+
return self._say(f"blueprint sheet ready ({self._sheet['seconds']} s): {self._sheet['svg']}")
|
|
1122
|
+
if "render" in res:
|
|
1123
|
+
self._render_path = res["render"]
|
|
1124
|
+
self.renderChanged.emit()
|
|
1125
|
+
self._say(f"render ready ({res.get('seconds', 0):.0f} s): {res['render']}")
|
|
1126
|
+
return
|
|
1127
|
+
prog = res.get("program")
|
|
1128
|
+
if prog is None:
|
|
1129
|
+
return
|
|
1130
|
+
if "base" in res and res["base"] is not self._program:
|
|
1131
|
+
self._say("agent result dropped: the build changed while the model was working (nothing lost; ask again)")
|
|
1132
|
+
return
|
|
1133
|
+
if "project" in res:
|
|
1134
|
+
self._project = Path(res["project"])
|
|
1135
|
+
self._watch(None)
|
|
1136
|
+
self._ev = Evaluator(self._project)
|
|
1137
|
+
self._history.clear()
|
|
1138
|
+
self._future.clear()
|
|
1139
|
+
self._geo_cache.clear()
|
|
1140
|
+
self._program = None
|
|
1141
|
+
elif "names" not in res:
|
|
1142
|
+
OUT.mkdir(parents=True, exist_ok=True)
|
|
1143
|
+
(OUT / time.strftime("%Y%m%d-%H%M%S.json")).write_text(json.dumps(prog, indent=1))
|
|
1144
|
+
self.libraryChanged.emit()
|
|
1145
|
+
self._set_program(prog, f"built: {prog.get('name', '')} ({len(prog['ops'])} steps)",
|
|
1146
|
+
keep_step=res.get("keep", False) or bool(self._mode_after))
|
|
1147
|
+
if "keep" not in res:
|
|
1148
|
+
self._load_explanation()
|
|
1149
|
+
if self._mode_after:
|
|
1150
|
+
self.setMode(self._mode_after)
|
|
1151
|
+
self._mode_after = None
|
|
1152
|
+
if "names" in res:
|
|
1153
|
+
self._report.setdefault("ledger", []).extend(
|
|
1154
|
+
reverse.ledger_entry(f"{v.get('label')}: {v.get('role', '')}", "inferred",
|
|
1155
|
+
f"local model {self._engine}, from observed size and position", subject=k,
|
|
1156
|
+
confidence=v.get("confidence", 0.5)) for k, v in res["names"].items())
|
|
1157
|
+
for item in self._report.get("checklist", []):
|
|
1158
|
+
if item["q"].startswith("What is each part called"):
|
|
1159
|
+
item.update(status="partly answered", by=f"inferred by {self._engine}")
|
|
1160
|
+
if self._project and (self._project / "reverse_report.json").exists():
|
|
1161
|
+
(self._project / "reverse_report.json").write_text(json.dumps(self._report, indent=1))
|
|
1162
|
+
self.reportChanged.emit()
|
|
1163
|
+
|
|
1164
|
+
# ------------------------------------------------------------------ export and render
|
|
1165
|
+
@Slot(str, result=str)
|
|
1166
|
+
def exportAs(self, fmt: str) -> str:
|
|
1167
|
+
if not self._program or fmt not in ("glb", "stl", "obj", "3mf", "step", "sim", "dxf"):
|
|
1168
|
+
return ""
|
|
1169
|
+
name = "".join(c if c.isalnum() else "-" for c in self.title.lower()).strip("-") or "build"
|
|
1170
|
+
if fmt == "sim":
|
|
1171
|
+
return self._export_sim(name)
|
|
1172
|
+
path, n = OUT / f"{name}.{fmt}", 2
|
|
1173
|
+
while path.exists(): # never overwrite an earlier export
|
|
1174
|
+
path, n = OUT / f"{name}-{n}.{fmt}", n + 1
|
|
1175
|
+
try:
|
|
1176
|
+
OUT.mkdir(parents=True, exist_ok=True)
|
|
1177
|
+
shapes = self._ev.step(self._program)
|
|
1178
|
+
if fmt in ("stl", "step") and any(isinstance(s.manifold, RawMesh) for s in shapes):
|
|
1179
|
+
raise ValueError(f"imported pieces that are not watertight cannot go to {fmt.upper()}")
|
|
1180
|
+
if fmt == "dxf":
|
|
1181
|
+
from ..core import dxf
|
|
1182
|
+
dxf.write(shapes, path, self._program.get("units", "mm"))
|
|
1183
|
+
self._say(f"exported {path} (views at full size, {self._program.get('units', 'mm')})")
|
|
1184
|
+
return str(path)
|
|
1185
|
+
exporter.export(shapes, self._program.get("materials", {}), path, name=self.title,
|
|
1186
|
+
units=self._program.get("units", "mm"), printer=printers.active(self._cfg))
|
|
1187
|
+
self._say(f"exported {path}")
|
|
1188
|
+
return str(path)
|
|
1189
|
+
except (OSError, ValueError, EvalError, ImportError) as e:
|
|
1190
|
+
path.unlink(missing_ok=True)
|
|
1191
|
+
self._say(f"export failed: {e}" + (" (3MF needs core support that is not installed)" if fmt == "3mf" else ""))
|
|
1192
|
+
return ""
|
|
1193
|
+
|
|
1194
|
+
def _export_sim(self, name: str) -> str:
|
|
1195
|
+
"""URDF and MJCF side by side in a new folder, with one STL per component in meshes/."""
|
|
1196
|
+
from ..core import robot
|
|
1197
|
+
folder, n = OUT / f"{name}-sim", 2
|
|
1198
|
+
while folder.exists():
|
|
1199
|
+
folder, n = OUT / f"{name}-sim-{n}", n + 1
|
|
1200
|
+
try:
|
|
1201
|
+
shapes = self._ev.step(self._program)
|
|
1202
|
+
folder.mkdir(parents=True)
|
|
1203
|
+
robot.write(self._program, shapes, folder / f"{name}.urdf")
|
|
1204
|
+
robot.write(self._program, shapes, folder / f"{name}.xml")
|
|
1205
|
+
self._say(f"exported URDF and MJCF to {folder}")
|
|
1206
|
+
return str(folder)
|
|
1207
|
+
except (OSError, ValueError, EvalError) as e:
|
|
1208
|
+
self._say(f"simulator export failed: {e}")
|
|
1209
|
+
return ""
|
|
1210
|
+
|
|
1211
|
+
@Slot(str)
|
|
1212
|
+
def renderShowcase(self, camera_json: str):
|
|
1213
|
+
"""Path-traced still from the current camera: Blender Cycles on the CPU (no GPU), OIDN denoised."""
|
|
1214
|
+
if not self._program:
|
|
1215
|
+
return
|
|
1216
|
+
from ..core import render
|
|
1217
|
+
try:
|
|
1218
|
+
cam = json.loads(camera_json)
|
|
1219
|
+
work = OUT / "renders"
|
|
1220
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
1221
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
1222
|
+
shapes = self._ev.step(self._program)
|
|
1223
|
+
glb = exporter.export(shapes, self._program.get("materials", {}), work / f"{stamp}.glb")
|
|
1224
|
+
except (OSError, ValueError, EvalError) as e:
|
|
1225
|
+
return self._say(f"render failed: {e}")
|
|
1226
|
+
mats = self._program.get("materials", {})
|
|
1227
|
+
part_mats = {s.id: s.material for s in shapes if s.material}
|
|
1228
|
+
ground = self._ground
|
|
1229
|
+
|
|
1230
|
+
def job(log):
|
|
1231
|
+
log("render: Blender Cycles on the CPU (32 threads), about a minute")
|
|
1232
|
+
t = time.time()
|
|
1233
|
+
png = render.cycles_still(glb, work / f"{stamp}.png", cam, mats, ground=ground, log=log,
|
|
1234
|
+
part_materials=part_mats)
|
|
1235
|
+
return {"render": str(png), "seconds": time.time() - t}
|
|
1236
|
+
self._run_job("Rendering (Cycles, CPU)", job)
|
|
1237
|
+
|
|
1238
|
+
@Slot()
|
|
1239
|
+
def openInBlender(self):
|
|
1240
|
+
"""Hand the build to Blender (mcp-for-blender socket on localhost:9876) for agents or hand edits."""
|
|
1241
|
+
if not self._program:
|
|
1242
|
+
return
|
|
1243
|
+
from ..core import blender_link
|
|
1244
|
+
try:
|
|
1245
|
+
work = OUT / "blender"
|
|
1246
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
1247
|
+
shapes = self._ev.step(self._program)
|
|
1248
|
+
glb = exporter.export(shapes, self._program.get("materials", {}),
|
|
1249
|
+
work / time.strftime("%Y%m%d-%H%M%S.glb"))
|
|
1250
|
+
except (OSError, ValueError, EvalError) as e:
|
|
1251
|
+
return self._say(f"Blender hand-off failed: {e}")
|
|
1252
|
+
mats = self._program.get("materials", {})
|
|
1253
|
+
labels = {c.id: c.label for c in assembly.components(self._program, shapes)}
|
|
1254
|
+
parts = {s.id: {"id": s.id, "label": s.label, "component": s.component,
|
|
1255
|
+
"component_label": labels.get(s.component, s.component), "material": s.material}
|
|
1256
|
+
for s in shapes}
|
|
1257
|
+
|
|
1258
|
+
def job(log):
|
|
1259
|
+
if blender_link.is_up():
|
|
1260
|
+
raise RuntimeError("a Blender with the MCP socket is already open (localhost:9876); close it first")
|
|
1261
|
+
blender_link.open_in_blender(glb, mats, parts)
|
|
1262
|
+
log("blender: starting (CUDA hidden, update check off)")
|
|
1263
|
+
if not blender_link.wait_up(60):
|
|
1264
|
+
raise RuntimeError("Blender opened but the MCP socket did not come up on localhost:9876")
|
|
1265
|
+
info = blender_link.send("get_scene_info")
|
|
1266
|
+
log(f"blender: MCP socket up on localhost:9876 ({info.get('status')})")
|
|
1267
|
+
return {"note": "Blender is live: agents can drive it through mcp-for-blender; Pull brings it back."}
|
|
1268
|
+
self._run_job("Opening Blender", job)
|
|
1269
|
+
|
|
1270
|
+
@Slot()
|
|
1271
|
+
def pullFromBlender(self):
|
|
1272
|
+
"""Bring the live Blender scene back as a reverse-engineered program (Dissect, Timeline, Showcase)."""
|
|
1273
|
+
from ..core import blender_link
|
|
1274
|
+
dest = OUT / "blender" / time.strftime("pulled-%Y%m%d-%H%M%S.glb")
|
|
1275
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
1276
|
+
proj = OUT / "reverse" / dest.stem
|
|
1277
|
+
|
|
1278
|
+
def job(log):
|
|
1279
|
+
if not blender_link.is_up():
|
|
1280
|
+
raise RuntimeError("no Blender MCP socket on localhost:9876 (use Open in Blender first)")
|
|
1281
|
+
blender_link.pull_scene(dest)
|
|
1282
|
+
log(f"blender: exported {dest.name}; reverse engineering it")
|
|
1283
|
+
proj.mkdir(parents=True, exist_ok=True)
|
|
1284
|
+
prog, rep = reverse.analyze_mesh(dest, proj)
|
|
1285
|
+
prog["name"] = "Reverse: from Blender"
|
|
1286
|
+
return {"program": prog, "project": str(proj)}
|
|
1287
|
+
self._run_job("Pulling from Blender", job, mode_after="reverse")
|
|
1288
|
+
|
|
1289
|
+
@Slot()
|
|
1290
|
+
def clearRender(self):
|
|
1291
|
+
if self._render_path:
|
|
1292
|
+
self._render_path = ""
|
|
1293
|
+
self.renderChanged.emit()
|
|
1294
|
+
|
|
1295
|
+
# ------------------------------------------------------------------ explain
|
|
1296
|
+
@Slot()
|
|
1297
|
+
def explain(self):
|
|
1298
|
+
"""How the open object works: research lane -> local model -> every sentence checked (core/explain.py)."""
|
|
1299
|
+
if not self._program:
|
|
1300
|
+
return
|
|
1301
|
+
prog, comps, dims = self._program, list(self._comps), list(self._dims)
|
|
1302
|
+
subject = self.title.removeprefix("Reverse: ")
|
|
1303
|
+
bp = prog.get("blueprint") or {}
|
|
1304
|
+
dreamed = bool(bp.get("parts"))
|
|
1305
|
+
origin = ("a concept dreamed by a local model from a text prompt" if dreamed else
|
|
1306
|
+
"a 3D shape generated from a picture" if prog.get("reference") else
|
|
1307
|
+
"an imported 3D model that was taken apart into pieces" if subject != self.title else
|
|
1308
|
+
"a model built by hand in the workshop")
|
|
1309
|
+
facts = explain.component_facts(comps, dims, prog.get("units", "mm"))
|
|
1310
|
+
glance = explain.at_a_glance(subject, comps, dims, prog.get("units", "mm"))
|
|
1311
|
+
rest = explain.rest_pose(self._ev.step(prog))
|
|
1312
|
+
engine, cfg, project = self._engine, dict(self._cfg), self._project
|
|
1313
|
+
labels = [c.label for c in comps if not c.label.lower().startswith(("detached", "piece", "body"))]
|
|
1314
|
+
|
|
1315
|
+
def job(log):
|
|
1316
|
+
from ..research import lane
|
|
1317
|
+
sources = [dict(s) for s in bp.get("sources", [])]
|
|
1318
|
+
if cfg["research"]:
|
|
1319
|
+
qs = client.research_queries(subject + (". " + bp.get("summary", "") if bp.get("summary") else ""),
|
|
1320
|
+
labels, engine, log=log)
|
|
1321
|
+
found = lane.gather(qs, [subject] + labels, cfg["search_url"], log=log)
|
|
1322
|
+
sources = [s.as_dict() for s in found] or sources
|
|
1323
|
+
else:
|
|
1324
|
+
log("explain: web research is off (Preferences); only measurements"
|
|
1325
|
+
+ (" and concept reasoning" if dreamed else "") + " can be shown")
|
|
1326
|
+
block = lane.context_block([lane.Source(**s) for s in sources])
|
|
1327
|
+
raw = client.explain(subject, origin, facts, block, engine, log=log)
|
|
1328
|
+
checked = explain.verify(raw, sources, facts, force_concept=dreamed)
|
|
1329
|
+
doc = explain.finish(subject, checked, glance, sources, rest, engine)
|
|
1330
|
+
doc["research"] = bool(cfg["research"])
|
|
1331
|
+
if project:
|
|
1332
|
+
(project / "explanation.json").write_text(json.dumps(doc, indent=1))
|
|
1333
|
+
return {"explanation": doc}
|
|
1334
|
+
self._run_job("Explaining", job)
|
|
1335
|
+
|
|
1336
|
+
@Slot(str, str)
|
|
1337
|
+
def setService(self, key: str, value_json: str):
|
|
1338
|
+
if key not in config.DEFAULTS:
|
|
1339
|
+
return
|
|
1340
|
+
try:
|
|
1341
|
+
v = json.loads(value_json)
|
|
1342
|
+
except ValueError:
|
|
1343
|
+
return
|
|
1344
|
+
if not isinstance(v, type(config.DEFAULTS[key])):
|
|
1345
|
+
return
|
|
1346
|
+
self._cfg[key] = v.strip() if isinstance(v, str) else v
|
|
1347
|
+
config.save(self._cfg)
|
|
1348
|
+
self.servicesChanged.emit()
|
|
1349
|
+
|
|
1350
|
+
# ------------------------------------------------------------------ voice (optional; CPU only)
|
|
1351
|
+
@Slot(str)
|
|
1352
|
+
def speak(self, text: str):
|
|
1353
|
+
"""Read `text` aloud. Emits voiceChanged when it starts and when it ends."""
|
|
1354
|
+
self.stopSpeaking()
|
|
1355
|
+
if not text.strip():
|
|
1356
|
+
return
|
|
1357
|
+
self._say_token += 1
|
|
1358
|
+
token, cfg = self._say_token, dict(self._cfg)
|
|
1359
|
+
self._speaking = True
|
|
1360
|
+
self.voiceChanged.emit()
|
|
1361
|
+
|
|
1362
|
+
def run():
|
|
1363
|
+
try:
|
|
1364
|
+
wav = voice.synthesize(text, cfg)
|
|
1365
|
+
if token != self._say_token:
|
|
1366
|
+
return
|
|
1367
|
+
self._player = voice.player(wav)
|
|
1368
|
+
self._player.wait()
|
|
1369
|
+
wav.unlink(missing_ok=True)
|
|
1370
|
+
self._voiceEvent.emit("said", str(token))
|
|
1371
|
+
except Exception as e: # noqa: BLE001 - reported in the console, the presentation carries on silently
|
|
1372
|
+
self._voiceEvent.emit("error", f"{token}|voice: {e}")
|
|
1373
|
+
threading.Thread(target=run, daemon=True).start()
|
|
1374
|
+
|
|
1375
|
+
@Slot()
|
|
1376
|
+
def stopSpeaking(self):
|
|
1377
|
+
self._say_token += 1
|
|
1378
|
+
if self._player and self._player.poll() is None:
|
|
1379
|
+
self._player.terminate()
|
|
1380
|
+
self._player = None
|
|
1381
|
+
if self._speaking:
|
|
1382
|
+
self._speaking = False
|
|
1383
|
+
self.voiceChanged.emit()
|
|
1384
|
+
|
|
1385
|
+
@Slot()
|
|
1386
|
+
def toggleDictation(self):
|
|
1387
|
+
"""First call starts recording the microphone, the second stops it and transcribes (signal `dictated`)."""
|
|
1388
|
+
if self._rec is None:
|
|
1389
|
+
try:
|
|
1390
|
+
self._rec = voice.recorder()
|
|
1391
|
+
except RuntimeError as e:
|
|
1392
|
+
self._say(f"dictation: {e}")
|
|
1393
|
+
return
|
|
1394
|
+
self._listening = True
|
|
1395
|
+
self.voiceChanged.emit()
|
|
1396
|
+
return
|
|
1397
|
+
proc, wav = self._rec
|
|
1398
|
+
self._rec = None
|
|
1399
|
+
proc.terminate()
|
|
1400
|
+
self._listening = False
|
|
1401
|
+
self.voiceChanged.emit()
|
|
1402
|
+
cfg = dict(self._cfg)
|
|
1403
|
+
|
|
1404
|
+
def run():
|
|
1405
|
+
try:
|
|
1406
|
+
proc.wait(timeout=5)
|
|
1407
|
+
self._voiceEvent.emit("heard", voice.transcribe(wav, cfg))
|
|
1408
|
+
except Exception as e: # noqa: BLE001
|
|
1409
|
+
self._voiceEvent.emit("error", f"0|dictation: {e}")
|
|
1410
|
+
finally:
|
|
1411
|
+
wav.unlink(missing_ok=True)
|
|
1412
|
+
threading.Thread(target=run, daemon=True).start()
|
|
1413
|
+
|
|
1414
|
+
def _on_voice(self, kind: str, payload: str):
|
|
1415
|
+
if kind == "heard":
|
|
1416
|
+
self._say(f"dictation: “{payload}”")
|
|
1417
|
+
self.dictated.emit(payload)
|
|
1418
|
+
elif kind == "said":
|
|
1419
|
+
if payload == str(self._say_token) and self._speaking:
|
|
1420
|
+
self._speaking = False
|
|
1421
|
+
self.voiceChanged.emit()
|
|
1422
|
+
else:
|
|
1423
|
+
token, _, msg = payload.partition("|")
|
|
1424
|
+
self._say(msg)
|
|
1425
|
+
if token in ("0", str(self._say_token)) and self._speaking:
|
|
1426
|
+
self._speaking = False
|
|
1427
|
+
self.voiceChanged.emit()
|