""" The Mighty Pencil - Blue Pencil retarget and import GUI for Maya 2024+. (c) 2026 Dr Jack Parry WHAT THIS DOES Takes a Blue Pencil archive exported from The Mighty Pencil (or from Maya itself), rewrites it so the drawings attach to YOUR shot camera instead of whatever camera it was exported against, applies an optional frame offset, and imports it. USAGE Open it in the Script Editor (Python tab) and run it. A small window appears: Archive browse to the Mighty Pencil *_bluepencil_*.zip Camera pick the camera your shot is animated through (defaults to the camera of the active viewport) Frame offset added to every frame time; leave at 0 if the offset was already set when the archive was exported Click Retarget + Import. A retargeted copy of the archive is written next to the original (suffixed with the camera name) so the original stays untouched. ON IMPORTING The import is silent. bluePencilFrame -importArchive takes a path, which is the flag this tool uses. The neighbouring -importFrames takes no argument and only raises the file browser, which is the menu action and the fallback here if the archive flag is ever missing. Blue Pencil appears to bind an imported archive to the camera being looked through, so the panel is pointed at the chosen camera for the duration of the import and put back afterwards. The archive XML is retargeted as well, so either behaviour lands on the right camera. """ import os import shutil import tempfile import zipfile import xml.etree.ElementTree as ET import maya.cmds as cmds import maya.mel as mel MARKER = "MIGHTYPENCIL-BP-2026-08-09-b-importArchive" WIN = "mightyPencilBluePencilWin" # ---------------------------------------------------------------- cameras def _cameras(): return cmds.listCameras() or [] def _current_panel_camera(): try: panel = cmds.getPanel(withFocus=True) if panel and cmds.getPanel(typeOf=panel) == "modelPanel": cam = cmds.modelPanel(panel, query=True, camera=True) # the panel may hand back a shape; the menu lists transforms if cmds.nodeType(cam) == "camera": parents = cmds.listRelatives(cam, parent=True) or [] if parents: cam = parents[0] return cam except Exception: pass return None # ------------------------------------------------------------- retargeting def _retarget(zip_path, camera, offset): """Rewrite the archive XML for the chosen camera and frame offset. Returns the path of the retargeted copy; the original is untouched. """ zip_path = os.path.abspath(zip_path) base = os.path.splitext(os.path.basename(zip_path))[0] safe_cam = "".join(ch if ch.isalnum() or ch == "_" else "_" for ch in camera) out_zip = os.path.join(os.path.dirname(zip_path), "%s_%s.zip" % (base, safe_cam)) tmp = tempfile.mkdtemp(prefix="mightypencil_bp_") try: with zipfile.ZipFile(zip_path) as z: z.extractall(tmp) xml_path = None for root_dir, _dirs, files in os.walk(tmp): for f in files: if f.lower().endswith(".xml"): xml_path = os.path.join(root_dir, f) if not xml_path: raise RuntimeError("No XML manifest found inside the archive.") tree = ET.parse(xml_path) root = tree.getroot() for cam_el in root.iter("camera"): cam_el.set("name", camera) if offset: for fr in root.iter("frame"): fr.set("time", str(int(float(fr.get("time"))) + offset)) tree.write(xml_path, encoding="UTF-8", xml_declaration=True) if os.path.exists(out_zip): os.remove(out_zip) with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as z: for root_dir, _dirs, files in os.walk(tmp): for f in files: full = os.path.join(root_dir, f) rel = os.path.relpath(full, tmp) z.write(full, rel.replace(os.sep, "/")) finally: shutil.rmtree(tmp, ignore_errors=True) return out_zip # ---------------------------------------------------------------- clipboard def _to_clipboard(text): """Put text on the system clipboard. Maya 2026 is PySide6, older is 2.""" for mod in ("PySide6.QtWidgets", "PySide2.QtWidgets", "PySide.QtGui"): try: name = mod.rsplit(".", 1)[0] qt = __import__(mod, globals(), locals(), ["QApplication"]) app = qt.QApplication.instance() if app: app.clipboard().setText(text) return True except Exception: continue return False # ------------------------------------------------------------------ import def _has_runtime(name): try: return bool(cmds.runTimeCommand(name, exists=True)) except Exception: return False def _model_panel(): panel = cmds.getPanel(withFocus=True) if panel and cmds.getPanel(typeOf=panel) == "modelPanel": return panel for p in cmds.getPanel(type="modelPanel") or []: if cmds.modelPanel(p, query=True, exists=True): return p return None def _try_import(archive, camera): """Import the archive through the chosen camera. Returns 'auto', 'browser' or 'none'. -importArchive takes the path and does the whole job; the browser route is only there in case a build lacks the flag. """ unix_path = archive.replace("\\", "/") # Blue Pencil attaches to the camera in view, so look through the target # while the import runs, then put the panel back exactly as it was. panel = _model_panel() restore = None if panel and camera: try: restore = cmds.modelPanel(panel, query=True, camera=True) if restore != camera: cmds.lookThru(panel, camera) else: restore = None except Exception: restore = None try: for attempt in ( lambda: cmds.bluePencilFrame(importArchive=unix_path), lambda: mel.eval('bluePencilFrame -importArchive "%s";' % unix_path)): try: attempt() return "auto" except Exception as exc: last = exc print("// Mighty Pencil: importArchive unavailable (%s)" % last) finally: if restore: try: cmds.lookThru(panel, restore) except Exception: pass # fallback: the menu action, which takes no path and raises a browser if _has_runtime("ImportBluePencilFrames"): _to_clipboard(unix_path) answer = cmds.confirmDialog( title="Open the Blue Pencil importer", message=("The silent import is not available on this build, so " "the last step is yours.\n\nThe retargeted file is on " "your clipboard. Click Open, then paste the path into " "the file browser:\n\n%s" % unix_path), button=["Open importer", "Cancel"], defaultButton="Open importer", cancelButton="Cancel") if answer == "Open importer": try: mel.eval("ImportBluePencilFrames") return "browser" except Exception as exc: cmds.warning("ImportBluePencilFrames failed: %s" % exc) return "none" return "none" # ---------------------------------------------------------------------- ui def _go(*_args): zip_path = cmds.textFieldButtonGrp("doZip", query=True, text=True).strip() if not zip_path or not os.path.exists(zip_path): cmds.warning("Choose the Blue Pencil .zip first.") return camera = cmds.optionMenuGrp("doCam", query=True, value=True) offset = cmds.intFieldGrp("doOff", query=True, value1=True) try: out = _retarget(zip_path, camera, offset) except Exception as exc: cmds.confirmDialog(title="Mighty Pencil import", message="Could not retarget the archive:\n%s" % exc, button=["OK"]) return print("// Mighty Pencil: retargeted archive written to " + out) result = _try_import(out, camera) if result == "auto": cmds.inViewMessage( amg="Draw-overs imported to %s" % camera, pos="midCenter", fade=True) elif result == "none": cmds.confirmDialog( title="Retargeted archive ready", message=("The archive is retargeted to %s. Import it with\n" "Blue Pencil > Import Blue Pencil Frames:\n\n%s" % (camera, out)), button=["OK"]) def _browse(*_args): picked = cmds.fileDialog2( fileMode=1, fileFilter="Blue Pencil archive (*.zip)", caption="Choose the Mighty Pencil Blue Pencil zip") if picked: cmds.textFieldButtonGrp("doZip", edit=True, text=picked[0]) def show(): if cmds.window(WIN, exists=True): cmds.deleteUI(WIN) cmds.window(WIN, title="Mighty Pencil - Blue Pencil import", sizeable=False, widthHeight=(430, 210)) cmds.columnLayout(adjustableColumn=True, rowSpacing=8, columnOffset=("both", 10)) cmds.separator(style="none", height=2) cmds.text(label="Retarget a Mighty Pencil Blue Pencil archive to your " "shot camera and import it.", align="left", wordWrap=True) cmds.textFieldButtonGrp("doZip", label="Archive", buttonLabel="Browse...", buttonCommand=_browse, text="", columnWidth3=(70, 250, 90)) cmds.optionMenuGrp("doCam", label="Camera", columnWidth2=(70, 250)) current = _current_panel_camera() for cam in _cameras(): cmds.menuItem(label=cam) if current: try: cmds.optionMenuGrp("doCam", edit=True, value=current) except Exception: pass cmds.intFieldGrp("doOff", label="Frame offset", value1=0, columnWidth2=(70, 80), annotation="Added to every frame time. Leave at 0 if " "the offset was set when the archive was " "exported from The Mighty Pencil.") cmds.button(label="Retarget + Import", height=34, command=_go) cmds.separator(style="none", height=2) cmds.setParent("..") cmds.showWindow(WIN) def onMayaDroppedPythonFile(*args): show() if __name__ == "__main__": show()