mirror of
https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry.git
synced 2026-11-30 09:22:10 +00:00
[GH-ISSUE #5] feat: experimental multithreading #3
Reference in New Issue
Block a user
No description provided.
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @allankoechke on GitHub (Jun 24, 2026).
Original GitHub issue: https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/issues/5
Originally assigned to: @allankoechke on GitHub.
When exploding objects with several faces/meshes/segments/etc, the process can take long as every operation is tied on the main thread. Lets find a means of splitting tasks across threads to quicken the process. The catch however is, there are lots of items that are not thread safe, like on thread decoupling a face, changing the indexes which another thread depends on.
Research Findings
Researched 2026-06-24 | Branch
5-experimental-multithreading| Commit1fa4756| Scope: Python script only (Python/explode_geometry.py)Summary
3ds Max is fundamentally single-threaded for scene graph operations. All node creation, modifier application, stack collapse, and transform mutations must happen on the main thread -- this applies to
pymxsand all MAXScript-backed calls.pymxs.mxstoken()is deprecated and non-functional. There is no way to run scene-mutating work in parallel.However, substantial speedups are achievable without true multithreading by suppressing per-iteration overhead (undo recording,
processEventsthrottling) and by restructuring the MNMesh path. True parallelism can be applied only to pure-Python computation on extracted mesh data (nopymxscalls), which is currently a small fraction of total time.Key Discoveries
polyop.detachFacesmutates the source mesh in-place and shifts face indices after each call -- cannot be parallelized (Python/explode_geometry.py:360-362). The reverse iteration order (range(num_faces, 0, -1)) exists specifically because of this dependency.rt.getFace,rt.getVert) safe to separate from node creation (Python/explode_geometry.py:330-334)QApplication.processEvents()is called once per face (Python/explode_geometry.py:258-259), adding Qt event loop overhead on every iteration regardless of mesh sizepymxs.runtimecalls cannot be made from background threads --mxstoken()is deprecated. The only safe background work is pure Python (NumPy, math, data structures)TODO: parallelize thiscomment exists in the classic Python version at the MNMesh loop (Python/explode_geometry_classic.py:276)Detailed Findings
pymxs Threading Constraints
pymxs.runtimecalls (any)pymxs.mxstoken()rt.mesh(),rt.polyop.*rt.addModifier,rt.maxOps.collapseNodert.getFace,rt.getVert(read-only)concurrent.futures.ThreadPoolExecutor(no pymxs)multiprocessingPer-Face Bottleneck Analysis (Python)
Most expensive operations per face (ordered by cost):
rt.maxOps.collapseNode(n, True)-- evaluates the full modifier stack per facert.addModifier(n, mod)x2 -- Shell + Edit Mesh modifier application; each goes through the pymxs bridgert.polyop.detachFaces(node, rt.Array(face_idx), asNode=True)-- modifies source MNMesh topology + creates new scene nodert.mesh(vertices=..., faces=...)-- creates mesh object + scene node in one callrt.centerPivot(n)-- computes bounding box + adjusts offset transformQApplication.processEvents()-- Qt event loop pump called once per faceOptimization Strategies (Ranked by Impact)
QApplication.processEvents()to every N facesdetachFacesconcurrent.futures,threading,multiprocessingfor pymxs callsReferences
Explode Geometry Performance Optimization Implementation Plan
Overview
Research confirmed that
pymxs.runtimecalls cannot be made from background threads — 3ds Max is single-threaded for all scene graph operations. "Multithreading" is therefore implemented as a set of main-thread performance optimizations: disabling scene redraws during the face loop, suppressing per-face undo recording, throttling the Qt event-loop pump, and restructuring the MNMesh path to eliminate an inherent sequential index-shifting dependency. BothPython/explode_geometry.pyandBundle2/Contents/python/explode_geometry.pyare identical and both require the same changes.Current State Analysis
Key Discoveries:
rt.mesh(),rt.addModifier(), andrt.maxOps.collapseNode()triggers a viewport update per face (Python/explode_geometry.py:261-296)QApplication.processEvents()is called once per face via_prog(), adding Qt event-loop overhead on every iteration (Python/explode_geometry.py:257-259)with pymxs.undo(True, "Explode Geometry"):exists but individual per-face calls still record internal undo data, adding overhead (Python/explode_geometry.py:261)polyop.detachFaceswhich mutates the source mesh per call and shifts face indices, forcing a reverse-order sequential loop (Python/explode_geometry.py:360-362)rt.redrawViews()is already called once after the loop (Python/explode_geometry.py:296) — viewport state is recoverable if redraws are suppressed during the loopBundle2/Contents/python/explode_geometry.pyis identical toPython/explode_geometry.pyand needs the same changesDesired End State
The explode operation on large meshes (100+ faces) completes measurably faster. The viewport does not flicker per-face during the operation. A single
Ctrl+Zreverts the entire explode. The progress bar updates at reasonable intervals (~every 20 faces). All existing functionality (Shell modifier, Edit Mesh, collapse stack, center pivot, delete original, TriMesh/MNMesh modes) is preserved and produces identical geometry output.Verification: Run explode on a 500+ face mesh with Shell + Collapse Stack enabled. Record the
elapsedtime printed to the MAXScript Listener. Compare to the pre-patch baseline on the same mesh.What We're NOT Doing
threading.Thread,concurrent.futures.ThreadPoolExecutor, ormultiprocessingforpymxscalls (confirmed impossible per Autodesk documentation)pymxs.mxstoken()usage (deprecated, non-functional)pymxs(deadlock risk)Python/explode_geometry_classic.py(MaxPlus-based, legacy/unsupported since 3ds Max 2022)Implementation Approach
Implement the four ranked optimizations from the research in priority order. Tasks 1 and 2 (redraw suppression + undo suppression) are the highest-impact changes. Task 3 (processEvents throttle) is a quick secondary improvement. Task 4 (MNMesh refactor) eliminates an algorithmic sequential dependency. All changes are applied to both script files.
IMPORTANT: Checkboxes are for implementation steps only. Steps requiring manual human verification are in the numbered "Manual Testing Steps" section at the bottom.
TASK 1: Disable Scene Redraws During the Explode Loop [HIGH PRIORITY]
Status: NOT STARTED
Milestone: The 3ds Max viewport no longer updates per-face during explode; a single
rt.redrawViews()fires once at the end.rt.disableSceneRedraw()andrt.enableSceneRedraw()are accessible viapymxs.runtime(test in MAXScript Listener:python.execute "import pymxs; pymxs.runtime.disableSceneRedraw()")rt.execute("disableSceneRedraw()")andrt.execute("enableSceneRedraw()")as fallbackdo_explode()inPython/explode_geometry.py, addrt.disableSceneRedraw()immediately before thewith pymxs.undo(True, "Explode Geometry"):block (before line 261)try/finallythat callsrt.enableSceneRedraw()thenrt.redrawViews()in thefinallyclausert.redrawViews()at line 296 since it is now inside thefinallyblockBundle2/Contents/python/explode_geometry.pyValidation: Run explode on a 200+ face mesh. Viewport must not flicker per-face.
rt.redrawViews()fires once at completion. MAXScript Listener shows lowerelapsedtime vs pre-patch baseline.Requirements from spec:
rt.redrawViews()) after explode completesFiles to Modify:
Python/explode_geometry.py—do_explode()method (~line 261)Bundle2/Contents/python/explode_geometry.py— identical changeImplementation Details:
TASK 2: Suppress Per-Face Undo Entries [HIGH PRIORITY]
Status: NOT STARTED
Milestone: The undo stack shows a single "Explode Geometry" entry; per-face undo recording overhead is eliminated.
convert_to_triangle_faces()inPython/explode_geometry.py(lines 330-347), wrap the per-face block (rt.mesh(...)throughapplySettings(...)) inwith pymxs.undo(False):convert_to_mnmesh_faces()inPython/explode_geometry.py(lines 360-372), wrap the per-face block (rt.polyop.detachFaces(...)throughapplySettings(...)) inwith pymxs.undo(False):with pymxs.undo(True, "Explode Geometry"):indo_explode()intact — it provides the single undo group entryBundle2/Contents/python/explode_geometry.pyValidation: Explode a 50+ face mesh. Press
Ctrl+Zonce. The entire explode operation (all created nodes removed, original restored) must be undone in a single step. The Edit menu undo history must show exactly one "Explode Geometry" entry.Requirements from spec:
with pymxs.undo(False):insidewith pymxs.undo(True, ...):must correctly scope undo to the outer block (test this before committing)Files to Modify:
Python/explode_geometry.py—convert_to_triangle_faces()(~lines 330-347) andconvert_to_mnmesh_faces()(~lines 360-372)Bundle2/Contents/python/explode_geometry.py— same changesImplementation Details:
In
convert_to_triangle_faces:TASK 3: Throttle
processEvents()to Every N Faces [MEDIUM PRIORITY]Status: NOT STARTED
Milestone: Qt event-loop pump overhead is reduced from O(faces) to O(faces/20) while the progress bar remains responsive.
do_explode()inPython/explode_geometry.py, update the_prog()inner function (lines 257-259) to only callQtWidgets.QApplication.processEvents()whencur % 20 == 0 or cur == totself.progress_bar.setValue(...)updating every call — it is cheap and ensures accurate display whenprocessEvents()does fireQtWidgets.QApplication.processEvents()at line 254 (after showing the progress panel) unchanged — that call is outside the hot pathBundle2/Contents/python/explode_geometry.pyValidation: On a 200-face mesh, the progress bar must advance in visible steps (~10% increments). The UI must remain responsive (window can be moved, not frozen). No single progress jump exceeds ~20% in one tick.
Requirements from spec:
Files to Modify:
Python/explode_geometry.py—_prog()inner function insidedo_explode()(~lines 257-259)Bundle2/Contents/python/explode_geometry.py— same changeImplementation Details:
TASK 4: Refactor MNMesh Path to Read-Then-Create Pattern [MEDIUM PRIORITY]
Status: NOT STARTED
Milestone:
convert_to_mnmesh_faces()no longer usespolyop.detachFaces. All vertex data is read in Phase 1 before any node is created in Phase 2, removing the index-shifting sequential dependency._create_poly_node_from_positions(positions)toPython/explode_geometry.py(after_random_wire_color). It must: create a newPolyMeshObjectnode viart.newObjectNode(rt.PolyMeshObject()), callrt.polyop.setNumVerts,rt.polyop.setVertfor each position, thenrt.polyop.createFacewith a 1-based index arrayrt.newObjectNodeorrt.PolyMeshObjectare not accessible in pymxs, usert.execute("newObjectNode (PolyMeshObject())")and retrieve the node viart.objects[-1]convert_to_mnmesh_faces()inPython/explode_geometry.py(lines 351-373): Phase 1 iteratesrange(1, num_faces + 1)(forward order), callsrt.polyop.getFaceVertsandrt.polyop.getVertfor each vertex, stores results as plain Python(x, y, z)tuples — retains no pymxs objects after this phase_create_poly_node_from_positions(positions)per face, setswireColor, callsapplySettingsrange(num_faces, 0, -1)fromconvert_to_mnmesh_faces— forward order is correct since Phase 1 does not mutate the sourcert.delete(node)(thedeleteOriginalpath indo_explode()) is called only after both phases complete, since Phase 1 reads from the source meshBundle2/Contents/python/explode_geometry.pyValidation: Explode a quad-face plane in MNMesh mode. Each resulting node must be a single-face Editable Poly with correct vertex positions (check in modifier panel). Explode a pentagon (5-vert n-gon) to confirm n-gon topology is preserved, not triangulated.
Requirements from spec:
Files to Modify:
Python/explode_geometry.py— add_create_poly_node_from_positions()helper; refactorconvert_to_mnmesh_faces()(~lines 351-373)Bundle2/Contents/python/explode_geometry.py— same changesImplementation Details:
Phase 1 (read, no mutation):
Phase 2 (create from plain Python data):
Helper function:
Testing Strategy
Unit Tests:
Integration Tests:
Manual Testing Steps:
Python/explode_geometry.py, create a GeoSphere with 100+ facesCtrl+Zonce after explode — verify full operation is undone in a single stepPerformance Considerations
detachFacesper-call overhead and removing the reverse-iteration constraint@allankoechke commented on GitHub (Jun 24, 2026):
Lets work only with Python script for this tests
@allankoechke commented on GitHub (Jun 24, 2026):
Applied changes to research:
Diff
@@ -1,148 +1,168 @@ ## Research Findings -_Researched 2026-06-24 | Branch `5-experimental-multithreading` | Com -mit `1fa4756`_ +_Researched 2026-06-24 | Branch `5-experimental-multithreading` | Com +mit `1fa4756` | Scope: **Python script only** (`Python/explode_geomet +ry.py`)_ ### Summary -**3ds Max is fundamentally single-threaded for scene graph operations -.** All node creation, modifier application, stack collapse, and tran -sform mutations must happen on the main thread -- this applies equall -y to the C++ SDK, the .NET wrapper (`Autodesk.Max`), and `pymxs`. The - `pymxs.mxstoken()` context manager is deprecated and non-functional. - There is no workaround. +**3ds Max is fundamentally single-threaded for scene graph operations +.** All node creation, modifier application, stack collapse, and tran +sform mutations must happen on the main thread -- this applies to `py +mxs` and all MAXScript-backed calls. `pymxs.mxstoken()` is deprecated + and non-functional. There is no way to run scene-mutating work in pa +rallel. -However, **substantial speedups (2-5x) are achievable without true mu -ltithreading** by suppressing per-iteration overhead (viewport redraw -s, undo recording, Modify Panel updates). True parallelism can be app -lied only to the data-preparation phase (extracting face/vertex data -into plain structs), which is currently ~5-10% of total time. +However, **substantial speedups are achievable without true multithre +ading** by suppressing per-iteration overhead (undo recording, `proce +ssEvents` throttling) and by restructuring the MNMesh path. True para +llelism can be applied only to pure-Python computation on extracted m +esh data (no `pymxs` calls), which is currently a small fraction of t +otal time. ### Key Discoveries -- **The per-face loop is ~80% scene mutations**: Each face iteration -performs ~19-29 mutating operations (node creation, modifier applicat -ion, stack collapse, transform) vs ~6 read operations -- a ~4:1 mutat -ion-to-read ratio (`Source/ADNUtilities.cs:284-351`) -- **`DisableSceneRedraw()` is already in the code but commented out** - (`Source/XAML/ExplodeGeomUserControl1.xaml.cs:271`). Enabling it is -the single highest-impact optimization -- **The MNMesh/polygon Python path is inherently sequential**: `polyo -p.detachFaces` mutates the source mesh in-place, shifting indices aft -er each call -- cannot be parallelized at all (`Python/explode_geomet -ry.py:360-362`) -- **The C# polygon path reads without mutating the source**, making i -t theoretically amenable to data-parallel extraction (`Source/ADNUtil -ities.cs:469`) -- **`MakeNameUnique` gets slower as faces are processed** -- it must -scan all scene nodes, and the scene grows by one node per iteration ( -`Source/ADNUtilities.cs:306`) -- **A `TODO: parallelize this` comment exists** in the classic Python - version (`Python/explode_geometry_classic.py:276`) -- **Official Autodesk sources confirm**: "3ds Max is not thread-safe. - You should not call any function from multiple threads concurrently. -" ([Thread Safety - 3ds Max SDK](https://help.autodesk.com/cloudhelp/ -2018/ENU/Max-Developer-Help/developer/best_practices/thread_safety.ht -ml)) +- **The MNMesh/polygon path is inherently sequential**: `polyop.detac +hFaces` mutates the source mesh in-place and shifts face indices afte +r each call -- cannot be parallelized (`Python/explode_geometry.py:36 +0-362`). The reverse iteration order (`range(num_faces, 0, -1)`) exis +ts specifically because of this dependency. +- **The TriMesh path reads without mutating the source**, making face +/vertex extraction (`rt.getFace`, `rt.getVert`) safe to separate from + node creation (`Python/explode_geometry.py:330-334`) +- **`QApplication.processEvents()` is called once per face** (`Python +/explode_geometry.py:258-259`), adding Qt event loop overhead on ever +y iteration regardless of mesh size +- **`pymxs.runtime` calls cannot be made from background threads** -- + `mxstoken()` is deprecated. The only safe background work is pure Py +thon (NumPy, math, data structures) +- **A `TODO: parallelize this` comment exists** in the classic Python + version at the MNMesh loop (`Python/explode_geometry_classic.py:276` +) +- **Official Autodesk sources confirm**: "3ds Max is a single-threade +d application, which means that Python threads cannot interact with 3 +ds Max, either the UI or the MAXScript environment." ([Threading in P +ython with 3ds Max](https://help.autodesk.com/view/MAXDEV/2025/ENU/?g +uid=MAXDEV_Python_threading_html)) ### Detailed Findings -#### 3ds Max Threading Model +#### pymxs Threading Constraints | Operation | Thread-Safe? | Notes | |---|---|---| -| `IGlobal.Instance` / `COREInterface14` | **NO** | Singleton COM-bas -ed core interface | -| `CreateObjectNode` | **NO** | Scene graph is single-threaded | -| `SetNodeTM`, `CenterPivot` | **NO** | Triggers evaluation pipeline -| -| Modifier application (`AddModifier`) | **NO** | Confirmed crash eve -n with `mxstoken` | -| `CollapseNode` | **NO** | Full modifier stack evaluation | -| `IMesh`/`IMNMesh` reading | **NOT DOCUMENTED SAFE** | Evaluation pi -peline risk | -| Copied mesh data in plain arrays | **YES** | Copy on main thread, p -rocess on background | -| `pymxs.runtime` calls | **NO** | `mxstoken()` is deprecated/non-fun -ctional | -| Pure Python/C# computation (no SDK) | **YES** | File I/O, NumPy, TP -L | +| `pymxs.runtime` calls (any) | **NO** | Main thread only; threading +raises runtime exception | +| `pymxs.mxstoken()` | **NO** | Deprecated and non-functional as of 2 +024+ | +| `rt.mesh()`, `rt.polyop.*` | **NO** | Scene graph mutation, main th +read only | +| `rt.addModifier`, `rt.maxOps.collapseNode` | **NO** | Modifier stac +k evaluation, main thread only | +| `rt.getFace`, `rt.getVert` (read-only) | **NOT DOCUMENTED SAFE** | +Goes through pymxs bridge; copy to plain Python first | +| Plain Python computation (no pymxs) | **YES** | NumPy arrays, math, + data structures | +| `concurrent.futures.ThreadPoolExecutor` (no pymxs) | **YES** | Safe + for pure Python work only | +| `multiprocessing` | **IMPRACTICAL** | IPC overhead exceeds any bene +fit for this workload | -**Main-thread dispatching mechanisms available:** -- **.NET**: `System.Windows.Threading.Dispatcher.Invoke()` -- the WPF - Dispatcher captured on the main thread -- **C++ SDK**: `IMainThreadTaskManager::PostTask()` -- official main- -thread dispatch (not exposed in .NET wrapper) -- **Python**: ADN-DevTech `mxthread` module uses Qt signal/slot patte -rn with `QWaitCondition` +**Main-thread marshaling from Python background threads:** -**Sources**: [Thread Safety (2023)](https://help.autodesk.com/view/MA -XDEV/2023/ENU/?guid=thread_safety), [Threading in Python (2025)](http -s://help.autodesk.com/view/MAXDEV/2025/ENU/?guid=MAXDEV_Python_thread -ing_html), [pymxs crash report](https://forums.autodesk.com/t5/3ds-ma -x-programming/pymxs-threading-and-modify-tab-crash/td-p/9680135) +ADN-DevTech's `mxthread` module demonstrates the only viable pattern: + a `QThread` worker emits Qt signals, and slot handlers on the main t +hread execute `pymxs` operations. Critical constraint: **the main thr +ead cannot wait/block for the worker -- this causes a deadlock.** For + the explode operation (which already runs on the main thread via a b +utton click), no marshaling is needed -- all `pymxs` work is already +on the correct thread. -#### Per-Face Bottleneck Analysis +**Source**: [Threading in Python with 3ds Max (2025)](https://help.au +todesk.com/view/MAXDEV/2025/ENU/?guid=MAXDEV_Python_threading_html), +[ADN-DevTech mxthread](https://github.com/ADN-DevTech/3dsMax-Python-H +owTos/blob/master/src/packages/mxthread/README.md) +#### Per-Face Bottleneck Analysis (Python) + **Most expensive operations per face** (ordered by cost): -1. **`CollapseNode`** -- evaluates the entire modifier stack per face - (`ADNUtilities.cs:340`) -2. **`AddOsmShell` / `AddOsmEditMesh`** -- each involves `CreateInsta -nce` + `CreateDerivedObject` + `AddModifier` + `ObjectRef` assignment - (~6 sub-ops each, `ADNUtilities.cs:334,337`) -3. **`polyop.detachFaces`** (Python MNMesh) -- compound: modifies sou -rce mesh + creates new node (`explode_geometry.py:362`) -4. **`CreateObjectNode`** -- inserts into scene graph, triggers notif -ications (`ADNUtilities.cs:302`) -5. **`MakeNameUnique`** -- linear scan of scene nodes, gets slower as - scene grows (`ADNUtilities.cs:306`) -6. **`CenterPivot`** -- computes bounding box + adjusts offset transf -orm (`ADNUtilities.cs:349`) +1. **`rt.maxOps.collapseNode(n, True)`** -- evaluates the full modifi +er stack per face; called in `applySettings` (`explode_geometry.py:39 +1`) +2. **`rt.addModifier(n, mod)` x2** -- Shell + Edit Mesh modifier appl +ication (`explode_geometry.py:383, 388`); each goes through the pymxs + bridge with Python-to-MAXScript marshalling overhead +3. **`rt.polyop.detachFaces(node, rt.Array(face_idx), asNode=True)`** + -- compound: modifies source MNMesh topology + creates new scene nod +e (`explode_geometry.py:362`) +4. **`rt.mesh(vertices=..., faces=...)`** -- compound: creates mesh o +bject + scene node in one call (`explode_geometry.py:338`) +5. **`rt.centerPivot(n)`** -- computes bounding box + adjusts offset +transform (`explode_geometry.py:394`) +6. **`QApplication.processEvents()`** -- Qt event loop pump called on +ce per face (`explode_geometry.py:259`) **Least expensive (parallelizable in principle):** -- `mesh.GetFace()`, `mesh.GetVert()` -- direct array lookups -- `SetNumFaces`, `SetNumVerts`, `SetVert` on new isolated mesh -- no -scene notifications +- `rt.getFace(node, face_idx)`, `rt.getVert(node, int(...))` -- read- +only index lookups; once copied to plain Python tuples/lists, no pymx +s needed +- Pure Python arithmetic, list construction -#### Parallelization Strategies (Ranked by Impact) +#### Optimization Strategies (Ranked by Impact, Python-Specific) -**1. [HIGH IMPACT] Enable `DisableSceneRedraw`** _(estimated 2-5x spe -edup)_ +**1. [HIGH IMPACT] Disable scene redraws around the loop** _(estimate +d 2-5x speedup)_ -Already in the code at `ExplodeGeomUserControl1.xaml.cs:271` but comm -ented out. Each `CreateObjectNode`, `InvalidateGeomCache`, `CollapseN -ode`, and transform assignment currently triggers viewport updates. W -rapping the loop suppresses these until the final `RedrawViews` call -at line 312. +Each `rt.mesh()`, `rt.addModifier()`, and `rt.maxOps.collapseNode()` +call triggers viewport updates. Wrap the entire loop with MAXScript-l +evel redraw suppression: -```csharp -ip.DisableSceneRedraw(); -try { - for (int nfaceIndex = 0; nfaceIndex < nNumFaces; nfaceIndex++) { - // ... existing face loop ... - } -} finally { - ip.EnableSceneRedraw(); - ip.RedrawViews(0, RedrawFlags.Normal, null); -} +```python +with pymxs.undo(True, "Explode Geometry"): + rt.disableSceneRedraw() + try: + for i, n in enumerate(transformation_set, 1): + convert_to_triangle_faces(n, ...) + finally: + rt.enableSceneRedraw() + rt.redrawViews() ``` -**2. [HIGH IMPACT] Suspend undo recording in the inner loop** +The current code calls `rt.redrawViews()` once after the loop (`explo +de_geometry.py:296`) but does not suppress per-node redraws during th +e loop. This is already the pattern for the C# version (commented-out + `DisableSceneRedraw`) and is the single highest-impact change. -The outer `theHold.Begin()`/`Accept()` (lines 255, 309) wraps the who -le operation, but each sub-operation still records undo data internal -ly. Use `theHold.Suspend()`/`Resume()` during the inner loop, or expl -ore the C++ SDK `SuspendAll` class (suspends undo, macro recording, a -nimation keys, and reference message passing simultaneously). +**2. [HIGH IMPACT] Suspend undo recording inside the inner face loop* +* -**3. [MEDIUM IMPACT] Suspend Modify Panel updates** +`pymxs.undo(True, ...)` wraps the whole operation (`explode_geometry. +py:261`), but each individual `rt.mesh()`, `rt.addModifier()`, and `r +t.maxOps.collapseNode()` call still records undo data internally per +face. Use `with pymxs.undo(False): ...` inside the per-face work if y +ou only need a single top-level undo entry: -Each modifier application and `CollapseNode` triggers Modify Panel re -fresh. Call the equivalent of `suspendEditing` before the loop and `r -esumeEditing` after. +```python +with pymxs.undo(True, "Explode Geometry"): + rt.disableSceneRedraw() + try: + for face_idx in range(1, num_faces + 1): + with pymxs.undo(False): # suppress per-face undo entries + new_node = rt.mesh(...) + applySettings(new_node, ...) + finally: + rt.enableSceneRedraw() + rt.redrawViews() +``` -**4. [MEDIUM IMPACT] Pre-extract mesh data into plain structs** +**3. [MEDIUM IMPACT] Throttle `QApplication.processEvents()` to every + N faces** -Separate the read phase from the write phase. Extract all face/vertex - data from the source mesh into a C# struct array before entering the - node-creation loop. This enables future TPL parallelization of any h -eavier per-face computation. +Currently called once per face via `_prog()` (`explode_geometry.py:25 +8-259`). For large meshes (1000+ faces), this is 1000+ event loop pum +p calls. Throttle to every 10-50 faces: -```csharp -struct FaceData { - public IPoint3[] Vertices; -} +```python +def _prog(cur, tot): + self.progress_bar.setValue(int(cur * 100 / tot) if tot else 0) + if cur % 20 == 0 or cur == tot: # update every 20 faces + QtWidgets.QApplication.processEvents() +``` -var faces = new FaceData[nNumFaces]; -for (int i = 0; i < nNumFaces; i++) { - IFace face = mesh.GetFace(i); - faces[i].Vertices = new IPoint3[face.V.Count()]; - for (int v = 0; v < face.V.Count(); v++) - faces[i].Vertices[v] = triOriginal.Mesh.GetVert((int)face.Get -Vert(v)); -} -// Then iterate faces[] for node creation -- source mesh no longer ne -eded +**4. [MEDIUM IMPACT] Refactor MNMesh path away from `detachFaces`** + +The current `convert_to_mnmesh_faces` function (`explode_geometry.py: +351-373`) uses `polyop.detachFaces` which mutates the source mesh, ma +king each iteration depend on the previous one. An alternative approa +ch -- reading all face vertex data first, then creating independent p +oly nodes -- would eliminate this sequential dependency and match the + TriMesh path's structure: + +```python +def convert_to_mnmesh_faces(node, ...): + rt.convertToPoly(node) + num_faces = rt.polyop.getNumFaces(node) + # Phase 1: extract all face vertex data (read-only, no source mut +ation) + face_verts = [] + for face_idx in range(1, num_faces + 1): + verts = rt.polyop.getFaceVerts(node, face_idx) + positions = [rt.polyop.getVert(node, int(v)) for v in verts] + face_verts.append(positions) + # Phase 2: create nodes from extracted data (source mesh untouche +d) + for i, positions in enumerate(face_verts): + new_node = _create_poly_from_positions(positions) + applySettings(new_node, ...) ``` -**5. [LOW IMPACT now, HIGH for future] Use TPL `Parallel.For` for ext -ended computation** +This also opens the door for `concurrent.futures.ThreadPoolExecutor` +on Phase 1 if position data is copied to plain Python tuples first (n +o pymxs references held across threads). -If heavier per-face work is added (normals, UV computation, spatial s -orting), use `System.Threading.Tasks.Parallel.For` on the plain-data -arrays. Proven by Munich Filmworks for Thinking Particles -- achieved - 100% CPU utilization with TPL + `System.Collections.Concurrent`. Tip -: enable server GC mode for better multi-core utilization. +**5. [LOW IMPACT] Pre-extract TriMesh face data into plain Python str +uctures** -**6. [NOT RECOMMENDED] Python/pymxs threading, GPU compute, or MaxScr -ipt parallelism** +For the TriMesh path, `rt.getFace` and `rt.getVert` are already read- +only, but they go through the pymxs bridge on each call. Pre-extracti +ng to plain Python tuples reduces bridge overhead during node creatio +n: -None address the actual bottleneck (serial scene graph mutation). `py -mxs.mxstoken()` is deprecated. `multiprocessing` would require IPC ov -erhead exceeding any benefit. GPU compute via CUDA is technically pos -sible but the bottleneck is CPU-bound SDK calls, not computation. +```python +# Before the node-creation loop: +face_data = [] +for face_idx in range(1, num_faces + 1): + face = rt.getFace(node, face_idx) + v1 = rt.getVert(node, int(face.x)) + v2 = rt.getVert(node, int(face.y)) + v3 = rt.getVert(node, int(face.z)) + face_data.append(((v1.x, v1.y, v1.z), (v2.x, v2.y, v2.z), (v3.x, +v3.y, v3.z))) +# Then use face_data[i] in node creation -- no more pymxs bridge for +reads +``` -#### Python-Specific Considerations +**6. [NOT RECOMMENDED] `concurrent.futures`, `threading`, `multiproce +ssing` for pymxs calls** -For the Python implementation (`explode_geometry.py`): -- Use `with pymxs.undo(False, ...)` or split the undo wrapper to redu -ce overhead -- The `QApplication.processEvents()` call per face (line 259) is nece -ssary for UI responsiveness but adds overhead -- consider calling it -every N faces instead of every face -- The `convert_to_mnmesh_faces` path using `polyop.detachFaces` (line - 362) is inherently sequential due to source mesh mutation -- conside -r refactoring to the C#-style approach of reading face data and creat -ing independent nodes instead +None can call `pymxs.runtime` from a background thread. `mxstoken()` +is deprecated. `multiprocessing` requires IPC serialization that exce +eds any benefit for this workload. `ThreadPoolExecutor` is only usefu +l for pure Python computation on already-extracted data. ### Files Requiring Changes | File | Lines | Change | |------|-------|--------| -| `Source/XAML/ExplodeGeomUserControl1.xaml.cs` | 271 | Uncomment `ip -.DisableSceneRedraw()`, add `EnableSceneRedraw` in `finally` block | -| `Source/XAML/ExplodeGeomUserControl1.xaml.cs` | 255-309 | Add `theH -old.Suspend()`/`Resume()` around inner loop, or explore `SuspendAll` -| -| `Source/ADNUtilities.cs` | 226-359 | Refactor `ConvertToTriangleFac -es` to separate data extraction from node creation | -| `Source/ADNUtilities.cs` | 372-546 | Same refactoring for `ConvertT -oPolygonFaces` | -| `Python/explode_geometry.py` | 257-259 | Throttle `processEvents()` - to every N faces instead of every face | -| `Python/explode_geometry.py` | 351-373 | Consider refactoring MNMes -h path away from `detachFaces` to independent node creation | +| `Python/explode_geometry.py` | 261-296 | Wrap `do_explode` loop wit +h `rt.disableSceneRedraw()` / `rt.enableSceneRedraw()` | +| `Python/explode_geometry.py` | 261 | Use `with pymxs.undo(False): . +..` inside per-face work to suppress individual undo entries | +| `Python/explode_geometry.py` | 257-259 | Throttle `processEvents()` + to every N faces | +| `Python/explode_geometry.py` | 351-373 | Refactor `convert_to_mnmes +h_faces` to read-then-create pattern, removing `detachFaces` dependen +cy | +| `Python/explode_geometry.py` | 323-348 | Optionally pre-extract fac +e/vertex data to plain Python tuples before node-creation loop | ### Open Questions -1. **Is `SuspendAll` accessible via the .NET `Autodesk.Max` wrapper?* -* If not, can we achieve the same effect through individual `Suspend` -/`Resume` calls on each subsystem? -2. **How much does `MakeNameUnique` contribute to total time on very -large meshes (10k+ faces)?** Could a batch naming scheme (e.g., pre-g -enerating unique names with a counter) bypass the scene scan? -3. **Would the C# polygon path benefit from the same data-extraction -refactor as the triangle path?** The C# version already reads without - mutating the source (unlike the Python `detachFaces` approach), but -separating phases could still improve cache behavior. -4. **Is the dual `ObjOffsetPos` assignment at lines 344 and 348 in `A -DNUtilities.cs` intentional or a bug?** It sets `ObjOffsetPos` twice -with the same value. +1. **Does `rt.disableSceneRedraw()` / `rt.enableSceneRedraw()` exist +in pymxs?** Or must it be invoked via `rt.execute("disableSceneRedraw +()")` / MAXScript execute? +2. **How much does per-face `processEvents()` contribute to total tim +e?** Profiling with `cProfile` or `time.perf_counter` around the `_pr +og` callback would quantify this. +3. **Is the refactored MNMesh path (read-then-create) functionally eq +uivalent to `detachFaces`?** The detach approach preserves material I +Ds, smoothing groups, and UV mapping automatically -- a manual vertex +-copy approach may need to handle these explicitly. +4. **Would nesting `with pymxs.undo(False)` inside `with pymxs.undo(T +rue, ...)` correctly scope undo to just the outer block?** Needs test +ing to confirm pymxs undo nesting behavior. ### References -- [Thread Safety - 3ds Max SDK (2018)](https://help.autodesk.com/clou -dhelp/2018/ENU/Max-Developer-Help/developer/best_practices/thread_saf -ety.html) -- [Thread Safety - 3ds Max SDK (2023)](https://help.autodesk.com/view -/MAXDEV/2023/ENU/?guid=thread_safety) - [Threading in Python with 3ds Max (2025)](https://help.autodesk.com /view/MAXDEV/2025/ENU/?guid=MAXDEV_Python_threading_html) - [pymxs Threading Crash Report](https://forums.autodesk.com/t5/3ds-m ax-programming/pymxs-threading-and-modify-tab-crash/td-p/9680135) -- [Multicore Processing in 3ds Max - Munich Filmworks](https://munich --filmworks.com/multithreading-tp/) - [ADN-DevTech mxthread](https://github.com/ADN-DevTech/3dsMax-Python -HowTos/blob/master/src/packages/mxthread/README.md) -- [ThreadTools Class Reference (2026)](https://help.autodesk.com/clou -dhelp/2026/ENU/MAXDEV-CPP-API-REF/class_max_s_d_k_1_1_performance_too -ls_1_1_thread_tools.html) -- [MainThreadTaskManager (C++ SDK)](https://help.autodesk.com/cloudhe -lp/2023/ENU/Max-Developer-Help/cpp_ref/class_i_main_thread_task_manag -er.html) -- [SuspendAll Class (C++ SDK)](https://help.autodesk.com/cloudhelp/20 -16/ENU/Max-SDK/cpp_ref/class_suspend_all.html) -- [Tips and Tricks - 3ds Max SDK (2017)](https://help.autodesk.com/cl -oudhelp/2017/ENU/Max-SDK/files/GUID-0FA27485-D808-40B7-8465-B1C293077 -597.htm) +- [MaxScript Performance Tips - disableSceneRedraw](https://help.auto +desk.com/cloudhelp/2017/ENU/MAXScript-Help/files/GUID-75BB21C9-2283-4 +9BD-853C-78006717FBE2.htm) +- [MaxScript Performance Tips - undo off](https://help.autodesk.com/c +loudhelp/2017/ENU/MAXScript-Help/files/GUID-A731E672-9B9A-4D5B-A8A7-E +A584AD12FE5.htm)@allankoechke commented on GitHub (Jul 21, 2026):
Implementation complete! PR ready for review: https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/pull/6