bambu-printer-mcp 1.1.93 → 1.1.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +6 -3
  2. package/dist/3mf_parser.js +3 -2
  3. package/dist/cad/contracts.d.ts +10 -0
  4. package/dist/cad/contracts.js +41 -1
  5. package/dist/cad-engine.d.ts +5 -0
  6. package/dist/cad-engine.js +74 -3
  7. package/dist/counterpart/diagnostics.d.ts +163 -0
  8. package/dist/counterpart/diagnostics.js +816 -0
  9. package/dist/counterpart/flight-tools.d.ts +2 -2
  10. package/dist/counterpart/info.js +1 -0
  11. package/dist/counterpart/make-3mf.d.ts +10 -0
  12. package/dist/counterpart/make-3mf.js +472 -65
  13. package/dist/counterpart/model-plates.d.ts +8 -1
  14. package/dist/counterpart/model-plates.js +9 -4
  15. package/dist/counterpart/plate-filaments.d.ts +19 -0
  16. package/dist/counterpart/plate-filaments.js +72 -10
  17. package/dist/counterpart/remote.js +1 -0
  18. package/dist/counterpart/schemas.d.ts +8 -2
  19. package/dist/counterpart/schemas.js +1 -0
  20. package/dist/index.js +100 -2
  21. package/dist/tool-annotations.js +1 -0
  22. package/package.json +2 -2
  23. package/src/3mf_parser.ts +3 -2
  24. package/src/cad/contracts.ts +46 -1
  25. package/src/cad/examples/desk_clamp_hook.py +32 -0
  26. package/src/cad/examples/desk_edge_cable_holder.py +24 -0
  27. package/src/cad/examples/phone_stand.py +26 -0
  28. package/src/cad/geometry.py +52 -2
  29. package/src/cad/project3mf.py +426 -0
  30. package/src/cad/purpose.py +492 -0
  31. package/src/cad/worker.py +17 -2
  32. package/src/cad-engine.ts +73 -3
  33. package/src/counterpart/diagnostics.ts +775 -0
  34. package/src/counterpart/info.ts +1 -0
  35. package/src/counterpart/make-3mf.ts +446 -61
  36. package/src/counterpart/model-plates.ts +17 -5
  37. package/src/counterpart/plate-filaments.ts +75 -7
  38. package/src/counterpart/remote.ts +1 -0
  39. package/src/counterpart/schemas.ts +3 -0
  40. package/src/index.ts +83 -2
  41. package/src/tool-annotations.ts +1 -0
@@ -35,6 +35,15 @@ P = {
35
35
  "print_in_place": False, # two parts assembled by hand: only touching is a problem
36
36
  }
37
37
 
38
+ # What it is for, as data: cad_run compiles it into requirements and evaluates them on use() below.
39
+ PURPOSE = {
40
+ "for": "a hook that clamps under my 25 mm desk to hang my headphones",
41
+ "modelled_on": "Brainwavz Hoist headphone hanger with adjustable clamp",
42
+ "holds": [{"body": "headphones", "mass_g": 350}],
43
+ "mounts": [{"body": "desk", "by": "clamp"}],
44
+ "material": "PETG",
45
+ }
46
+
38
47
 
39
48
  def thread(root_r, crest_r, z0, length):
40
49
  """A 45 degree trapezoid swept along a helix about Z, from z0. root_r > crest_r makes the nut's thread."""
@@ -89,3 +98,26 @@ def build():
89
98
  turn = 360 * (lift + kh + 1 - z_nut) / P["pitch"] + 180
90
99
  used = Rot(90, 0, 0) * Compound([frame, to_frame * Pos(0, 0, lift) * Rot(0, 0, turn) * screw])
91
100
  return Pos(0, 0, -used.bounding_box().min.Z) * used
101
+
102
+
103
+ def use():
104
+ """As used: clamped on a desk_t desk whose top is the plane the top jaw lies on, a headband resting on the hook.
105
+ A clamp's strength is not computed; its loads are, from where the headphones hang."""
106
+ pose = P["pose"]
107
+ P["pose"] = "assembled"
108
+ try:
109
+ shown = build()
110
+ finally:
111
+ P["pose"] = pose
112
+ desk_top = shown.bounding_box().max.Z - P["bar_t"] # the top jaw lies on the desk
113
+ parts = shown.solids()
114
+ for k, s in enumerate(parts):
115
+ s.label = f"body {k + 1}"
116
+ w = P["width"]
117
+ desk = Pos(150, -w / 2, desk_top - P["desk_t"] / 2) * Box(300, 300, P["desk_t"])
118
+ desk.label = "world:desk"
119
+ hook_top = desk_top - P["opening"] - P["drop"] # top of the hook arm
120
+ x = P["reach"] + P["bend_r"] - P["hook_len"] / 2
121
+ band = Pos(x, -w / 2, hook_top + 15) * Box(30, 60, 30) # the headband where it rests
122
+ band.label = "held:headphones"
123
+ return Compound(children=[*parts, band, desk])
@@ -25,6 +25,15 @@ P = {
25
25
  "edge": 0.6, # chamfer round both faces of the comb: no sharp edge on a cable jacket
26
26
  }
27
27
 
28
+ # What it is for, as data: cad_run compiles it into requirements and evaluates them on use() below.
29
+ PURPOSE = {
30
+ "for": "an organizer that parks five charging cables at the edge of my desk so the plugs don't fall behind it",
31
+ "modelled_on": "Orico CBS5 5-slot self-adhesive desk cable holder",
32
+ "holds": [{"body": "cables", "mass_g": 40}], # the last 200 mm of five cables, about 8 g each
33
+ "mounts": [{"body": "desk", "by": "tape"}],
34
+ "material": "PETG",
35
+ }
36
+
28
37
 
29
38
  def build():
30
39
  seat_r = (P["cable_max"] + P["seat_clear"]) / 2
@@ -53,3 +62,18 @@ def build():
53
62
 
54
63
  rail = extrude(comb, P["depth"])
55
64
  return chamfer(rail.edges().group_by(Axis.Z)[0] + rail.edges().group_by(Axis.Z)[-1], P["edge"])
65
+
66
+
67
+ def use():
68
+ """As used: the taped base on the desk top (Z = 0), the last 200 mm of a 4 mm cable lying in each seat. cad_run computes the tape's
69
+ load from this, so the rail's size is checked against what it carries, not asserted."""
70
+ seat_r = (P["cable_max"] + P["seat_clear"]) / 2
71
+ rail = Rot(90, 0, 0) * build() # the comb's up (Y) becomes Z; its depth runs along -Y
72
+ rail.label = "rail"
73
+ z = P["base_t"] - P["cradle"] + 2.0 # a 4 mm cable resting in the bottom of its seat
74
+ cables = Compound([Pos((i - (P["slots"] - 1) / 2) * P["pitch"], -P["depth"] / 2, z) * (Rot(90, 0, 0) * Cylinder(2.0, 200))
75
+ for i in range(P["slots"])])
76
+ cables.label = "held:cables"
77
+ desk = Pos(0, -P["depth"] / 2, -10) * Box(300, 200, 20)
78
+ desk.label = "world:desk"
79
+ return Compound(children=[rail, cables, desk])
@@ -35,6 +35,15 @@ P = {
35
35
  "edge_r": 1.9, # rounding on hooks and panel top (the 4 mm lip becomes a full round)
36
36
  }
37
37
 
38
+ # What it is for, as data: cad_run compiles it into requirements and evaluates them on use() below.
39
+ PURPOSE = {
40
+ "for": "a stand that holds my phone on my desk at a reading angle while it charges",
41
+ "modelled_on": "Lamicall S1 desk phone stand",
42
+ "holds": [{"body": "phone", "mass_g": 249}], # the tallest iPhone it takes
43
+ "mounts": [{"body": "desk", "by": "rests"}],
44
+ "user": [0.0, -450.0, 330.0], # a seated person's eye, in front of the stand
45
+ }
46
+
38
47
 
39
48
  def build():
40
49
  lean, neck, t = radians(P["lean_deg"]), radians(P["neck_deg"]), P["thick"]
@@ -91,3 +100,20 @@ def build():
91
100
  rest = Plane(seat, x_dir=(1, 0, 0), z_dir=out)
92
101
  slot = extrude(SlotOverall(P["slot_len"], P["cable_gap"] - 6, rotation=90), 2 * t, both=True)
93
102
  return body - rest * Pos(0, 3 - P["slot_len"] / 2) * slot
103
+
104
+
105
+ def use():
106
+ """As used: on the desk (Z = 0) with the tallest iPhone (163.4 x 78.0 x 8.75 mm) on the hooks and against the back.
107
+ cad_run checks from this that the stand neither tips nor slides when the screen is pressed, and that the screen
108
+ faces the user's eye."""
109
+ lean = radians(P["lean_deg"])
110
+ up = Vector(0, sin(lean), cos(lean))
111
+ out = Vector(0, -cos(lean), sin(lean))
112
+ seat = Vector(0, P["nose_y"], P["nose_h"]) + up * P["seat_up"] + out * (P["thick"] / 2)
113
+ stand = build()
114
+ stand.label = "stand"
115
+ phone = Pos(*(seat + up * (163.4 / 2) + out * (8.75 / 2))) * (Rot(-P["lean_deg"], 0, 0) * Box(78.0, 8.75, 163.4))
116
+ phone.label = "held:phone"
117
+ desk = Pos(0, P["foot_y"], -10) * Box(300, 300, 20)
118
+ desk.label = "world:desk"
119
+ return Compound(children=[stand, phone, desk])
@@ -39,12 +39,62 @@ def inspect(request):
39
39
  assembly = bodies(step, request) if step is not None else None
40
40
  except Exception as e: # a failed measurement must not cost the person the export; it is reported, not passed
41
41
  assembly = {'error': f'{type(e).__name__}: {e}'[:300]}
42
+ # What the part is for, evaluated on the design as it is used (purpose.py): ready, and why not.
43
+ from purpose import inspect_purpose
44
+ try:
45
+ purpose = inspect_purpose(request, step)
46
+ except Exception as e:
47
+ why = f'the purpose could not be evaluated: {type(e).__name__}: {e}'[:300]
48
+ purpose = {'declared': None, 'requirements': [], 'loads': [], 'not_checked': [], 'blocked': [why], 'ready': False}
49
+ renders = render(m, base.parent / (base.name + '.renders'))
50
+ if purpose is not None and Path(str(base) + '.use.step').exists():
51
+ try:
52
+ renders['use'] = use_view(Path(str(base) + '.use.step'), base.parent / (base.name + '.renders'), purpose.get('user'))
53
+ except Exception as e:
54
+ purpose['not_checked'].append(f'the view of the design in use could not be drawn: {type(e).__name__}')
55
+ found = evidence(assembly)
56
+ if purpose is not None:
57
+ found['checked'].append('what PURPOSE says it is for, compiled into requirements and evaluated on use(): the held objects, the mounts, the loads at each mount and whether it faces its user (purpose; anything not passing is in purpose.blocked)')
58
+ found['not_checked'] += purpose['not_checked']
42
59
  return {'valid': all(v for v in checks.values() if v is not None), 'units': 'mm', 'bounds_mm': bounds,
43
60
  'size_mm': m.extents.tolist(), 'volume_mm3': float(m.volume) if m.is_volume else None,
44
61
  'step_volume_mm3': float(step.volume) if step is not None else None, 'solid_count': len(step.solids()) if step is not None else len(m.split(only_watertight=True)),
45
62
  'mesh_components': len(m.split(only_watertight=False)), 'checks': checks,
46
- **evidence(assembly),
47
- 'renders': render(m, base.parent / (base.name + '.renders'))}
63
+ **found, 'renders': renders,
64
+ # ready needs sound geometry too; problems (body gaps) stay advisory, as they were
65
+ **({'purpose': purpose, 'ready': purpose['ready'] and all(v for v in checks.values() if v is not None)} if purpose is not None else {})}
66
+
67
+
68
+ def use_view(step, folder, eye=None):
69
+ """The design as it is used, held objects and the surfaces it meets included, seen from the user's eye when given."""
70
+ user = eye is not None
71
+ from build123d import Box, Compound, Pos, import_step
72
+ from purpose import _mesh
73
+ shape = import_step(str(step))
74
+ kids = list(shape.children) if isinstance(shape, Compound) else []
75
+ world = [c for c in kids if (c.label or '').startswith('world:')]
76
+ if world and len(world) < len(kids):
77
+ # Only the part of a wall, desk or dash near the design: a whole slab would fill the picture.
78
+ rest = Compound(children=[c for c in kids if c not in world]).bounding_box()
79
+ near = Pos(*rest.center()) * Box(rest.size.X + 50, rest.size.Y + 50, rest.size.Z + 50)
80
+ clipped = [c & near for c in world]
81
+ shape = Compound(children=[c for c in kids if c not in world] + [c for c in clipped if c.solids()])
82
+ m = _mesh(shape, 0.1)
83
+ az, el = 35.0, 26.0
84
+ if eye is None and world and len(world) < len(kids):
85
+ # No eye given: look from the part's side of the surface it meets, so a wall or armrest never hides it.
86
+ towards = np.array(list(rest.center()), float) - np.array(list(Compound(children=world).bounding_box().center()), float)
87
+ if np.linalg.norm(towards) > 1e-6:
88
+ default = np.array([math.sin(math.radians(az)) * math.cos(math.radians(el)), -math.cos(math.radians(az)) * math.cos(math.radians(el)), math.sin(math.radians(el))])
89
+ eye = m.bounds.mean(axis=0) + 1000 * (towards / np.linalg.norm(towards) + 0.7 * default)
90
+ if eye is not None:
91
+ d = np.asarray(eye, float) - m.bounds.mean(axis=0)
92
+ az, el = math.degrees(math.atan2(d[0], -d[1])), max(-75.0, min(75.0, math.degrees(math.atan2(d[2], math.hypot(d[0], d[1])))))
93
+ im = perspective(m, 1200, az, el)
94
+ label = 'in use' + (', from the user\'s eye' if user else ', from the side it is used from' if eye is not None else ', from the front right and above')
95
+ ImageDraw.Draw(im).text((24, 20), label, fill='black', font=ImageFont.load_default(size=28))
96
+ file = folder / 'use.png'; im.resize((800, 800), Image.LANCZOS).save(file)
97
+ return str(file)
48
98
 
49
99
 
50
100
  # Starting print-in-place gap between separate bodies: Prusa's first value for movable parts is "at least 0.3 mm"
@@ -0,0 +1,426 @@
1
+ """3MF project output for cad_run: project_3mf() inside build().
2
+
3
+ A design script returns a project_3mf() instead of a shape when the result is a multi-part, multi-colour 3MF:
4
+ either a new project (parts with names, filaments and plates) or an edit of a declared input 3MF (a designer's
5
+ project), which keeps everything it does not change: print settings, painting, plates and other parts.
6
+
7
+ This module runs inside the sandbox. It reads the input 3MF, tessellates the script's geometry and writes STL
8
+ parts plus a manifest into the job folder; the trusted MCP process writes the 3MF itself and checks it.
9
+ """
10
+ import json
11
+ import math
12
+ import re
13
+ import zipfile
14
+ import xml.etree.ElementTree as ET
15
+ from pathlib import Path
16
+
17
+ CORE = '{http://schemas.microsoft.com/3dmanufacturing/core/2015/02}'
18
+ PRODUCTION = '{http://schemas.microsoft.com/3dmanufacturing/production/2015/06}'
19
+ ROOT_MODEL = '3D/3dmodel.model'
20
+ MAX_PARTS = 64
21
+ MAX_FILAMENT = 64
22
+ MAX_PLATES = 64
23
+ SKIPPED_SUBTYPES = ('negative_part', 'modifier_part', 'support_blocker', 'support_enforcer')
24
+
25
+
26
+ def _matrix(text):
27
+ """A 3MF transform (12 numbers, row vectors) as a 4x4 column-vector matrix."""
28
+ import numpy as np
29
+ m = np.eye(4)
30
+ if not text:
31
+ return m
32
+ values = [float(v) for v in text.split()]
33
+ if len(values) != 12 or not all(math.isfinite(v) for v in values):
34
+ raise ValueError('3MF transform must have 12 finite numbers.')
35
+ m[:3, :3] = np.array(values[:9]).reshape(3, 3).T
36
+ m[:3, 3] = values[9:]
37
+ return m
38
+
39
+
40
+ def _metadata(element):
41
+ return {m.get('key'): m.get('value', '') for m in element.findall('metadata') if m.get('key')}
42
+
43
+
44
+ def _int(value):
45
+ try:
46
+ number = int(str(value).strip())
47
+ except (TypeError, ValueError):
48
+ return 0
49
+ return number
50
+
51
+
52
+ class Part:
53
+ """A model part of a 3MF object: its mesh in the object's frame (component transform applied)."""
54
+
55
+ def __init__(self, object_id, part_id, path, name, filament, mesh, painted, local):
56
+ self.object_id = object_id
57
+ self.id = part_id
58
+ self.path = path
59
+ self.name = name
60
+ self.filament = filament
61
+ self.mesh = mesh
62
+ self.painted = painted
63
+ self._local = local # component transform: mesh coordinates -> object frame
64
+ self.plain = False # the object is this one mesh, without parts (a plain 3MF): it cannot be edited
65
+
66
+ def __repr__(self):
67
+ return f'Part(id={self.id}, name={self.name!r}, filament={self.filament}, painted={self.painted})'
68
+
69
+
70
+ class Object:
71
+ """A root object of the 3MF (what a build item places) with its parts."""
72
+
73
+ def __init__(self, object_id, name, plate, parts, placements):
74
+ self.id = object_id
75
+ self.name = name
76
+ self.plate = plate
77
+ self.parts = parts
78
+ self.placements = placements # build-item transforms: object frame -> plate (build) frame
79
+
80
+ def part(self, name_or_id):
81
+ for part in self.parts:
82
+ if str(part.id) == str(name_or_id) or part.name == name_or_id:
83
+ return part
84
+ raise ValueError(f'Object {self.name!r} has no part {name_or_id!r}.')
85
+
86
+ def __repr__(self):
87
+ return f'Object(id={self.id}, name={self.name!r}, plate={self.plate}, parts={self.parts!r})'
88
+
89
+
90
+ def _read(path):
91
+ """The input 3MF's objects with their parts as trimesh meshes in each object's frame."""
92
+ import numpy as np
93
+ import trimesh
94
+ with zipfile.ZipFile(path) as archive:
95
+ names = set(archive.namelist())
96
+ if ROOT_MODEL not in names:
97
+ raise ValueError('The input 3MF has no 3D/3dmodel.model.')
98
+ if any(re.fullmatch(r'Metadata/plate_\d+\.gcode', n) for n in names):
99
+ raise ValueError('The input 3MF holds G-code: edit the project file, not a sliced .gcode.3mf.')
100
+ # The input is a bounded snapshot (64 MiB): its model parts and settings are read once, here.
101
+ raw = {n: archive.read(n) for n in names if n.endswith('.model') or n in ('Metadata/model_settings.config', 'Metadata/project_settings.config')}
102
+ models = {}
103
+
104
+ def model(name):
105
+ name = name.lstrip('/')
106
+ if name not in models:
107
+ if name not in raw:
108
+ raise ValueError(f'The input 3MF names a missing model part {name}.')
109
+ models[name] = ET.fromstring(raw[name])
110
+ return models[name]
111
+
112
+ settings = ET.fromstring(raw['Metadata/model_settings.config']) if 'Metadata/model_settings.config' in raw else ET.Element('config')
113
+ root = model(ROOT_MODEL)
114
+ resources = {o.get('id'): o for o in root.iter(CORE + 'object')}
115
+ config = {o.get('id'): o for o in settings.findall('object')}
116
+ plate_of = {}
117
+ for plate in settings.findall('plate'):
118
+ number = _int(_metadata(plate).get('plater_id'))
119
+ for instance in plate.findall('model_instance'):
120
+ plate_of.setdefault(_metadata(instance).get('object_id'), number)
121
+ placements = {}
122
+ for item in root.iter(CORE + 'item'):
123
+ placements.setdefault(item.get('objectid'), []).append(_matrix(item.get('transform')))
124
+
125
+ def mesh_of(element):
126
+ mesh = element.find(CORE + 'mesh')
127
+ if mesh is None:
128
+ return None, False
129
+ vertices = np.array([[float(v.get(a)) for a in 'xyz'] for v in mesh.iter(CORE + 'vertex')], dtype=float).reshape(-1, 3)
130
+ triangles = list(mesh.iter(CORE + 'triangle'))
131
+ faces = np.array([[int(t.get(a)) for a in ('v1', 'v2', 'v3')] for t in triangles], dtype=np.int64).reshape(-1, 3)
132
+ painted = any(t.get('paint_color') for t in triangles)
133
+ return trimesh.Trimesh(vertices, faces, process=False), painted
134
+
135
+ objects = []
136
+ for object_id, items in placements.items():
137
+ element = resources.get(object_id)
138
+ if element is None:
139
+ continue
140
+ own = config.get(object_id)
141
+ meta = _metadata(own) if own is not None else {}
142
+ object_filament = _int(meta.get('extruder')) or 1
143
+ part_config = {p.get('id'): p for p in own.findall('part')} if own is not None else {}
144
+ parts = []
145
+ components = element.find(CORE + 'components')
146
+ if components is not None:
147
+ for component in components.findall(CORE + 'component'):
148
+ path = (component.get(PRODUCTION + 'path') or ROOT_MODEL).lstrip('/')
149
+ part_id = component.get('objectid')
150
+ part = part_config.get(part_id)
151
+ part_meta = _metadata(part) if part is not None else {}
152
+ if part is not None and part.get('subtype') == 'negative_part':
153
+ raise ValueError('CAD inspection of a 3MF project with negative volumes is not supported; '
154
+ 'the inspection mesh cannot yet apply their subtraction. Use a project with the cut baked into its mesh.')
155
+ if part is not None and part.get('subtype', 'normal_part') in SKIPPED_SUBTYPES:
156
+ continue
157
+ target = next((o for o in model(path).iter(CORE + 'object') if o.get('id') == part_id), None)
158
+ if target is None:
159
+ raise ValueError(f'Component {part_id} of object {object_id} is missing from {path}.')
160
+ mesh, painted = mesh_of(target)
161
+ if mesh is None:
162
+ raise ValueError('CAD inspection of nested or empty 3MF components is not supported; '
163
+ 'use a project whose object components directly contain meshes.')
164
+ local = _matrix(component.get('transform'))
165
+ mesh.apply_transform(local)
166
+ parts.append(Part(int(object_id), int(part_id), '/' + path, part_meta.get('name') or meta.get('name', ''),
167
+ _int(part_meta.get('extruder')) or object_filament, mesh, painted, local))
168
+ else:
169
+ mesh, painted = mesh_of(element)
170
+ if mesh is not None:
171
+ part = Part(int(object_id), int(object_id), '/' + ROOT_MODEL, meta.get('name', ''), object_filament, mesh, painted, np.eye(4))
172
+ part.plain = True
173
+ parts.append(part)
174
+ objects.append(Object(int(object_id), meta.get('name', ''), plate_of.get(object_id, 1), parts, items))
175
+ if not objects:
176
+ raise ValueError('The input 3MF has no object with a mesh.')
177
+ # The filaments the project declares: a part can only print in one of them.
178
+ declared = 0
179
+ try:
180
+ project = json.loads(raw.get('Metadata/project_settings.config', b'{}'))
181
+ declared = max(len(project.get(key) or []) for key in ('filament_colour', 'filament_type', 'filament_ids'))
182
+ except (ValueError, AttributeError, TypeError):
183
+ declared = 0
184
+ return objects, min(declared, MAX_FILAMENT)
185
+
186
+
187
+ def _geometry(value, label):
188
+ """A build123d Shape or a trimesh.Trimesh, as given."""
189
+ import trimesh
190
+ import build123d as cad
191
+ if isinstance(value, trimesh.Trimesh):
192
+ if not len(value.faces):
193
+ raise ValueError(label + ' is an empty mesh.')
194
+ return value
195
+ if isinstance(value, cad.Shape):
196
+ if not value.is_valid or not value.solids():
197
+ raise ValueError(label + ' must be a valid build123d Shape containing solids.')
198
+ return value
199
+ raise ValueError(label + ' must be a build123d Shape or a trimesh.Trimesh.')
200
+
201
+
202
+ def _filament(value, label):
203
+ if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= MAX_FILAMENT:
204
+ raise ValueError(f'{label} must be an integer filament from 1 to {MAX_FILAMENT}.')
205
+ return value
206
+
207
+
208
+ def _name(value, label):
209
+ if not isinstance(value, str) or not value.strip() or '\0' in value or len(value) > 200:
210
+ raise ValueError(label + ' must be a non-empty name of at most 200 characters.')
211
+ return value.strip()
212
+
213
+
214
+ class Project3mf:
215
+ """What build() returns for a 3MF project. Made by project_3mf(base=None)."""
216
+
217
+ def __init__(self, base, base_path):
218
+ self.base = base
219
+ self.objects, self.filaments = _read(base_path) if base_path else ([], 0)
220
+ self._new = [] # new project: {object, plate, name, filament, geometry}
221
+ self._edits = [] # edit: operations on the base
222
+
223
+ def object(self, name_or_id):
224
+ """A base object by its root object id, or by its name when only one object has it."""
225
+ for obj in self.objects:
226
+ if str(obj.id) == str(name_or_id):
227
+ return obj
228
+ named = [obj for obj in self.objects if obj.name == name_or_id]
229
+ if len(named) > 1:
230
+ raise ValueError(f'{len(named)} objects are named {name_or_id!r} (ids ' + ', '.join(str(o.id) for o in named)
231
+ + '): pick one by id, or edit each copy.')
232
+ if named:
233
+ return named[0]
234
+ raise ValueError(f'The input 3MF has no object {name_or_id!r}; objects: ' + ', '.join(repr(o.name) for o in self.objects))
235
+
236
+ def _declared(self, filament, label):
237
+ filament = _filament(filament, label)
238
+ if self.base and self.filaments and filament > self.filaments:
239
+ raise ValueError(f'{label} {filament} is not one of the {self.filaments} filaments the input 3MF declares.')
240
+ return filament
241
+
242
+ def _count(self):
243
+ if len(self._new) + sum(1 for e in self._edits if 'geometry' in e) >= MAX_PARTS:
244
+ raise ValueError(f'A project takes at most {MAX_PARTS} new or replaced parts.')
245
+
246
+ def add_part(self, geometry, *, name, filament=None, object=None, plate=1):
247
+ """Add a part. Editing a 3MF: into the base object `object` (name or id), in that object's frame.
248
+ A new project: into the object named `object` (default: one object per part's name) on `plate`."""
249
+ self._count()
250
+ name = _name(name, 'name')
251
+ geometry = _geometry(geometry, f'Part {name!r}')
252
+ if self.base:
253
+ if object is None:
254
+ raise ValueError('Editing a 3MF, add_part needs object=: the base object (name or id) the part joins.')
255
+ target = self.object(object)
256
+ if any(part.plain for part in target.parts):
257
+ raise ValueError(f'Object {target.name!r} is one mesh without parts (a plain 3MF): only a Bambu Studio or OrcaSlicer project\'s objects take new parts.')
258
+ if plate != 1:
259
+ raise ValueError('Editing a 3MF, a new part sits on its object\'s plate; plate cannot be set.')
260
+ self._edits.append({'op': 'add_part', 'object_id': target.id, 'name': name,
261
+ 'filament': self._declared(filament if filament is not None else (target.parts[0].filament if target.parts else 1), 'filament'),
262
+ 'geometry': geometry})
263
+ else:
264
+ if isinstance(plate, bool) or not isinstance(plate, int) or not 1 <= plate <= MAX_PLATES:
265
+ raise ValueError(f'plate must be an integer from 1 to {MAX_PLATES}.')
266
+ self._new.append({'object': _name(object, 'object') if object is not None else name, 'plate': plate, 'name': name,
267
+ 'filament': _filament(filament if filament is not None else len(self._new) + 1, 'filament'),
268
+ 'geometry': geometry})
269
+ return self
270
+
271
+ def _base_part(self, part):
272
+ if not self.base:
273
+ raise ValueError('Only an edited 3MF has parts to change; add_part builds a new project.')
274
+ if not isinstance(part, Part):
275
+ raise ValueError('Pass a part from project.objects[...].parts (or project.object(...).part(...)).')
276
+ if part.plain:
277
+ raise ValueError(f'Part {part.name!r} is a plain 3MF object\'s only mesh, with no part settings to change: edit a Bambu Studio or OrcaSlicer project.')
278
+ return part
279
+
280
+ def replace_part(self, part, geometry):
281
+ """Replace a base part's mesh with new geometry in its object's frame. Its painting goes with the old mesh."""
282
+ part = self._base_part(part)
283
+ self._count()
284
+ self._edits.append({'op': 'replace_part', 'object_id': part.object_id, 'part_id': part.id, 'path': part.path,
285
+ 'geometry': _geometry(geometry, f'Replacement for {part.name!r}'), 'local': part._local})
286
+ return self
287
+
288
+ def set_part(self, part, *, name=None, filament=None):
289
+ """Rename a base part or change its filament (1-based). Painting on it is kept."""
290
+ part = self._base_part(part)
291
+ edit = {'op': 'set_part', 'object_id': part.object_id, 'part_id': part.id}
292
+ if name is not None:
293
+ edit['name'] = _name(name, 'name')
294
+ if filament is not None:
295
+ edit['filament'] = self._declared(filament, 'filament')
296
+ if len(edit) == 3:
297
+ raise ValueError('set_part needs name= or filament=.')
298
+ self._edits.append(edit)
299
+ return self
300
+
301
+
302
+ def project_factory(inputs):
303
+ declared = dict(inputs)
304
+
305
+ def project_3mf(base=None):
306
+ """A 3MF project for build() to return: new (base=None) or an edit of the declared input 3MF `base`."""
307
+ if base is None:
308
+ return Project3mf(None, None)
309
+ if base not in declared or not str(declared[base]).lower().endswith('.3mf'):
310
+ raise ValueError('project_3mf(base) needs the name of a declared .3mf input.')
311
+ return Project3mf(base, declared[base])
312
+ return project_3mf
313
+
314
+
315
+ def _fused(meshes):
316
+ """An object's parts as one body for the checks, as the STEP path fuses them: colour parts that touch or overlap
317
+ print as one piece, and their shared faces are not the object's surface. A part that is not a closed solid is kept
318
+ as it is, beside the others, so the checks still see the defect."""
319
+ import numpy as np
320
+ import trimesh
321
+ import manifold3d as mf
322
+ if len(meshes) < 2:
323
+ return meshes
324
+ solids, open_parts = [], []
325
+ for m in meshes:
326
+ part = m.copy()
327
+ part.merge_vertices()
328
+ solid = mf.Manifold(mf.Mesh(np.asarray(part.vertices, dtype=np.float32), np.asarray(part.faces, dtype=np.uint32))) if part.is_volume else None
329
+ if solid is None or solid.status() != mf.Error.NoError:
330
+ open_parts.append(m)
331
+ else:
332
+ solids.append(solid)
333
+ if len(solids) < 2:
334
+ return meshes
335
+ union = mf.Manifold.batch_boolean(solids, mf.OpType.Add)
336
+ body = union.to_mesh()
337
+ if union.status() != mf.Error.NoError or not len(body.tri_verts):
338
+ return meshes
339
+ return [trimesh.Trimesh(np.asarray(body.vert_properties, dtype=float)[:, :3], np.asarray(body.tri_verts, dtype=np.int64), process=False)] + open_parts
340
+
341
+
342
+ def export(project, out, mode):
343
+ """Write the project's parts as STL, a manifest the MCP writes the 3MF from, and one combined STL (plus STEP for a
344
+ new all-solid project) for the engine's usual checks and renders. The combined STL holds one fused body per object
345
+ placement, as the STEP holds one fused body per object."""
346
+ import numpy as np
347
+ import trimesh
348
+ import build123d as cad
349
+ if not project._new and not project._edits:
350
+ raise ValueError('The 3MF project is empty: add_part, replace_part or set_part first.')
351
+ if project.base and mode == 'solid':
352
+ raise ValueError('Editing a 3MF runs with mode: "mesh": the designer\'s parts are meshes, with no STEP.')
353
+ parts_dir = Path(str(out) + '.parts')
354
+ parts_dir.mkdir()
355
+ counter = [0]
356
+
357
+ def stl(geometry, transform=None):
358
+ index = counter[0]
359
+ counter[0] += 1
360
+ target = parts_dir / f'{index}.stl'
361
+ if isinstance(geometry, trimesh.Trimesh):
362
+ mesh = geometry.copy()
363
+ else:
364
+ cad.export_stl(geometry, str(target), tolerance=0.01, angular_tolerance=0.1)
365
+ mesh = trimesh.load(str(target), force='mesh')
366
+ if transform is not None:
367
+ mesh.apply_transform(transform)
368
+ mesh.export(str(target))
369
+ return index, mesh
370
+
371
+ manifest = {'version': 1, 'base': project.base}
372
+ combined = []
373
+ if project.base:
374
+ edits = []
375
+ replaced = {}
376
+ for edit in project._edits:
377
+ entry = {k: v for k, v in edit.items() if k not in ('geometry', 'local')}
378
+ if edit['op'] == 'add_part':
379
+ entry['stl'], mesh = stl(edit['geometry'])
380
+ replaced.setdefault((None, edit['object_id'], 'new'), []).append(mesh)
381
+ elif edit['op'] == 'replace_part':
382
+ # The replacement is drawn in the object's frame; the file keeps the part's component transform.
383
+ entry['stl'], mesh = stl(edit['geometry'], np.linalg.inv(edit['local']))
384
+ # A part is its (model file, object, part id): two model files may reuse an object id. The mesh is kept
385
+ # in its file's coordinates: an object that places it twice shows it under each component transform.
386
+ replaced[(edit['path'], edit['object_id'], edit['part_id'])] = mesh
387
+ edits.append(entry)
388
+ manifest['edits'] = edits
389
+ # The whole project as the build places it, with the edits, for the checks and renders.
390
+ for obj in project.objects:
391
+ meshes = []
392
+ for part in obj.parts:
393
+ fresh = replaced.get((part.path, obj.id, part.id))
394
+ meshes.append(part.mesh if fresh is None else fresh.copy().apply_transform(part._local))
395
+ meshes += replaced.get((None, obj.id, 'new'), [])
396
+ meshes = _fused(meshes)
397
+ for placement in obj.placements:
398
+ combined += [m.copy().apply_transform(placement) for m in meshes]
399
+ else:
400
+ objects, meshes = {}, {}
401
+ for part in project._new:
402
+ key = part['object']
403
+ if key in objects and objects[key]['plate'] != part['plate']:
404
+ raise ValueError(f'Object {key!r} has parts on two plates; one object sits on one plate.')
405
+ index, mesh = stl(part['geometry'])
406
+ objects.setdefault(key, {'name': key, 'plate': part['plate'], 'parts': []})['parts'].append(
407
+ {'stl': index, 'name': part['name'], 'filament': part['filament']})
408
+ meshes.setdefault(key, []).append(mesh)
409
+ for key in objects:
410
+ combined += _fused(meshes[key])
411
+ manifest['objects'] = list(objects.values())
412
+ shapes = [p['geometry'] for p in project._new]
413
+ if mode == 'solid':
414
+ if not all(isinstance(s, cad.Shape) for s in shapes):
415
+ raise ValueError('A project with mesh parts runs with mode: "mesh".')
416
+ # One body per object, its parts fused: the parts of a multi-colour object print as one piece, so the
417
+ # engine's body checks measure objects against each other, not an inlay against its own tile.
418
+ labelled = []
419
+ for key in objects:
420
+ members = [p['geometry'] for p in project._new if p['object'] == key]
421
+ body = members[0].fuse(*members[1:]) if len(members) > 1 else members[0].moved(cad.Location())
422
+ body.label = key
423
+ labelled.append(body)
424
+ cad.export_step(cad.Compound(children=labelled), str(out) + '.step')
425
+ trimesh.util.concatenate(combined).export(str(out) + '.stl')
426
+ Path(str(out) + '.project.json').write_text(json.dumps(manifest))