[GH-ISSUE #5] feat: experimental multithreading #3

Closed
opened 2026-10-14 09:52:32 +00:00 by allankoech · 3 comments
Owner

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 | Commit 1fa4756 | 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 pymxs and 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, processEvents throttling) and by restructuring the MNMesh path. True parallelism can be applied only to pure-Python computation on extracted mesh data (no pymxs calls), which is currently a small fraction of total time.

Key Discoveries

  • The MNMesh/polygon path is inherently sequential: polyop.detachFaces mutates 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.
  • 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 every iteration regardless of mesh size
  • pymxs.runtime calls cannot be made from background threads -- mxstoken() is deprecated. The only safe background work is pure Python (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-threaded application, which means that Python threads cannot interact with 3ds Max, either the UI or the MAXScript environment."

Detailed Findings

pymxs Threading Constraints

Operation Thread-Safe? Notes
pymxs.runtime calls (any) NO Main thread only; threading raises runtime exception
pymxs.mxstoken() NO Deprecated and non-functional as of 2024+
rt.mesh(), rt.polyop.* NO Scene graph mutation, main thread only
rt.addModifier, rt.maxOps.collapseNode NO Modifier stack 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 benefit for this workload

Per-Face Bottleneck Analysis (Python)

Most expensive operations per face (ordered by cost):

  1. rt.maxOps.collapseNode(n, True) -- evaluates the full modifier stack per face
  2. rt.addModifier(n, mod) x2 -- Shell + Edit Mesh modifier application; each goes through the pymxs bridge
  3. rt.polyop.detachFaces(node, rt.Array(face_idx), asNode=True) -- modifies source MNMesh topology + creates new scene node
  4. rt.mesh(vertices=..., faces=...) -- creates mesh object + scene node in one call
  5. rt.centerPivot(n) -- computes bounding box + adjusts offset transform
  6. QApplication.processEvents() -- Qt event loop pump called once per face

Optimization Strategies (Ranked by Impact)

  1. [HIGH IMPACT] Disable scene redraws around the loop (estimated 2-5x speedup)
  2. [HIGH IMPACT] Suspend undo recording inside the inner face loop
  3. [MEDIUM IMPACT] Throttle QApplication.processEvents() to every N faces
  4. [MEDIUM IMPACT] Refactor MNMesh path away from detachFaces
  5. [LOW IMPACT] Pre-extract TriMesh face data into plain Python structures
  6. [NOT RECOMMENDED] concurrent.futures, threading, multiprocessing for pymxs calls

References


Explode Geometry Performance Optimization Implementation Plan

Overview

Research confirmed that pymxs.runtime calls 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. Both Python/explode_geometry.py and Bundle2/Contents/python/explode_geometry.py are identical and both require the same changes.

Current State Analysis

Key Discoveries:

  • Scene redraws are NOT suppressed during the inner face loop — each rt.mesh(), rt.addModifier(), and rt.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)
  • The outer with pymxs.undo(True, "Explode Geometry"): exists but individual per-face calls still record internal undo data, adding overhead (Python/explode_geometry.py:261)
  • The MNMesh path uses polyop.detachFaces which 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 loop
  • Bundle2/Contents/python/explode_geometry.py is identical to Python/explode_geometry.py and needs the same changes

Desired 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+Z reverts 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 elapsed time printed to the MAXScript Listener. Compare to the pre-patch baseline on the same mesh.

What We're NOT Doing

  • No threading.Thread, concurrent.futures.ThreadPoolExecutor, or multiprocessing for pymxs calls (confirmed impossible per Autodesk documentation)
  • No pymxs.mxstoken() usage (deprecated, non-functional)
  • No Qt worker threads that call back into pymxs (deadlock risk)
  • No changes to the UI layout or any feature set
  • No changes to 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.

  • Confirm rt.disableSceneRedraw() and rt.enableSceneRedraw() are accessible via pymxs.runtime (test in MAXScript Listener: python.execute "import pymxs; pymxs.runtime.disableSceneRedraw()")
  • If direct pymxs access fails, use rt.execute("disableSceneRedraw()") and rt.execute("enableSceneRedraw()") as fallback
  • In do_explode() in Python/explode_geometry.py, add rt.disableSceneRedraw() immediately before the with pymxs.undo(True, "Explode Geometry"): block (before line 261)
  • Wrap the undo block in a try/finally that calls rt.enableSceneRedraw() then rt.redrawViews() in the finally clause
  • Remove the standalone rt.redrawViews() at line 296 since it is now inside the finally block
  • Apply the identical structural change to Bundle2/Contents/python/explode_geometry.py

Validation: Run explode on a 200+ face mesh. Viewport must not flicker per-face. rt.redrawViews() fires once at completion. MAXScript Listener shows lower elapsed time vs pre-patch baseline.

Requirements from spec:

  • All scene operations remain on the main thread
  • Viewport must be fully refreshed (redraws re-enabled + rt.redrawViews()) after explode completes

Files to Modify:

  • Python/explode_geometry.py — do_explode() method (~line 261)
  • Bundle2/Contents/python/explode_geometry.py — identical change

Implementation Details:

rt.disableSceneRedraw()
try:
    with pymxs.undo(True, "Explode Geometry"):
        if self.trimesh_option.isChecked():
            ...  # existing TriMesh loop
        if self.mnmesh_option.isChecked():
            ...  # existing MNMesh loop
finally:
    rt.enableSceneRedraw()
    rt.redrawViews()

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.

  • In convert_to_triangle_faces() in Python/explode_geometry.py (lines 330-347), wrap the per-face block (rt.mesh(...) through applySettings(...)) in with pymxs.undo(False):
  • In convert_to_mnmesh_faces() in Python/explode_geometry.py (lines 360-372), wrap the per-face block (rt.polyop.detachFaces(...) through applySettings(...)) in with pymxs.undo(False):
  • Keep the outer with pymxs.undo(True, "Explode Geometry"): in do_explode() intact — it provides the single undo group entry
  • Apply the same changes to Bundle2/Contents/python/explode_geometry.py

Validation: Explode a 50+ face mesh. Press Ctrl+Z once. 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:

  • The whole explode must be reversible with a single undo
  • Nesting with pymxs.undo(False): inside with 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) and convert_to_mnmesh_faces() (~lines 360-372)
  • Bundle2/Contents/python/explode_geometry.py — same changes

Implementation Details:

In convert_to_triangle_faces:

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))
    with pymxs.undo(False):
        new_node = rt.mesh(vertices=rt.Array(v1, v2, v3),
                           faces=rt.Array(rt.Point3(1, 2, 3)))
        rt.update(new_node)
        new_node.wireColor = _random_wire_color()
        applySettings(new_node, addShell, shell_amount, addEditMesh, collapseNode, centerPivot)
    if on_progress:
        on_progress(face_idx, num_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.

  • In do_explode() in Python/explode_geometry.py, update the _prog() inner function (lines 257-259) to only call QtWidgets.QApplication.processEvents() when cur % 20 == 0 or cur == tot
  • Keep self.progress_bar.setValue(...) updating every call — it is cheap and ensures accurate display when processEvents() does fire
  • Keep the existing QtWidgets.QApplication.processEvents() at line 254 (after showing the progress panel) unchanged — that call is outside the hot path
  • Apply the same change to Bundle2/Contents/python/explode_geometry.py

Validation: 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:

  • Progress bar must remain visually responsive during long operations
  • Throttle interval of 20 faces is a starting point; adjust between 10-50 based on testing

Files to Modify:

  • Python/explode_geometry.py — _prog() inner function inside do_explode() (~lines 257-259)
  • Bundle2/Contents/python/explode_geometry.py — same change

Implementation Details:

def _prog(cur, tot):
    self.progress_bar.setValue(int(cur * 100 / tot) if tot else 0)
    if cur % 20 == 0 or cur == tot:
        QtWidgets.QApplication.processEvents()

TASK 4: Refactor MNMesh Path to Read-Then-Create Pattern [MEDIUM PRIORITY]

Status: NOT STARTED
Milestone: convert_to_mnmesh_faces() no longer uses polyop.detachFaces. All vertex data is read in Phase 1 before any node is created in Phase 2, removing the index-shifting sequential dependency.

  • Add a new helper function _create_poly_node_from_positions(positions) to Python/explode_geometry.py (after _random_wire_color). It must: create a new PolyMeshObject node via rt.newObjectNode(rt.PolyMeshObject()), call rt.polyop.setNumVerts, rt.polyop.setVert for each position, then rt.polyop.createFace with a 1-based index array
  • If rt.newObjectNode or rt.PolyMeshObject are not accessible in pymxs, use rt.execute("newObjectNode (PolyMeshObject())") and retrieve the node via rt.objects[-1]
  • Refactor convert_to_mnmesh_faces() in Python/explode_geometry.py (lines 351-373): Phase 1 iterates range(1, num_faces + 1) (forward order), calls rt.polyop.getFaceVerts and rt.polyop.getVert for each vertex, stores results as plain Python (x, y, z) tuples — retains no pymxs objects after this phase
  • Phase 2 iterates the plain Python list, calls _create_poly_node_from_positions(positions) per face, sets wireColor, calls applySettings
  • Remove the reverse iteration range(num_faces, 0, -1) from convert_to_mnmesh_faces — forward order is correct since Phase 1 does not mutate the source
  • Verify that rt.delete(node) (the deleteOriginal path in do_explode()) is called only after both phases complete, since Phase 1 reads from the source mesh
  • Apply the same changes to Bundle2/Contents/python/explode_geometry.py

Validation: 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:

  • Polygon topology (quads, n-gons) must be preserved — do not triangulate faces
  • Vertex positions must match the source mesh exactly
  • Source mesh must not be mutated during Phase 1

Files to Modify:

  • Python/explode_geometry.py — add _create_poly_node_from_positions() helper; refactor convert_to_mnmesh_faces() (~lines 351-373)
  • Bundle2/Contents/python/explode_geometry.py — same changes

Implementation Details:

Phase 1 (read, no mutation):

rt.convertToPoly(node)
num_faces = rt.polyop.getNumFaces(node)
face_data = []
for face_idx in range(1, num_faces + 1):
    verts = rt.polyop.getFaceVerts(node, face_idx)
    positions = [(rt.polyop.getVert(node, int(v)).x,
                  rt.polyop.getVert(node, int(v)).y,
                  rt.polyop.getVert(node, int(v)).z) for v in verts]
    face_data.append(positions)

Phase 2 (create from plain Python data):

for i, positions in enumerate(face_data, 1):
    with pymxs.undo(False):
        new_node = _create_poly_node_from_positions(positions)
        new_node.wireColor = _random_wire_color()
        applySettings(new_node, addShell, shell_amount, addEditMesh, collapseNode, centerPivot)
    if on_progress:
        on_progress(i, num_faces)

Helper function:

def _create_poly_node_from_positions(positions):
    n = len(positions)
    node = rt.newObjectNode(rt.PolyMeshObject())
    rt.polyop.setNumVerts(node, n)
    for i, (x, y, z) in enumerate(positions, 1):
        rt.polyop.setVert(node, i, rt.Point3(x, y, z))
    rt.polyop.createFace(node, rt.Array(*range(1, n + 1)))
    return node

Assumption: rt.newObjectNode and rt.PolyMeshObject are available as pymxs runtime calls. If not, fall back to rt.execute(...) and rt.objects[-1].


Testing Strategy

Unit Tests:

  • No standalone unit test framework exists in this project (3ds Max plugin context)
  • Correctness is verified by comparing geometry output against the pre-patch baseline

Integration Tests:

  • Run TriMesh explode on a Box primitive (12 triangles) — verify exactly 12 TriMesh face nodes are created
  • Run MNMesh explode on a Plane primitive (quad faces) — verify N single-face Editable Poly nodes are created
  • Run MNMesh explode on an n-gon face — verify face topology is preserved (not triangulated)
  • Confirm single undo entry reverts entire operation

Manual Testing Steps:

  1. Open 3ds Max, load Python/explode_geometry.py, create a GeoSphere with 100+ faces
  2. Record baseline elapsed time from the MAXScript Listener before patching
  3. Apply Task 1 patch; repeat the same explode and compare elapsed time — viewport must not flicker
  4. Apply Task 2 patch; press Ctrl+Z once after explode — verify full operation is undone in a single step
  5. Apply Task 3 patch; run explode on a 200+ face mesh — verify progress bar advances in steps of ~20 faces
  6. Apply Task 4 patch; run MNMesh explode on a quad plane — open modifier panel on a resulting node and verify vertex coordinates match the original face
  7. Test the most expensive path end-to-end: Shell modifier enabled + Collapse Stack enabled on a 500+ face mesh — confirm elapsed time improvement and no crashes

Performance Considerations

  • Tasks 1 + 2 combined are estimated at 2–5x speedup on large meshes based on research; viewport redraw suppression is the single largest contributor
  • Task 3 impact is proportional to mesh size; most noticeable on 500+ face objects
  • Task 4 restructures the MNMesh algorithm but does not reduce O(n) complexity; gains come from eliminating the detachFaces per-call overhead and removing the reverse-iteration constraint
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. --- <details> <summary><h2>Research Findings</h2></summary> _Researched 2026-06-24 | Branch `5-experimental-multithreading` | Commit `1fa4756` | 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 `pymxs` and 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, `processEvents` throttling) and by restructuring the MNMesh path. True parallelism can be applied only to pure-Python computation on extracted mesh data (no `pymxs` calls), which is currently a small fraction of total time. ### Key Discoveries - **The MNMesh/polygon path is inherently sequential**: `polyop.detachFaces` mutates 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. - **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 every iteration regardless of mesh size - **`pymxs.runtime` calls cannot be made from background threads** -- `mxstoken()` is deprecated. The only safe background work is pure Python (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-threaded application, which means that Python threads cannot interact with 3ds Max, either the UI or the MAXScript environment." ### Detailed Findings #### pymxs Threading Constraints | Operation | Thread-Safe? | Notes | |---|---|---| | `pymxs.runtime` calls (any) | **NO** | Main thread only; threading raises runtime exception | | `pymxs.mxstoken()` | **NO** | Deprecated and non-functional as of 2024+ | | `rt.mesh()`, `rt.polyop.*` | **NO** | Scene graph mutation, main thread only | | `rt.addModifier`, `rt.maxOps.collapseNode` | **NO** | Modifier stack 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 benefit for this workload | #### Per-Face Bottleneck Analysis (Python) **Most expensive operations per face** (ordered by cost): 1. **`rt.maxOps.collapseNode(n, True)`** -- evaluates the full modifier stack per face 2. **`rt.addModifier(n, mod)` x2** -- Shell + Edit Mesh modifier application; each goes through the pymxs bridge 3. **`rt.polyop.detachFaces(node, rt.Array(face_idx), asNode=True)`** -- modifies source MNMesh topology + creates new scene node 4. **`rt.mesh(vertices=..., faces=...)`** -- creates mesh object + scene node in one call 5. **`rt.centerPivot(n)`** -- computes bounding box + adjusts offset transform 6. **`QApplication.processEvents()`** -- Qt event loop pump called once per face #### Optimization Strategies (Ranked by Impact) 1. **[HIGH IMPACT]** Disable scene redraws around the loop _(estimated 2-5x speedup)_ 2. **[HIGH IMPACT]** Suspend undo recording inside the inner face loop 3. **[MEDIUM IMPACT]** Throttle `QApplication.processEvents()` to every N faces 4. **[MEDIUM IMPACT]** Refactor MNMesh path away from `detachFaces` 5. **[LOW IMPACT]** Pre-extract TriMesh face data into plain Python structures 6. **[NOT RECOMMENDED]** `concurrent.futures`, `threading`, `multiprocessing` for pymxs calls ### References - [Threading in Python with 3ds Max (2025)](https://help.autodesk.com/view/MAXDEV/2025/ENU/?guid=MAXDEV_Python_threading_html) - [ADN-DevTech mxthread](https://github.com/ADN-DevTech/3dsMax-Python-HowTos/blob/master/src/packages/mxthread/README.md) - [MaxScript Performance Tips - disableSceneRedraw](https://help.autodesk.com/cloudhelp/2017/ENU/MAXScript-Help/files/GUID-75BB21C9-2283-49BD-853C-78006717FBE2.htm) - [MaxScript Performance Tips - undo off](https://help.autodesk.com/cloudhelp/2017/ENU/MAXScript-Help/files/GUID-A731E672-9B9A-4D5B-A8A7-EA584AD12FE5.htm) </details> --- <!-- kiln:plan --> # Explode Geometry Performance Optimization Implementation Plan ## Overview Research confirmed that `pymxs.runtime` calls 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. Both `Python/explode_geometry.py` and `Bundle2/Contents/python/explode_geometry.py` are identical and both require the same changes. ## Current State Analysis ### Key Discoveries: - Scene redraws are NOT suppressed during the inner face loop — each `rt.mesh()`, `rt.addModifier()`, and `rt.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`) - The outer `with pymxs.undo(True, "Explode Geometry"):` exists but individual per-face calls still record internal undo data, adding overhead (`Python/explode_geometry.py:261`) - The MNMesh path uses `polyop.detachFaces` which 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 loop - `Bundle2/Contents/python/explode_geometry.py` is identical to `Python/explode_geometry.py` and needs the same changes ## Desired 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+Z` reverts 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 `elapsed` time printed to the MAXScript Listener. Compare to the pre-patch baseline on the same mesh. ## What We're NOT Doing - No `threading.Thread`, `concurrent.futures.ThreadPoolExecutor`, or `multiprocessing` for `pymxs` calls (confirmed impossible per Autodesk documentation) - No `pymxs.mxstoken()` usage (deprecated, non-functional) - No Qt worker threads that call back into `pymxs` (deadlock risk) - No changes to the UI layout or any feature set - No changes to `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. - [ ] Confirm `rt.disableSceneRedraw()` and `rt.enableSceneRedraw()` are accessible via `pymxs.runtime` (test in MAXScript Listener: `python.execute "import pymxs; pymxs.runtime.disableSceneRedraw()"`) - [ ] If direct pymxs access fails, use `rt.execute("disableSceneRedraw()")` and `rt.execute("enableSceneRedraw()")` as fallback - [ ] In `do_explode()` in `Python/explode_geometry.py`, add `rt.disableSceneRedraw()` immediately before the `with pymxs.undo(True, "Explode Geometry"):` block (before line 261) - [ ] Wrap the undo block in a `try/finally` that calls `rt.enableSceneRedraw()` then `rt.redrawViews()` in the `finally` clause - [ ] Remove the standalone `rt.redrawViews()` at line 296 since it is now inside the `finally` block - [ ] Apply the identical structural change to `Bundle2/Contents/python/explode_geometry.py` **Validation:** Run explode on a 200+ face mesh. Viewport must not flicker per-face. `rt.redrawViews()` fires once at completion. MAXScript Listener shows lower `elapsed` time vs pre-patch baseline. **Requirements from spec:** - All scene operations remain on the main thread - Viewport must be fully refreshed (redraws re-enabled + `rt.redrawViews()`) after explode completes **Files to Modify:** - `Python/explode_geometry.py` — `do_explode()` method (~line 261) - `Bundle2/Contents/python/explode_geometry.py` — identical change **Implementation Details:** ```python rt.disableSceneRedraw() try: with pymxs.undo(True, "Explode Geometry"): if self.trimesh_option.isChecked(): ... # existing TriMesh loop if self.mnmesh_option.isChecked(): ... # existing MNMesh loop finally: rt.enableSceneRedraw() rt.redrawViews() ``` --- ### 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. - [ ] In `convert_to_triangle_faces()` in `Python/explode_geometry.py` (lines 330-347), wrap the per-face block (`rt.mesh(...)` through `applySettings(...)`) in `with pymxs.undo(False):` - [ ] In `convert_to_mnmesh_faces()` in `Python/explode_geometry.py` (lines 360-372), wrap the per-face block (`rt.polyop.detachFaces(...)` through `applySettings(...)`) in `with pymxs.undo(False):` - [ ] Keep the outer `with pymxs.undo(True, "Explode Geometry"):` in `do_explode()` intact — it provides the single undo group entry - [ ] Apply the same changes to `Bundle2/Contents/python/explode_geometry.py` **Validation:** Explode a 50+ face mesh. Press `Ctrl+Z` once. 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:** - The whole explode must be reversible with a single undo - Nesting `with pymxs.undo(False):` inside `with 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) and `convert_to_mnmesh_faces()` (~lines 360-372) - `Bundle2/Contents/python/explode_geometry.py` — same changes **Implementation Details:** In `convert_to_triangle_faces`: ```python 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)) with pymxs.undo(False): new_node = rt.mesh(vertices=rt.Array(v1, v2, v3), faces=rt.Array(rt.Point3(1, 2, 3))) rt.update(new_node) new_node.wireColor = _random_wire_color() applySettings(new_node, addShell, shell_amount, addEditMesh, collapseNode, centerPivot) if on_progress: on_progress(face_idx, num_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. - [ ] In `do_explode()` in `Python/explode_geometry.py`, update the `_prog()` inner function (lines 257-259) to only call `QtWidgets.QApplication.processEvents()` when `cur % 20 == 0 or cur == tot` - [ ] Keep `self.progress_bar.setValue(...)` updating every call — it is cheap and ensures accurate display when `processEvents()` does fire - [ ] Keep the existing `QtWidgets.QApplication.processEvents()` at line 254 (after showing the progress panel) unchanged — that call is outside the hot path - [ ] Apply the same change to `Bundle2/Contents/python/explode_geometry.py` **Validation:** 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:** - Progress bar must remain visually responsive during long operations - Throttle interval of 20 faces is a starting point; adjust between 10-50 based on testing **Files to Modify:** - `Python/explode_geometry.py` — `_prog()` inner function inside `do_explode()` (~lines 257-259) - `Bundle2/Contents/python/explode_geometry.py` — same change **Implementation Details:** ```python def _prog(cur, tot): self.progress_bar.setValue(int(cur * 100 / tot) if tot else 0) if cur % 20 == 0 or cur == tot: QtWidgets.QApplication.processEvents() ``` --- ### TASK 4: Refactor MNMesh Path to Read-Then-Create Pattern [MEDIUM PRIORITY] **Status:** NOT STARTED **Milestone:** `convert_to_mnmesh_faces()` no longer uses `polyop.detachFaces`. All vertex data is read in Phase 1 before any node is created in Phase 2, removing the index-shifting sequential dependency. - [ ] Add a new helper function `_create_poly_node_from_positions(positions)` to `Python/explode_geometry.py` (after `_random_wire_color`). It must: create a new `PolyMeshObject` node via `rt.newObjectNode(rt.PolyMeshObject())`, call `rt.polyop.setNumVerts`, `rt.polyop.setVert` for each position, then `rt.polyop.createFace` with a 1-based index array - [ ] If `rt.newObjectNode` or `rt.PolyMeshObject` are not accessible in pymxs, use `rt.execute("newObjectNode (PolyMeshObject())")` and retrieve the node via `rt.objects[-1]` - [ ] Refactor `convert_to_mnmesh_faces()` in `Python/explode_geometry.py` (lines 351-373): Phase 1 iterates `range(1, num_faces + 1)` (forward order), calls `rt.polyop.getFaceVerts` and `rt.polyop.getVert` for each vertex, stores results as plain Python `(x, y, z)` tuples — retains no pymxs objects after this phase - [ ] Phase 2 iterates the plain Python list, calls `_create_poly_node_from_positions(positions)` per face, sets `wireColor`, calls `applySettings` - [ ] Remove the reverse iteration `range(num_faces, 0, -1)` from `convert_to_mnmesh_faces` — forward order is correct since Phase 1 does not mutate the source - [ ] Verify that `rt.delete(node)` (the `deleteOriginal` path in `do_explode()`) is called only after both phases complete, since Phase 1 reads from the source mesh - [ ] Apply the same changes to `Bundle2/Contents/python/explode_geometry.py` **Validation:** 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:** - Polygon topology (quads, n-gons) must be preserved — do not triangulate faces - Vertex positions must match the source mesh exactly - Source mesh must not be mutated during Phase 1 **Files to Modify:** - `Python/explode_geometry.py` — add `_create_poly_node_from_positions()` helper; refactor `convert_to_mnmesh_faces()` (~lines 351-373) - `Bundle2/Contents/python/explode_geometry.py` — same changes **Implementation Details:** Phase 1 (read, no mutation): ```python rt.convertToPoly(node) num_faces = rt.polyop.getNumFaces(node) face_data = [] for face_idx in range(1, num_faces + 1): verts = rt.polyop.getFaceVerts(node, face_idx) positions = [(rt.polyop.getVert(node, int(v)).x, rt.polyop.getVert(node, int(v)).y, rt.polyop.getVert(node, int(v)).z) for v in verts] face_data.append(positions) ``` Phase 2 (create from plain Python data): ```python for i, positions in enumerate(face_data, 1): with pymxs.undo(False): new_node = _create_poly_node_from_positions(positions) new_node.wireColor = _random_wire_color() applySettings(new_node, addShell, shell_amount, addEditMesh, collapseNode, centerPivot) if on_progress: on_progress(i, num_faces) ``` Helper function: ```python def _create_poly_node_from_positions(positions): n = len(positions) node = rt.newObjectNode(rt.PolyMeshObject()) rt.polyop.setNumVerts(node, n) for i, (x, y, z) in enumerate(positions, 1): rt.polyop.setVert(node, i, rt.Point3(x, y, z)) rt.polyop.createFace(node, rt.Array(*range(1, n + 1))) return node ``` > **Assumption:** `rt.newObjectNode` and `rt.PolyMeshObject` are available as pymxs runtime calls. If not, fall back to `rt.execute(...)` and `rt.objects[-1]`. --- ## Testing Strategy ### Unit Tests: - No standalone unit test framework exists in this project (3ds Max plugin context) - Correctness is verified by comparing geometry output against the pre-patch baseline ### Integration Tests: - Run TriMesh explode on a Box primitive (12 triangles) — verify exactly 12 TriMesh face nodes are created - Run MNMesh explode on a Plane primitive (quad faces) — verify N single-face Editable Poly nodes are created - Run MNMesh explode on an n-gon face — verify face topology is preserved (not triangulated) - Confirm single undo entry reverts entire operation ### Manual Testing Steps: 1. Open 3ds Max, load `Python/explode_geometry.py`, create a GeoSphere with 100+ faces 2. Record baseline elapsed time from the MAXScript Listener before patching 3. Apply Task 1 patch; repeat the same explode and compare elapsed time — viewport must not flicker 4. Apply Task 2 patch; press `Ctrl+Z` once after explode — verify full operation is undone in a single step 5. Apply Task 3 patch; run explode on a 200+ face mesh — verify progress bar advances in steps of ~20 faces 6. Apply Task 4 patch; run MNMesh explode on a quad plane — open modifier panel on a resulting node and verify vertex coordinates match the original face 7. Test the most expensive path end-to-end: Shell modifier enabled + Collapse Stack enabled on a 500+ face mesh — confirm elapsed time improvement and no crashes ## Performance Considerations - Tasks 1 + 2 combined are estimated at 2–5x speedup on large meshes based on research; viewport redraw suppression is the single largest contributor - Task 3 impact is proportional to mesh size; most noticeable on 500+ face objects - Task 4 restructures the MNMesh algorithm but does not reduce O(n) complexity; gains come from eliminating the `detachFaces` per-call overhead and removing the reverse-iteration constraint <!-- /kiln:plan -->
allankoech added the
kiln
research_ready
plan_ready
pr_ready
cleaned_up
labels 2026-10-14 09:52:32 +00:00
Author
Owner

@allankoechke commented on GitHub (Jun 24, 2026):

Lets work only with Python script for this tests

<!-- gh-comment-id:4788451963 --> @allankoechke commented on GitHub (Jun 24, 2026): Lets work only with Python script for this tests
Author
Owner

@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)
<!-- gh-comment-id:4788467053 --> @allankoechke commented on GitHub (Jun 24, 2026): <!-- kiln:response --> Applied changes to **research**: <details> <summary>Diff</summary> <pre lang="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**: &#34;3ds Max is not thread-safe. - You should not call any function from multiple threads concurrently. -&#34; ([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**: &#34;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.&#34; ([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&#39;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 &lt; nNumFaces; nfaceIndex++) { - // ... existing face loop ... - } -} finally { - ip.EnableSceneRedraw(); - ip.RedrawViews(0, RedrawFlags.Normal, null); -} +```python +with pymxs.undo(True, &#34;Explode Geometry&#34;): + 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, &#34;Explode Geometry&#34;): + 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 &lt; nNumFaces; i++) { - IFace face = mesh.GetFace(i); - faces[i].Vertices = new IPoint3[face.V.Count()]; - for (int v = 0; v &lt; 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&#39;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(&#34;disableSceneRedraw +()&#34;)` / 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) </pre> </details> <!-- /kiln:response -->
Author
Owner

@allankoechke commented on GitHub (Jul 21, 2026):

Implementation complete! PR ready for review: https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/pull/6

<!-- gh-comment-id:5037566614 --> @allankoechke commented on GitHub (Jul 21, 2026): <!-- kiln:log --> Implementation complete! PR ready for review: https://github.com/allankoechke/ADN-3dsMax-Explode-Geometry/pull/6 <!-- /kiln:log -->
allankoech added
pr_ready
and removed
pr_ready
labels 2026-10-21 17:01:36 +00:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: allankoech/ADN-3dsMax-Explode-Geometry#3
No description provided.