diff --git a/README.md b/README.md index 9914006..4d419ce 100644 --- a/README.md +++ b/README.md @@ -447,7 +447,16 @@ headlessly in a scratch directory, forcing two machine facts the stock presets get wrong: the nozzle type the printer reports and the build plate declared in its profile. The resulting `.3mf` is then validated and queued like any other upload, and the job carries `provenance` (source mesh hash, presets, slicer -version). Slicing runs inline in the request. +version, placement). Slicing runs inline in the request. + +By default the slicer centres the part. The optional form field +`placement=front_left` instead puts its footprint `slicer.placement_margin_mm` +(default 10 mm, room for a brim) in from the front-left corner of the printable +area, resting on the plate and keeping its orientation. The gateway wraps the +mesh in a one-object 3MF whose build transform carries the offset and slices +with `--arrange 0`, since the CLI drops a bare STL off the plate when arrange +is off. On the A1 this keeps the part clear of the purge line, which runs along +the front edge at X 108-158. For A1 server-side PLA slicing, add the following alongside existing printer entries under `slicer.machine_profiles` in the local configuration: @@ -458,10 +467,20 @@ bambu_a1_01: process: 0.20mm Standard @BBL A1 filaments: PLA: Generic PLA @BBL A1 + end_bed_y_mm: 250 # optional: park the bed forward for pickup ``` +`end_bed_y_mm` rewrites the Y of the stock end gcode's final park move (the +A1's `G1 X-48 Y180 F3600`, just before the motors are released) so a finished +plate is presented further forward; on the A1 a larger Y moves the bed toward +the front. It must lie within the printable area, and a preset whose end gcode +has no such move is refused rather than guessed at. The value is recorded as +`provenance.end_bed_y_mm` and returned by `pickup-targets` as `bed_park_y_mm`, +because object positions move with the bed. + Agents upload multipart fields `file=design.stl`, -`target_machine=bambu_a1_01`, and `material=PLA` to `POST /submissions` +`target_machine=bambu_a1_01`, `material=PLA` and optionally +`placement=front_left` to `POST /submissions` through the authenticated edge with their own API key and `X-Agent-Id`. A1 agent mode must be on. There is no separate `/slice` endpoint. HTTP 201 returns a stored submission; inspect its validation and state before approval. diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 788d70f..33338ab 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -89,6 +89,11 @@ does not affect validation or establish physical spool identity after a swap. `POST /submissions` accepts an artifact (`.3mf`, `.gcode`, or `.stl` where slicing is enabled for the target; `.stl` requires `material`) and metadata, validates it, and queues passing jobs. A sliced job carries `provenance`. +For an `.stl`, optional `placement` is `auto` (default: the slicer centres the +part) or `front_left` (the part's footprint `slicer.placement_margin_mm`, +default 10 mm, in from the front-left corner of the printable area, resting on +the plate, orientation unchanged). A part that does not fit there is refused +with 422; `placement` on a `.3mf` or `.gcode` is refused with 422. Approval and cancellation update gateway records only, and approval alone does not establish a filament-to-slot mapping or sufficient remaining quantity. @@ -178,7 +183,13 @@ the file does not say. There is no robot frame; the arm agent owns calibration. `GET /submissions/{id}/pickup-targets` returns those objects with `bed_size_mm`, `pickup: {bed_temperature_c, safe_bed_temperature_c, cooled, observed_at}` from the monitor's cache, and `ready` (finished, cooled, and at -least one object). It never contacts a printer or a robot. +least one object). It never contacts a printer or a robot. `bed_park_y_mm` is +the Y axis position the job's end gcode left the bed at, when the gateway set +it while slicing (`slicer.machine_profiles..end_bed_y_mm`); `null` means +unknown (the stock end move, or a file sliced elsewhere). Object positions are +in the bed's own frame and move with the bed: on a bed-slinger such as the A1, +parking at Y 250 instead of the stock Y 180 puts every object 70 mm further +toward the front of the printer. `GET /events?after=` is a pollable lifecycle feed: `job.started`, `job.finished`, `job.failed`, `job.rejected`, `job.cancelled`, `job.cooled` diff --git a/printers.example.yaml b/printers.example.yaml index bed14f7..abb0e0a 100644 --- a/printers.example.yaml +++ b/printers.example.yaml @@ -65,6 +65,7 @@ slicer: profiles_dir: /home/you/.local/opt/bambu-studio/squashfs-root/resources/profiles/BBL work_dir: var/slicer timeout_s: 600 + placement_margin_mm: 10 # gap to the bed edges for placement=front_left # Defaults for a printer that does not name its own process or filaments. process_profile: "0.20mm Standard @BBL X1C" filament_profiles: # material a submitter names -> filament preset @@ -82,6 +83,7 @@ slicer: # process: "0.20mm Standard @BBL A1" # filaments: # PLA: "Bambu PLA Basic @BBL A1" + # end_bed_y_mm: 250 # park the bed forward when done (stock Y180) printers: - id: bambu_x1c_01 diff --git a/src/bambu_server/agent_workflow.py b/src/bambu_server/agent_workflow.py index 824ac2c..ee04a65 100644 --- a/src/bambu_server/agent_workflow.py +++ b/src/bambu_server/agent_workflow.py @@ -233,5 +233,10 @@ class PickupInfo(BaseModel): ready: bool reason: str bed_size_mm: tuple[float, float] | None = None + #: The Y axis position the job's end gcode parked the bed at, when the + #: gateway set it while slicing. Object positions are in the bed's own + #: frame and move with it, so the arm needs this to find them; None means + #: unknown (the stock end move, or a file sliced elsewhere). + bed_park_y_mm: float | None = None pickup: PickupReadiness objects: list[ObjectPosition] = Field(default_factory=list) diff --git a/src/bambu_server/config.py b/src/bambu_server/config.py index e1449db..6dc8567 100644 --- a/src/bambu_server/config.py +++ b/src/bambu_server/config.py @@ -260,6 +260,11 @@ class SlicerPrinterPresets(BaseModel): machine: str = Field(min_length=1) process: str | None = Field(default=None, min_length=1) filaments: dict[str, str] | None = None + #: Where the stock end gcode's final park move leaves the bed, as the Y + #: axis position in bed millimetres. Unset keeps the stock move (the A1's + #: ``G1 X-48 Y180``). On a bed-slinger a larger Y brings the plate further + #: toward the front for pickup; stay short of the printable area's edge. + end_bed_y_mm: float | None = Field(default=None, ge=0, le=1000) @field_validator("filaments", mode="before") @classmethod @@ -296,6 +301,9 @@ class SlicerSettings(BaseModel): machine_profiles: dict[str, SlicerPrinterPresets] = Field(default_factory=dict) #: Ceiling on an uploaded mesh. max_stl_bytes: int = Field(default=100 * 1024 * 1024, ge=1024) + #: Gap, in millimetres, between a ``front_left`` part's footprint and the + #: front and left edges of the printable area: room for a brim or skirt. + placement_margin_mm: float = Field(default=10.0, ge=0, le=100) @field_validator("filament_profiles", mode="before") @classmethod diff --git a/src/bambu_server/docs/AGENT_GUIDE.md b/src/bambu_server/docs/AGENT_GUIDE.md index 8cb3995..7221251 100644 --- a/src/bambu_server/docs/AGENT_GUIDE.md +++ b/src/bambu_server/docs/AGENT_GUIDE.md @@ -72,6 +72,15 @@ preset provenance. Allow time for slicing; it is synchronous with the upload request. It does not send any printer command. The server selects the target's presets, so callers cannot silently use P1S process settings for an A1. +To put the part near the front-left corner of the plate instead of the centre, +add `placement=front_left`. The part keeps its orientation and is moved so its +footprint starts `slicer.placement_margin_mm` (default 10 mm) from the front +and left edges of the printable area, in the bed frame (origin front-left, +X +right, +Y toward the back). A part too large to fit there is refused with 422. +`provenance.placement` records the choice and `GET /submissions/{id}/objects` +reports where the slicer actually put it. `placement` is accepted only with an +`.stl`; a sliced `.3mf` prints where its own slicer placed it. + An agent may instead slice locally with Bambu Studio and submit the result. Use A1 machine, process and filament presets for an A1; P1S/X1C process settings are not substitutes. Check the validation verdict returned by submission. @@ -151,6 +160,12 @@ Temperature alone does not establish safe robot clearance, part release or graspability. Objects are in bed millimetres, origin front-left, +X right, +Y back, Z up. The arm agent owns its calibration and transform; the gateway never commands the arm. Unknown positions are an empty list, never a guess. +On the A1 the bed itself moves in Y, so bed coordinates do not fix a world +position on their own: `bed_park_y_mm` says where the job's end gcode parked +the bed (`null` when unknown, e.g. the stock Y 180 end move). A larger value +puts the plate, and every object on it, that much further toward the front. +After the print the bed motors are released, so the bed can be pushed; check +it has not moved before relying on it. `/submissions/{id}/artifact` returns the exact stored bytes and SHA-256 ETag. `/result` returns the durable versioned bundle; `final: false` means the job is diff --git a/src/bambu_server/main.py b/src/bambu_server/main.py index e0934d3..031a700 100644 --- a/src/bambu_server/main.py +++ b/src/bambu_server/main.py @@ -104,7 +104,13 @@ Transport, urllib_transport, ) -from .slicer import BambuStudioSlicer, SliceRequest, SlicerError, SlicerUnavailable +from .slicer import ( + BambuStudioSlicer, + Placement, + SliceRequest, + SlicerError, + SlicerUnavailable, +) from .submissions import ( TERMINAL_STATES as TERMINAL_JOB_STATES, ) @@ -707,6 +713,14 @@ async def create_submission( requested_by: Annotated[str | None, Form(max_length=120)] = None, material: Annotated[str | None, Form(max_length=60)] = None, eln_project: Annotated[str | None, Form(max_length=120)] = None, + placement: Annotated[ + Placement | None, + Form( + description="Where the gateway puts an uploaded .stl on the plate: " + "`auto` (default; the slicer centres it) or `front_left` (a margin in " + "from the front-left corner of the bed). Only for an .stl." + ), + ] = None, ) -> SubmissionJob: """Accept a print artifact, validate it, and queue it if it passes. @@ -716,6 +730,8 @@ async def create_submission( ``eln_project`` optionally names the ELN project the finished record is filed under, through the central server. An agent (``X-Agent-Id`` or an agent edge role) may submit only to a printer in agent mode. + ``placement`` positions an ``.stl`` the gateway slices; a sliced file + is printed where its slicer put it, so it is refused there. """ # A verified identity wins over the form field: a signed-in person must @@ -743,6 +759,13 @@ async def create_submission( material=material, eln_project=eln_project, agent_id=agent_id, + placement=placement or "auto", + ) + if placement is not None: + raise HTTPException( + status_code=422, + detail="placement applies only to an .stl the gateway slices; " + "a sliced file prints where its slicer placed it", ) kind = ARTIFACT_EXTENSIONS.get(extension) if kind is None: @@ -800,6 +823,7 @@ async def _slice_and_accept( material: str | None, eln_project: str | None = None, agent_id: str | None = None, + placement: Placement = "auto", ) -> SubmissionJob: """Slice an uploaded mesh for the target machine, then intake the 3mf. @@ -846,6 +870,7 @@ async def _slice_and_accept( material=material, nozzle_type=monitor.profile().nozzle_type, plate=monitor.definition.profile.plate, + placement=placement, ) try: machine, process, filament = slicer.resolve_presets(request) @@ -864,6 +889,8 @@ async def _slice_and_accept( machine_preset=machine.stem, process_preset=process.stem, filament_preset=filament.stem, + placement=placement, + end_bed_y_mm=result.end_bed_y_mm, warnings=list(result.warnings), ) @@ -1103,6 +1130,7 @@ async def pickup_targets( ready=ready, reason=reason, bed_size_mm=keeper.bed_size(job.target_machine), + bed_park_y_mm=job.provenance.end_bed_y_mm if job.provenance else None, pickup=pickup, objects=objects, ) diff --git a/src/bambu_server/slicer.py b/src/bambu_server/slicer.py index 45c3c69..d60148e 100644 --- a/src/bambu_server/slicer.py +++ b/src/bambu_server/slicer.py @@ -24,6 +24,13 @@ bed temperatures and the plate named in the gcode belong to the surface the printer actually has. +Placement: by default the CLI auto-arranges the part onto the plate centre. +``front_left`` instead puts the part's footprint a margin in from the front-left +corner of the printable area (the origin of the bed frame). The CLI has no +translate option and drops a bare STL off the plate when arrange is disabled, +so the mesh is wrapped in a minimal 3MF whose build-item transform carries the +offset, and the slice runs with ``--arrange 0``. + Slicing touches no printer. It is pure computation on the gateway host. """ @@ -34,8 +41,11 @@ import logging import re import shutil +import struct +import zipfile from dataclasses import dataclass from pathlib import Path +from typing import Literal from .config import BedPlate, SlicerSettings from .plates import PRINTER_TO_SLICER @@ -51,6 +61,12 @@ _SUCCESS_RETURN_CODE = 0 +#: Where an uploaded mesh goes on the plate. ``auto`` is the slicer's own +#: arrangement (centred); ``front_left`` is a margin in from the bed origin. +Placement = Literal["auto", "front_left"] +PLACEMENTS: tuple[Placement, ...] = ("auto", "front_left") + + class SlicerError(RuntimeError): """The mesh could not be sliced. The message is safe to show a submitter.""" @@ -65,6 +81,7 @@ class SliceRequest: material: str nozzle_type: str | None plate: BedPlate | None + placement: Placement = "auto" @dataclass(frozen=True) @@ -73,6 +90,12 @@ class SliceResult: slicer_version: str | None estimated_minutes: float | None warnings: tuple[str, ...] + #: Where the mesh's footprint was put, front-left corner first, in bed + #: millimetres; None when the slicer arranged it. + placed_min_xy_mm: tuple[float, float] | None = None + #: The Y axis position the end gcode parks the bed at, when the gateway + #: set it; None when the stock end gcode was left alone. + end_bed_y_mm: float | None = None class BambuStudioSlicer: @@ -172,6 +195,14 @@ async def slice( # `curr_bed_type` is a project-level setting; the CLI takes it from any # loaded settings file and the exported plate gcode carries it. machine_body["curr_bed_type"] = PRINTER_TO_SLICER[request.plate] + presets = self._settings.presets_for(request.printer_id) + end_bed_y = presets.end_bed_y_mm if presets is not None else None + if end_bed_y is not None: + machine_body["machine_end_gcode"] = _with_end_bed_y( + machine_body.get("machine_end_gcode"), + end_bed_y, + printable_area=_printable_area(machine_body), + ) override = job_dir / "machine.json" override.write_text(json.dumps(machine_body, indent=2), encoding="utf-8") process = job_dir / "process.json" @@ -182,20 +213,37 @@ async def slice( datadir.mkdir(exist_ok=True) output = job_dir / "plate.3mf" + model_input = mesh + arrange = "1" + placed: tuple[float, float] | None = None + if request.placement == "front_left": + model_input = job_dir / "placed.3mf" + placed = await asyncio.to_thread( + _place_front_left, + mesh, + model_input, + printable_area=_printable_area(machine_body), + margin_mm=self._settings.placement_margin_mm, + ) + arrange = "0" + argv = [ str(self._settings.executable), "--debug", "1", "--datadir", str(datadir), "--load-settings", f"{override};{process}", "--load-filaments", str(filament), - "--arrange", "1", + "--arrange", arrange, "--orient", "0", "--slice", "0", "--export-3mf", output.name, "--outputdir", str(job_dir), - str(mesh), + str(model_input), ] - logger.info("Slicing %s for %s (%s)", mesh.name, request.printer_id, request.material) + logger.info( + "Slicing %s for %s (%s, placement %s)", + mesh.name, request.printer_id, request.material, request.placement, + ) try: process_handle = await asyncio.create_subprocess_exec( *argv, @@ -248,6 +296,8 @@ async def slice( slicer_version=_slicer_version(stderr), estimated_minutes=estimated, warnings=tuple(warnings), + placed_min_xy_mm=placed, + end_bed_y_mm=end_bed_y, ) def discard(self, job_dir: Path) -> None: @@ -322,6 +372,209 @@ def _compatible_printers(preset: Path) -> list[str]: return [name for name in listed if isinstance(name, str)] +#: The stock end gcode's last park move, e.g. the A1's ``G1 X-48 Y180 F3600``: +#: toolhead to the left parking spot, bed to a Y position, just before the +#: motors are released. Only the Y word is ever rewritten. +_END_PARK_MOVE_RE = re.compile( + r"^(?PG1 X-?\d+(?:\.\d+)? )Y\d+(?:\.\d+)?(?P F\d+[^\n]*)$", re.MULTILINE +) + + +def _with_end_bed_y( + end_gcode: object, y_mm: float, *, printable_area: tuple[float, float, float, float] +) -> str: + """The machine end gcode with its final bed park move set to ``y_mm``. + + The last absolute ``G1 X.. Y.. F..`` after the stock ``G90`` is the park + move. A preset whose end gcode does not have one is refused rather than + guessed at, and so is a position outside the printable area. + """ + + _, area_min_y, _, area_max_y = printable_area + if not area_min_y <= y_mm <= area_max_y: + raise SlicerUnavailable( + f"end_bed_y_mm {y_mm:g} is outside the bed's Y travel " + f"({area_min_y:g}-{area_max_y:g} mm)" + ) + if not isinstance(end_gcode, str): + raise SlicerUnavailable("the machine preset has no end gcode to set the bed position in") + matches = list(_END_PARK_MOVE_RE.finditer(end_gcode)) + if not matches: + raise SlicerUnavailable( + "the machine end gcode has no final park move, so end_bed_y_mm cannot be applied" + ) + last = matches[-1] + if "G90" not in end_gcode[: last.start()]: + raise SlicerUnavailable( + "the machine end gcode's park move is not in absolute positioning" + ) + replacement = ( + f"{last.group('head')}Y{y_mm:g}{last.group('tail')} " + "; bed parked for pickup (gateway end_bed_y_mm)" + ) + return end_gcode[: last.start()] + replacement + end_gcode[last.end():] + + +_STL_TRIANGLE = struct.Struct("<12x9f2x") +_ASCII_VERTEX_RE = re.compile(rb"^\s*vertex\s+(\S+)\s+(\S+)\s+(\S+)", re.MULTILINE) +_AREA_POINT_RE = re.compile(r"^\s*(-?[0-9.]+)\s*x\s*(-?[0-9.]+)\s*$") + +Vertex = tuple[float, float, float] + + +def _read_stl(path: Path) -> tuple[list[Vertex], list[tuple[int, int, int]]]: + """An STL's shared vertices and its triangles as vertex indices. + + Binary STL is recognised by its exact length (80-byte header, a triangle + count, 50 bytes per triangle); anything else starting with ``solid`` is + read as ASCII. Vertices are shared by exact value so the 3MF stays one + connected mesh, as the STL describes it. + """ + + data = path.read_bytes() + coordinates: list[float] + if len(data) >= 84: + (count,) = struct.unpack_from("= 0 and len(data) == 84 + 50 * count: + coordinates = [ + value for triangle in _STL_TRIANGLE.iter_unpack(data[84:]) for value in triangle + ] + elif data.lstrip().startswith(b"solid"): + try: + coordinates = [ + float(value) for match in _ASCII_VERTEX_RE.finditer(data) for value in match.groups() + ] + except ValueError as exc: + raise SlicerError("the uploaded mesh is not a readable STL") from exc + if len(coordinates) % 9: + raise SlicerError("the uploaded mesh is not a readable STL") + else: + raise SlicerError("the uploaded mesh is not a readable STL") + if not coordinates: + raise SlicerError("the uploaded mesh has no triangles") + if any(value != value or value in (float("inf"), float("-inf")) for value in coordinates): + raise SlicerError("the uploaded mesh has non-finite coordinates") + + index: dict[Vertex, int] = {} + vertices: list[Vertex] = [] + triangles: list[tuple[int, int, int]] = [] + for start in range(0, len(coordinates), 9): + corners = [] + for offset in (0, 3, 6): + vertex = ( + coordinates[start + offset], + coordinates[start + offset + 1], + coordinates[start + offset + 2], + ) + found = index.get(vertex) + if found is None: + found = index[vertex] = len(vertices) + vertices.append(vertex) + corners.append(found) + if len(set(corners)) == 3: # a degenerate triangle has no area to print + triangles.append((corners[0], corners[1], corners[2])) + if not triangles: + raise SlicerError("the uploaded mesh has no triangles") + return vertices, triangles + + +def _printable_area(machine_body: dict[str, object]) -> tuple[float, float, float, float]: + """The machine's printable rectangle as ``(min_x, min_y, max_x, max_y)``.""" + + points: list[tuple[float, float]] = [] + raw = machine_body.get("printable_area") + for entry in raw if isinstance(raw, list) else []: + match = _AREA_POINT_RE.match(str(entry)) + if match: + points.append((float(match.group(1)), float(match.group(2)))) + if len(points) < 3: + raise SlicerUnavailable("the machine preset does not declare its printable area") + xs = [x for x, _ in points] + ys = [y for _, y in points] + return min(xs), min(ys), max(xs), max(ys) + + +def _place_front_left( + mesh: Path, + output: Path, + *, + printable_area: tuple[float, float, float, float], + margin_mm: float, +) -> tuple[float, float]: + """Write ``mesh`` as a one-object 3MF placed at the front-left of the bed. + + The part keeps its orientation; it is only translated so its footprint's + front-left corner sits ``margin_mm`` in from the printable area's and its + lowest point rests on the plate. The margin leaves room for a brim or a + skirt. A part too large to fit with the margin is refused rather than + hung off the bed. Returns the footprint's new front-left corner. + """ + + vertices, triangles = _read_stl(mesh) + min_x = min(v[0] for v in vertices) + min_y = min(v[1] for v in vertices) + min_z = min(v[2] for v in vertices) + size_x = max(v[0] for v in vertices) - min_x + size_y = max(v[1] for v in vertices) - min_y + area_min_x, area_min_y, area_max_x, area_max_y = printable_area + target_x = area_min_x + margin_mm + target_y = area_min_y + margin_mm + if target_x + size_x > area_max_x or target_y + size_y > area_max_y: + raise SlicerError( + f"the part ({size_x:.1f} x {size_y:.1f} mm) does not fit at the front left " + f"with a {margin_mm:g} mm margin on a " + f"{area_max_x - area_min_x:g} x {area_max_y - area_min_y:g} mm bed" + ) + tx, ty, tz = target_x - min_x, target_y - min_y, -min_z + + with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr( + "[Content_Types].xml", + '\n' + '' + '' + '' + "", + ) + archive.writestr( + "_rels/.rels", + '\n' + '' + '' + "", + ) + with archive.open("3D/3dmodel.model", "w") as model: + model.write( + b'\n' + b'' + b'' + ) + model.write( + "".join( + f'' for x, y, z in vertices + ).encode("ascii") + ) + model.write(b"") + model.write( + "".join(f'' for a, b, c in triangles).encode( + "ascii" + ) + ) + model.write( + b"" + + f''.encode("ascii") + + b"" + ) + return round(target_x, 3), round(target_y, 3) + + _VERSION_RE = re.compile(r"BambuStudio Version (\S+)") diff --git a/src/bambu_server/submissions.py b/src/bambu_server/submissions.py index ae51f4d..9d0f9a5 100644 --- a/src/bambu_server/submissions.py +++ b/src/bambu_server/submissions.py @@ -170,6 +170,12 @@ class SliceProvenance(BaseModel): machine_preset: str process_preset: str filament_preset: str + #: Where the mesh was put on the plate: ``auto`` (the slicer arranged it) + #: or ``front_left``. The job's object positions say where it landed. + placement: str = "auto" + #: The Y axis position the end gcode parks the bed at for pickup, when the + #: gateway set it; None means the stock end move was left as it was. + end_bed_y_mm: float | None = None warnings: list[str] = Field(default_factory=list) diff --git a/tests/test_slicer.py b/tests/test_slicer.py index b70f82e..be91ecf 100644 --- a/tests/test_slicer.py +++ b/tests/test_slicer.py @@ -9,9 +9,12 @@ import json import stat +import struct import sys +import zipfile from collections.abc import Iterator from pathlib import Path +from xml.etree import ElementTree import pytest from fastapi.testclient import TestClient @@ -31,6 +34,7 @@ def value(flag): out = Path(value("--outputdir")) settings = value("--load-settings").split(";") (out / "seen_settings.json").write_text(json.dumps(settings)) +(out / "seen_argv.json").write_text(json.dumps(args)) if Path(args[-1]).read_bytes().startswith(b"broken"): (out / "result.json").write_text(json.dumps({{"return_code": -51, "error_string": "Nothing to be sliced"}})) sys.exit(0) @@ -51,7 +55,11 @@ def _write(root: Path, kind: str, body: dict[str, object]) -> None: def _profiles(root: Path) -> Path: # Shaped like the bundled BBL tree: the instantiable preset holds only its # own keys; the bed, gcode and temperatures live in parents and includes. - _write(root, "machine", {"name": "fdm_machine_test_common", "printable_area": ["0x0", "256x0", "256x256", "0x256"], "retraction_length": ["0.8"]}) + _write(root, "machine", { + "name": "fdm_machine_test_common", "printable_area": ["0x0", "256x0", "256x256", "0x256"], + "retraction_length": ["0.8"], + "machine_end_gcode": "G1 X0 Y128 F18000\nM104 S0\nG90\nG1 X-48 Y180 F3600\nM400\nM18 X Y Z\n", + }) _write(root, "machine", {"name": "Bambu Lab Test 0.4 nozzle template machine_start_gcode", "instantiation": "false", "machine_start_gcode": ";===== machine: Test ====="}) _write(root, "machine", { "name": "Bambu Lab Test 0.4 nozzle", "inherits": "fdm_machine_test_common", @@ -156,6 +164,182 @@ async def test_a_slicer_failure_is_reported(slicer_settings: SlicerSettings, tmp ) +def _cube_stl(origin: tuple[float, float, float], size: tuple[float, float, float]) -> bytes: + """A binary STL box with one corner at ``origin``.""" + + corners = [ + (origin[0] + dx * size[0], origin[1] + dy * size[1], origin[2] + dz * size[2]) + for dx in (0, 1) for dy in (0, 1) for dz in (0, 1) + ] + faces = [(0, 2, 3), (0, 3, 1), (4, 5, 7), (4, 7, 6), (0, 1, 5), (0, 5, 4), + (2, 6, 7), (2, 7, 3), (0, 4, 6), (0, 6, 2), (1, 3, 7), (1, 7, 5)] + body = b"".join( + struct.pack("<3f", 0, 0, 0) + + b"".join(struct.pack("<3f", *corners[i]) for i in face) + + b"\0\0" + for face in faces + ) + return b"\0" * 80 + struct.pack(" tuple[float, float, float, float, float, int]: + """(min_x, min_y, max_x, max_y, min_z, vertex count) of the build item, transformed.""" + + ns = {"m": "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"} + with zipfile.ZipFile(model_3mf) as archive: + root = ElementTree.fromstring(archive.read("3D/3dmodel.model")) + vertices = [ + (float(v.get("x")), float(v.get("y")), float(v.get("z"))) + for v in root.iterfind(".//m:vertex", ns) + ] + transform = [float(t) for t in root.find(".//m:item", ns).get("transform").split()] + assert transform[:9] == [1, 0, 0, 0, 1, 0, 0, 0, 1] # translated, never rotated + tx, ty, tz = transform[9:] + xs = [x + tx for x, _, _ in vertices] + ys = [y + ty for _, y, _ in vertices] + zs = [z + tz for _, _, z in vertices] + return min(xs), min(ys), max(xs), max(ys), min(zs), len(vertices) + + +async def test_front_left_places_the_part_a_margin_from_the_bed_origin( + slicer_settings: SlicerSettings, tmp_path: Path +) -> None: + mesh = tmp_path / "cube.stl" + mesh.write_bytes(_cube_stl((100.0, 150.0, 5.0), (20.0, 30.0, 10.0))) + job_dir = slicer_settings.work_dir / "job" + + result = await BambuStudioSlicer(slicer_settings).slice( + mesh, _request(placement="front_left"), job_dir=job_dir + ) + + argv = json.loads((job_dir / "seen_argv.json").read_text()) + assert argv[argv.index("--arrange") + 1] == "0" # arranging would re-centre it + assert argv[-1].endswith("placed.3mf") + min_x, min_y, max_x, max_y, min_z, count = _placed_bounds(job_dir / "placed.3mf") + margin = slicer_settings.placement_margin_mm + assert (min_x, min_y) == pytest.approx((margin, margin)) + assert (max_x, max_y) == pytest.approx((margin + 20.0, margin + 30.0)) + assert min_z == pytest.approx(0.0) # rests on the plate + assert count == 8 # shared vertices: one connected mesh, not loose triangles + assert result.placed_min_xy_mm == (margin, margin) + + +async def test_front_left_reads_an_ascii_stl( + slicer_settings: SlicerSettings, tmp_path: Path +) -> None: + mesh = tmp_path / "tri.stl" + mesh.write_text( + "solid t\nfacet normal 0 0 1\nouter loop\n" + "vertex -50 -40 2\nvertex -30 -40 2\nvertex -50 -20 7\n" + "endloop\nendfacet\nendsolid t\n" + ) + job_dir = slicer_settings.work_dir / "job" + settings = slicer_settings.model_copy(update={"placement_margin_mm": 5.0}) + await BambuStudioSlicer(settings).slice(mesh, _request(placement="front_left"), job_dir=job_dir) + + min_x, min_y, max_x, max_y, min_z, _ = _placed_bounds(job_dir / "placed.3mf") + assert (min_x, min_y, max_x, max_y, min_z) == pytest.approx((5.0, 5.0, 25.0, 25.0, 0.0)) + + +async def test_auto_placement_lets_the_slicer_arrange_the_stl( + slicer_settings: SlicerSettings, tmp_path: Path +) -> None: + mesh = tmp_path / "cube.stl" + mesh.write_bytes(_cube_stl((0.0, 0.0, 0.0), (10.0, 10.0, 10.0))) + job_dir = slicer_settings.work_dir / "job" + result = await BambuStudioSlicer(slicer_settings).slice(mesh, _request(), job_dir=job_dir) + + argv = json.loads((job_dir / "seen_argv.json").read_text()) + assert argv[argv.index("--arrange") + 1] == "1" + assert argv[-1] == str(mesh) + assert result.placed_min_xy_mm is None + + +@pytest.mark.parametrize( + ("stl", "reason"), + [ + (_cube_stl((0.0, 0.0, 0.0), (250.0, 20.0, 10.0)), "does not fit"), + (b"not a mesh at all", "not a readable STL"), + (b"solid empty\nendsolid empty\n", "no triangles"), + ], +) +async def test_front_left_refuses_a_part_it_cannot_place( + slicer_settings: SlicerSettings, tmp_path: Path, stl: bytes, reason: str +) -> None: + mesh = tmp_path / "part.stl" + mesh.write_bytes(stl) + job_dir = slicer_settings.work_dir / "job" + with pytest.raises(SlicerError, match=reason): + await BambuStudioSlicer(slicer_settings).slice( + mesh, _request(placement="front_left"), job_dir=job_dir + ) + assert not (job_dir / "result.json").exists() # the CLI never ran + + +def _with_park(settings: SlicerSettings, y_mm: float) -> SlicerSettings: + payload = settings.model_dump(mode="json") + payload["machine_profiles"]["bambu_test_01"]["end_bed_y_mm"] = y_mm + return SlicerSettings.model_validate(payload) + + +async def test_end_bed_y_moves_only_the_final_park_move( + slicer_settings: SlicerSettings, tmp_path: Path +) -> None: + mesh = tmp_path / "cube.stl" + mesh.write_text("solid cube\nendsolid cube\n") + job_dir = slicer_settings.work_dir / "job" + result = await BambuStudioSlicer(_with_park(slicer_settings, 250)).slice( + mesh, _request(), job_dir=job_dir + ) + + end = json.loads((job_dir / "machine.json").read_text())["machine_end_gcode"] + assert "G1 X-48 Y250 F3600 ; bed parked for pickup" in end + assert "Y180" not in end + assert "G1 X0 Y128 F18000" in end # earlier moves are untouched + assert end.index("Y250") < end.index("M18") # parked before the motors are released + assert result.end_bed_y_mm == 250 + + +async def test_stock_end_gcode_is_kept_without_end_bed_y( + slicer_settings: SlicerSettings, tmp_path: Path +) -> None: + mesh = tmp_path / "cube.stl" + mesh.write_text("solid cube\nendsolid cube\n") + job_dir = slicer_settings.work_dir / "job" + result = await BambuStudioSlicer(slicer_settings).slice(mesh, _request(), job_dir=job_dir) + + end = json.loads((job_dir / "machine.json").read_text())["machine_end_gcode"] + assert "G1 X-48 Y180 F3600\n" in end + assert result.end_bed_y_mm is None + + +async def test_end_bed_y_beyond_the_bed_is_refused( + slicer_settings: SlicerSettings, tmp_path: Path +) -> None: + mesh = tmp_path / "cube.stl" + mesh.write_text("solid cube\nendsolid cube\n") + with pytest.raises(SlicerUnavailable, match="outside the bed"): + await BambuStudioSlicer(_with_park(slicer_settings, 300)).slice( + mesh, _request(), job_dir=slicer_settings.work_dir / "job" + ) + + +async def test_end_bed_y_without_a_park_move_is_refused( + slicer_settings: SlicerSettings, tmp_path: Path +) -> None: + root = slicer_settings.profiles_dir + common = root / "machine" / "fdm_machine_test_common.json" + body = json.loads(common.read_text()) + body["machine_end_gcode"] = "M104 S0\nM18 X Y Z\n" + common.write_text(json.dumps(body)) + mesh = tmp_path / "cube.stl" + mesh.write_text("solid cube\nendsolid cube\n") + with pytest.raises(SlicerUnavailable, match="no final park move"): + await BambuStudioSlicer(_with_park(slicer_settings, 250)).slice( + mesh, _request(), job_dir=slicer_settings.work_dir / "job" + ) + + def test_unknown_material_and_unknown_printer_are_refused( slicer_settings: SlicerSettings, ) -> None: @@ -347,6 +531,70 @@ def test_an_stl_upload_is_sliced_validated_and_queued( assert backend.uploads == [] +def test_an_stl_can_be_placed_front_left( + slicing_client: TestClient, slicer_settings: SlicerSettings +) -> None: + response = slicing_client.post( + "/submissions", + files={"file": ("cube.stl", _cube_stl((40.0, 40.0, 0.0), (20.0, 20.0, 20.0)), "model/stl")}, + data={ + "target_machine": "bambu_test_01", "requested_by": "u", + "material": "PLA", "placement": "front_left", + }, + ) + assert response.status_code == 201, response.text + assert response.json()["provenance"]["placement"] == "front_left" + assert list(slicer_settings.work_dir.iterdir()) == [] + + +def test_placement_is_refused_for_an_already_sliced_file( + slicing_client: TestClient, tmp_path: Path +) -> None: + artifact = write_3mf(tmp_path / "sliced.3mf").read_bytes() + response = slicing_client.post( + "/submissions", + files={"file": ("sliced.3mf", artifact, "model/3mf")}, + data={"target_machine": "bambu_test_01", "requested_by": "u", "placement": "front_left"}, + ) + assert response.status_code == 422 + assert "only to an .stl" in response.json()["detail"] + + +def test_an_unknown_placement_is_refused(slicing_client: TestClient) -> None: + response = slicing_client.post( + "/submissions", + files={"file": ("cube.stl", _cube_stl((0.0, 0.0, 0.0), (5.0, 5.0, 5.0)), "model/stl")}, + data={ + "target_machine": "bambu_test_01", "requested_by": "u", + "material": "PLA", "placement": "back_right", + }, + ) + assert response.status_code == 422 + + +def test_the_park_position_reaches_provenance_and_pickup_targets( + settings: Settings, slicer_settings: SlicerSettings, backend: FakeBackend +) -> None: + payload = settings.model_dump(mode="json") + payload["printers"][0]["profile"]["plate"] = "textured_plate" + built = Settings.model_validate(payload) + built.slicer = _with_park(slicer_settings, 250) + app = create_app(settings=built, backend_factory=lambda _d, _c: backend) + with TestClient(app) as client: + response = client.post( + "/submissions", + files={"file": ("cube.stl", b"solid cube\nendsolid\n", "model/stl")}, + data={"target_machine": "bambu_test_01", "requested_by": "u", "material": "PLA"}, + ) + assert response.status_code == 201, response.text + job = response.json() + assert job["provenance"]["end_bed_y_mm"] == 250 + pickup = client.get(f"/submissions/{job['submission_id']}/pickup-targets") + assert pickup.status_code == 200, pickup.text + assert pickup.json()["bed_park_y_mm"] == 250 + assert backend.uploads == [] + + def test_an_stl_needs_a_material(slicing_client: TestClient) -> None: response = slicing_client.post( "/submissions",