Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Maya bridge, fewer clicks (#42): Get automatically on once the folder is set, Send to Maya in the top bar, Auto on the Maya shelf

islandmed8a0b8be98124
diff --git a/changes/feat-maya-one-click.md b/changes/feat-maya-one-click.md
new file mode 100644
index 00000000..e520b9f4
--- /dev/null
+++ b/changes/feat-maya-one-click.md
@@ -0,0 +1,12 @@
+---
+whats_new: **Maya bridge, fewer clicks**: what Maya sends loads by itself, **Send to Maya** is one click in the top bar, and the Maya shelf's new **Auto** loads what SculptForge sends. Thanks @tristratos.
+changed: Maya bridge (#42, thanks @tristratos): **Get automatically** is on once an exchange folder is chosen; a
+ **Send to Maya** button sits in the top bar while the bridge is on; the Maya shelf gets **Auto** (on by default),
+ which loads what SculptForge sends by itself. Both sides check only the other side's manifest (time and size),
+ once a second; still no ports or connections. Reinstall the shelf (`install_shelf()`) to get the Auto button.
+testers:
+ - Maya 2022+: copy the new sculptforge_maya.py, run install_shelf() again, same folder in both. Send from Maya: SculptForge loads it within a second, no click.
+ - Click Send to Maya in SculptForge's top bar: Maya loads it within a second (Auto), as one undo step.
+ - Click Auto on the shelf (it says Manual): a send from SculptForge waits for Get.
+---
+Follow-ups in REPORT.md.
diff --git a/docs/guide/maya.md b/docs/guide/maya.md
index 765910ae..4fdcd6b4 100644
--- a/docs/guide/maya.md
+++ b/docs/guide/maya.md
@@ -16,7 +16,8 @@ there. The bridge is off until you choose the folder.
2. Copy `sculptforge_maya.py` into your Maya scripts folder: `Documents\maya\scripts\` on Windows,
`~/Library/Preferences/Autodesk/maya/scripts/` on macOS, `~/maya/scripts/` on Linux.
3. In Maya open the **Script Editor**, and in a **Python** tab run `import sculptforge_maya` and then
- `sculptforge_maya.install_shelf()`. A **SculptForge** shelf appears with **Send**, **Get** and **Folder**.
+ `sculptforge_maya.install_shelf()`. A **SculptForge** shelf appears with **Send**, **Get**, **Auto** and
+ **Folder**. (Updating from an older shelf: copy the new file and run `install_shelf()` again.)
The script uses plain `maya.cmds` and Maya's own OBJ exporter; it needs Maya 2022 or newer.
@@ -26,21 +27,27 @@ The script uses plain `maya.cmds` and Maya's own OBJ exporter; it needs Maya 202
empty `Documents/SculptForge Maya`.
2. In Maya click **Folder** on the SculptForge shelf and pick the same folder.
-**File > Maya** shows the folder; **Turn the Maya bridge off** forgets it (nothing in it is deleted).
+**File > Maya** shows the folder; **Turn the Maya bridge off** forgets it (nothing in it is deleted). While the
+bridge is on, the top bar has a **Send to Maya** button.
## A round trip
1. In Maya select one or more meshes and click **Send** on the SculptForge shelf.
-2. In SculptForge choose **File > Maya > Get from Maya**. Each mesh becomes a Part with its Maya name; a
- Part with that name already there is replaced (one undo step on that Part).
+2. SculptForge loads them by itself. Each mesh becomes a Part with its Maya name; a Part with that name already
+ there is replaced (one undo step on that Part).
3. Sculpt, paint, divide, remesh: anything SculptForge does.
-4. Choose **File > Maya > Send to Maya**. Every visible Part goes.
-5. In Maya click **Get**. Each object that came from Maya gets the new mesh and keeps its transform, parent and
- shading groups; a Part you added in SculptForge becomes a new object. The whole Get is one undo step in
- Maya.
+4. Click **Send to Maya** in the top bar (or **File > Maya > Send to Maya**). Every visible Part goes.
+5. Maya loads them by itself. Each object that came from Maya gets the new mesh and keeps its transform,
+ parent and shading groups; a Part you added in SculptForge becomes a new object. The whole Get is one undo
+ step in Maya.
-**Get automatically** (in **File > Maya**, off by default) loads what Maya sends as soon as it arrives:
-SculptForge checks the folder's manifest once a second.
+Both sides pick up a send by checking the other side's manifest once a second (its modification time and size
+only), and only for sends made after the bridge started: something sent earlier waits for a manual Get.
+
+- In SculptForge, **File > Maya > Get automatically** is on once you choose the folder; turn it off to load
+ only with **Get from Maya**.
+- In Maya, **Auto** on the shelf is on by default and starts with the first Send, Get or Folder click in a Maya
+ session; click it to switch to **Manual**, where only **Get** loads.
## What comes across
@@ -78,5 +85,7 @@ The commands are `maya_send folder=<folder>` and `maya_receive folder=<folder>`
- **"Nothing has been sent from Maya yet"**: check that both apps use the same folder (open **File > Maya** in
SculptForge; click **Folder** in Maya to see or change it).
- **Get in Maya says nothing has been sent**: choose **File > Maya > Send to Maya** in SculptForge first.
+- **Maya doesn't load a send by itself**: Auto starts with the first click on the shelf in a Maya session; click
+ **Get** once (or **Send**), and check that the button says **Auto**, not **Manual**.
- **A mesh came in as a new object instead of replacing one**: Get matches the transform's name; renaming the
object in Maya or the Part's Maya name breaks the link.
diff --git a/integrations/maya/README.md b/integrations/maya/README.md
index feaa91e9..bde6625e 100644
--- a/integrations/maya/README.md
+++ b/integrations/maya/README.md
@@ -25,8 +25,8 @@ servers, and neither app runs anything it finds in the folder. Meshes travel as
sculptforge_maya.install_shelf()
```
- A **SculptForge** shelf appears with three buttons: **Send**, **Get** and **Folder**. You only do this once;
- Maya keeps the shelf.
+ A **SculptForge** shelf appears with four buttons: **Send**, **Get**, **Auto** and **Folder**. You only do
+ this once; Maya keeps the shelf. (Updating: copy the new file and run `install_shelf()` again.)
## Use
@@ -34,11 +34,16 @@ servers, and neither app runs anything it finds in the folder. Meshes travel as
example `Documents/SculptForge Maya`). In Maya click **Folder** on the SculptForge shelf and pick the same
folder.
2. In Maya select one or more meshes and click **Send**.
-3. In SculptForge choose **File > Maya > Get from Maya** (or turn on **Get automatically**, which checks the
- folder once a second). Each mesh becomes a Part with its Maya name.
-4. Sculpt, then choose **File > Maya > Send to Maya**.
-5. In Maya click **Get**. Each object that came from Maya gets its new mesh, keeping its transform, parent and
- shading groups; a Part you added in SculptForge becomes a new object. The whole Get is one undo step.
+3. SculptForge loads them by itself (**Get automatically**, on once the folder is chosen; or **File > Maya >
+ Get from Maya**). Each mesh becomes a Part with its Maya name.
+4. Sculpt, then click **Send to Maya** in SculptForge's top bar.
+5. Maya loads them by itself (**Auto**; with **Manual**, click **Get**). Each object that came from Maya gets
+ its new mesh, keeping its transform, parent and shading groups; a Part you added in SculptForge becomes a new
+ object. The whole Get is one undo step.
+
+**Auto** is on by default and starts with the first Send, Get or Folder click in a Maya session: a background
+thread looks at the modification time and size of SculptForge's manifest once a second and nothing else, and
+the Get itself runs in Maya's main thread. Something sent before it started waits for **Get**.
## What comes across
diff --git a/integrations/maya/sculptforge_maya.py b/integrations/maya/sculptforge_maya.py
index ad6e6646..bdc50a1c 100644
--- a/integrations/maya/sculptforge_maya.py
+++ b/integrations/maya/sculptforge_maya.py
@@ -11,13 +11,17 @@ space, Maya's own units, one object per file); a small JSON manifest per directi
<folder>/sculptforge_to_maya/manifest.json + r<rev>_<k>.obj written by SculptForge (File > Maya > Send to Maya)
Get from SculptForge replaces each object's mesh by name, keeping its transform, parent and shading groups, as
-one undo step; objects Maya doesn't have yet are created. Plain maya.cmds (and maya.mel for the shelf); no other
-modules. Install: see README.md beside this file, or run install_shelf() once.
+one undo step; objects Maya doesn't have yet are created. Auto (on by default) does the Get by itself when
+SculptForge sends: once a second a background thread 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, in Maya's main thread. Plain
+maya.cmds (maya.mel for the shelf, maya.utils for Auto) and the standard library. Install: see README.md beside
+this file, or run install_shelf() once.
"""
import json
import os
import re
+import threading
FORMAT = "sculptforge-maya"
VERSION = 1
@@ -30,6 +34,9 @@ MAX_FILE_NAME = 64
FOLDER_VAR = "sculptforgeExchangeFolder"
REVISION_VAR = "sculptforgeLastRevision"
+AUTO_VAR = "sculptforgeAutoGet"
+AUTO_BUTTON = "sculptforgeAutoButton"
+POLL_SECONDS = 1.0
SHELF = "SculptForge"
IMPORT_NAMESPACE = "sculptforge_get"
OBJ_EXPORT_OPTIONS = "groups=0;ptgroups=0;materials=0;smoothing=0;normals=0"
@@ -171,6 +178,50 @@ def remove_old_sends(box, keep_prefix):
pass # open elsewhere: the next send tries again
+def manifest_stamp(box):
+ """The modification time and size of <box>/manifest.json, or None when there is none: what Auto checks once a
+ second (cheap, and safe from any thread); 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)
+
+
+class Watcher(object):
+ """Auto: watches one box's manifest from a daemon thread and hands `on_change` to `defer` (Maya's
+ executeDeferred: the main thread, when Maya is idle) when it changed. What is there when it starts is old
+ news: Get loads it."""
+
+ def __init__(self, box, defer, on_change):
+ self.box = box
+ self.defer = defer
+ self.on_change = on_change
+ self.seen = manifest_stamp(box)
+ self.stopped = threading.Event()
+ self.thread = None
+
+ def poll(self):
+ """One check: True when the manifest is there and changed since the last check."""
+ stamp = manifest_stamp(self.box)
+ if stamp is None or stamp == self.seen:
+ return False
+ self.seen = stamp
+ return True
+
+ def _run(self):
+ while not self.stopped.wait(POLL_SECONDS):
+ if self.poll():
+ self.defer(self.on_change)
+
+ def start(self):
+ self.thread = threading.Thread(target=self._run, name="SculptForge Auto Get", daemon=True)
+ self.thread.start()
+
+ def stop(self):
+ self.stopped.set()
+
+
def unique_names(names):
out = []
for name in names:
@@ -213,6 +264,7 @@ def choose_folder():
folder = picked[0]
cmds.optionVar(sv=(FOLDER_VAR, folder))
_message("exchange folder: " + folder)
+ start_auto_get()
return folder
@@ -293,6 +345,7 @@ def send_to_sculptforge():
write_atomically(os.path.join(box, "manifest.json"),
write_manifest(objects, revision, cmds.about(version=True), cmds.currentUnit(q=True, linear=True)))
remove_old_sends(box, prefix)
+ start_auto_get()
return _message("sent %d mesh%s to SculptForge" % (len(objects), "" if len(objects) == 1 else "es"))
@@ -348,6 +401,7 @@ def get_from_sculptforge():
if not folder:
return _message("no exchange folder chosen", warning=True)
box = os.path.join(folder, TO_MAYA)
+ start_auto_get()
try:
manifest = read_manifest(box) if os.path.isdir(box) and not os.path.islink(box) else None
except ValueError as e:
@@ -380,8 +434,73 @@ def get_from_sculptforge():
return _message("got %d mesh%s from SculptForge" % (len(done), "" if len(done) == 1 else "es"))
+# ---- Auto: Get by itself when SculptForge sends ----
+
+_watcher = None
+
+
+def auto_get_on():
+ """Auto is on unless turned off with the shelf's Auto button."""
+ cmds = _cmds()
+ return not cmds.optionVar(exists=AUTO_VAR) or bool(cmds.optionVar(q=AUTO_VAR))
+
+
+def _auto_get_new():
+ """Main thread, after the manifest changed: Get, unless that revision is already loaded (or Auto went off)."""
+ cmds = _cmds()
+ folder = exchange_folder(ask=False)
+ if not auto_get_on() or not folder:
+ return
+ try:
+ manifest = read_manifest(os.path.join(folder, TO_MAYA))
+ except ValueError:
+ manifest = None # half written, or not valid: Get says why; the next change is checked again
+ if not manifest or not manifest["objects"]:
+ return
+ if cmds.optionVar(exists=REVISION_VAR) and cmds.optionVar(q=REVISION_VAR) == manifest["revision"]:
+ return
+ get_from_sculptforge()
+
+
+def start_auto_get():
+ """Starts watching what SculptForge sends (Send, Get and Folder call this: Auto runs from the first use of the
+ shelf in a Maya session). Stops when Auto is off or there is no folder."""
+ global _watcher
+ folder = exchange_folder(ask=False) if auto_get_on() else ""
+ box = os.path.join(folder, TO_MAYA) if folder else ""
+ if _watcher and _watcher.box == box:
+ return _watcher
+ if _watcher:
+ _watcher.stop()
+ _watcher = None
+ if box:
+ import maya.utils
+ _watcher = Watcher(box, maya.utils.executeDeferred, _auto_get_new)
+ _watcher.start()
+ return _watcher
+
+
+def _auto_label():
+ return "Auto" if auto_get_on() else "Manual"
+
+
+def toggle_auto_get():
+ """The shelf's Auto button: Get by itself when SculptForge sends (on), or only with Get (off)."""
+ cmds = _cmds()
+ cmds.optionVar(iv=(AUTO_VAR, 0 if auto_get_on() else 1))
+ start_auto_get()
+ try:
+ if cmds.shelfButton(AUTO_BUTTON, exists=True):
+ cmds.shelfButton(AUTO_BUTTON, edit=True, label=_auto_label(), imageOverlayLabel=_auto_label())
+ except Exception:
+ pass
+ if auto_get_on():
+ return _message("Auto on: what SculptForge sends loads by itself")
+ return _message("Auto off: click Get to load what SculptForge sends")
+
+
def install_shelf():
- """Creates the SculptForge shelf: Send, Get and Folder buttons. Run once, after putting this file in a
+ """Creates the SculptForge shelf: Send, Get, Auto and Folder buttons. Run once, after putting this file in a
folder on Maya's script path (README.md)."""
cmds = _cmds()
import maya.mel as mel
@@ -392,14 +511,17 @@ def install_shelf():
buttons = [
("Send", "Send the selected meshes to SculptForge", "send_to_sculptforge"),
("Get", "Get what SculptForge sent (replaces meshes by name)", "get_from_sculptforge"),
+ (_auto_label(), "Auto: get what SculptForge sends by itself (click to turn on or off)", "toggle_auto_get"),
("Folder", "Choose the exchange folder (the same one as in SculptForge)", "choose_folder"),
]
for label, tip, func in buttons:
- cmds.shelfButton(parent=shelf, label=label, imageOverlayLabel=label, annotation=tip,
+ name = [AUTO_BUTTON] if func == "toggle_auto_get" else []
+ cmds.shelfButton(*name, parent=shelf, label=label, imageOverlayLabel=label, annotation=tip,
image="pythonFamily.png", sourceType="python",
command="import sculptforge_maya\nsculptforge_maya.%s()" % func)
try:
mel.eval("saveAllShelves $gShelfTopLevel")
except Exception:
pass
+ start_auto_get()
return _message("SculptForge shelf installed")
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index edac560a..f4631743 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -579,7 +579,8 @@ void App::initActions() {
add("file.maya_folder", "Exchange folder...", "File > Maya", nullptr, [this] { chooseMayaFolder(); },
ICON_LC_FOLDER_OPEN, nullptr, nullptr, nullptr,
"Choose the folder SculptForge and Maya exchange meshes through (pick the same one in Maya's shelf script). "
- "SculptForge reads and writes only there, and only when you send or get.");
+ "SculptForge reads and writes only there: when you send or get, and when Maya sends while Get "
+ "automatically is on.");
add("brush.paste", "Paste brush", "Brush", "Ctrl+V", [this] { pasteBrush(); }, ICON_LC_CLIPBOARD_PASTE, nullptr, nullptr,
nullptr, "Add the brush on the clipboard: a brush code someone shared, or the text of a .sfbrush file.");
// Per-brush settings (#78, BrushSettingsUi.cpp).
diff --git a/src/app/Config.h b/src/app/Config.h
index 7858f92b..15d308f7 100644
--- a/src/app/Config.h
+++ b/src/app/Config.h
@@ -136,7 +136,7 @@ struct UiPrefs {
// File > Maya (#42). Kept in <prefs>/maya.json, never in ui.json, so a shared UI layout can't point the bridge
// at a folder: it is set only by the user's own pick (App::setMayaFolder).
std::string mayaFolder; // "" = the bridge is off
- bool mayaAutoReceive = false; // Get automatically: check that folder's manifest once a second
+ bool mayaAutoReceive = false; // Get automatically (on once a folder is chosen): check its manifest once a second
};
Json toJson(const UiPrefs& prefs);
diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cpp
index fdc0fcc1..094a3375 100644
--- a/src/app/I18nSimplifiedChinese.cpp
+++ b/src/app/I18nSimplifiedChinese.cpp
@@ -936,9 +936,9 @@ constexpr Entry kSimplifiedChinese[] = {
"加载 Maya 最后通过工具架的 Send to SculptForge 发送的内容。每个对象会替换同名的部件(可撤销)或成为新部件。"},
{"Exchange folder...", "交换文件夹..."},
{"Choose the folder SculptForge and Maya exchange meshes through (pick the same one in Maya's shelf script). "
- "SculptForge reads and writes only there, and only when you send or get.",
- "选择 SculptForge 与 Maya 交换网格的文件夹(在 Maya 的工具架脚本中选同一个)。SculptForge 只在该处读写,且只在"
- "你发送或获取时进行。"},
+ "SculptForge reads and writes only there: when you send or get, and when Maya sends while Get automatically is on.",
+ "选择 SculptForge 与 Maya 交换网格的文件夹(在 Maya 的工具架脚本中选同一个)。SculptForge 只在该处读写:在"
+ "你发送或获取时,以及开启“自动获取”后 Maya 发送时。"},
{"Add the brush on the clipboard: a brush code someone shared, or the text of a .sfbrush file.",
"加入剪贴板中的笔刷:别人分享的笔刷代码,或 .sfbrush 文件的文本。"},
{"Every brush keeps its own Size, Intensity, Falloff, Colour intensity, stroke and alpha while you work. This "
@@ -1795,8 +1795,8 @@ constexpr Entry kSimplifiedChinese[] = {
// --- PanelMaya.cpp (tools/i18n/coverage.py) ---
{"Get automatically", "自动获取"},
{"Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest once a second "
- "(its modification time and size only). Off by default; off: use Get from Maya.",
- "Maya 传来的内容一到就加载:SculptForge 每秒检查一次交换文件夹的列表文件(只看修改时间与大小)。默认关闭;关闭时:"
+ "(its modification time and size only). On once you choose the folder; off: use Get from Maya.",
+ "Maya 传来的内容一到就加载:SculptForge 每秒检查一次交换文件夹的列表文件(只看修改时间与大小)。选好文件夹后即开启;关闭时:"
"请使用“从 Maya 获取”。"},
{"Turn the Maya bridge off", "关闭 Maya 桥接"},
{"Forget the exchange folder; nothing in it is deleted.", "忘记交换文件夹;其中的内容不会被删除。"},
diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cpp
index cbca1f9f..43f863c4 100644
--- a/src/app/I18nSpanish.cpp
+++ b/src/app/I18nSpanish.cpp
@@ -1100,9 +1100,10 @@ constexpr Entry kSpanish[] = {
"nombre (se puede deshacer) o pasa a ser una nueva."},
{"Exchange folder...", "Carpeta de intercambio..."},
{"Choose the folder SculptForge and Maya exchange meshes through (pick the same one in Maya's shelf script). "
- "SculptForge reads and writes only there, and only when you send or get.",
+ "SculptForge reads and writes only there: when you send or get, and when Maya sends while Get automatically is on.",
"Elige la carpeta por la que SculptForge y Maya intercambian mallas (elige la misma en el script del estante de "
- "Maya). SculptForge solo lee y escribe ahí, y solo cuando envías o recibes."},
+ "Maya). SculptForge solo lee y escribe ahí: cuando envías o recibes, y cuando Maya envía con Recibir "
+ "automáticamente activado."},
{"Add the brush on the clipboard: a brush code someone shared, or the text of a .sfbrush file.",
"Añade el pincel del portapapeles: un código de pincel que alguien compartió, o el texto de un archivo .sfbrush."},
{"Every brush keeps its own Size, Intensity, Falloff, Colour intensity, stroke and alpha while you work. This "
@@ -2067,10 +2068,10 @@ constexpr Entry kSpanish[] = {
// --- PanelMaya.cpp (tools/i18n/coverage.py) ---
{"Get automatically", "Recibir automáticamente"},
{"Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest once a second "
- "(its modification time and size only). Off by default; off: use Get from Maya.",
+ "(its modification time and size only). On once you choose the folder; off: use Get from Maya.",
"Carga lo que envía Maya en cuanto llega: SculptForge comprueba el manifiesto de la carpeta de intercambio una "
- "vez por segundo (solo su fecha de modificación y su tamaño). Desactivado por defecto; desactivado: usa Recibir "
- "de Maya."},
+ "vez por segundo (solo su fecha de modificación y su tamaño). Activado al elegir la carpeta; desactivado: usa "
+ "Recibir de Maya."},
{"Turn the Maya bridge off", "Desactivar el puente con Maya"},
{"Forget the exchange folder; nothing in it is deleted.",
"Olvida la carpeta de intercambio; no se borra nada de ella."},
diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cpp
index cf787c0e..b71f139a 100644
--- a/src/app/I18nTraditionalChinese.cpp
+++ b/src/app/I18nTraditionalChinese.cpp
@@ -936,9 +936,9 @@ constexpr Entry kTraditionalChinese[] = {
"載入 Maya 最後透過工具架的 Send to SculptForge 傳送的內容。每個物件會取代同名的部件(可復原)或成為新部件。"},
{"Exchange folder...", "交換資料夾..."},
{"Choose the folder SculptForge and Maya exchange meshes through (pick the same one in Maya's shelf script). "
- "SculptForge reads and writes only there, and only when you send or get.",
- "選擇 SculptForge 與 Maya 交換網格的資料夾(在 Maya 的工具架指令碼中選同一個)。SculptForge 只在該處讀寫,且只在"
- "你傳送或取得時進行。"},
+ "SculptForge reads and writes only there: when you send or get, and when Maya sends while Get automatically is on.",
+ "選擇 SculptForge 與 Maya 交換網格的資料夾(在 Maya 的工具架指令碼中選同一個)。SculptForge 只在該處讀寫:在"
+ "你傳送或取得時,以及開啟「自動取得」後 Maya 傳送時。"},
{"Add the brush on the clipboard: a brush code someone shared, or the text of a .sfbrush file.",
"加入剪貼簿中的筆刷:別人分享的筆刷代碼,或 .sfbrush 檔案的文字。"},
{"Every brush keeps its own Size, Intensity, Falloff, Colour intensity, stroke and alpha while you work. This "
@@ -1795,8 +1795,8 @@ constexpr Entry kTraditionalChinese[] = {
// --- PanelMaya.cpp (tools/i18n/coverage.py) ---
{"Get automatically", "自動取得"},
{"Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest once a second "
- "(its modification time and size only). Off by default; off: use Get from Maya.",
- "Maya 傳來的內容一到就載入:SculptForge 每秒檢查一次交換資料夾的清單檔(只看修改時間與大小)。預設關閉;關閉時:"
+ "(its modification time and size only). On once you choose the folder; off: use Get from Maya.",
+ "Maya 傳來的內容一到就載入:SculptForge 每秒檢查一次交換資料夾的清單檔(只看修改時間與大小)。選好資料夾後即開啟;關閉時:"
"請使用「從 Maya 取得」。"},
{"Turn the Maya bridge off", "關閉 Maya 橋接"},
{"Forget the exchange folder; nothing in it is deleted.", "忘記交換資料夾;其中的內容不會被刪除。"},
diff --git a/src/app/PanelMaya.cpp b/src/app/PanelMaya.cpp
index 17cdaf70..91325f55 100644
--- a/src/app/PanelMaya.cpp
+++ b/src/app/PanelMaya.cpp
@@ -3,9 +3,10 @@
//
// File > Maya (#42): the file-exchange bridge to the SculptForge shelf script for Maya (io/MayaBridge.h,
// integrations/maya). Off until the user picks an exchange folder with the native folder dialog; SculptForge
-// then reads and writes only inside that folder, only when the user sends or gets, or (Get automatically, off
-// by default) after a once-a-second modification-time check of that folder's one manifest. No sockets, no
-// ports, and nothing from the folder is ever run.
+// then reads and writes only inside that folder, only when the user sends or gets, or (Get automatically, on
+// once a folder is chosen) after a once-a-second modification-time check of that folder's one manifest. No
+// sockets, no ports, and nothing from the folder is ever run. While the bridge is on, the top bar has a Send to
+// Maya button (Shell.cpp).
#include "app/App.h"
#include "app/Ui.h"
@@ -40,8 +41,9 @@ void menuAction(App& app, const char* id) {
ui::HelpAction(app, id);
}
-// <prefs>/maya.json: {"folder": "...", "auto": false}. Read strictly: a small file, a string path to an existing
-// folder (else the bridge stays off).
+// <prefs>/maya.json: {"folder": "...", "auto_get": true}. Read strictly: a small file, a string path to an existing
+// folder (else the bridge stays off). Get automatically is on unless the user turned it off: "auto_get", not the
+// old "auto", which every earlier version wrote as false (its default was off).
void loadMayaPrefs(const std::string& configDir, UiPrefs& p) {
if (configDir.empty()) return;
std::ifstream f(fsPath(configDir + "maya.json"), std::ios::binary);
@@ -52,14 +54,14 @@ void loadMayaPrefs(const std::string& configDir, UiPrefs& p) {
if (text.size() > 16384 || !Json::parse(text, j, err) || !j.isObject()) return;
if (j["folder"].isString() && j["folder"].asString().size() < 4096 && isFolder(j["folder"].asString()))
p.mayaFolder = j["folder"].asString();
- p.mayaAutoReceive = !p.mayaFolder.empty() && j["auto"].asBool(false);
+ p.mayaAutoReceive = !p.mayaFolder.empty() && j["auto_get"].asBool(true);
}
void saveMayaPrefs(const std::string& configDir, const UiPrefs& p) {
if (configDir.empty()) return;
Json j = Json::object();
j.set("folder", p.mayaFolder);
- j.set("auto", p.mayaAutoReceive);
+ j.set("auto_get", p.mayaAutoReceive);
std::ofstream f(fsPath(configDir + "maya.json"), std::ios::binary | std::ios::trunc);
f << j.dump(true) << "\n";
}
@@ -71,6 +73,7 @@ void App::setMayaFolder(const std::string& folder) {
status_ = "Not a folder: " + folder;
return;
}
+ if (uiPrefs_.mayaFolder.empty()) uiPrefs_.mayaAutoReceive = true; // the bridge turns on with Get automatically
uiPrefs_.mayaFolder = folder;
// What is already there is old news: Get from Maya loads it, Get automatically waits for the next send.
const std::string inbox = mayaInbox(folder);
@@ -117,7 +120,7 @@ void App::drawMayaMenu() {
}
ui::HelpText("Get automatically", nullptr,
"Load what Maya sends as soon as it arrives: SculptForge checks the exchange folder's manifest once a "
- "second (its modification time and size only). Off by default; off: use Get from Maya.",
+ "second (its modification time and size only). On once you choose the folder; off: use Get from Maya.",
"File > Maya");
ImGui::Separator();
menuAction(*this, "file.maya_folder");
diff --git a/src/app/Shell.cpp b/src/app/Shell.cpp
index cdab8534..df8f8d5d 100644
--- a/src/app/Shell.cpp
+++ b/src/app/Shell.cpp
@@ -1029,11 +1029,13 @@ void App::drawTitleStrip(const ShellGeometry& g) {
const ImGuiStyle& st = ImGui::GetStyle();
auto buttonW = [&](const char* label) { return ImGui::CalcTextSize(label, nullptr, true).x + st.FramePadding.x * 2.0f; };
const bool quickSave = actions_.find("file.quicksave") != nullptr;
+ const bool maya = !uiPrefs_.mayaFolder.empty(); // the Maya bridge is on (#42): one click sends back
const float searchW = 150.0f * s;
const float windowButtonW = buttonH + 6.0f * s; // minimise and close, at the far right
float rightW = searchW + buttonW(tr(ICON_LC_MENU " Menus")) + 3.0f * (buttonH + 2.0f * s) + 18.0f * s +
10.0f * s + 2.0f * windowButtonW + 2.0f * s;
if (quickSave) rightW += buttonW(tr("Save Snapshot")) + 8.0f * s;
+ if (maya) rightW += buttonW((std::string(ICON_LC_SEND " ") + tr("Send to Maya")).c_str()) + 8.0f * s;
const float rightX = g.title.w - 8.0f * s - rightW;
// Info readout and the status message, elided to fit: secondary, so in the 12 px font.
@@ -1102,6 +1104,10 @@ void App::drawTitleStrip(const ShellGeometry& g) {
ImGui::PushStyleColor(ImGuiCol_Button, theme::toggleOff);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, theme::toggleOffHover);
ImGui::PushStyleColor(ImGuiCol_Text, theme::textOff);
+ if (maya) {
+ ui::ActionButton(*this, "file.send_maya", ImVec2(0, buttonH), ui::Look::IconLabel);
+ ImGui::SameLine(0.0f, 8.0f * s);
+ }
if (quickSave) {
ui::ActionButton(*this, "file.quicksave", ImVec2(0, buttonH));
ImGui::SameLine(0.0f, 8.0f * s);
@@ -1487,6 +1493,13 @@ void App::drawStatusBar(const ShellGeometry& g) {
const float wsW = buttonH + 4.0f * s;
const float presetsX = right - 3.0f * wsW - 2.0f * s;
right = presetsX - 14.0f * s;
+ // The Maya bridge is on (#42): Send to Maya, one click, left of the workspaces; never over the menus (a narrow
+ // window, #105, keeps File > Maya > Send to Maya).
+ const std::string mayaLabel = std::string(ICON_LC_SEND) + " " + (caps ? upper(tr("Send to Maya")) : std::string(tr("Send to Maya")));
+ const float mayaW = textW(monoSmall, mayaLabel) + 16.0f * s;
+ const float mayaX = right - mayaW;
+ const bool maya = !uiPrefs_.mayaFolder.empty() && mayaX > menusEnd;
+ if (maya) right = mayaX - 10.0f * s;
// Modules: mode, brush, document, triangles, frame rate.
std::vector<StatusModule> mods;
@@ -1595,6 +1608,23 @@ void App::drawStatusBar(const ShellGeometry& g) {
}
}
+ if (maya) {
+ ImGui::SetCursorScreenPos(ImVec2(mayaX, o.y + (h - buttonH) * 0.5f));
+ const bool clicked = ImGui::InvisibleButton((std::string(tr("Send to Maya")) + "##file.send_maya").c_str(), ImVec2(mayaW, buttonH));
+ const bool hovered = ImGui::IsItemHovered();
+ const ImVec2 p = ImGui::GetItemRectMin();
+ dl->AddRectFilled(p, ImVec2(p.x + mayaW, p.y + buttonH), theme::u32(hovered ? theme::frameHover : theme::frame));
+ if (theme::look.tiled) dl->AddRect(p, ImVec2(p.x + mayaW, p.y + buttonH), theme::u32(theme::tileBorder));
+ textAt(monoSmall, p.x + 8.0f * s, hovered ? theme::textBright : theme::text, mayaLabel);
+ if (clicked) {
+ if (const Action* a = actions_.find("file.send_maya"); a && a->run) {
+ actions_.touch(a->id);
+ a->run();
+ }
+ }
+ ui::HelpAction(*this, "file.send_maya");
+ }
+
// Layout presets 1 2 3, drawn as workspaces.
for (int i = 1; i <= 3; ++i) {
const std::string id = "ui.preset." + std::to_string(i);
diff --git a/tests/maya/test_sculptforge_maya.py b/tests/maya/test_sculptforge_maya.py
index acc1e240..8cf01d09 100644
--- a/tests/maya/test_sculptforge_maya.py
+++ b/tests/maya/test_sculptforge_maya.py
@@ -217,20 +217,29 @@ class FakeCmds(types.ModuleType):
def deleteUI(self, name, layout=False):
self.option_vars["_shelves"].pop(name)
- def shelfButton(self, parent=None, command="", sourceType="", **kw):
- self.option_vars["_shelves"][parent].append((sourceType, command))
+ def shelfButton(self, *name, parent=None, command="", sourceType="", exists=False, edit=False, **kw):
+ if exists:
+ return any(name and b[2] == name[0] for b in self.option_vars.get("_shelves", {}).get("SculptForge", []))
+ if edit:
+ return
+ self.option_vars["_shelves"][parent].append((sourceType, command, name[0] if name else kw.get("label")))
def install_fake_maya(folder):
cmds = FakeCmds(folder)
mel = types.ModuleType("maya.mel")
mel.eval = lambda text: "ShelfLayout"
+ utils = types.ModuleType("maya.utils")
+ cmds.deferred = []
+ utils.executeDeferred = cmds.deferred.append # Maya runs these in its main thread when idle; tests by hand
maya = types.ModuleType("maya")
maya.cmds = cmds
maya.mel = mel
+ maya.utils = utils
sys.modules["maya"] = maya
sys.modules["maya.cmds"] = cmds
sys.modules["maya.mel"] = mel
+ sys.modules["maya.utils"] = utils
return cmds
@@ -239,8 +248,9 @@ def test_shelf(sm):
sm.install_shelf()
sm.install_shelf() # again: replaces the shelf
buttons = cmds.option_vars["_shelves"][sm.SHELF]
- check(len(buttons) == 3 and all(t == "python" for t, _ in buttons), "the shelf has three Python buttons")
- for _, command in buttons:
+ check(len(buttons) == 4 and all(t == "python" for t, _, _ in buttons), "the shelf has four Python buttons")
+ check(any(n == sm.AUTO_BUTTON for _, _, n in buttons), "the Auto button has its name (its label shows on / off)")
+ for _, command, _ in buttons:
func = command.split("sculptforge_maya.")[1].rstrip("()")
check(callable(getattr(sm, func, None)), "shelf button calls sculptforge_maya.%s" % func)
@@ -393,6 +403,64 @@ def test_send_and_get(sm, tmp, cli):
check(cmds.warnings and cmds.nodes == before, "get: a traversal attempt is refused and nothing changes")
+def write_sculptforge_send(sm, out, revision, names):
+ """What SculptForge's maya_send writes: the OBJs, then the manifest."""
+ os.makedirs(out, exist_ok=True)
+ objects = []
+ for k, name in enumerate(names):
+ file_name = "r%d_%03d.obj" % (revision, k)
+ with open(os.path.join(out, file_name), "w") as f:
+ f.write(CUBE_OBJ.replace("# Maya OBJ export", "# SculptForge r%d" % revision))
+ objects.append((name, file_name))
+ sm.write_atomically(os.path.join(out, "manifest.json"),
+ sm.write_manifest(objects, revision).replace('"maya"', '"sculptforge"'))
+
+
+def test_auto(sm, tmp):
+ """Auto: what SculptForge sends after the shelf is used loads by itself (in Maya's main thread); what was
+ there before waits for Get; Auto off leaves it to Get. Only the manifest's time and size are checked."""
+ folder = os.path.join(tmp, "auto")
+ os.makedirs(folder)
+ cmds = install_fake_maya(folder)
+ sm.POLL_SECONDS = 3600 # the thread never ticks here: the test polls by hand
+ cmds.add_mesh("|pCube1", CUBE_OBJ)
+ out = os.path.join(folder, sm.TO_MAYA)
+ write_sculptforge_send(sm, out, 1, ["pCube1"]) # sent before Maya's shelf was used: old news
+ cmds.selection = ["|pCube1"]
+ sm.send_to_sculptforge()
+ w = sm._watcher
+ check(w is not None and w.thread.daemon and w.box == out, "auto: on by default, watching SculptForge's box only")
+ check(not w.poll() and not cmds.deferred, "auto: what was there before isn't loaded")
+
+ write_sculptforge_send(sm, out, 2, ["pCube1"])
+ os.utime(os.path.join(out, "manifest.json"), ns=(1, 2_000_000_000)) # (coarse clocks: a time of its own)
+ check(w.poll() and not w.poll(), "auto: a new send is seen once")
+ w.defer(w.on_change)
+ check(len(cmds.deferred) == 1, "auto: the Get is handed to Maya's main thread")
+ cmds.deferred.pop()()
+ shape = cmds.nodes["|pCube1|pCube1Shape"]
+ check("# SculptForge r2" in shape["obj"], "auto: the new send replaced pCube1's mesh")
+ check(cmds.option_vars.get(sm.REVISION_VAR) == 2, "auto: the revision is remembered")
+ shape["obj"] = CUBE_OBJ
+ sm._auto_get_new() # the same revision again (a touch of the manifest): not loaded twice
+ check(cmds.nodes["|pCube1|pCube1Shape"]["obj"] == CUBE_OBJ, "auto: a revision already loaded isn't loaded again")
+
+ with open(os.path.join(out, "manifest.json"), "w") as f:
+ f.write('{"format": "sculptforge-maya", "ver') # half written / not valid: nothing happens, no warning
+ cmds.warnings = []
+ sm._auto_get_new()
+ check(not cmds.warnings and cmds.nodes["|pCube1|pCube1Shape"]["obj"] == CUBE_OBJ, "auto: a bad manifest is skipped")
+
+ sm.toggle_auto_get()
+ check(not sm.auto_get_on() and sm._watcher is None and w.stopped.is_set(), "auto off: the thread stops")
+ write_sculptforge_send(sm, out, 3, ["pCube1"])
+ sm._auto_get_new()
+ check(cmds.nodes["|pCube1|pCube1Shape"]["obj"] == CUBE_OBJ, "auto off: nothing loads by itself")
+ sm.toggle_auto_get()
+ check(sm.auto_get_on() and sm._watcher is not None and not sm._watcher.poll(), "auto on again: from now on")
+ sm._watcher.stop()
+
+
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cli", help="sculptforge-cli, for the round trip through SculptForge")
@@ -402,6 +470,7 @@ def main():
try:
test_format(sm, tmp)
test_send_and_get(sm, tmp, args.cli)
+ test_auto(sm, tmp)
test_shelf(sm)
finally:
shutil.rmtree(tmp, ignore_errors=True)
diff --git a/tests/ui/maya_bridge.sfui b/tests/ui/maya_bridge.sfui
index 910a2ee3..0844c8a9 100644
--- a/tests/ui/maya_bridge.sfui
+++ b/tests/ui/maya_bridge.sfui
@@ -1,8 +1,8 @@
# The Maya bridge (File > Maya, #42): off until an exchange folder is chosen (here: what the native folder
-# dialog would answer), then Get from Maya loads what the shelf script sent, Send to Maya writes the Parts
-# back, and with Get automatically on a second send from Maya replaces the Part by name (undoable) and adds
-# the new object. The sends are staged from tests/ui/data/maya into a folder in the working directory (the build
-# folder under ctest).
+# dialog would answer). Then Get automatically is on and the top bar has Send to Maya: what was in the folder
+# waits for Get from Maya, a second send from Maya replaces the Part by name by itself (undoable) and adds the
+# new object, and one click sends the Parts back. The sends are staged from tests/ui/data/maya into a folder in
+# the working directory (the build folder under ctest).
run ui_look look=classic layout=classic # written for the Classic look and the classic palette bar and shelves
run new_sphere subdivisions=3
copy data/maya/send1 sf_ui_maya/maya_to_sculptforge
@@ -23,14 +23,18 @@ hover "Exchange folder...##file.maya_folder"
expect_help "only there"
hold none
-# What File > Maya > Exchange folder's dialog answers. Nothing loads by itself (Get automatically is off).
+# What File > Maya > Exchange folder's dialog answers. Get automatically turns on, but what was already there
+# waits for Get from Maya; the top bar gets Send to Maya.
choose_file maya_folder sf_ui_maya
-wait 0.2
+wait 0.3
expect_status "Maya exchange folder:"
expect_value parts == 1
+expect "Send to Maya##file.send_maya"
+shot topbar_on
hover "Maya"
wait 0.2
expect_text Folder:
+shot menu_on
click "Get from Maya##file.receive_maya"
expect_status "Received 1 object from Maya"
expect_value parts == 1
@@ -39,10 +43,6 @@ expect_value quads > 0
shot received
# Get automatically: the next send from Maya loads by itself.
-click "File##palette.file"
-hover "Maya"
-wait 0.2
-click "Get automatically##maya"
copy data/maya/send2 sf_ui_maya/maya_to_sculptforge
wait 0.3
expect_status "Received 2 objects from Maya"
@@ -51,12 +51,49 @@ expect_text pCube2
expect_value can_undo == 1
shot updated
-# Send to Maya: both Parts, under their Maya names.
+# Send to Maya: one click in the top bar, both Parts, under their Maya names.
+click "Send to Maya##file.send_maya"
+expect_status "Sent 2 objects to Maya"
+
+# The Forge look's status bar has it too, at 1x and on a HiDPI display (150 %); a window
+# too narrow for it (200 %: 800 logical px) keeps the menus whole and File > Maya > Send to Maya.
+run ui_look look=forge layout=sculptforge
+wait 0.3
+expect "Send to Maya##file.send_maya"
+shot forge_bar
+click "Send to Maya##file.send_maya"
+expect_status "Sent 2 objects to Maya"
+display_scale 150
+wait 0.5
+expect "Send to Maya##file.send_maya"
+shot forge_bar_hidpi
+display_scale 200
+wait 0.5
+expect_not "Send to Maya##file.send_maya"
+shot forge_bar_narrow
+run ui_look look=classic layout=classic
+wait 0.3
+shot classic_bar_hidpi
+display_scale 100
+wait 0.3
+
+# Get automatically off: Maya's next send waits for Get from Maya; the bridge off: no Send to Maya in the bar.
click "File##palette.file"
hover "Maya"
wait 0.2
-click "Send to Maya##file.send_maya"
-expect_status "Sent 2 objects to Maya"
+click "Get automatically##maya"
+copy data/maya/send1 sf_ui_maya/maya_to_sculptforge
+wait 0.3
+expect_no_text Received 1 object from Maya
+expect_value parts == 2
+click "File##palette.file"
+hover "Maya"
+wait 0.2
+click "Turn the Maya bridge off##maya"
+wait 0.2
+expect_status "Maya bridge off"
+expect_not "Send to Maya##file.send_maya"
+
# Both receives into pCube1 are undo steps: the update, then the first one (which replaced the fresh sphere).
key ctrl+z
expect_value can_undo == 1