editor: the new SDK operations through the sketch document and the assembly document

/api/sketch/op reaches fillet_corner, chamfer_corner and project (the source is another sketch feature of the notebook, named by
from_sketch); the assembly document can carry an exploded view: the product becomes scad.explode_rassembly of the solved assembly
and the factor is a slider variable.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-11-03 03:19:55 +08:00
parent a4ddd705aa
commit f2aa06e122
6 changed files with 97 additions and 6 deletions
+26 -4
View File
@@ -121,7 +121,20 @@ def validate(doc: Mapping[str, Any]) -> dict[str, Any]:
constraints.append(item)
if constraints and ground is None:
raise AssemblyError("constraints need a grounded component: the solver moves everything else relative to it")
return {"components": components, "ground": ground, "constraints": constraints}
explode = doc.get("explode")
clean: dict[str, Any] = {"components": components, "ground": ground, "constraints": constraints}
if explode is not None:
if not isinstance(explode, Mapping):
raise AssemblyError("explode is {factor, center?, axis?}")
item = {"factor": _number(explode.get("factor", 0.0), "explode factor")}
for key, size in (("center", 3), ("axis", 3)):
if explode.get(key) is not None:
vec = explode[key]
if not (isinstance(vec, (list, tuple)) and len(vec) == size):
raise AssemblyError(f"explode {key}: three numbers")
item[key] = [_number(v, f"explode {key}") for v in vec]
clean["explode"] = item
return clean
def _ref(side: Mapping[str, str]) -> str:
@@ -141,8 +154,9 @@ def render(slug: str, name: str, doc: Mapping[str, Any], notebook_dir: Path | No
variable = f"{slug}_{key}".upper()
step = "1.0" if high - low >= 20 else "0.1"
params.append(
f"{variable} = scad.var(name={json.dumps(variable.lower())}, default={_num(value)}, unit={json.dumps(unit)}, "
f"comment={json.dumps(label)}) # ui: slider({_num(low)}, {_num(high)}, step={step}, label={json.dumps(label)})"
f"{variable} = scad.var(name={json.dumps(variable.lower())}, default={_num(value)}, "
+ (f"unit={json.dumps(unit)}, " if unit else "")
+ f"comment={json.dumps(label)}) # ui: slider({_num(low)}, {_num(high)}, step={step}, label={json.dumps(label)})"
)
var[key] = variable
return variable
@@ -188,7 +202,15 @@ def render(slug: str, name: str, doc: Mapping[str, Any], notebook_dir: Path | No
a_name, b_name = ("pitch_radius_a", "pitch_radius_b") if kind == "gear" else ("pulley_radius_a", "pulley_radius_b")
phase = f", phase_offset={_num(con['phase'])}" if "phase" in con else ""
lines.append(head + f"connector_a={_ref(con['a'])}, connector_b={_ref(con['b'])}, {a_name}={_num(con[a_name])}, {b_name}={_num(con[b_name])}{phase}")
lines.append(f"{slug} = scad.solve_assembly_constraints_rassembly(assembly=_assembly)" if doc["constraints"] else f"{slug} = _assembly")
solved = "scad.solve_assembly_constraints_rassembly(assembly=_assembly)" if doc["constraints"] else "_assembly"
if "explode" in doc:
# the product is the exploded view; the factor is a slider (0 puts everything back)
factor = slider("explode", "explode factor", doc["explode"]["factor"], "", 0.0, max(2.0, doc["explode"]["factor"] * 2))
extra = "".join(f", {k}=({', '.join(_num(v) for v in doc['explode'][k])})" for k in ("center", "axis") if k in doc["explode"])
lines.append(f"_solved = {solved}")
lines.append(f"{slug} = scad.explode_rassembly(assembly=_solved, factor={factor}{extra})")
else:
lines.append(f"{slug} = {solved}")
return {"params": params, "uses": uses, "layout": lines}
+8
View File
@@ -186,6 +186,14 @@ class FeatureService:
out[spec.id] = chosen
return out
def sketch_document(self, ref: str) -> dict[str, Any] | None:
"""The document of the sketch feature named *ref* (slug or cell), or ``None``."""
for feature in self.snapshot()["features"]:
gui = feature["gui"]
if ref in (feature["slug"], feature["cell"]) and gui and gui["spec"] == "sketch":
return gui["values"].get("sketch")
return None
# -- commands -----------------------------------------------------------------------------------------------------
def add(self, request: Mapping[str, Any]) -> dict[str, Any]:
with self._lock:
+7 -1
View File
@@ -2044,7 +2044,13 @@ def create_app(state: WorkspaceState) -> Starlette:
return JSONResponse({"ok": False, "error": "body is not JSON"}, status_code=400)
body = body if isinstance(body, dict) else {}
try:
result = await asyncio.to_thread(apply_edit, body.get("sketch") or {}, str(body.get("op", "")), body.get("args") or {})
args = dict(body.get("args") or {})
if "from_sketch" in args: # project: name another sketch feature of this notebook as the source
source = state.features.sketch_document(str(args.pop("from_sketch")))
if source is None:
return JSONResponse({"ok": False, "error": "from_sketch: there is no such sketch feature in this notebook"}, status_code=400)
args["source_doc"] = source
result = await asyncio.to_thread(apply_edit, body.get("sketch") or {}, str(body.get("op", "")), args)
except SketchError as exc:
return JSONResponse({"ok": False, "error": str(exc)}, status_code=400)
return JSONResponse({"ok": True, **result})
+3 -1
View File
@@ -307,7 +307,7 @@ def solve(doc: Mapping[str, Any], *, max_profiles: int = 16) -> dict[str, Any]:
# only how a GUI holds a sketch. These adapters turn a document into an SDK ``Sketch``, call the operation by its SDK name and
# turn the result back into a document: there is no geometry here.
EDIT_OPERATIONS = frozenset({"trim", "extend"}) # the SDK's ``<name>_rsketch`` functions that edit a sketch (add more as the SDK gains them)
EDIT_OPERATIONS = frozenset({"trim", "extend", "fillet_corner", "chamfer_corner", "project"}) # the SDK's ``<name>_rsketch`` functions that edit a sketch (add more as the SDK gains them)
def to_sketch(doc: Mapping[str, Any]) -> Any:
@@ -383,6 +383,8 @@ def apply_edit(doc: Mapping[str, Any], operation: str, args: Mapping[str, Any])
kwargs = dict(args)
if "at" in kwargs and isinstance(kwargs["at"], (list, tuple)):
kwargs["at"] = tuple(kwargs["at"])
if "source_doc" in kwargs: # project_rsketch takes another sketch: the caller sends its document
kwargs["source"] = to_sketch(kwargs.pop("source_doc"))
before = to_sketch(doc)
try:
after = getattr(scad, f"{operation}_rsketch")(sketch=before, **kwargs)
+31
View File
@@ -181,3 +181,34 @@ def test_connectors_of_a_gui_part_are_written_into_its_product_cell_and_read_bac
if state.kernel is not None:
state.kernel.stop()
server.should_exit = True
def test_an_exploded_view_is_the_product_and_its_factor_is_a_slider(tmp_path):
import uvicorn
from simplecadapi.editor.server import WorkspaceState, create_app
from simplecadapi.editor.templates import create_notebook
from test_editor_features import _wait_idle
_write_part(tmp_path, "base")
_write_part(tmp_path, "arm")
path = create_notebook(tmp_path, "view", "blank")
state = WorkspaceState(tmp_path)
state.port = 17738
server = uvicorn.Server(uvicorn.Config(create_app(state), port=state.port, log_level="error"))
threading.Thread(target=server.run, daemon=True).start()
state.hub.attach_loop(__import__("asyncio").new_event_loop())
try:
state.start_kernel(path)
doc = copy.deepcopy(DOC) | {"explode": {"factor": 1.0}}
state.features.add({"spec": "assembly", "name": "view", "values": {"assembly": doc}})
_wait_idle(state)
snap = state.features.snapshot()
assert all(not f["errors"] for f in snap["features"]), snap["features"]
text = path.read_text()
assert "view = scad.explode_rassembly(assembly=_solved, factor=VIEW_EXPLODE)" in text and "VIEW_EXPLODE = scad.var(" in text
assert snap["assembly"]["doc"]["explode"]["factor"] == 1.0
finally:
if state.kernel is not None:
state.kernel.stop()
server.should_exit = True
+22
View File
@@ -97,3 +97,25 @@ def test_an_agent_trims_a_sketch_feature_from_the_command_line(tmp_path, monkeyp
if state.kernel is not None:
state.kernel.stop()
server.should_exit = True
def _corner():
return _doc({"a": (0, 0), "b": (10, 0), "c": (10, 10)}, [_line("l0", "a", "b"), _line("l1", "b", "c")])
def test_fillet_and_chamfer_corner_are_sdk_operations_reached_through_the_document():
filleted = S.apply_edit(_corner(), "fillet_corner", {"a": "l0", "b": "l1", "radius": 2.0})
assert any(e["kind"] == "arc" for e in filleted["sketch"]["entities"]) and filleted["created"]
chamfered = S.apply_edit(_corner(), "chamfer_corner", {"a": "l0", "b": "l1", "distance": 2.0})
assert not any(e["kind"] == "arc" for e in chamfered["sketch"]["entities"]) and len(chamfered["sketch"]["entities"]) == 3
with pytest.raises(S.SketchError):
S.apply_edit(_corner(), "fillet_corner", {"a": "l0", "b": "l1", "radius": 50.0})
def test_project_brings_another_sketchs_geometry_in_as_fixed_reference():
source = _doc({"s": (2, 3), "t": (8, 3)}, [_line("edge", "s", "t")])
target = _doc({"o": (0, 0)}, [])
answer = S.apply_edit(target, "project", {"source_doc": source})
projected = [e for e in answer["sketch"]["entities"] if e["id"].startswith("proj_")]
assert projected and all(e["construction"] for e in projected)
assert any(c["kind"] == "fix" for c in answer["sketch"]["constraints"])