Skip to content

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

Blender add-on: ZBrush-style keys in Sculpt Mode (preference; S/U/O radial controls, B brush list, Space menu, Alt/Ctrl/Ctrl+Shift, X, D/Shift+D, Ctrl+D...), verified in Blender 4.2.23 and 5.2.3 with VDM EXR orientation checks

islandmed42450563ebee
diff --git a/addons/blender/build_addon.py b/addons/blender/build_addon.py
index 036c7daf..19f0d2b0 100644
--- a/addons/blender/build_addon.py
+++ b/addons/blender/build_addon.py
@@ -23,7 +23,7 @@ import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
SOURCE = os.path.join(HERE, "sculptforge_bridge")
LICENSE = os.path.join(HERE, "..", "..", "LICENSE")
-FILES = ["__init__.py", "exchange.py"]
+FILES = ["__init__.py", "exchange.py", "zbrush_keys.py"]
EPOCH = (2026, 1, 1, 0, 0, 0) # fixed timestamps: the same sources give the same zip
diff --git a/addons/blender/sculptforge_bridge/__init__.py b/addons/blender/sculptforge_bridge/__init__.py
index a573b279..05ab42f4 100644
--- a/addons/blender/sculptforge_bridge/__init__.py
+++ b/addons/blender/sculptforge_bridge/__init__.py
@@ -9,6 +9,8 @@
# What travels: positions (object space, with each object's matrix_world in the manifest), triangles
# and quads (n-gons as triangle fans), the active UV map, the active colour attribute (polypaint),
# the sculpt mask (.sculpt_mask) and face sets (.sculpt_face_set, SculptForge's polygroups).
+#
+# The preference "ZBrush-style keys in Sculpt Mode" adds ZBrush's keys to Blender's Sculpt Mode (zbrush_keys.py).
bl_info = { # legacy add-on install (Blender 4.2+ reads blender_manifest.toml instead)
"name": "SculptForge Bridge",
@@ -30,7 +32,7 @@ import bpy
import numpy as np
from bpy.props import BoolProperty, EnumProperty, StringProperty
-from . import exchange
+from . import exchange, zbrush_keys
APPLIED_KEY = "sculptforge_applied_modifiers"
MASK = ".sculpt_mask"
@@ -521,6 +523,13 @@ class SculptForgePreferences(bpy.types.AddonPreferences):
name="Receive automatically",
description="After a send, load what SculptForge sends back as soon as it arrives (checked once a second)",
default=True)
+ zbrush_keys: BoolProperty(
+ name="ZBrush-style keys in Sculpt Mode",
+ description="S / U / O for Draw Size / Z Intensity / Focal Shift, B for the brush list, Space for the quick "
+ "menu, Alt to dig in, Ctrl to mask, Ctrl+Shift to hide, D / Shift+D for SDiv... Turning it off "
+ "removes them again and Blender's own keys are back",
+ default=False,
+ update=lambda self, context: _apply_zbrush_keys(self))
def draw(self, context):
layout = self.layout
@@ -531,6 +540,17 @@ class SculptForgePreferences(bpy.types.AddonPreferences):
layout.label(text="Exchange folder: " + exchange_root(self))
layout.prop(self, "modifiers")
layout.prop(self, "auto_receive")
+ layout.prop(self, "zbrush_keys")
+ if self.zbrush_keys:
+ box = layout.box()
+ col = box.column(align=True)
+ for zkey, what, *_ in zbrush_keys.key_table():
+ if zkey:
+ col.label(text="%s: %s" % (zkey, what))
+ col.separator()
+ col.label(text="Not in Blender:", icon="INFO")
+ for zkey, why in zbrush_keys.MISSING:
+ col.label(text="%s: %s" % (zkey, why))
def _object_menu(self, context):
@@ -550,9 +570,25 @@ def _import_menu(self, context):
CLASSES = (SculptForgePreferences, SCULPTFORGE_OT_send, SCULPTFORGE_OT_receive, SCULPTFORGE_PT_panel)
+def _apply_zbrush_keys(p=None):
+ p = p or prefs()
+ if p is not None and p.zbrush_keys:
+ zbrush_keys.enable()
+ else:
+ zbrush_keys.disable()
+
+
+def _apply_zbrush_keys_later():
+ _apply_zbrush_keys() # (the preferences are loaded by the time Blender runs timers)
+ return None
+
+
def register():
for cls in CLASSES:
bpy.utils.register_class(cls)
+ zbrush_keys.register()
+ _apply_zbrush_keys()
+ bpy.app.timers.register(_apply_zbrush_keys_later, first_interval=0.1)
bpy.types.VIEW3D_MT_object.append(_object_menu)
bpy.types.TOPBAR_MT_file_export.append(_export_menu)
bpy.types.TOPBAR_MT_file_import.append(_import_menu)
@@ -569,5 +605,6 @@ def unregister():
bpy.types.TOPBAR_MT_file_import.remove(_import_menu)
bpy.types.TOPBAR_MT_file_export.remove(_export_menu)
bpy.types.VIEW3D_MT_object.remove(_object_menu)
+ zbrush_keys.unregister() # (removes the ZBrush keys)
for cls in reversed(CLASSES):
bpy.utils.unregister_class(cls)
diff --git a/addons/blender/sculptforge_bridge/zbrush_keys.py b/addons/blender/sculptforge_bridge/zbrush_keys.py
new file mode 100644
index 00000000..9e63cd94
--- /dev/null
+++ b/addons/blender/sculptforge_bridge/zbrush_keys.py
@@ -0,0 +1,276 @@
+# SculptForge bridge for Blender: ZBrush-style keys in Sculpt Mode
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# The add-on preference "ZBrush-style keys in Sculpt Mode" adds these to Blender's add-on keymap (they take
+# priority over Blender's own Sculpt keys while it is on, and are removed again when it is turned off or the
+# add-on is disabled). Only keys with a real Blender equivalent are mapped; MISSING lists the rest, for the
+# preferences and docs/guide/blender.md.
+#
+# Blender 4.2 picks sculpt brushes as tools (builtin_brush.*); 4.3 and newer as brush assets from the
+# Essentials library. The radial controls read the size and strength from the unified paint settings, which
+# moved from the tool settings into each paint mode in Blender 5.
+
+import bpy
+from bpy.props import IntProperty, StringProperty
+
+# (ZBrush name, ZBrush's B-letters, Blender 4.3+ Essentials brush, Blender 4.2 sculpt_tool, Blender 4.2 tool id)
+BRUSHES = [
+ ("Standard", "ST", "Draw", "DRAW", "builtin_brush.Draw"),
+ ("DamStandard", "DS", "Draw Sharp", "DRAW_SHARP", "builtin_brush.Draw Sharp"),
+ ("Clay", "CL", "Clay", "CLAY", "builtin_brush.Clay"),
+ ("ClayBuildup", "CB", "Clay Strips", "CLAY_STRIPS", "builtin_brush.Clay Strips"),
+ ("Inflate", "IN", "Inflate/Deflate", "INFLATE", "builtin_brush.Inflate"),
+ ("Layer", "LY", "Layer", "LAYER", "builtin_brush.Layer"),
+ ("Crease", "CR", "Crease Sharp", "CREASE", "builtin_brush.Crease"),
+ ("Smooth", "SM", "Smooth", "SMOOTH", "builtin_brush.Smooth"),
+ ("Flatten", "FL", "Flatten/Contrast", "FLATTEN", "builtin_brush.Flatten"),
+ ("TrimDynamic", "TD", "Trim", "SCRAPE", "builtin_brush.Scrape"),
+ ("Pinch", "PI", "Pinch/Magnify", "PINCH", "builtin_brush.Pinch"),
+ ("Move", "MV", "Grab", "GRAB", "builtin_brush.Grab"),
+ ("Move Elastic", "", "Elastic Grab", "ELASTIC_DEFORM", "builtin_brush.Elastic Deform"),
+ ("SnakeHook", "SH", "Snake Hook", "SNAKE_HOOK", "builtin_brush.Snake Hook"),
+ ("Nudge", "NU", "Nudge", "NUDGE", "builtin_brush.Nudge"),
+ ("MaskPen", "", "Mask", "MASK", "builtin_brush.Mask"),
+]
+
+ESSENTIALS = "brushes/essentials_brushes-mesh_sculpt.blend/Brush/"
+
+
+def brush_assets():
+ """Blender 4.3+ picks brushes as assets (bpy.ops.brush.asset_activate); 4.2 as tools."""
+ return bpy.app.version >= (4, 3, 0)
+
+# ZBrush keys Blender has nothing for (or that can't be bound the same way), shown in the preferences.
+MISSING = [
+ ("I", "RGB Intensity: Blender's sculpt brushes don't paint"),
+ ("Ctrl+drag on the model", "painting the mask with any brush held: Blender can't swap to the Mask brush "
+ "for one stroke, so Ctrl+drag draws a mask lasso instead (B M P picks the Mask brush)"),
+ ("Drag on the background", "rotating: a keymap can't tell the model from the background (use the middle "
+ "button, or Blender's Emulate 3 Button Mouse)"),
+ ("Ctrl+click the background", "invert or clear the mask: use Ctrl+I (invert) and Alt+M (clear)"),
+ ("Ctrl+Shift+click the background", "show everything: use Alt+H"),
+ ("B, then two letters", "Blender menus take one key at a time: B opens the brush list; type the letters "
+ "(or any part of the name) to filter it, Enter picks"),
+ ("Alt+click a SubTool", "Blender's objects aren't SubTools: Alt+Q switches the object being sculpted"),
+ ("Strokes (DragRect, Spray...)", "Blender's stroke methods live in each brush's Stroke panel"),
+]
+
+_items = [] # (keymap, keymap item) added by enable()
+
+
+def _unified_path():
+ """Where the unified size / strength live: each paint mode in Blender 5, the tool settings before."""
+ if "unified_paint_settings" in bpy.types.Paint.bl_rna.properties:
+ return "tool_settings.sculpt.unified_paint_settings"
+ return "tool_settings.unified_paint_settings"
+
+
+def radial_properties(prop, unified_toggle=""):
+ """wm.radial_control settings for the sculpt brush's `prop` (what Blender's own F / Shift+F use)."""
+ brush = "tool_settings.sculpt.brush"
+ props = {"data_path_primary": brush + "." + prop, "rotation_path": brush + ".texture_slot.angle",
+ "color_path": brush + ".cursor_color_add", "image_id": brush}
+ if unified_toggle:
+ unified = _unified_path()
+ props["data_path_secondary"] = unified + "." + prop
+ props["use_secondary"] = unified + "." + unified_toggle
+ return props
+
+
+def _brush_entry(name):
+ return next((b for b in BRUSHES if b[0] == name), None)
+
+
+class SCULPTFORGE_OT_zbrush_brush(bpy.types.Operator):
+ bl_idname = "sculptforge.zbrush_brush"
+ bl_label = "ZBrush Brush"
+ bl_description = "Sculpt with the Blender brush closest to this ZBrush brush"
+ bl_options = {"REGISTER"}
+
+ brush: StringProperty(name="Brush", description="ZBrush brush name")
+
+ def execute(self, context):
+ entry = _brush_entry(self.brush)
+ if entry is None:
+ self.report({"ERROR"}, "No ZBrush brush called %s" % self.brush)
+ return {"CANCELLED"}
+ name, _, asset, sculpt_tool, tool_id = entry
+ if brush_assets():
+ result = bpy.ops.brush.asset_activate(asset_library_type="ESSENTIALS",
+ relative_asset_identifier=ESSENTIALS + asset)
+ if "FINISHED" not in result:
+ self.report({"ERROR"}, "Blender's %s brush is missing" % asset)
+ return {"CANCELLED"}
+ else: # Blender 4.2: brushes are tools of the 3D View
+ done = False
+ if context.space_data is not None and context.space_data.type == "VIEW_3D":
+ done = "FINISHED" in bpy.ops.wm.tool_set_by_id(name=tool_id)
+ if not done: # (no 3D View, e.g. from a script) the brush itself
+ brush = next((b for b in bpy.data.brushes if b.use_paint_sculpt and b.sculpt_tool == sculpt_tool), None)
+ if brush is None or context.tool_settings.sculpt is None:
+ self.report({"ERROR"}, "Blender has no %s brush here" % asset)
+ return {"CANCELLED"}
+ context.tool_settings.sculpt.brush = brush
+ self.report({"INFO"}, "%s: Blender's %s" % (name, asset))
+ return {"FINISHED"}
+
+
+class SCULPTFORGE_OT_zbrush_sdiv(bpy.types.Operator):
+ bl_idname = "sculptforge.zbrush_sdiv"
+ bl_label = "ZBrush SDiv"
+ bl_description = "Sculpt one Multires level higher or lower (ZBrush D / Shift+D); never adds a level"
+ bl_options = {"REGISTER", "UNDO"}
+
+ step: IntProperty(name="Step", default=1, min=-1, max=1)
+
+ @classmethod
+ def poll(cls, context):
+ return context.active_object is not None and any(m.type == "MULTIRES" for m in context.active_object.modifiers)
+
+ def execute(self, context):
+ multires = next(m for m in context.active_object.modifiers if m.type == "MULTIRES")
+ level = max(0, min(multires.total_levels, multires.sculpt_levels + self.step))
+ multires.sculpt_levels = level
+ multires.levels = level # the viewport shows the level being sculpted, as ZBrush does
+ self.report({"INFO"}, "SDiv %d of %d" % (level, multires.total_levels))
+ return {"FINISHED"}
+
+
+class SCULPTFORGE_OT_zbrush_divide(bpy.types.Operator):
+ bl_idname = "sculptforge.zbrush_divide"
+ bl_label = "ZBrush Divide"
+ bl_description = "Add a subdivision level to the Multires modifier (adding one if needed) and sculpt on it (ZBrush Ctrl+D)"
+ bl_options = {"REGISTER", "UNDO"}
+
+ @classmethod
+ def poll(cls, context):
+ return context.active_object is not None and context.active_object.type == "MESH"
+
+ def execute(self, context):
+ obj = context.active_object
+ multires = next((m for m in obj.modifiers if m.type == "MULTIRES"), None)
+ if multires is None:
+ multires = obj.modifiers.new("Multires", "MULTIRES")
+ result = bpy.ops.object.multires_subdivide(modifier=multires.name, mode="CATMULL_CLARK")
+ if "FINISHED" not in result:
+ return {"CANCELLED"}
+ multires.sculpt_levels = multires.levels = multires.total_levels
+ self.report({"INFO"}, "SDiv %d of %d" % (multires.sculpt_levels, multires.total_levels))
+ return {"FINISHED"}
+
+
+class SCULPTFORGE_MT_zbrush_brushes(bpy.types.Menu):
+ bl_idname = "SCULPTFORGE_MT_zbrush_brushes"
+ bl_label = "ZBrush Brushes"
+ bl_options = {"SEARCH_ON_KEY_PRESS"} # typing filters, as ZBrush's B pop-up does
+
+ def draw(self, context):
+ layout = self.layout
+ for name, keys, asset, _, _ in BRUSHES:
+ label = "%s (B %s)" % (name, " ".join(keys)) if keys else name
+ layout.operator(SCULPTFORGE_OT_zbrush_brush.bl_idname, text=label).brush = name
+
+
+def key_table():
+ """(ZBrush key, what it does, Blender operator, key, ctrl, shift, alt, value, properties)."""
+ toggle = "wm.context_toggle"
+ lasso = "paint.mask_lasso_gesture"
+ return [
+ ("S", "Draw Size", "wm.radial_control", "S", False, False, False, "PRESS", radial_properties("size", "use_unified_size")),
+ ("U", "Z Intensity", "wm.radial_control", "U", False, False, False, "PRESS",
+ radial_properties("strength", "use_unified_strength")),
+ ("O", "Focal Shift (Blender: Hardness)", "wm.radial_control", "O", False, False, False, "PRESS",
+ radial_properties("hardness")),
+ ("Space", "the quick menu at the cursor (Blender's Sculpt context menu)", "wm.call_panel", "SPACE", False,
+ False, False, "PRESS", {"name": "VIEW3D_PT_sculpt_context_menu"}),
+ ("B", "the brush pop-up: type to narrow, Enter picks", "wm.call_menu", "B", False, False, False, "PRESS",
+ {"name": SCULPTFORGE_MT_zbrush_brushes.bl_idname}),
+ ("Alt+drag", "Zsub (the brush digs in)", "sculpt.brush_stroke", "LEFTMOUSE", False, False, True, "PRESS",
+ {"mode": "INVERT"}),
+ ("Ctrl+drag", "mask (a lasso)", lasso, "LEFTMOUSE", True, False, False, "PRESS", {"mode": "VALUE", "value": 1.0}),
+ ("Ctrl+Alt+drag", "unmask (a lasso)", lasso, "LEFTMOUSE", True, False, True, "PRESS", {"mode": "VALUE", "value": 0.0}),
+ ("Ctrl+Shift+drag", "show only what's inside", "paint.hide_show", "LEFTMOUSE", True, True, False, "PRESS",
+ {"action": "HIDE", "area": "OUTSIDE"}),
+ ("Ctrl+Shift+Alt+drag", "hide what's inside", "paint.hide_show", "LEFTMOUSE", True, True, True, "PRESS",
+ {"action": "HIDE", "area": "INSIDE"}), # (Blender spells this enum item "Inside": see _set)
+ ("X", "Symmetry X", toggle, "X", False, False, False, "PRESS", {"data_path": "object.data.use_mirror_x"}),
+ ("Shift+F", "PolyFrame (wireframe)", toggle, "F", False, True, False, "PRESS",
+ {"data_path": "space_data.overlay.show_wireframes"}),
+ ("F", "Frame the model", "view3d.view_all", "F", False, False, False, "PRESS", {}),
+ ("P", "Perspective on / off", "view3d.view_persportho", "P", False, False, False, "PRESS", {}),
+ ("L", "LazyMouse (Blender: Stabilize Stroke)", toggle, "L", False, False, False, "PRESS",
+ {"data_path": "tool_settings.sculpt.brush.use_smooth_stroke"}),
+ ("Ctrl+D", "Divide (adds a Multires level)", SCULPTFORGE_OT_zbrush_divide.bl_idname, "D", True, False, False,
+ "PRESS", {}),
+ ("D", "SDiv up", SCULPTFORGE_OT_zbrush_sdiv.bl_idname, "D", False, False, False, "PRESS", {"step": 1}),
+ ("Shift+D", "SDiv down", SCULPTFORGE_OT_zbrush_sdiv.bl_idname, "D", False, True, False, "PRESS", {"step": -1}),
+ ("Ctrl+W", "Group Visible (a face set)", "sculpt.face_sets_create", "W", True, False, False, "PRESS",
+ {"mode": "VISIBLE"}),
+ ("W / E / R", "Move / Scale / Rotate", "wm.tool_set_by_id", "W", False, False, False, "PRESS",
+ {"name": "builtin.move"}),
+ ("", "", "wm.tool_set_by_id", "E", False, False, False, "PRESS", {"name": "builtin.scale"}),
+ ("", "", "wm.tool_set_by_id", "R", False, False, False, "PRESS", {"name": "builtin.rotate"}),
+ ]
+
+
+def _set(properties, name, value):
+ """Sets an operator setting; enum items match regardless of case (paint.hide_show's area items are 'OUTSIDE'
+ and 'Inside')."""
+ prop = properties.bl_rna.properties.get(name)
+ if prop is not None and prop.type == "ENUM" and isinstance(value, str):
+ value = next((e.identifier for e in prop.enum_items if e.identifier.upper() == value.upper()), value)
+ setattr(properties, name, value)
+
+
+def enabled():
+ return bool(_items)
+
+
+skipped = [] # keys that could not be bound in this Blender (operator or setting missing), with why
+
+
+def enable():
+ """Adds the keys (once). Returns how many were added; 0 without an add-on keyconfig (Blender's -b mode has
+ one; some embedded builds don't)."""
+ if _items:
+ return len(_items)
+ kc = bpy.context.window_manager.keyconfigs.addon
+ if kc is None:
+ return 0
+ km = kc.keymaps.new(name="Sculpt", space_type="EMPTY")
+ skipped.clear()
+ for zkey, _, idname, key, ctrl, shift, alt, value, props in key_table():
+ kmi = km.keymap_items.new(idname, key, value, ctrl=ctrl, shift=shift, alt=alt)
+ try:
+ for name, v in props.items():
+ _set(kmi.properties, name, v)
+ except (TypeError, AttributeError, ValueError) as e: # one key never stops the others
+ km.keymap_items.remove(kmi)
+ skipped.append((zkey or key, str(e)))
+ continue
+ _items.append((km, kmi))
+ return len(_items)
+
+
+def disable():
+ while _items:
+ km, kmi = _items.pop()
+ try:
+ km.keymap_items.remove(kmi)
+ except (ReferenceError, RuntimeError): # the keyconfig went first (Blender quitting)
+ pass
+
+
+CLASSES = (SCULPTFORGE_OT_zbrush_brush, SCULPTFORGE_OT_zbrush_sdiv, SCULPTFORGE_OT_zbrush_divide,
+ SCULPTFORGE_MT_zbrush_brushes)
+
+
+def register():
+ for cls in CLASSES:
+ bpy.utils.register_class(cls)
+
+
+def unregister():
+ disable()
+ for cls in reversed(CLASSES):
+ bpy.utils.unregister_class(cls)
diff --git a/tests/blender/test_in_blender.py b/tests/blender/test_in_blender.py
index 863d89bd..0b09d988 100644
--- a/tests/blender/test_in_blender.py
+++ b/tests/blender/test_in_blender.py
@@ -7,7 +7,10 @@
# Sends a small scene to SculptForge (sculptforge-cli stands in for the app: blender_receive, then
# blender_send), receives it back and checks that the objects are unchanged: positions, n-gons,
# transforms, materials, modifiers, UVs, colours, mask and face sets. Then a topology change (subdivide)
-# and a new SubTool come back as a rebuilt mesh and a new object. CMake runs it when `blender` is found.
+# and a new SubTool come back as a rebuilt mesh and a new object. The ZBrush-style keys preference adds and
+# removes its keymap items, each bound to a real operator with valid settings. Vector displacement maps that
+# SculptForge exports read in Blender with the same orientation, and Blender's EXRs load in SculptForge.
+# CMake runs it when `blender` is found.
import os
import subprocess
import sys
@@ -102,6 +105,126 @@ def build_scene():
return ["Box", "Disc ü", "Suzanne"]
+def addon_sculpt_items():
+ km = bpy.context.window_manager.keyconfigs.addon.keymaps.get("Sculpt")
+ return list(km.keymap_items) if km else []
+
+
+def test_zbrush_keys():
+ keys = bridge.zbrush_keys
+ p = bridge.prefs()
+ before = len(addon_sculpt_items())
+ check(not p.zbrush_keys and not keys.enabled(), "ZBrush keys: off by default")
+ p.zbrush_keys = True
+ table = keys.key_table()
+ items = addon_sculpt_items()
+ check(len(items) == before + len(table), "ZBrush keys: one keymap item per key (%d)" % len(table))
+ for zkey, what, idname, key, ctrl, shift, alt, value, props in table:
+ kmi = next((i for i in items if i.idname == idname and i.type == key and i.ctrl == ctrl and i.shift == shift
+ and i.alt == alt), None)
+ check(kmi is not None and kmi.active, "ZBrush keys: %s -> %s" % (zkey or key, idname))
+ mod, fn = idname.split(".")
+ try: # (hasattr is always true on bpy.ops: the operator is looked up when called)
+ getattr(getattr(bpy.ops, mod), fn).get_rna_type()
+ exists = True
+ except (AttributeError, KeyError, RuntimeError):
+ exists = False
+ check(exists, "ZBrush keys: operator %s exists" % idname)
+ for name, v in props.items():
+ got = getattr(kmi.properties, name) if kmi else None
+ same = got == v or (isinstance(v, str) and isinstance(got, str) and got.upper() == v.upper()) or \
+ (isinstance(v, float) and abs(got - v) < 1e-6)
+ check(same, "ZBrush keys: %s %s = %r" % (idname, name, v))
+ check(not keys.skipped, "ZBrush keys: none skipped %s" % keys.skipped)
+ # Every data path the keys use resolves in Sculpt Mode (they changed between Blender 4.2 and 5).
+ for obj in list(bpy.data.objects):
+ bpy.data.objects.remove(obj)
+ bpy.ops.mesh.primitive_uv_sphere_add(segments=16, ring_count=8)
+ bpy.ops.object.mode_set(mode="SCULPT")
+ for zkey, what, idname, key, ctrl, shift, alt, value, props in table:
+ for name, path in props.items():
+ if name in ("data_path_primary", "data_path_secondary", "use_secondary", "rotation_path", "color_path",
+ "image_id") or (idname == "wm.context_toggle" and name == "data_path" and
+ not path.startswith("space_data")):
+ try:
+ bpy.context.path_resolve(path)
+ ok = True
+ except ValueError:
+ ok = False
+ check(ok, "ZBrush keys: %s resolves (%s)" % (path, zkey or key))
+ check(bpy.types.Menu.bl_rna_get_subclass_py(keys.SCULPTFORGE_MT_zbrush_brushes.bl_idname) is not None,
+ "ZBrush keys: the brush menu is registered")
+ # The brush menu's picks.
+ for name, _, asset, sculpt_tool, _ in keys.BRUSHES:
+ r = bpy.ops.sculptforge.zbrush_brush(brush=name)
+ brush = bpy.context.tool_settings.sculpt.brush
+ got = brush.name if keys.brush_assets() else brush.sculpt_tool
+ check(r == {"FINISHED"} and got == (asset if keys.brush_assets() else sculpt_tool),
+ "ZBrush brush %s -> Blender %s (%s)" % (name, asset, got))
+ # Ctrl+D divides (a Multires level); D / Shift+D step between levels without adding any.
+ check(bpy.ops.sculptforge.zbrush_divide() == {"FINISHED"}, "Ctrl+D: Divide")
+ bpy.ops.sculptforge.zbrush_divide()
+ multires = next((m for m in bpy.context.active_object.modifiers if m.type == "MULTIRES"), None)
+ check(multires is not None and multires.total_levels == 2, "Ctrl+D in Sculpt Mode adds Multires levels")
+ if multires is not None:
+ bpy.ops.sculptforge.zbrush_sdiv(step=-1)
+ bpy.ops.sculptforge.zbrush_sdiv(step=-1)
+ bpy.ops.sculptforge.zbrush_sdiv(step=-1)
+ check(multires.sculpt_levels == 0 and multires.total_levels == 2, "Shift+D steps down to SDiv 0")
+ bpy.ops.sculptforge.zbrush_sdiv(step=1)
+ bpy.ops.sculptforge.zbrush_sdiv(step=1)
+ bpy.ops.sculptforge.zbrush_sdiv(step=1)
+ check(multires.sculpt_levels == 2 and multires.total_levels == 2, "D steps up to the top, adds nothing")
+ bpy.ops.object.mode_set(mode="OBJECT")
+ p.zbrush_keys = False
+ check(len(addon_sculpt_items()) == before and not keys.enabled(), "ZBrush keys: turning it off removes them")
+ p.zbrush_keys = True # (the add-on's unregister removes them too: checked after disabling it)
+
+
+def read_sfvdm(path):
+ with open(path, "rb") as f:
+ b = f.read()
+ w, h, n = np.frombuffer(b[8:20], dtype="<u4")
+ return np.frombuffer(b[20 + n:], dtype="<f4").reshape(h, w, 3)
+
+
+def test_vdm_exr():
+ # SculptForge's Horn as an EXR and as .sfvdm (row 0 = the top of the map, +Y).
+ exr = os.path.join(ROOT, "horn.exr")
+ raw = os.path.join(ROOT, "horn.sfvdm")
+ sculptforge(['vdm_export name=horn path="%s"' % exr, 'vdm_export name=horn path="%s"' % raw])
+ ours = read_sfvdm(raw)
+ img = bpy.data.images.load(exr)
+ img.colorspace_settings.is_data = True
+ w, h = img.size
+ px = np.array(img.pixels[:], dtype=np.float32).reshape(h, w, img.channels)[::-1, :, :3] # Blender: bottom row first
+ check((w, h) == (256, 256), "VDM EXR: Blender reads 256 x 256")
+ check(np.abs(px - ours).max() < 1e-6, "VDM EXR: Blender sees the same vectors, the same way up (max diff %g)"
+ % np.abs(px - ours).max())
+ # The horn leans toward the top of the image: +Y in Blender's texture space too.
+ check(px[128, 128, 1] > 0.3 and px[128, 128, 2] > 0.6, "VDM EXR: the horn's tip points up the map and out")
+ # Blender's EXRs (32-bit ZIP, as its VDM Brush Baker writes, and 16-bit) load in SculptForge unchanged.
+ rng = np.random.default_rng(3)
+ vec = rng.uniform(-0.5, 0.5, (32, 48, 3)).astype(np.float32) # rows from the top
+ for depth, codec, tol in (("32", "ZIP", 1e-6), ("16", "ZIP", 2e-3), ("32", "PIZ", 1e-6)):
+ made = bpy.data.images.new("vdm%s%s" % (depth, codec), 48, 32, alpha=True, float_buffer=True, is_data=True)
+ rgba = np.ones((32, 48, 4), dtype=np.float32)
+ rgba[:, :, :3] = vec
+ made.pixels.foreach_set(rgba[::-1].ravel())
+ path = os.path.join(ROOT, "blender_%s_%s.exr" % (depth, codec))
+ scene = bpy.context.scene
+ settings = scene.render.image_settings
+ settings.file_format = "OPEN_EXR"
+ settings.color_depth = depth
+ settings.exr_codec = codec
+ made.save_render(path, scene=scene)
+ back = os.path.join(ROOT, "blender_%s_%s.sfvdm" % (depth, codec))
+ sculptforge(['vdm_set path="%s" save=false' % path, 'vdm_export path="%s"' % back])
+ got = read_sfvdm(back) if os.path.exists(back) else np.zeros_like(vec)
+ check(got.shape == vec.shape and np.abs(got - vec).max() < tol,
+ "VDM EXR: Blender's %s-bit %s EXR loads in SculptForge (max diff %g)" % (depth, codec, np.abs(got - vec).max()))
+
+
def main():
check(bridge.prefs() is not None, "add-on enabled with its preferences")
# No real SculptForge here: never start one.
@@ -169,7 +292,11 @@ def main():
bpy.ops.sculptforge.receive()
check(not box.modifiers["Bevel"].show_viewport, "the applied modifier is turned off")
+ test_zbrush_keys()
+ test_vdm_exr()
+
addon_utils.disable("sculptforge_bridge")
+ check(not bridge.zbrush_keys.enabled(), "disabling the add-on removes the ZBrush keys")
print("%d failure(s)" % len(failures))
sys.exit(1 if failures else 0)
diff --git a/tests/test_vdm.cpp b/tests/test_vdm.cpp
index 26670b86..2c4cc77d 100644
--- a/tests/test_vdm.cpp
+++ b/tests/test_vdm.cpp
@@ -388,3 +388,30 @@ TEST(vdm_library_commands) {
{"radius", 0.5}}));
CHECK(s.mesh.positions != before);
}
+
+// The VDM plane keeps its UVs through Divide (finer detail to sculpt), and a stamp at the highest subdivision
+// level survives stepping down and back up.
+TEST(vdm_with_subdivision_levels) {
+ Document plane = makeDoc(makeVdmPlane(32));
+ CHECK(run(plane, "subdiv_divide", {{"smooth", false}}));
+ CHECK(run(plane, "subdiv_divide", {{"smooth", false}}));
+ CHECK(plane.mesh.vertexCount() == 129u * 129u && plane.mesh.hasUvs());
+ for (glm::vec3& p : plane.mesh.positions) p += sculptedOffset(p);
+ VectorDisplacement captured;
+ std::string err;
+ CHECK(captureVdm(plane.mesh, 128, captured, err));
+ const glm::vec3 o = sculptedOffset(glm::vec3(0.1f, 0.0f, -0.2f));
+ CHECK(glm::length(captured.sample(0.1f, 0.2f) - glm::vec3(o.x, -o.z, o.y)) < 0.01f);
+
+ Document d = makeDoc(makeIcosphere(3, 1.0f));
+ CHECK(run(d, "subdiv_divide"));
+ CHECK(run(d, "subdiv_divide"));
+ d.brushVdm = builtinVdm("horn");
+ CHECK(run(d, "vdm_stamp", {{"point", std::string("0,0,0")}, {"view", std::string("0,0,-1")}, {"radius", 0.4}}));
+ const auto stamped = d.mesh.positions;
+ CHECK(run(d, "subdiv_level", {{"level", 1.0}}));
+ CHECK(run(d, "subdiv_level", {{"level", 3.0}}));
+ float worst = 0.0f;
+ for (size_t v = 0; v < stamped.size(); ++v) worst = std::max(worst, glm::distance(stamped[v], d.mesh.positions[v]));
+ CHECK(worst < 1e-4f);
+}