# SculptForge - open source digital sculpting # SPDX-License-Identifier: GPL-3.0-or-later """SculptForge bridge for 3ds Max. Sends the selected meshes from 3ds Max to SculptForge and gets them back, through ONE exchange folder that you pick in both apps. Nothing else is shared: no ports, sockets or servers, and neither side runs anything it finds in the folder. Meshes travel as OBJ (quads and UVs, world space, Y-up, one object per file); a small JSON manifest per direction lists the objects. This is the same folder design as the Maya bridge: /max_to_sculptforge/manifest.json + r_.obj written here (Send to SculptForge) /sculptforge_to_max/manifest.json + r_.obj written by SculptForge (File > 3ds Max > Send to 3ds Max) 3ds Max is Z-up: positions are turned to Y-up on the way out and back on the way in, so the folder always holds what SculptForge shows. Units are not converted (what you see in Max is what SculptForge gets, 1:1). Get from SculptForge replaces each object's mesh by name (names are reduced to letters, digits and '_': "My Box" is "My_Box" in the folder), keeping its transform, parent and material, as one undo step; objects 3ds Max doesn't have yet are created. Watch (on after your first Send, Get or Folder click) does the Get by itself when SculptForge sends: every 250 ms a Qt timer looks at the modification time and size of SculptForge's manifest (nothing else in the folder), and only when they change is the Get run. Python 3 and pymxs (3ds Max 2022 or newer) and the standard library; nothing else. Install: see README.md beside this file, or run this file once from 3ds Max (Scripting > Run Script) to add the SculptForge menu and macros. """ # This script's own version (its integration lane: a tag max-vX.Y.Z releases it, docs/releasing.md). What it can # read from SculptForge is the manifest VERSION below, not the app's version. __version__ = "1.0.0" import json import os import re import sys import uuid FORMAT = "sculptforge-max" VERSION = 1 TO_SCULPTFORGE = "max_to_sculptforge" FROM_SCULPTFORGE = "sculptforge_to_max" MAX_MANIFEST_BYTES = 256 * 1024 MAX_OBJECTS = 256 MAX_NAME = 128 MAX_FILE_NAME = 64 MAX_OBJ_BYTES = 1 << 30 # a Python list of vertices is what limits a Get; SculptForge writes much bigger files POLL_MS = 250 MENU = "SculptForge" CONFIG_FILE = "sculptforge_max.json" _FILE_CHARS = re.compile(r"^[A-Za-z0-9_.\-]+$") _NAME_BAD = re.compile(r"[^A-Za-z0-9_]") # ---- The exchange format (no 3ds Max needed: tests/max/test_sculptforge_max.py runs these with plain Python) ---- def safe_name(name): """The name a node has in the folder: letters, digits and '_' only, not starting with a digit, at most MAX_NAME.""" s = _NAME_BAD.sub("_", (name or "").encode("utf-8", "replace").decode("ascii", "replace").replace("�", "_")) s = s[:MAX_NAME] if not s: return "Part" if s[0].isdigit(): s = ("_" + s)[:MAX_NAME] return s def file_name_ok(name): """A file a manifest may list: a plain *.obj name inside the manifest's own folder.""" return (isinstance(name, str) and 4 < len(name) <= MAX_FILE_NAME and not name.startswith(".") and ".." not in name and _FILE_CHARS.match(name) is not None and name.lower().endswith(".obj")) def unique_names(names): """Name, Name1, Name2... for repeats (after safe_name).""" out = [] for n in names: wanted, name, k = safe_name(n), safe_name(n), 0 while name in out: k += 1 name = wanted + str(k) out.append(name) return out def write_manifest(objects, revision, sender_version="", unit="", writer=""): """The manifest text. `objects` is a list of (name, file).""" data = {"format": FORMAT, "version": VERSION, "revision": int(revision), "sender": "max", "sender_version": str(sender_version)[:64]} if unit: data["unit"] = str(unit)[:64] if writer: data["writer"] = str(writer)[:64] data["objects"] = [{"name": n, "file": f} for n, f in objects] return json.dumps(data, indent=2) + "\n" def parse_manifest(text): """Checks a manifest as strictly as SculptForge does. Returns {"revision", "sender", "objects": [(name, file)]}; raises ValueError with the reason.""" if len(text) > MAX_MANIFEST_BYTES: raise ValueError("the manifest is too big") try: data = json.loads(text) except (ValueError, RecursionError) as e: raise ValueError("the manifest is not valid JSON (%s)" % e) if not isinstance(data, dict) or data.get("format") != FORMAT: raise ValueError("not a SculptForge 3ds Max bridge manifest") version = data.get("version") if isinstance(version, bool) or not isinstance(version, (int, float)) or version < 1 or version != int(version): raise ValueError("the manifest has no valid version") if version > VERSION: raise ValueError("the manifest is from a newer SculptForge (version %d): update this script" % version) revision = data.get("revision") if (isinstance(revision, bool) or not isinstance(revision, (int, float)) or revision < 0 or revision != int(revision) or revision > 2 ** 53): raise ValueError("the manifest has no valid revision") for key in ("sender", "sender_version", "unit", "writer"): if key in data and (not isinstance(data[key], str) or len(data[key]) > 64): raise ValueError("the manifest has a bad %r" % key) objects = data.get("objects") if not isinstance(objects, list): raise ValueError("the manifest lists no objects") if len(objects) > MAX_OBJECTS: raise ValueError("the manifest lists too many objects (%d, at most %d)" % (len(objects), MAX_OBJECTS)) out, files = [], set() for o in objects: if not isinstance(o, dict) or not isinstance(o.get("name"), str) or not isinstance(o.get("file"), str): raise ValueError("the manifest has an object without a name and a file") if not file_name_ok(o["file"]): raise ValueError("the manifest names a file this script won't read: %r" % o["file"][:MAX_FILE_NAME]) if o["file"] in files: raise ValueError("the manifest lists %r twice" % o["file"]) if len(o["name"].encode("utf-8")) > 4 * MAX_NAME: raise ValueError("the manifest has a name that is too long") files.add(o["file"]) out.append((safe_name(o["name"]), o["file"])) return {"revision": int(revision), "sender": data.get("sender", ""), "writer": data.get("writer", ""), "objects": out} def read_manifest(box): """The parsed manifest in `box`, or None when nothing has been sent. Raises ValueError when it is not valid.""" path = os.path.join(box, "manifest.json") if not os.path.lexists(path): return None if os.path.islink(path) or not os.path.isfile(path): raise ValueError("%s is not a plain file" % path) if os.path.getsize(path) > MAX_MANIFEST_BYTES: raise ValueError("the manifest is too big") with open(path, "r", encoding="utf-8") as f: return parse_manifest(f.read(MAX_MANIFEST_BYTES + 1)) def object_file(box, file_name): """The full path of a file a manifest lists, checked: a plain file directly inside `box`.""" if not file_name_ok(file_name): raise ValueError("bad file name %r" % file_name) path = os.path.join(box, file_name) if (os.path.dirname(os.path.realpath(path)) != os.path.realpath(box) or os.path.islink(path) or not os.path.isfile(path)): raise ValueError("%s is missing or not a plain file in the exchange folder" % file_name) if os.path.getsize(path) > MAX_OBJ_BYTES: raise ValueError("%s is too big for this script" % file_name) return path def remove_entry(path): """Removes a file or link (never what a link points to), so a planted link can't redirect a write.""" if os.path.lexists(path) and not os.path.isdir(path) or os.path.islink(path): os.remove(path) def write_atomically(path, text): tmp = path + ".tmp" remove_entry(tmp) with open(tmp, "w", encoding="utf-8", newline="\n") as f: f.write(text) os.replace(tmp, path) def next_revision(box): try: m = read_manifest(box) except ValueError: m = None return (m["revision"] if m else 0) + 1 def remove_old_sends(box, keep_prefix): """Removes r_* files of earlier sends (and nothing else).""" for n in os.listdir(box): if re.match(r"^r[0-9]+_", n) and not n.startswith(keep_prefix): try: os.remove(os.path.join(box, n)) except OSError: pass # open elsewhere: the next send tries again def manifest_stamp(box): """The modification time and size of /manifest.json, or None when there is none: what Watch checks every 250 ms (cheap); the manifest itself is read only when this changes.""" try: st = os.lstat(os.path.join(box, "manifest.json")) except OSError: return None return (st.st_mtime_ns, st.st_size) # ---- OBJ and mesh maths (also plain Python) ---- def to_yup(p): """3ds Max is Z-up, SculptForge Y-up: a quarter turn about X.""" return (p[0], p[2], -p[1]) def from_yup(p): return (p[0], -p[2], p[1]) def _g(x): return "%.7g" % x def write_obj(path, verts, polys, uvs=None): """`verts`: Y-up positions. `polys`: lists of corners, each corner a vertex index or a (vertex, uv) pair (0-based); `uvs`: the (u, v) list those pairs point into.""" lines = ["# SculptForge bridge for 3ds Max"] lines += ["v %s %s %s" % (_g(x), _g(y), _g(z)) for x, y, z in verts] if uvs: lines += ["vt %s %s" % (_g(u), _g(v)) for u, v in uvs] for poly in polys: if uvs: lines.append("f " + " ".join("%d/%d" % (c[0] + 1, c[1] + 1) for c in poly)) else: lines.append("f " + " ".join(str((c[0] if isinstance(c, tuple) else c) + 1) for c in poly)) with open(path, "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(lines) + "\n") def parse_obj(path): """Reads v, vt and f lines (nothing else is looked at). Returns (verts, uvs, polys): `polys` are lists of (vertex, uv or None) 0-based corners. Raises ValueError for a face that points outside the file.""" verts, uvs, polys = [], [], [] with open(path, "r", encoding="utf-8", errors="replace") as f: for line in f: parts = line.split() if not parts: continue tag = parts[0] if tag == "v" and len(parts) >= 4: verts.append((float(parts[1]), float(parts[2]), float(parts[3]))) elif tag == "vt" and len(parts) >= 3: uvs.append((float(parts[1]), float(parts[2]))) elif tag == "f" and len(parts) >= 4: poly = [] for token in parts[1:]: ids = token.split("/") v = _obj_index(ids[0], len(verts)) t = _obj_index(ids[1], len(uvs)) if len(ids) > 1 and ids[1] else None poly.append((v, t)) polys.append(poly) for poly in polys: for v, t in poly: if v >= len(verts) or (t is not None and t >= len(uvs)): raise ValueError("%s has a face that points outside the file" % os.path.basename(path)) return verts, uvs, polys def _obj_index(text, count): i = int(text) if i < 0: i = count + i + 1 # negative: relative to the vertices read so far if i < 1: raise ValueError("a face has an index of 0") return i - 1 def triangulate(polys): """Fan triangles for each polygon, and for each triangle which of its edges (v1v2, v2v3, v3v1) is a diagonal that 3ds Max should hide again, so quads stay quads. Returns (tris, hidden).""" tris, hidden = [], [] for poly in polys: n = len(poly) for i in range(1, n - 1): tris.append((poly[0], poly[i], poly[i + 1])) hidden.append((i > 1, False, i + 1 < n - 1)) return tris, hidden def merge_quads(tris, hidden): """The inverse of triangulate for what 3ds Max hands over: two triangles whose shared edge is hidden in both become one quad. Corners are (vertex, uv) pairs. Everything else (n-gons come as triangles) stays a triangle.""" shared = {} for t, tri in enumerate(tris): for k in range(3): if hidden[t][k]: a, b = tri[k][0], tri[(k + 1) % 3][0] shared.setdefault((min(a, b), max(a, b)), []).append((t, k)) used, polys = set(), [] for t, tri in enumerate(tris): if t in used: continue poly = list(tri) for k in range(3): if not hidden[t][k]: continue u, v, p = tri[k], tri[(k + 1) % 3], tri[(k + 2) % 3] others = [o for o in shared.get((min(u[0], v[0]), max(u[0], v[0])), []) if o[0] != t and o[0] not in used] if len(others) != 1: continue t2, k2 = others[0] tri2 = tris[t2] if tri2[k2][0] != v[0] or tri2[(k2 + 1) % 3][0] != u[0]: continue # the two triangles face opposite ways: leave them alone poly = [p, u, tri2[(k2 + 2) % 3], v] used.add(t2) break used.add(t) polys.append(poly) return polys def _row_apply(rows, p): """p * matrix (3ds Max's row-vector convention): rows are the matrix's row1..row4 as (x, y, z).""" return tuple(p[0] * rows[0][i] + p[1] * rows[1][i] + p[2] * rows[2][i] + rows[3][i] for i in range(3)) # ---- 3ds Max (pymxs) ---- _state = {"folder": "", "seen": None, "stamp": None, "sent": {}, "timer": None, "watch": False} WRITER = uuid.uuid4().hex[:16] # this 3ds Max session's id in the manifests it writes def _rt(): from pymxs import runtime return runtime def _say(text, error=False): print("SculptForge: " + text) try: rt = _rt() if error: rt.messageBox(text, title="SculptForge") else: rt.displayTempPrompt(text, 5000) except Exception: pass def _config_path(): try: return os.path.join(_rt().pathConfig.getDir(_rt().Name("plugcfg")), CONFIG_FILE) except Exception: return os.path.join(os.path.expanduser("~"), "." + CONFIG_FILE) def _load_folder(): if _state["folder"]: return _state["folder"] try: with open(_config_path(), "r", encoding="utf-8") as f: folder = json.load(f).get("folder", "") if isinstance(folder, str) and os.path.isdir(folder): _state["folder"] = folder except (OSError, ValueError, AttributeError): pass return _state["folder"] def choose_folder(): """Pick the exchange folder (the same one as in SculptForge: File > 3ds Max > Exchange folder...).""" rt = _rt() folder = rt.getSavePath(caption="Choose the SculptForge exchange folder", initialDir=_state["folder"] or "") if not folder or not os.path.isdir(folder): return None _state["folder"] = str(folder) _state["seen"] = _revision_in(os.path.join(folder, FROM_SCULPTFORGE)) # what is there already is old news _state["stamp"] = manifest_stamp(os.path.join(folder, FROM_SCULPTFORGE)) try: with open(_config_path(), "w", encoding="utf-8") as f: json.dump({"folder": _state["folder"]}, f) except OSError: pass _say("exchange folder: %s (pick the same one in SculptForge: File > 3ds Max > Exchange folder...)" % folder) start_watch() return _state["folder"] def _folder(ask=True): folder = _load_folder() if not folder and ask: folder = choose_folder() return folder def _revision_in(box): try: m = read_manifest(box) except ValueError: return None return m["revision"] if m else None def _scene_meshes(): rt = _rt() return [n for n in rt.geometry if rt.canConvertTo(n, rt.Editable_mesh)] def _selected_meshes(): rt = _rt() return [n for n in rt.selection if rt.superClassOf(n) == rt.GeometryClass and rt.canConvertTo(n, rt.Editable_mesh)] def extract_mesh(node): """The node as it renders (modifiers on), world space, Y-up: (verts, polys, uvs). Quads come from the edges 3ds Max keeps hidden inside a polygon.""" rt = _rt() m = rt.snapshotAsMesh(node) # world space, modifiers applied verts = [] for i in range(1, int(m.numverts) + 1): p = rt.getVert(m, i) verts.append(to_yup((float(p.x), float(p.y), float(p.z)))) uvs, tvfaces = [], None if rt.meshop.getMapSupport(m, 1): for i in range(1, int(rt.meshop.getNumMapVerts(m, 1)) + 1): t = rt.meshop.getMapVert(m, 1, i) uvs.append((float(t.x), float(t.y))) tvfaces = [rt.meshop.getMapFace(m, 1, f) for f in range(1, int(m.numfaces) + 1)] tris, hidden = [], [] for f in range(1, int(m.numfaces) + 1): face = rt.getFace(m, f) v = (int(face.x) - 1, int(face.y) - 1, int(face.z) - 1) if tvfaces: tv = tvfaces[f - 1] t = (int(tv.x) - 1, int(tv.y) - 1, int(tv.z) - 1) else: t = (None, None, None) tris.append(tuple(zip(v, t))) hidden.append(tuple(not rt.getEdgeVis(m, f, e) for e in (1, 2, 3))) return verts, merge_quads(tris, hidden), uvs def _unit(): try: return str(_rt().units.SystemType).lstrip("#") except Exception: return "" def send_to_sculptforge(): """Send the selected meshes to SculptForge (File > 3ds Max > Get from 3ds Max, or Get automatically, loads them).""" folder = _folder() if not folder: return nodes = _selected_meshes() if not nodes: _say("select one or more meshes first", True) return if len(nodes) > MAX_OBJECTS: _say("too many objects to send at once (at most %d)" % MAX_OBJECTS, True) return box = os.path.join(folder, TO_SCULPTFORGE) try: if os.path.lexists(box) and (os.path.islink(box) or not os.path.isdir(box)): raise ValueError("%s is not a plain folder" % box) os.makedirs(box, exist_ok=True) revision = next_revision(box) prefix = "r%d_" % revision for n in os.listdir(box): # a planted link named like one of this send's files is removed, not written through if n.startswith(prefix) or n == "manifest.json.tmp": remove_entry(os.path.join(box, n)) names = unique_names([str(n.name) for n in nodes]) objects = [] for k, (node, name) in enumerate(zip(nodes, names)): verts, polys, uvs = extract_mesh(node) file_name = "%s%03d.obj" % (prefix, k) tmp = os.path.join(box, file_name + ".tmp") write_obj(tmp, verts, polys, uvs) os.replace(tmp, os.path.join(box, file_name)) objects.append((name, file_name)) _state["sent"][name] = int(node.handle) write_atomically(os.path.join(box, "manifest.json"), write_manifest(objects, revision, __version__, _unit(), WRITER)) remove_old_sends(box, prefix) except (OSError, ValueError) as e: _say("send failed: %s" % e, True) return _say("sent %d object%s to SculptForge" % (len(nodes), "" if len(nodes) == 1 else "s")) start_watch() def _find_node(name): """The scene node a name in the folder means: the one it was sent from, else the geometry whose safe name matches.""" rt = _rt() handle = _state["sent"].get(name) if handle is not None: node = rt.maxOps.getNodeByHandle(handle) if node is not None and not rt.isDeleted(node): return node for node in _scene_meshes(): if safe_name(str(node.name)) == name: return node return None def build_trimesh(world_verts, polys, uvs): """A TriMesh of the polygons (Z-up world positions), quads kept by hiding their diagonals, smoothing group 1.""" rt = _rt() tris, hidden = triangulate(polys) tm = rt.TriMesh() rt.setNumVerts(tm, len(world_verts)) for i, p in enumerate(world_verts): rt.setVert(tm, i + 1, rt.Point3(*p)) rt.setNumFaces(tm, len(tris)) for f, tri in enumerate(tris, 1): rt.setFace(tm, f, tri[0][0] + 1, tri[1][0] + 1, tri[2][0] + 1) rt.setFaceSmoothGroup(tm, f, 1) for e in range(3): rt.setEdgeVis(tm, f, e + 1, not hidden[f - 1][e]) if uvs and all(c[1] is not None for tri in tris for c in tri): rt.meshop.setMapSupport(tm, 1, True) rt.meshop.setNumMapVerts(tm, 1, len(uvs)) for i, (u, v) in enumerate(uvs): rt.meshop.setMapVert(tm, 1, i + 1, rt.Point3(u, v, 0)) rt.meshop.setNumMapFaces(tm, 1, len(tris)) for f, tri in enumerate(tris, 1): rt.meshop.setMapFace(tm, 1, f, rt.Point3(tri[0][1] + 1, tri[1][1] + 1, tri[2][1] + 1)) return tm def _replace_mesh(node, tm): """Puts the TriMesh's geometry (world space) into `node`: its transform, parent, materials and modifiers stay. Returns False (and does nothing) for a parametric object with modifiers.""" rt = _rt() base = node.baseobject if rt.classOf(base) not in (rt.Editable_Poly, rt.Editable_mesh): if node.modifiers.count: return False # collapse it first: SculptForge won't throw away someone's modifier stack rt.convertToPoly(node) base = node.baseobject neither = rt.Name("neither") new = rt.mesh(mesh=tm) if rt.classOf(base) == rt.Editable_Poly: rt.convertToPoly(new) # hidden diagonals become quads rt.polyop.deleteFaces(node, rt.Name("all")) rt.polyop.attach(node, new, attachMat=neither) else: rt.meshop.deleteFaces(node, rt.Name("all")) rt.meshop.attach(node, new, attachMat=neither) return True def get_from_sculptforge(): """Load what SculptForge last sent: each object replaces the mesh of the node with its name (one undo step); an object 3ds Max has no node for becomes a new Editable Poly.""" folder = _folder() if not folder: return box = os.path.join(folder, FROM_SCULPTFORGE) try: m = read_manifest(box) if m is None or not m["objects"]: _say("nothing has been sent from SculptForge yet") return loaded = [(name, parse_obj(object_file(box, f))) for name, f in m["objects"]] except (OSError, ValueError) as e: _say("get failed: %s" % e, True) return import pymxs rt = _rt() done, skipped = 0, [] with pymxs.undo(True, "Get from SculptForge"), pymxs.redraw(False): for name, (verts, uvs, polys) in loaded: if not polys: skipped.append(name + " (no faces)") continue tm = build_trimesh([from_yup(v) for v in verts], polys, uvs) node = _find_node(name) if node is None: new = rt.mesh(mesh=tm) new.name = name rt.convertToPoly(new) _state["sent"][name] = int(new.handle) elif not _replace_mesh(node, tm): skipped.append(name + " (modifiers on a parametric object: collapse it first)") continue done += 1 _state["seen"] = m["revision"] _state["stamp"] = manifest_stamp(box) text = "got %d object%s from SculptForge" % (done, "" if done == 1 else "s") _say(text + ("; skipped " + ", ".join(skipped) if skipped else ""), bool(skipped)) # ---- Watch: Get by itself when SculptForge sends ---- def _poll(): """One look at SculptForge's manifest (called by the Qt timer in 3ds Max's main thread).""" folder = _state["folder"] if not folder or not _state["watch"]: return box = os.path.join(folder, FROM_SCULPTFORGE) stamp = manifest_stamp(box) if stamp is None or stamp == _state["stamp"]: return _state["stamp"] = stamp try: m = read_manifest(box) except ValueError: return # half written: the next change is checked if m is None or m["revision"] == _state["seen"]: return if m["writer"] and m["writer"] == WRITER: _state["seen"] = m["revision"] return get_from_sculptforge() def start_watch(): """Turn Watch on (it is on after the first Send, Get or Folder click). Needs PySide2 or PySide6 (3ds Max has one).""" if _state["timer"] is not None: _state["watch"] = True return True for module in ("PySide6", "PySide2"): try: QtCore = __import__(module + ".QtCore", fromlist=["QtCore"]) except ImportError: continue timer = QtCore.QTimer() timer.timeout.connect(_poll) timer.start(POLL_MS) _state["timer"], _state["watch"] = timer, True return True return False def toggle_watch(): on = not _state["watch"] if on: _state["stamp"] = manifest_stamp(os.path.join(_state["folder"], FROM_SCULPTFORGE)) if _state["folder"] else None on = start_watch() else: _state["watch"] = False _say("Watch %s" % ("on: SculptForge's sends load by themselves" if on else "off: use Get from SculptForge")) # ---- The menu and macros ---- _MACROS = [ ("SculptForgeSend", "Send to SculptForge", "send_to_sculptforge"), ("SculptForgeGet", "Get from SculptForge", "get_from_sculptforge"), ("SculptForgeWatch", "Watch SculptForge", "toggle_watch"), ("SculptForgeFolder", "Exchange folder...", "choose_folder"), ] def _script_folder(): """The folder this file is in (Run Script may not set __file__: then 3ds Max asks).""" path = globals().get("__file__") if not path: path = _rt().getOpenFileName(caption="Locate sculptforge_max.py", types="Python (*.py)|*.py") return os.path.dirname(os.path.abspath(str(path))).replace("\\", "/") if path else "" def macro_script(folder, function): """The MAXScript of one macro: python.Execute "". The folder goes into the Python as a string literal (json.dumps: any quote, backslash or non-ASCII character), and the whole code into the MAXScript string with \\ and \" escaped, so a path like C:/Users/O'Brien can't break the macro.""" code = ("import sys; p = %s; sys.path.insert(0, p) if p not in sys.path else None; import sculptforge_max; " "sculptforge_max.%s()") % (json.dumps(folder), function) return 'python.Execute "%s"' % code.replace("\\", "\\\\").replace('"', '\\"') def install(): """Adds the macros (Customize > Toolbars > category SculptForge, to drag onto a toolbar) and a SculptForge menu.""" rt = _rt() here = _script_folder() if not here or not os.path.isfile(os.path.join(here, "sculptforge_max.py")): _say("install: choose sculptforge_max.py", True) return for name, label, function in _MACROS: rt.macros.new(MENU, name, label, label, macro_script(here, function)) items = "".join('sub.addItem (mm.createActionItem "%s" "%s") -1\n' % (name, MENU) for name, _, _ in _MACROS) try: # menuMan is the legacy menu API: where it is gone, the macros above are still there to drag onto a toolbar rt.execute('''( local mm = menuMan local old = mm.findMenu "%s" if old != undefined do mm.unRegisterMenu old local sub = mm.createMenu "%s" %s local bar = mm.getMainMenuBar() bar.addItem (mm.createSubMenuItem "%s" sub) (bar.numItems() + 1) mm.updateMenuBar() )''' % (MENU, MENU, items, MENU)) _say("installed: SculptForge menu and macros (category SculptForge)") except Exception as e: _say("installed the macros (category SculptForge); no menu: %s" % e) if __name__ == "__main__": # Scripting > Run Script install()