Skip to content

Transform your 3D texturing workflow with the power of generative AI, directly within Blender!

use new comfyui-trellis2 node version and implement multi-color 3d print suite, sliced viewport previews, and retopology/ui refinements

sakalond61592efe4c2e
diff --git a/.gitignore b/.gitignore
index 804749a..87d9f2c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -175,3 +175,17 @@ cython_debug/
stablegen/feather.oso
stablegen.zip
ref/
+
+# StableGen specific ignores
+AGENTS.md
+scratch/
+stablegen/scratch/
+script.py
+sg_wheels/
+stablegen/.claude/
+stablegen/mesh_gen/test_planar.py
+stablegen/texturing/debug_solver_expanded.py
+stablegen/texturing/debug_solver_penalty.py
+t.3mf
+test_output.3mf
+
diff --git a/installer.py b/installer.py
index c45c4a1..1653ee1 100644
--- a/installer.py
+++ b/installer.py
@@ -551,12 +551,11 @@ DEPENDENCIES: Dict[str, Dict[str, Any]] = {
# --- TRELLIS.2 ---
"cn_trellis2": {
"id": "cn_trellis2", "type": "node", "name": "ComfyUI TRELLIS.2",
- "git_url": "https://github.com/sakalond/ComfyUI-TRELLIS2.git",
- "commit": "6b0b2148f45bbafa0b86bfd25c63602b63a7aae0",
+ "git_url": "https://github.com/PozzettiAndrea/ComfyUI-TRELLIS2.git",
"target_dir_relative": "custom_nodes",
"repo_name": "ComfyUI-TRELLIS2",
"license": "MIT (Note: textured pipeline uses NVIDIA non-commercial libs)", "packages": ["trellis2"],
- "pip_packages": ["comfy-env==0.2.0", "numpy<2.0.0"],
+ "pip_packages": ["numpy<2.0.0"],
"clean_envs": True,
"run_install_script": True,
"post_clone_patches": [
@@ -811,11 +810,87 @@ def install_pip_packages(pip_packages: List[str], comfyui_path: Path, force_rein
def _apply_all_comfy_env_patches(comfyui_path: Path):
- """Apply all comfy-env patches (platform tag, wheel fallback, site isolation, dist-info)."""
+ """Apply all comfy-env patches (platform tag, wheel fallback, site isolation, dist-info, validator)."""
_patch_comfy_env_platform_tag(comfyui_path)
_patch_comfy_env_wheel_fallback(comfyui_path)
_patch_comfy_env_user_site_isolation(comfyui_path)
_patch_comfy_env_distinfo_normalize(comfyui_path)
+ _patch_comfy_env_validator(comfyui_path)
+
+
+def _patch_comfy_env_validator(comfyui_path: Path):
+ """Patch comfy-env's _validate_node_config to strip torch/torchvision instead of crashing."""
+ python_exe = find_comfyui_python(comfyui_path)
+ result = subprocess.run(
+ [python_exe, "-c",
+ "import importlib.util as u, os; s=u.find_spec('comfy_env'); print(os.path.join(os.path.dirname(s.origin), 'packages', 'toml_generator.py') if s and s.origin else '')"],
+ capture_output=True, text=True,
+ )
+ if result.returncode != 0:
+ print(" WARNING: Could not locate comfy_env toml_generator.py, skipping validator patch")
+ return
+
+ toml_gen_path = Path(result.stdout.strip().splitlines()[-1])
+ if not toml_gen_path.is_file():
+ print(f" WARNING: {toml_gen_path} not found, skipping validator patch")
+ return
+
+ content = toml_gen_path.read_text(encoding="utf-8")
+ marker = "# StableGen patch: bypass toml validation crash by stripping torch/torchvision"
+ if marker in content:
+ print(" comfy-env validator patch already applied")
+ return
+
+ old = (
+ "def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"
+ " \"\"\"Reject node configs that try to redefine the workspace torch pin.\"\"\"\n"
+ " bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"
+ " if bad:\n"
+ " raise ValueError(\n"
+ " f\"[{name}] comfy-env.toml has {bad} under [cuda] packages. \"\n"
+ " \"Plain torch/torchvision/torchaudio are pinned workspace-wide \"\n"
+ " \"(replicated into every feature so the rattler cache dedupes). \"\n"
+ " \"Remove them from [cuda] packages -- keep only CUDA-only wheels there \"\n"
+ " \"(cumesh, flash-attn, cc_torch, nvdiffrast, etc.).\"\n"
+ " )"
+ )
+
+ if old not in content:
+ old_alt = (
+ "def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"
+ " \"\"\"Reject node configs that try to redefine the workspace torch pin.\"\"\"\n"
+ " bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"
+ " if bad:\n"
+ " raise ValueError(\n"
+ " f\"[{name}] comfy-env.toml has {bad} under [cuda] packages. \"\n"
+ " \"Plain torch/torchvision/torchaudio are pinned workspace-wide \"\n"
+ " \"(replicated into every feature so the rattler cache dedupes). \"\n"
+ " \"Remove them from [cuda] packages -- keep only CUDA-only wheels there \"\n"
+ " \"(cumesh, flash-attn, cc_torch, nvdiffrast, etc.).\"\n"
+ " )\n"
+ )
+ if old_alt in content:
+ old = old_alt
+ else:
+ print(" WARNING: Could not find validator anchor in toml_generator.py (already modified?)")
+ return
+
+ new = (
+ "def _validate_node_config(name: str, cfg: ComfyEnvConfig) -> None:\n"
+ " " + marker + "\n"
+ " bad = [p for p in cfg.cuda_packages if p in _TORCH_PKGS]\n"
+ " if bad:\n"
+ " for p in bad:\n"
+ " try:\n"
+ " cfg.cuda_packages.remove(p)\n"
+ " except ValueError:\n"
+ " pass\n"
+ " print(f'[comfy-env] [{name}] stripped plain torch/torchvision from [cuda] packages list', file=sys.stderr)\n"
+ )
+
+ content = content.replace(old, new)
+ toml_gen_path.write_text(content, encoding="utf-8")
+ print(" Patched comfy-env _validate_node_config() to bypass invalid torch/torchvision declarations")
def _patch_comfy_env_platform_tag(comfyui_path: Path):
@@ -1157,10 +1232,10 @@ def run_node_install_script(item_details: Dict[str, Any], comfyui_path: Path):
# the widest wheel coverage for flex_gemm / nvdiffrast.
#
# The first attempt's requirements.txt installs downgraded
- # comfy-env to 0.1.92 on disk (patches wiped). Restore 0.2.0
+ # comfy-env on disk (patches wiped). Restore comfy-env
# with patches before retrying so the new subprocess sees them.
- print(" Install failed. Restoring comfy-env 0.2.0 + patches for retry...")
- install_pip_packages(["comfy-env==0.2.0"], comfyui_path, force_reinstall=True)
+ print(" Install failed. Restoring comfy-env + patches for retry...")
+ install_pip_packages(["comfy-env"], comfyui_path, force_reinstall=True)
_apply_all_comfy_env_patches(comfyui_path)
print(" Retrying with CUDA 12.4 fallback...")
@@ -1673,11 +1748,11 @@ def main():
run_node_install_script(item_details, comfyui_base_path)
# Fix flex_gemm/triton version mismatch in comfy-env isolated envs
_patch_flex_gemm_autotuner(target_full_path)
- # Force comfy-env back to 0.2.0 and re-apply patches AFTER install.py,
+ # Force comfy-env (latest) and re-apply patches AFTER install.py,
# since the node's requirements.txt may pin an older version
if item_details.get("pip_packages") and any("comfy-env" in p for p in item_details["pip_packages"]):
- print(" Re-installing comfy-env==0.2.0 (overriding node requirements.txt)...")
- install_pip_packages(["comfy-env==0.2.0"], comfyui_base_path, force_reinstall=True)
+ print(" Re-installing comfy-env (overriding node requirements.txt)...")
+ install_pip_packages(["comfy-env"], comfyui_base_path, force_reinstall=True)
_apply_all_comfy_env_patches(comfyui_base_path)
elif item_details["type"] == "model":
target_full_path = comfyui_base_path / item_details["target_path_relative"] / item_details["filename"]
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index 7dd9ff1..8e5f954 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -12,7 +12,7 @@ from .ui.presets import (
ApplyPreset, SavePreset, DeletePreset,
ResetQwenPrompt, SwitchToMeshGeneration,
)
-from .ui.panel import StableGenPanel
+from .ui.panel import StableGenPanel, StableGenPrintPanel
from .ui.queue import (
SG_UL_SceneQueueList, SceneQueueAdd, SceneQueueRemove, SceneQueueClear,
SceneQueueMoveUp, SceneQueueMoveDown, SceneQueueOpenResult,
@@ -23,6 +23,12 @@ from .texturing.rendering import (
)
from .texturing.orbit_export import ExportOrbitGIF
from .texturing.game_export import ExportForGameEngine
+from .texturing.print_export import (
+ StableGenPaletteColor, StableGenAddPaletteColor, StableGenRemovePaletteColor,
+ StableGenPreviewQuantization, StableGenClearQuantizationPreview,
+ StableGenPreviewSliced, StableGenPreviewSlicedCancel,
+ ExportSTL, Export3MF, Export3MFCancel,
+)
from .cameras import (
AddCameras, ApplyAutoAspect, CloneCamera, MirrorCamera, ToggleCameraLabels,
CollectCameraPrompts,
@@ -34,7 +40,7 @@ from .utils import AddHDRI, ApplyModifiers, CurvesToMesh
from .texturing.generator import (
ComfyUIGenerate, Reproject, Regenerate, MirrorReproject,
)
-from .mesh_gen.trellis2 import Trellis2Generate
+from .mesh_gen.trellis2 import Trellis2Generate, StableGenLocalPostProcess
from .mesh_gen.batch import (
TRELLIS2_OT_BatchSelectFolder, TRELLIS2_OT_BatchGenerate,
TRELLIS2_OT_BatchCancel, TRELLIS2_OT_BatchClear,
@@ -61,7 +67,7 @@ bl_info = {
"name": "StableGen",
"category": "Object",
"author": "Ondrej Sakala",
- "version": (0, 3, 0),
+ "version": (0, 3, 1),
'blender': (4, 2, 0)
}
@@ -78,6 +84,7 @@ classes = [
ControlNetUnit,
LoRAUnit,
SceneQueueItem,
+ StableGenPaletteColor,
# Preferences
STABLEGEN_UL_ControlNetMappingList,
RefreshControlNetMappings,
@@ -96,6 +103,7 @@ classes = [
Regenerate,
MirrorReproject,
Trellis2Generate,
+ StableGenLocalPostProcess,
TRELLIS2_OT_BatchSelectFolder,
TRELLIS2_OT_BatchGenerate,
TRELLIS2_OT_BatchCancel,
@@ -110,6 +118,15 @@ classes = [
SwitchMaterial,
ExportOrbitGIF,
ExportForGameEngine,
+ StableGenAddPaletteColor,
+ StableGenRemovePaletteColor,
+ StableGenPreviewQuantization,
+ StableGenClearQuantizationPreview,
+ StableGenPreviewSliced,
+ StableGenPreviewSlicedCancel,
+ ExportSTL,
+ Export3MF,
+ Export3MFCancel,
CollectCameraPrompts,
SG_UL_CameraOrderList,
SyncCameraOrder,
@@ -139,6 +156,7 @@ classes = [
SceneQueueProcess,
# Main panel (must be last – it uses all the above)
StableGenPanel,
+ StableGenPrintPanel,
]
# Append debug classes (defined in debug_tools.py)
classes.extend(_debug_classes)
diff --git a/stablegen/blender_manifest.toml b/stablegen/blender_manifest.toml
index 6d80c93..e2e2c0c 100644
--- a/stablegen/blender_manifest.toml
+++ b/stablegen/blender_manifest.toml
@@ -1,6 +1,6 @@
schema_version = "1.0.0"
id = "stablegen"
-version = "0.3.0"
+version = "0.3.1"
name = "StableGen"
tagline = "AI-Powered 3D Asset Generation & Texturing"
maintainer = "Ondrej Sakala <[email protected]>"
@@ -19,6 +19,7 @@ wheels = [
"./wheels/websocket_client-1.8.0-py3-none-any.whl",
"./wheels/websockets-15.0.1-py3-none-any.whl",
"./wheels/imageio-2.37.0-py3-none-any.whl",
+ "./wheels/trimesh-4.12.2-py3-none-any.whl",
# Windows specific
@@ -26,6 +27,7 @@ wheels = [
"./wheels/opencv_python_headless-4.11.0.86-cp37-abi3-win_amd64.whl",
"./wheels/pillow-11.2.1-cp311-cp311-win_amd64.whl",
"./wheels/pillow-11.2.1-cp313-cp313-win_amd64.whl",
+ "./wheels/fast_simplification-0.1.13-cp311-abi3-win_amd64.whl",
# Linux specific
@@ -33,13 +35,15 @@ wheels = [
"./wheels/opencv_python_headless-4.11.0.86-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
"./wheels/pillow-11.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
"./wheels/pillow-11.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
+ "./wheels/fast_simplification-0.1.12-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
# macOS Apple Silicon
"./wheels/imageio_ffmpeg-0.6.0-py3-none-macosx_11_0_arm64.whl",
"./wheels/opencv_python_headless-4.11.0.86-cp37-abi3-macosx_13_0_arm64.whl",
"./wheels/pillow-11.2.1-cp311-cp311-macosx_11_0_arm64.whl",
- "./wheels/pillow-11.2.1-cp313-cp313-macosx_11_0_arm64.whl"
+ "./wheels/pillow-11.2.1-cp313-cp313-macosx_11_0_arm64.whl",
+ "./wheels/fast_simplification-0.1.13-cp311-abi3-macosx_11_0_arm64.whl"
]
[permissions]
diff --git a/stablegen/core/callbacks.py b/stablegen/core/callbacks.py
index aea7de9..a6004a3 100644
--- a/stablegen/core/callbacks.py
+++ b/stablegen/core/callbacks.py
@@ -164,3 +164,149 @@ def update_combined(self, context):
load_handler(None)
return None
+
+
+def update_print_preset(self, context):
+ from . import state as _state
+ if _state._updating_print_preset:
+ return
+
+ scene = context.scene
+ preset = scene.stablegen_print_preset
+ if preset == 'CUSTOM':
+ return
+
+ _state._updating_print_preset = True
+ try:
+ scene.stablegen_print_palette.clear()
+
+ cyan = (0.0, 1.0, 1.0)
+ magenta = (1.0, 0.0, 1.0)
+ yellow = (1.0, 1.0, 0.0)
+ white = (1.0, 1.0, 1.0)
+ black = (0.0, 0.0, 0.0)
+
+ if preset == 'CMYW_DITHERED':
+ scene.stablegen_print_dithered = True
+ colors = [("Cyan", cyan), ("Magenta", magenta), ("Yellow", yellow), ("White", white)]
+ elif preset == 'CMYK_DITHERED':
+ scene.stablegen_print_dithered = True
+ colors = [("Cyan", cyan), ("Magenta", magenta), ("Yellow", yellow), ("Black", black)]
+ elif preset in ('CMYW_MIXES_SOLID', 'CMYK_MIXES_SOLID'):
+ scene.stablegen_print_dithered = False
+ fourth_color = white if preset == 'CMYW_MIXES_SOLID' else black
+ fourth_name = "White" if preset == 'CMYW_MIXES_SOLID' else "Black"
+
+ base_colors = [
+ ("Cyan", cyan),
+ ("Magenta", magenta),
+ ("Yellow", yellow),
+ (fourth_name, fourth_color)
+ ]
+
+ colors = list(base_colors)
+ n_base = len(base_colors)
+ for idx1 in range(n_base):
+ for idx2 in range(idx1 + 1, n_base):
+ name1, col1 = base_colors[idx1]
+ name2, col2 = base_colors[idx2]
+
+ def mix(c1, c2, w1, w2):
+ tot = w1 + w2
+ return (
+ (c1[0]*w1 + c2[0]*w2) / tot,
+ (c1[1]*w1 + c2[1]*w2) / tot,
+ (c1[2]*w1 + c2[2]*w2) / tot
+ )
+
+ colors.append((f"{name1}:{name2} 1:1", mix(col1, col2, 1.0, 1.0)))
+ colors.append((f"{name1}:{name2} 2:1", mix(col1, col2, 2.0, 1.0)))
+ colors.append((f"{name1}:{name2} 1:2", mix(col1, col2, 1.0, 2.0)))
+
+ for name, col in colors:
+ item = scene.stablegen_print_palette.add()
+ item.name = name
+ item.color = col
+
+ finally:
+ _state._updating_print_preset = False
+
+
+def check_print_preset_match(scene):
+ from . import state as _state
+ if _state._updating_print_preset:
+ return
+
+ preset = scene.stablegen_print_preset
+ if preset == 'CUSTOM':
+ return
+
+ cyan = (0.0, 1.0, 1.0)
+ magenta = (1.0, 0.0, 1.0)
+ yellow = (1.0, 1.0, 0.0)
+ white = (1.0, 1.0, 1.0)
+ black = (0.0, 0.0, 0.0)
+
+ import math
+ def is_close(c1, c2):
+ return all(math.isclose(x, y, abs_tol=1e-4) for x, y in zip(c1, c2))
+
+ palette = scene.stablegen_print_palette
+
+ if preset == 'CMYW_DITHERED':
+ if not scene.stablegen_print_dithered or len(palette) != 4:
+ scene.stablegen_print_preset = 'CUSTOM'
+ return
+ expected = [cyan, magenta, yellow, white]
+ for item, exp in zip(palette, expected):
+ if not is_close(item.color, exp):
+ scene.stablegen_print_preset = 'CUSTOM'
+ return
+
+ elif preset == 'CMYK_DITHERED':
+ if not scene.stablegen_print_dithered or len(palette) != 4:
+ scene.stablegen_print_preset = 'CUSTOM'
+ return
+ expected = [cyan, magenta, yellow, black]
+ for item, exp in zip(palette, expected):
+ if not is_close(item.color, exp):
+ scene.stablegen_print_preset = 'CUSTOM'
+ return
+
+ elif preset in ('CMYW_MIXES_SOLID', 'CMYK_MIXES_SOLID'):
+ if scene.stablegen_print_dithered or len(palette) != 22:
+ scene.stablegen_print_preset = 'CUSTOM'
+ return
+ fourth_color = white if preset == 'CMYW_MIXES_SOLID' else black
+ base_colors = [cyan, magenta, yellow, fourth_color]
+
+ expected = list(base_colors)
+ n_base = len(base_colors)
+ for idx1 in range(n_base):
+ for idx2 in range(idx1 + 1, n_base):
+ col1 = base_colors[idx1]
+ col2 = base_colors[idx2]
+ def mix(c1, c2, w1, w2):
+ tot = w1 + w2
+ return (
+ (c1[0]*w1 + c2[0]*w2) / tot,
+ (c1[1]*w1 + c2[1]*w2) / tot,
+ (c1[2]*w1 + c2[2]*w2) / tot
+ )
+ expected.append(mix(col1, col2, 1.0, 1.0))
+ expected.append(mix(col1, col2, 2.0, 1.0))
+ expected.append(mix(col1, col2, 1.0, 2.0))
+
+ for item, exp in zip(palette, expected):
+ if not is_close(item.color, exp):
+ scene.stablegen_print_preset = 'CUSTOM'
+ return
+
+
+def update_palette_color(self, context):
+ check_print_preset_match(self.id_data)
+
+
+def update_print_dithered(self, context):
+ check_print_preset_match(self.id_data)
+
diff --git a/stablegen/core/load_handlers.py b/stablegen/core/load_handlers.py
index 440f5a3..22457d4 100644
--- a/stablegen/core/load_handlers.py
+++ b/stablegen/core/load_handlers.py
@@ -18,11 +18,18 @@ def load_handler(dummy):
"""Set default ControlNet/LoRA units and sync checkpoint cache on file load."""
from ..ui.model_units import get_lora_models
from . import state as _state
+ from ..texturing.print_export import prepopulate_palette
if not bpy.context.scene:
return
scene = bpy.context.scene
+
+ # Pre-populate multi-color printing palette
+ try:
+ prepopulate_palette(scene)
+ except Exception as e:
+ print(f"[StableGen] Load Handler: failed to prepopulate palette: {e}")
addon_prefs = bpy.context.preferences.addons[ADDON_PKG].preferences
# Re-register aspect-ratio crop overlays
diff --git a/stablegen/core/preferences.py b/stablegen/core/preferences.py
index 2510235..8d8ff7e 100644
--- a/stablegen/core/preferences.py
+++ b/stablegen/core/preferences.py
@@ -84,6 +84,13 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
update=update_parameters
) # type: ignore
+ enable_print_tab: bpy.props.BoolProperty(
+ name="Enable 3D Print Tab",
+ description="Show 3D Printing Palette and Exporters in a separate Sidebar tab",
+ default=False,
+ update=update_parameters
+ ) # type: ignore
+
controlnet_mapping_index: bpy.props.IntProperty(
default=0, name="Active ControlNet Mapping Index"
) # type: ignore
@@ -148,6 +155,13 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
default=600.0, min=60.0, max=3600.0, step=100, precision=0,
) # type: ignore
+ enable_scene_queue: bpy.props.BoolProperty(
+ name="Enable Scene Queue",
+ description="Show the Scene Queue panel in the sidebar",
+ default=False,
+ update=update_parameters
+ ) # type: ignore
+
def draw(self, context):
layout = self.layout
layout.prop(self, "output_dir")
@@ -156,6 +170,8 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
row.operator("stablegen.check_server_status", text="", icon='FILE_REFRESH')
layout.prop(self, "save_blend_file")
+ layout.prop(self, "enable_print_tab")
+ layout.prop(self, "enable_scene_queue")
layout.separator()
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index 1f7dd7f..2eb6c10 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -15,6 +15,8 @@ from .callbacks import (
update_trellis2_generate_from,
update_trellis2_initial_image_arch,
update_trellis2_texture_mode,
+ update_print_preset,
+ update_print_dithered,
)
from . import ADDON_PKG
@@ -63,6 +65,103 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
name="Show Queue", default=False
)
+ # --- Multi-Color Print Palette (on Scene) ---
+ from ..texturing.print_export import StableGenPaletteColor
+ bpy.types.Scene.stablegen_print_palette = bpy.props.CollectionProperty(
+ type=StableGenPaletteColor, name="Print Palette"
+ )
+ bpy.types.Scene.stablegen_print_palette_index = bpy.props.IntProperty(
+ name="Palette Index", default=0
+ )
+ bpy.types.Scene.stablegen_print_preset = bpy.props.EnumProperty(
+ name="Print Preset",
+ description="Select a multi-color printing preset",
+ items=[
+ ('CUSTOM', 'Custom', 'Use custom palette and settings'),
+ ('CMYW_DITHERED', 'CMYW (Dithered)', 'Dithered mode with Cyan, Magenta, Yellow, White'),
+ ('CMYK_DITHERED', 'CMYK (Dithered)', 'Dithered mode with Cyan, Magenta, Yellow, Black'),
+ ('CMYW_MIXES_SOLID', 'CMYW + Mixes (Non-Dithered)', 'Solid mode with CMYW and all 1:1, 2:1, 1:2 mixtures'),
+ ('CMYK_MIXES_SOLID', 'CMYK + Mixes (Non-Dithered)', 'Solid mode with CMYK and all 1:1, 2:1, 1:2 mixtures'),
+ ],
+ default='CMYW_DITHERED',
+ update=update_print_preset
+ )
+ bpy.types.Scene.stablegen_print_dithered = bpy.props.BoolProperty(
+ name="Dithered (Full Spectrum)",
+ description="Slice and dither layers to blend colors. If disabled, faces are printed as solid colors using the closest filament.",
+ default=True,
+ update=update_print_dithered,
+ )
+ bpy.types.Scene.stablegen_print_layer_height = bpy.props.FloatProperty(
+ name="Layer Height",
+ description="Layer height in mm",
+ default=0.08, min=0.01, max=1.0, step=1, precision=3,
+ )
+ bpy.types.Scene.stablegen_print_model_height = bpy.props.FloatProperty(
+ name="Model Height",
+ description="Target height of the exported model in mm (scaled from Blender dimensions)",
+ default=50.0, min=0.1, max=1000.0, step=10, precision=1,
+ )
+ bpy.types.Scene.stablegen_print_smoothing = bpy.props.IntProperty(
+ name="Smoothing Passes",
+ description="Number of majority-vote island cleanup passes to apply to the quantization",
+ default=2, min=0, max=10
+ )
+ bpy.types.Scene.stablegen_print_chroma_threshold = bpy.props.FloatProperty(
+ name="Chromatic Threshold",
+ description="Saturation above which a colour is treated as chromatic for hue-matching",
+ default=0.35, min=0.0, max=1.0, step=1, precision=2,
+ )
+ bpy.types.Scene.stablegen_print_make_solid = bpy.props.BoolProperty(
+ name="Make Solid",
+ description="Extract outer shell via cylinder-raycast visibility, delete internal geometry, and fill bottom holes. Requires SG_PrintPreview color attribute.",
+ default=False,
+ )
+ bpy.types.Scene.stablegen_print_raycast_count = bpy.props.IntProperty(
+ name="Raycast Angles",
+ description="Number of angular sample directions around the bounding cylinder per height level (5 height levels are tested). Higher values help preserve narrow crevices but increase calculation time",
+ default=12, min=4, max=64,
+ )
+ bpy.types.Scene.stablegen_print_show_advanced = bpy.props.BoolProperty(
+ name="Show Advanced Settings",
+ description="Show advanced solver parameters for custom filament mixing",
+ default=False,
+ )
+ bpy.types.Scene.stablegen_print_solver_init = bpy.props.EnumProperty(
+ name="Initialization Method",
+ description="Select the starting state for the solver optimization loop",
+ items=[
+ ('EQUAL', 'Equal Fractions', 'Initialize all filaments with equal fractions (1/N)'),
+ ('CLOSEST', 'Closest Filament', 'Initialize with 100% of the single closest filament')
+ ],
+ default='CLOSEST',
+ )
+ bpy.types.Scene.stablegen_print_solver_steps = bpy.props.IntProperty(
+ name="Convergence Steps",
+ description="Number of iterations for the Frank-Wolfe optimization loop",
+ default=80, min=10, max=500,
+ )
+ bpy.types.Scene.stablegen_print_solver_formula = bpy.props.EnumProperty(
+ name="Mixing Model",
+ description="Algorithm used to simulate physical filament color mixing",
+ items=[
+ ('ADDITIVE', 'Linear Additive', 'Standard linear additive color mixing'),
+ ('SUBTRACTIVE', 'Linear Subtractive', 'Simple linear complement subtractive color mixing'),
+ ('KUBELKA_MUNK', 'Kubelka-Munk', 'Physical Kubelka-Munk model with absorption and scattering')
+ ],
+ default='KUBELKA_MUNK',
+ )
+ bpy.types.Scene.stablegen_print_scattering_weight = bpy.props.FloatProperty(
+ name="Opaque Scattering",
+ description="Scattering coefficient multiplier for bright/opaque filaments (e.g. Skin, White)",
+ default=10.0, min=1.0, max=50.0,
+ )
+ bpy.types.Scene.stablegen_print_saturation_penalty = bpy.props.FloatProperty(
+ name="Saturation Penalty",
+ description="Penalty weight to prevent mixing desaturated spot colors into saturated target regions. High values force primary colors",
+ default=1.0, min=0.0, max=10.0, precision=2,
+ )
+
# --- Queue GIF Export settings ---
bpy.types.WindowManager.sg_queue_gif_export = bpy.props.BoolProperty(
name="Export GIF After Each Item", default=False,
@@ -1215,7 +1314,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
('fp16', 'FP16', 'Float16 (most GPUs)'),
('fp32', 'FP32', 'Float32 (slowest, most compatible)'),
],
- default='auto', update=update_parameters
+ default='bf16', update=update_parameters
)
bpy.types.Scene.trellis2_attn_backend = bpy.props.EnumProperty(
name="Attention Backend", description="Attention implementation to use",
@@ -1250,7 +1349,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
)
bpy.types.Scene.trellis2_tex_guidance = bpy.props.FloatProperty(
name="Texture Guidance", description="Texture CFG scale. Higher = stronger adherence to input image",
- default=7.5, min=1.0, max=20.0, step=10, update=update_parameters
+ default=3.0, min=1.0, max=20.0, step=10, update=update_parameters
)
bpy.types.Scene.trellis2_tex_steps = bpy.props.IntProperty(
name="Texture Steps", description="Texture sampling steps. More steps = better quality but slower",
@@ -1260,7 +1359,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
name="Max Tokens",
description="Max sparse-voxel tokens during cascade upsampling (only affects cascade modes). "
"Higher = more detail but more VRAM. Increase to 49152 for maximum detail if VRAM allows",
- default=32768, min=16384, max=65536, step=4096, update=update_parameters
+ default=49152, min=16384, max=65536, step=4096, update=update_parameters
)
bpy.types.Scene.trellis2_texture_size = bpy.props.IntProperty(
name="Texture Size",
@@ -1272,15 +1371,51 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
name="Decimation Target", description="Target polygon count for mesh simplification. Lower = simpler mesh",
default=100000, min=1000, max=5000000, step=10000, update=update_parameters
)
- bpy.types.Scene.trellis2_remesh = bpy.props.BoolProperty(
- name="Remesh", description="Apply remeshing for cleaner topology",
- default=True, update=update_parameters
+ bpy.types.Scene.trellis2_remesh = bpy.props.EnumProperty(
+ name="Remesh/Retopo Method (Legacy)",
+ description="Legacy field - please use Decimation Method and Remesh/Retopo Method instead",
+ items=[
+ ('qdc', "QDC (Server)", ""),
+ ('none', "None (Raw)", ""),
+ ('decimate_collapse', "Collapse Decimate (Local)", ""),
+ ('quadriflow', "Quadriflow (Local) [Experimental]", ""),
+ ],
+ default='qdc',
+ update=update_parameters
+ )
+ bpy.types.Scene.trellis2_decimate_method = bpy.props.EnumProperty(
+ name="Decimation Method",
+ description="Method for decimation: Server-side, Collapse (Local), or None. Note: Server-Side QEM is required/recommended when using QDC (Server) remeshing",
+ items=[
+ ('none', "None (Raw)", "No decimation - keep the high-poly raw details"),
+ ('server', "Server-Side QEM", "Simplify on the ComfyUI server via edge-collapse (required/recommended for Server QDC remeshing)"),
+ ('collapse', "Collapse Decimate (Local)", "Adaptive decimation locally in Blender via QEM solver (best for None or local quad remeshing)"),
+ ],
+ default='server',
+ update=update_parameters
+ )
+ bpy.types.Scene.trellis2_remesh_method = bpy.props.EnumProperty(
+ name="Remesh/Retopo Method",
+ description="Method for remeshing/retopology: Server-side QDC, Local Quadriflow, or None. Note: QDC (Server) handles decimation natively on the ComfyUI server",
+ items=[
+ ('none', "None (Trimesh)", "Keep triangles (raw or decimated) - no retopology solver"),
+ ('qdc', "QDC (Server)", "Quad Dual Contouring - uniform server-side quad remeshing (handles both decimation and remeshing natively)"),
+ ('quadriflow', "Quadriflow (Local) [Experimental]", "Curvature-adaptive local quad retopology in Blender (Zero-dependency). Note: Experimental, might produce artifacts"),
+ ],
+ default='qdc',
+ update=update_parameters
)
bpy.types.Scene.trellis2_post_processing_enabled = bpy.props.BoolProperty(
name="Post-Processing",
description="Run ComfyUI-side mesh post-processing (decimation + remeshing). Disable to import the raw mesh for manual retopology",
default=True, update=update_parameters
)
+ bpy.types.Scene.trellis2_solidify = bpy.props.BoolProperty(
+ name="Solidify Mesh",
+ description="Apply watertight capping and hollowing to delete internal geometry, saving UV and texture space",
+ default=False, update=update_parameters
+ )
+
bpy.types.Scene.trellis2_auto_lighting = bpy.props.BoolProperty(
name="Auto Studio Lighting",
description="Create a three-point studio lighting rig (key, fill, rim) after import to showcase PBR materials",
@@ -1615,7 +1750,9 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'trellis2_ss_steps', 'trellis2_shape_guidance', 'trellis2_shape_steps',
'trellis2_tex_guidance', 'trellis2_tex_steps', 'trellis2_max_tokens',
'trellis2_texture_size', 'trellis2_decimation', 'trellis2_remesh',
+ 'trellis2_decimate_method', 'trellis2_remesh_method',
'trellis2_post_processing_enabled',
+ 'trellis2_solidify',
'trellis2_auto_lighting',
'trellis2_skip_texture', 'trellis2_bg_removal', 'trellis2_background_color',
]
@@ -1636,6 +1773,40 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
if hasattr(bpy.types.WindowManager, 'sg_show_queue'):
del bpy.types.WindowManager.sg_show_queue
+ # --- Multi-Color Print Palette cleanup ---
+ if hasattr(bpy.types.Scene, 'stablegen_print_palette'):
+ del bpy.types.Scene.stablegen_print_palette
+ if hasattr(bpy.types.Scene, 'stablegen_print_palette_index'):
+ del bpy.types.Scene.stablegen_print_palette_index
+ if hasattr(bpy.types.Scene, 'stablegen_print_preset'):
+ del bpy.types.Scene.stablegen_print_preset
+ if hasattr(bpy.types.Scene, 'stablegen_print_dithered'):
+ del bpy.types.Scene.stablegen_print_dithered
+ if hasattr(bpy.types.Scene, 'stablegen_print_layer_height'):
+ del bpy.types.Scene.stablegen_print_layer_height
+ if hasattr(bpy.types.Scene, 'stablegen_print_model_height'):
+ del bpy.types.Scene.stablegen_print_model_height
+ if hasattr(bpy.types.Scene, 'stablegen_print_smoothing'):
+ del bpy.types.Scene.stablegen_print_smoothing
+ if hasattr(bpy.types.Scene, 'stablegen_print_chroma_threshold'):
+ del bpy.types.Scene.stablegen_print_chroma_threshold
+ if hasattr(bpy.types.Scene, 'stablegen_print_make_solid'):
+ del bpy.types.Scene.stablegen_print_make_solid
+ if hasattr(bpy.types.Scene, 'stablegen_print_raycast_count'):
+ del bpy.types.Scene.stablegen_print_raycast_count
+ if hasattr(bpy.types.Scene, 'stablegen_print_show_advanced'):
+ del bpy.types.Scene.stablegen_print_show_advanced
+ if hasattr(bpy.types.Scene, 'stablegen_print_solver_init'):
+ del bpy.types.Scene.stablegen_print_solver_init
+ if hasattr(bpy.types.Scene, 'stablegen_print_solver_steps'):
+ del bpy.types.Scene.stablegen_print_solver_steps
+ if hasattr(bpy.types.Scene, 'stablegen_print_solver_formula'):
+ del bpy.types.Scene.stablegen_print_solver_formula
+ if hasattr(bpy.types.Scene, 'stablegen_print_scattering_weight'):
+ del bpy.types.Scene.stablegen_print_scattering_weight
+ if hasattr(bpy.types.Scene, 'stablegen_print_saturation_penalty'):
+ del bpy.types.Scene.stablegen_print_saturation_penalty
+
for attr in (
'sg_queue_gif_export', 'sg_queue_gif_duration', 'sg_queue_gif_fps',
'sg_queue_gif_resolution', 'sg_queue_gif_samples', 'sg_queue_gif_engine',
diff --git a/stablegen/core/state.py b/stablegen/core/state.py
index c657483..47ecd71 100644
--- a/stablegen/core/state.py
+++ b/stablegen/core/state.py
@@ -17,6 +17,7 @@ _cached_checkpoint_list = [("NONE_AVAILABLE", "None available", "Fetch models fr
_cached_lora_list = [("NONE_AVAILABLE", "None available", "Fetch models from server")]
_cached_checkpoint_architecture = None
_pending_checkpoint_refresh_architecture = None
+_updating_print_preset = False
# ── In-flight refresh counter ─────────────────────────────────────────────
diff --git a/stablegen/dae_import/batch_texture.py b/stablegen/dae_import/batch_texture.py
new file mode 100644
index 0000000..350c0e9
--- /dev/null
+++ b/stablegen/dae_import/batch_texture.py
@@ -0,0 +1,876 @@
+"""Batch DAE import + texture generation pipeline.
+
+Imports each .dae file, auto-places cameras, generates textures using
+the current scene settings, bakes, and exports to GLB — all without
+user intervention. Follows the same timer-based state-machine pattern
+as :pymod:`mesh_gen.batch`.
+"""
+
+import os
+import bpy # pylint: disable=import-error
+
+from ..utils import sg_modal_active
+
+# Reference image filenames (checked in order)
+_REF_NAMES = ('ref.png', 'ref.jpg', 'ref.jpeg')
+_IMAGE_EXTS = {'.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tiff'}
+
+# ── Module-level batch state ────────────────────────────────────────────────
+_batch_state = {
+ 'active': False,
+ 'cancelled': False,
+ 'files': [], # list of (abs_path, rel_path)
+ 'index': -1,
+ 'total': 0,
+ 'top_dir': '', # root directory (for fallback ref image)
+ 'out_dir': '',
+ 'phase': 'idle', # idle | import | cameras | texturing | bake | export
+ 'settle_count': 0,
+ # Operator settings (copied from the invoking operator)
+ 'settings': {},
+}
+
+_SETTLE_TICKS = 12
+_TICK_INTERVAL = 0.5
+
+
+def _redraw():
+ try:
+ for window in bpy.context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _sync_wm():
+ try:
+ wm = bpy.context.window_manager
+ wm.sg_batch_tex_running = _batch_state['active']
+ wm.sg_batch_tex_index = _batch_state['index'] + 1
+ wm.sg_batch_tex_total = _batch_state['total']
+ wm.sg_batch_tex_phase = _batch_state['phase']
+ _redraw()
+ except Exception: # noqa: BLE001
+ pass
+
+
+# ── Reference image resolution ──────────────────────────────────────────────
+
+def _find_ref_image(dae_path, top_dir, ref_dir=''):
+ """Return the path to a reference image for this model, or ''.
+
+ Search order:
+ 1. Separate reference directory (*ref_dir*): find an image file whose
+ name contains the building number (stem of the .dae filename) in the
+ matching subdirectory.
+ 2. Same subdirectory as the .dae file: look for ref.png / ref.jpg / ref.jpeg.
+ 3. Top-level model directory fallback: same ref names at *top_dir*.
+ """
+ dae_stem = os.path.splitext(os.path.basename(dae_path))[0]
+ dae_dir = os.path.dirname(dae_path)
+
+ # 1. Separate reference image directory (building-specific match)
+ if ref_dir and os.path.isdir(ref_dir):
+ rel = os.path.relpath(dae_dir, top_dir)
+ # Try the full relative path first, then progressively shorter
+ # suffixes (e.g. "3D_modely/Úzká" → "Úzká") so the ref dir
+ # doesn't need to replicate the exact model-tree prefix.
+ parts = rel.replace('\\', '/').split('/')
+ candidates = [os.path.join(*parts[i:]) for i in range(len(parts))]
+ candidates.append('.') # ref_dir root as final fallback
+ for suffix in candidates:
+ search_dir = os.path.join(ref_dir, suffix) if suffix != '.' else ref_dir
+ if not os.path.isdir(search_dir):
+ continue
+ for name in sorted(os.listdir(search_dir)):
+ ext = os.path.splitext(name)[1].lower()
+ if ext in _IMAGE_EXTS and dae_stem in name:
+ return os.path.join(search_dir, name)
+ elif ref_dir:
+ print(f"[BatchTex] ref_dir={ref_dir!r} isdir={os.path.isdir(ref_dir)}")
+
+ # 2. Same directory as the .dae file (subdir-level fallback)
+ for name in _REF_NAMES:
+ candidate = os.path.join(dae_dir, name)
+ if os.path.isfile(candidate):
+ return candidate
+
+ # 3. Separate ref dir — subdirectory fallback ref image
+ if ref_dir and os.path.isdir(ref_dir):
+ rel = os.path.relpath(dae_dir, top_dir)
+ parts = rel.replace('\\', '/').split('/')
+ candidates = [os.path.join(*parts[i:]) for i in range(len(parts))]
+ candidates.append('.')
+ for suffix in candidates:
+ search_dir = os.path.join(ref_dir, suffix) if suffix != '.' else ref_dir
+ if not os.path.isdir(search_dir):
+ continue
+ for name in _REF_NAMES:
+ candidate = os.path.join(search_dir, name)
+ if os.path.isfile(candidate):
+ return candidate
+
+ # 4. Top-level directory fallback
+ for name in _REF_NAMES:
+ candidate = os.path.join(top_dir, name)
+ if os.path.isfile(candidate):
+ return candidate
+ return ''
+
+
+# ── Phase handlers ──────────────────────────────────────────────────────────
+
+def _do_import():
+ """Import the current DAE file. Returns True on success."""
+ state = _batch_state
+ filepath = state['files'][state['index']][0]
+ settings = state['settings']
+
+ # Clear scene
+ bpy.ops.object.select_all(action='SELECT')
+ bpy.ops.object.delete(use_global=False)
+
+ try:
+ bpy.ops.stablegen.import_dae(
+ filepath=filepath,
+ merge_threshold=settings.get('merge_threshold', 0.001),
+ remove_interior=settings.get('remove_interior', True),
+ remove_ground=settings.get('remove_ground', True),
+ strip_materials=settings.get('strip_materials', True),
+ topology_method=settings.get('topology_method', 'FIX_FANS'),
+ edge_ratio=settings.get('edge_ratio', 2.5),
+ equalize_iterations=settings.get('equalize_iterations', 4),
+ voxel_size=settings.get('voxel_size', 0.0),
+ auto_scale=settings.get('auto_scale', 0.0),
+ shading_mode=settings.get('shading_mode', 'FLAT'),
+ center_origin=settings.get('center_origin', True),
+ join_meshes=True,
+ triangulate=settings.get('triangulate', True),
+ )
+ return True
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchTex] FAILED to import: {exc}")
+ return False
+
+
+def _do_cameras():
+ """Auto-place cameras around the imported mesh."""
+ scene = bpy.context.scene
+ settings = _batch_state['settings']
+
+ _pm = settings.get('placement_mode', 'normal_weighted')
+ _cam_kwargs = {
+ 'num_cameras': settings.get('camera_count', 8),
+ 'placement_mode': _pm,
+ 'auto_prompts': settings.get('auto_prompts', True),
+ 'review_placement': False,
+ 'purge_others': True,
+ 'exclude_bottom': settings.get('exclude_bottom', True),
+ 'exclude_bottom_angle': settings.get('exclude_bottom_angle', 1.5533),
+ 'auto_aspect': settings.get('auto_aspect', 'per_camera'),
+ 'occlusion_mode': settings.get('occlusion_mode', 'none'),
+ 'consider_existing': settings.get('consider_existing', True),
+ 'clamp_elevation': settings.get('clamp_elevation', False),
+ 'max_elevation_angle': settings.get('max_elevation', 1.2217),
+ 'min_elevation_angle': settings.get('min_elevation', -0.1745),
+ }
+ if _pm == 'greedy_coverage':
+ _cam_kwargs['coverage_target'] = settings.get('coverage_target', 0.95)
+ _cam_kwargs['max_auto_cameras'] = settings.get('max_auto_cameras', 12)
+ if _pm == 'fan_from_camera':
+ _cam_kwargs['fan_angle'] = settings.get('fan_angle', 90.0)
+
+ from .. import utils as _sg_utils
+
+ # Find a 3D viewport for temp_override
+ _v3d_area = None
+ _v3d_region = None
+ for window in bpy.context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ _v3d_area = area
+ for region in area.regions:
+ if region.type == 'WINDOW':
+ _v3d_region = region
+ break
+ break
+ if _v3d_area:
+ break
+
+ _sg_utils._sg_bypass_modal_check = True
+ try:
+ if _v3d_area and _v3d_region:
+ with bpy.context.temp_override(area=_v3d_area, region=_v3d_region):
+ bpy.ops.object.add_cameras(**_cam_kwargs)
+ else:
+ bpy.ops.object.add_cameras(**_cam_kwargs)
+ finally:
+ _sg_utils._sg_bypass_modal_check = False
+
+
+def _do_set_ref_image():
+ """Set the reference image for the current model on the scene properties."""
+ state = _batch_state
+ filepath = state['files'][state['index']][0]
+ ref = _find_ref_image(filepath, state['top_dir'],
+ state['settings'].get('ref_image_dir', ''))
+ scene = bpy.context.scene
+ arch = getattr(scene, 'model_architecture', 'sdxl')
+
+ if ref:
+ print(f"[BatchTex] Reference image: {ref}")
+ if arch == 'sdxl':
+ scene.use_ipadapter = True
+ scene.ipadapter_image = ref
+ elif arch in ('qwen_image_edit', 'flux2_klein'):
+ scene.qwen_use_external_style_image = True
+ scene.qwen_external_style_image = ref
+ elif arch == 'flux1':
+ scene.use_ipadapter = True
+ scene.ipadapter_image = ref
+ else:
+ print("[BatchTex] No reference image found")
+ # If the currently set path doesn't exist, disable IPAdapter
+ # to avoid validation errors (e.g. paths from another machine).
+ if arch == 'sdxl' and scene.use_ipadapter:
+ cur = bpy.path.abspath(scene.ipadapter_image)
+ if not cur or not os.path.isfile(cur):
+ scene.use_ipadapter = False
+ print("[BatchTex] Disabled IPAdapter (path not found)")
+ elif arch in ('qwen_image_edit', 'flux2_klein') and scene.qwen_use_external_style_image:
+ cur = bpy.path.abspath(scene.qwen_external_style_image)
+ if not cur or not os.path.isfile(cur):
+ scene.qwen_use_external_style_image = False
+ print("[BatchTex] Disabled external style image (path not found)")
+
+
+def _do_start_texturing():
+ """Select all cameras and invoke the texture generation operator."""
+ bpy.ops.object.select_all(action='DESELECT')
+ scene_cams = [obj for obj in bpy.context.scene.objects if obj.type == 'CAMERA']
+ for obj in scene_cams:
+ obj.select_set(True)
+
+ from .. import utils as _sg_utils
+ _sg_utils._sg_bypass_modal_check = True
+ try:
+ bpy.ops.object.test_stable('INVOKE_DEFAULT')
+ finally:
+ _sg_utils._sg_bypass_modal_check = False
+ print("[BatchTex] Texture generation started")
+
+
+def _do_bake():
+ """Bake textures for all mesh objects using the utility functions directly."""
+ from ..texturing.rendering import prepare_baking, bake_texture
+ from ..utils import get_dir_path
+
+ settings = _batch_state['settings']
+ tex_res = settings.get('bake_resolution', 2048)
+
+ context = bpy.context
+ original_engine = context.scene.render.engine
+
+ prepare_baking(context)
+
+ mesh_objects = [obj for obj in context.scene.objects if obj.type == 'MESH']
+ for obj in mesh_objects:
+ try:
+ # ── Create a fresh BakeUV and unwrap directly ──
+ # Remove all non-projection UV maps (DAE originals are per-material
+ # SketchUp UVs, not suitable as a bake atlas)
+ to_remove = [uv for uv in obj.data.uv_layers
+ if "ProjectionUV" not in uv.name
+ and uv.name != "_SG_ProjectionBuffer"
+ and uv.name != "BakeUV"]
+ for uv in to_remove:
+ obj.data.uv_layers.remove(uv)
+
+ # Ensure BakeUV exists and is active
+ bake_uv = obj.data.uv_layers.get("BakeUV")
+ if not bake_uv:
+ bake_uv = obj.data.uv_layers.new(name="BakeUV")
+ obj.data.uv_layers.active = bake_uv
+
+ # Smart UV Project directly (bypass unwrap() which has its own UV selection logic)
+ bpy.ops.object.select_all(action='DESELECT')
+ bpy.context.view_layer.objects.active = obj
+ obj.select_set(True)
+ bpy.ops.object.mode_set(mode='EDIT')
+ # UV sync must be ON so mesh face selection drives UV selection
+ bpy.context.scene.tool_settings.use_uv_select_sync = True
+ bpy.ops.mesh.select_all(action='SELECT')
+ # Set BakeUV as the active UV layer in edit mode too
+ obj.data.uv_layers.active = obj.data.uv_layers["BakeUV"]
+ # UV operators need a proper 3D viewport context — in a timer
+ # callback the default context has no area/region, causing
+ # smart_project to silently produce garbage UVs.
+ _v3d_area = _v3d_region = None
+ for window in bpy.context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ _v3d_area = area
+ for region in area.regions:
+ if region.type == 'WINDOW':
+ _v3d_region = region
+ break
+ break
+ if _v3d_area:
+ break
+ if _v3d_area and _v3d_region:
+ with bpy.context.temp_override(area=_v3d_area,
+ region=_v3d_region):
+ bpy.ops.uv.smart_project(correct_aspect=False)
+ else:
+ bpy.ops.uv.smart_project(correct_aspect=False)
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+ bake_texture(context, obj, texture_resolution=tex_res,
+ output_dir=get_dir_path(context, "baked"))
+ # Apply baked texture as a simple Principled BSDF material so
+ # GLB export sees a standard material instead of the complex
+ # StableGen projection node tree.
+ _apply_baked_material(context, obj)
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchTex] Bake failed for {obj.name}: {exc}")
+
+ if context.scene.render.engine != original_engine:
+ context.scene.render.engine = original_engine
+ print("[BatchTex] Bake complete")
+
+ if context.scene.render.engine != original_engine:
+ context.scene.render.engine = original_engine
+ print("[BatchTex] Bake complete")
+
+
+def _apply_baked_material(context, obj):
+ """Replace the projection material with a simple Principled BSDF using the baked texture."""
+ from ..utils import get_dir_path, get_file_path
+ import os as _os
+
+ output_dir = get_dir_path(context, "baked")
+ baked_path = get_file_path(context, "baked", object_name=obj.name)
+
+ if not baked_path or not _os.path.exists(baked_path):
+ print(f"[BatchTex] No baked texture found for {obj.name}, skipping material apply")
+ return
+
+ mat = bpy.data.materials.new(name=f"{obj.name}_baked")
+ mat.use_nodes = True
+ nodes = mat.node_tree.nodes
+ links = mat.node_tree.links
+ nodes.clear()
+
+ # Output node
+ output_node = nodes.new("ShaderNodeOutputMaterial")
+ output_node.location = (600, 0)
+
+ # Principled BSDF — fully matte so baked colour is displayed as-is
+ principled = nodes.new("ShaderNodeBsdfPrincipled")
+ principled.location = (300, 0)
+ principled.inputs["Roughness"].default_value = 1.0
+ principled.inputs["Metallic"].default_value = 0.0
+ links.new(principled.outputs[0], output_node.inputs["Surface"])
+
+ # UV Map (use BakeUV if available, otherwise first non-projection UV)
+ uv_node = nodes.new("ShaderNodeUVMap")
+ uv_node.location = (-400, 0)
+ if "BakeUV" in [uv.name for uv in obj.data.uv_layers]:
+ uv_node.uv_map = "BakeUV"
+ else:
+ for uv in obj.data.uv_layers:
+ if "ProjectionUV" not in uv.name and uv.name != "_SG_ProjectionBuffer":
+ uv_node.uv_map = uv.name
+ break
+
+ # Base Color texture
+ tex_node = nodes.new("ShaderNodeTexImage")
+ tex_node.image = bpy.data.images.load(baked_path)
+ tex_node.location = (-100, 0)
+ links.new(uv_node.outputs["UV"], tex_node.inputs["Vector"])
+ links.new(tex_node.outputs["Color"], principled.inputs["Base Color"])
+
+ # Clear all existing materials and assign the baked one
+ obj.data.materials.clear()
+ obj.data.materials.append(mat)
+ print(f"[BatchTex] Applied baked material to {obj.name}")
+
+
+def _do_export():
+ """Export the current textured mesh to GLB."""
+ state = _batch_state
+ rel_path = state['files'][state['index']][1]
+ name = os.path.splitext(os.path.basename(rel_path))[0]
+ rel_dir = os.path.dirname(rel_path)
+ file_out_dir = os.path.join(state['out_dir'], rel_dir) if rel_dir else state['out_dir']
+ os.makedirs(file_out_dir, exist_ok=True)
+
+ out_path = os.path.join(file_out_dir, f"{name}.glb")
+
+ # Select all mesh objects
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in bpy.context.scene.objects:
+ if obj.type == 'MESH':
+ obj.select_set(True)
+ if bpy.context.selected_objects:
+ bpy.context.view_layer.objects.active = bpy.context.selected_objects[0]
+
+ try:
+ bpy.ops.export_scene.gltf(filepath=out_path)
+ print(f"[BatchTex] Exported: {out_path}")
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchTex] FAILED to export: {exc}")
+
+
+# ── State machine tick ──────────────────────────────────────────────────────
+
+
+def _batch_tex_tick():
+ """Timer callback — drives the batch texturing state machine."""
+ from ..texturing.generator import ComfyUIGenerate
+
+ state = _batch_state
+
+ if state['cancelled'] or not state['active']:
+ state['active'] = False
+ state['cancelled'] = False
+ state['phase'] = 'idle'
+ _sync_wm()
+ print("[BatchTex] Batch stopped")
+ return None
+
+ phase = state['phase']
+
+ # ── IDLE: advance to next file ──────────────────────────────────────
+ if phase == 'idle':
+ next_idx = state['index'] + 1
+ # Skip files whose output GLB already exists (resume support)
+ while next_idx < state['total']:
+ rel_path = state['files'][next_idx][1]
+ name = os.path.splitext(os.path.basename(rel_path))[0]
+ rel_dir = os.path.dirname(rel_path)
+ file_out_dir = (os.path.join(state['out_dir'], rel_dir)
+ if rel_dir else state['out_dir'])
+ out_path = os.path.join(file_out_dir, f"{name}.glb")
+ if os.path.exists(out_path):
+ print(f"[BatchTex] Skipping {next_idx + 1}/{state['total']}: "
+ f"{rel_path} (already exported)")
+ next_idx += 1
+ else:
+ break
+
+ if next_idx >= state['total']:
+ state['active'] = False
+ state['phase'] = 'idle'
+ _sync_wm()
+ print(f"[BatchTex] Complete! {state['total']} file(s) processed.")
+ return None
+
+ state['index'] = next_idx
+ state['phase'] = 'import'
+ _sync_wm()
+ rel = state['files'][next_idx][1]
+ print(f"[BatchTex] {next_idx + 1}/{state['total']}: {rel}")
+ return _TICK_INTERVAL
+
+ # ── IMPORT ──────────────────────────────────────────────────────────
+ if phase == 'import':
+ ok = _do_import()
+ if not ok:
+ print(f"[BatchTex] Skipping file {state['index'] + 1} (import failed)")
+ state['phase'] = 'idle'
+ return _TICK_INTERVAL
+
+ state['phase'] = 'cameras'
+ return _TICK_INTERVAL
+
+ # ── CAMERAS ─────────────────────────────────────────────────────────
+ if phase == 'cameras':
+ try:
+ _do_cameras()
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchTex] Camera placement failed: {exc}")
+ state['phase'] = 'idle'
+ return _TICK_INTERVAL
+
+ # Set reference image before texturing
+ _do_set_ref_image()
+
+ state['phase'] = 'texturing'
+ state['settle_count'] = 0
+ # Small delay so Blender digests the new cameras
+ return _TICK_INTERVAL
+
+ # ── TEXTURING (wait for ComfyUIGenerate to finish) ──────────────────
+ if phase == 'texturing':
+ if state['settle_count'] == 0:
+ # First tick: start texturing
+ try:
+ _do_start_texturing()
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchTex] Texturing failed to start: {exc}")
+ state['phase'] = 'export'
+ return _TICK_INTERVAL
+ state['settle_count'] = 1
+ return _TICK_INTERVAL
+
+ if state['settle_count'] < _SETTLE_TICKS:
+ state['settle_count'] += 1
+ if ComfyUIGenerate._is_running:
+ state['settle_count'] = _SETTLE_TICKS # operator started
+ return _TICK_INTERVAL
+
+ # Past settling — wait for completion
+ if ComfyUIGenerate._is_running:
+ return _TICK_INTERVAL
+
+ # Check if generation was cancelled or failed
+ try:
+ had_error = bpy.context.scene.sg_last_gen_error
+ except Exception: # noqa: BLE001
+ had_error = False
+ gen_status = getattr(bpy.context.scene, 'generation_status', 'idle')
+ if had_error or gen_status == 'waiting':
+ print("[BatchTex] Generation was cancelled/failed — stopping batch")
+ state['active'] = False
+ state['phase'] = 'idle'
+ _sync_wm()
+ return None
+
+ # Texturing done — move to bake
+ if _batch_state['settings'].get('bake', True):
+ state['phase'] = 'bake'
+ state['settle_count'] = 0
+ else:
+ state['phase'] = 'export'
+ return _TICK_INTERVAL
+
+ # ── BAKE (synchronous — no operator popup) ──────────────────────────
+ if phase == 'bake':
+ try:
+ _do_bake()
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchTex] Bake failed: {exc}")
+
+ state['phase'] = 'export'
+ return _TICK_INTERVAL
+
+ # ── EXPORT ──────────────────────────────────────────────────────────
+ if phase == 'export':
+ try:
+ _do_export()
+ except Exception as exc: # noqa: BLE001
+ print(f"[BatchTex] Export failed: {exc}")
+
+ state['phase'] = 'idle'
+ return _TICK_INTERVAL
+
+ return _TICK_INTERVAL
+
+
+# ── Operators ───────────────────────────────────────────────────────────────
+
+class BatchTextureDAE(bpy.types.Operator):
+ """Batch import .dae files, auto-place cameras, generate textures,
+ bake, and export to .glb — fully automated pipeline."""
+
+ bl_idname = "stablegen.batch_texture_dae"
+ bl_label = "Batch Texture DAE Files"
+ bl_options = {'REGISTER'}
+
+ directory: bpy.props.StringProperty(
+ name="Directory",
+ description="Directory containing .dae files",
+ subtype='DIR_PATH',
+ ) # type: ignore
+
+ filter_glob: bpy.props.StringProperty(
+ default="*.dae",
+ options={'HIDDEN'},
+ ) # type: ignore
+
+ output_dir: bpy.props.StringProperty(
+ name="Output Directory",
+ description="Directory for exported .glb files (defaults to 'textured' subfolder)",
+ default="",
+ ) # type: ignore
+
+ recursive: bpy.props.BoolProperty(
+ name="Recursive",
+ description="Scan subdirectories recursively",
+ default=True,
+ ) # type: ignore
+
+ ref_image_dir: bpy.props.StringProperty(
+ name="Reference Images",
+ description=(
+ "Directory with reference images matching the model tree structure. "
+ "Images whose filename contains the building number are auto-matched. "
+ "Leave empty to use ref.png fallbacks only"
+ ),
+ default="",
+ ) # type: ignore
+
+ bake: bpy.props.BoolProperty(
+ name="Bake Textures",
+ description="Bake projected textures into an image texture before export",
+ default=True,
+ ) # type: ignore
+
+ bake_resolution: bpy.props.IntProperty(
+ name="Bake Resolution",
+ description="Resolution for baked texture images",
+ default=2048,
+ min=512,
+ max=8192,
+ ) # type: ignore
+
+ # ── Import / cleanup settings (same as BatchImportDAE) ──
+
+ merge_threshold: bpy.props.FloatProperty(
+ name="Merge Distance", default=0.001,
+ min=0.0, max=0.1, precision=4, unit='LENGTH',
+ ) # type: ignore
+
+ remove_interior: bpy.props.BoolProperty(
+ name="Remove Interior Faces", default=True,
+ ) # type: ignore
+
+ remove_ground: bpy.props.BoolProperty(
+ name="Remove Ground Plane",
+ description="Remove large horizontal faces at the bottom of the model (SketchUp ground planes)",
+ default=True,
+ ) # type: ignore
+
+ strip_materials: bpy.props.BoolProperty(
+ name="Replace Materials", default=True,
+ ) # type: ignore
+
+ triangulate: bpy.props.BoolProperty(
+ name="Triangulate", default=True,
+ ) # type: ignore
+
+ topology_method: bpy.props.EnumProperty(
+ name="Topology",
+ items=[
+ ('NONE', "None", "Keep original topology"),
+ ('FIX_FANS', "Fix Triangle Fans", "Fix fan patterns on flat surfaces"),
+ ('SUBDIVIDE_ONLY', "Subdivide Large Faces", "Subdivide faces above threshold"),
+ ('PLANAR_SUBDIVIDE', "Dissolve + Subdivide", "Merge coplanar then retriangulate"),
+ ('VOXEL', "Voxel Remesh", "Full remesh with uniform voxel size"),
+ ],
+ default='FIX_FANS',
+ ) # type: ignore
+
+ edge_ratio: bpy.props.FloatProperty(
+ name="Edge Ratio", default=2.5, min=1.5, max=10.0, precision=1,
+ ) # type: ignore
+
+ equalize_iterations: bpy.props.IntProperty(
+ name="Equalize Passes", default=4, min=0, max=10,
+ ) # type: ignore
+
+ voxel_size: bpy.props.FloatProperty(
+ name="Voxel Size", default=0.0, min=0.0, max=1.0, precision=4, unit='LENGTH',
+ ) # type: ignore
+
+ auto_scale: bpy.props.FloatProperty(
+ name="Target Size (BU)", default=0.0, min=0.0, max=100.0,
+ description="Scale so largest dimension equals this value. 0 = keep original",
+ ) # type: ignore
+
+ shading_mode: bpy.props.EnumProperty(
+ name="Shading",
+ items=[
+ ('FLAT', "Flat", "Flat shading"),
+ ('SMOOTH', "Smooth", "Smooth shading"),
+ ('AUTO', "Auto Smooth", "Smooth with auto-smooth angle"),
+ ],
+ default='FLAT',
+ ) # type: ignore
+
+ center_origin: bpy.props.BoolProperty(
+ name="Center at Origin", default=True,
+ ) # type: ignore
+
+ @classmethod
+ def poll(cls, context):
+ if _batch_state['active']:
+ return False
+ if sg_modal_active(context):
+ return False
+ addon_prefs = context.preferences.addons.get('stablegen')
+ if addon_prefs:
+ prefs = addon_prefs.preferences
+ if not getattr(prefs, 'server_online', False):
+ cls.poll_message_set("ComfyUI server is not connected")
+ return False
+ return True
+
+ def invoke(self, context, event):
+ context.window_manager.fileselect_add(self)
+ return {'RUNNING_MODAL'}
+
+ def draw(self, context):
+ layout = self.layout
+
+ layout.label(text="Output", icon='EXPORT')
+ box = layout.box()
+ box.prop(self, "output_dir")
+ box.prop(self, "recursive")
+ box.prop(self, "ref_image_dir")
+ box.prop(self, "bake")
+ if self.bake:
+ box.prop(self, "bake_resolution")
+
+ layout.separator()
+ layout.label(text="Import Cleanup", icon='BRUSH_DATA')
+ box = layout.box()
+ box.prop(self, "merge_threshold")
+ box.prop(self, "remove_interior")
+ box.prop(self, "remove_ground")
+ box.prop(self, "strip_materials")
+ box.prop(self, "triangulate")
+
+ layout.separator()
+ layout.label(text="Topology", icon='MOD_REMESH')
+ box = layout.box()
+ box.prop(self, "topology_method")
+ if self.topology_method == 'FIX_FANS':
+ box.prop(self, "edge_ratio")
+ box.prop(self, "equalize_iterations")
+ elif self.topology_method == 'VOXEL':
+ box.prop(self, "voxel_size")
+
+ layout.separator()
+ layout.label(text="Transform", icon='OBJECT_ORIGIN')
+ box = layout.box()
+ box.prop(self, "auto_scale")
+ box.prop(self, "shading_mode")
+ box.prop(self, "center_origin")
+
+ layout.separator()
+ layout.label(text="Camera & Texturing", icon='CAMERA_DATA')
+ box = layout.box()
+ box.label(text="Uses current scene generation settings")
+ box.label(text="Camera placement uses TRELLIS.2 camera settings")
+
+ def execute(self, context):
+ if not self.directory or not os.path.isdir(self.directory):
+ self.report({'ERROR'}, "No valid directory selected")
+ return {'CANCELLED'}
+
+ dae_files = self._collect_dae_files()
+ if not dae_files:
+ self.report({'WARNING'}, "No .dae files found")
+ return {'CANCELLED'}
+
+ out_dir = self.output_dir or os.path.join(
+ self.directory.rstrip('/\\'), "textured")
+ os.makedirs(out_dir, exist_ok=True)
+
+ scene = context.scene
+ _batch_state.update({
+ 'active': True,
+ 'cancelled': False,
+ 'files': dae_files,
+ 'index': -1,
+ 'total': len(dae_files),
+ 'top_dir': self.directory.rstrip('/\\'),
+ 'out_dir': out_dir,
+ 'phase': 'idle',
+ 'settle_count': 0,
+ 'settings': {
+ # Import settings
+ 'merge_threshold': self.merge_threshold,
+ 'remove_interior': self.remove_interior,
+ 'remove_ground': self.remove_ground,
+ 'strip_materials': self.strip_materials,
+ 'topology_method': self.topology_method,
+ 'edge_ratio': self.edge_ratio,
+ 'equalize_iterations': self.equalize_iterations,
+ 'voxel_size': self.voxel_size,
+ 'auto_scale': self.auto_scale,
+ 'shading_mode': self.shading_mode,
+ 'center_origin': self.center_origin,
+ 'triangulate': self.triangulate,
+ # Bake settings
+ 'bake': self.bake,
+ 'bake_resolution': self.bake_resolution,
+ # Reference image directory
+ 'ref_image_dir': self.ref_image_dir.rstrip('/\\') if self.ref_image_dir else '',
+ # Camera settings (read from current scene trellis2_* properties)
+ 'camera_count': getattr(scene, 'trellis2_camera_count', 8),
+ 'placement_mode': getattr(scene, 'trellis2_placement_mode', 'normal_weighted'),
+ 'auto_prompts': getattr(scene, 'trellis2_auto_prompts', True),
+ 'exclude_bottom': getattr(scene, 'trellis2_exclude_bottom', True),
+ 'exclude_bottom_angle': getattr(scene, 'trellis2_exclude_bottom_angle', 1.5533),
+ 'auto_aspect': getattr(scene, 'trellis2_auto_aspect', 'per_camera'),
+ 'occlusion_mode': getattr(scene, 'trellis2_occlusion_mode', 'none'),
+ 'consider_existing': getattr(scene, 'trellis2_consider_existing', True),
+ 'clamp_elevation': getattr(scene, 'trellis2_clamp_elevation', False),
+ 'max_elevation': getattr(scene, 'trellis2_max_elevation', 1.2217),
+ 'min_elevation': getattr(scene, 'trellis2_min_elevation', -0.1745),
+ 'coverage_target': getattr(scene, 'trellis2_coverage_target', 0.95),
+ 'max_auto_cameras': getattr(scene, 'trellis2_max_auto_cameras', 12),
+ 'fan_angle': getattr(scene, 'trellis2_fan_angle', 90.0),
+ },
+ })
+ _sync_wm()
+
+ self.report({'INFO'}, f"Batch texturing started: {len(dae_files)} file(s)")
+ print(f"[BatchTex] Starting: {len(dae_files)} file(s) from '{self.directory}'")
+ bpy.app.timers.register(_batch_tex_tick, first_interval=0.1)
+ return {'FINISHED'}
+
+ def _collect_dae_files(self):
+ root = self.directory.rstrip('/\\')
+ results = []
+ if self.recursive:
+ for dirpath, _dirs, files in os.walk(root):
+ for f in sorted(files):
+ if f.lower().endswith('.dae'):
+ abs_path = os.path.join(dirpath, f)
+ rel_path = os.path.relpath(abs_path, root)
+ results.append((abs_path, rel_path))
+ else:
+ for f in sorted(os.listdir(root)):
+ if f.lower().endswith('.dae'):
+ results.append((os.path.join(root, f), f))
+ return results
+
+
+class BatchTextureDAECancel(bpy.types.Operator):
+ """Cancel the running batch texture pipeline."""
+
+ bl_idname = "stablegen.batch_texture_dae_cancel"
+ bl_label = "Cancel Batch Texture"
+ bl_options = {'REGISTER'}
+
+ @classmethod
+ def poll(cls, context):
+ return _batch_state['active']
+
+ def execute(self, context):
+ _batch_state['cancelled'] = True
+ self.report({'WARNING'}, "Batch texturing cancelling after current model...")
+ return {'FINISHED'}
+
+
+BATCH_TEXTURE_CLASSES = [
+ BatchTextureDAE,
+ BatchTextureDAECancel,
+]
+
+
+def unregister_batch_texture():
+ """Stop any running batch texture timer. Called from addon unregister."""
+ _batch_state['cancelled'] = True
+ _batch_state['active'] = False
+ try:
+ if bpy.app.timers.is_registered(_batch_tex_tick):
+ bpy.app.timers.unregister(_batch_tex_tick)
+ except Exception: # noqa: BLE001
+ pass
diff --git a/stablegen/debug_tools.py b/stablegen/debug_tools.py
index 3af8d0c..fc7b62e 100644
--- a/stablegen/debug_tools.py
+++ b/stablegen/debug_tools.py
@@ -828,6 +828,248 @@ class SG_OT_DebugRestoreMaterial(bpy.types.Operator):
return {'FINISHED'}
+# ═════════════════════════════════════════════════════════════════════════
+# 9. Debug Make Solid
+# ═════════════════════════════════════════════════════════════════════════
+
+class SG_OT_DebugMakeSolid(bpy.types.Operator):
+ """Run the cylinder-based raycast solidification and hole-filling algorithm
+ in-place on the active mesh object. Requires the 'SG_PrintPreview' color attribute."""
+ bl_idname = "stablegen.debug_make_solid"
+ bl_label = "Debug Make Solid"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ fill_gaps: bpy.props.BoolProperty(
+ name="Fill Gaps",
+ description="Run boundary loop tracing and hole filling",
+ default=True,
+ )
+
+ @classmethod
+ def poll(cls, context):
+ prefs = context.preferences.addons.get(__package__)
+ if not prefs or not prefs.preferences.enable_debug:
+ return False
+ if sg_modal_active(context):
+ return False
+ return context.active_object and context.active_object.type == 'MESH'
+
+ def invoke(self, context, event):
+ return context.window_manager.invoke_props_dialog(self)
+
+ def execute(self, context):
+ from .texturing.print_export import (
+ _make_solid_mesh_object,
+ _match_colors_hsv,
+ _smooth_colors_vectorized,
+ linear_to_srgb_numpy,
+ srgb_to_linear_numpy,
+ classify_filaments,
+ decompose_subtractive,
+ solve_color_mixing_numpy,
+ )
+
+ obj = context.active_object
+ if not obj or obj.type != 'MESH':
+ self.report({'ERROR'}, "No active mesh object.")
+ return {'CANCELLED'}
+
+ if not obj.data.color_attributes.get("SG_PrintPreview"):
+ self.report({'ERROR'}, "Make Solid requires the 'SG_PrintPreview' color layer. Run 'Preview Colors' first.")
+ return {'CANCELLED'}
+
+ # Calculate cylinder bounds for visualization using current mesh
+ mesh = obj.data
+ verts_co = np.empty(len(mesh.vertices) * 3, dtype=np.float32)
+ mesh.vertices.foreach_get("co", verts_co)
+ verts_co = verts_co.reshape((-1, 3))
+
+ xmin, ymin, zmin = verts_co.min(axis=0)
+ xmax, ymax, zmax = verts_co.max(axis=0)
+
+ cx = (xmin + xmax) * 0.5
+ cy = (ymin + ymax) * 0.5
+ radius = max(xmax - xmin, ymax - ymin) * 0.5 * 1.25
+ z_top = zmax + (zmax - zmin) * 0.25
+ z_bottom = zmin
+ depth = z_top - z_bottom
+ z_center = (z_top + z_bottom) * 0.5
+
+ try:
+ # Delete any existing debug cylinder first
+ existing_cyl = context.scene.objects.get("SG_Debug_Solid_Cylinder")
+ if existing_cyl:
+ bpy.data.objects.remove(existing_cyl, do_unlink=True)
+
+ # Create cylinder visualization
+ bpy.ops.mesh.primitive_cylinder_add(
+ vertices=32,
+ radius=radius,
+ depth=depth,
+ location=(cx, cy, z_center),
+ end_fill_type='NOTHING'
+ )
+ cyl_obj = context.active_object
+ cyl_obj.name = "SG_Debug_Solid_Cylinder"
+ cyl_obj.display_type = 'WIRE'
+
+ # Restore selection to the original object
+ bpy.ops.object.select_all(action='DESELECT')
+ obj.select_set(True)
+ context.view_layer.objects.active = obj
+
+ solid_mesh = _make_solid_mesh_object(obj, fill_gaps=self.fill_gaps)
+
+ # Replace the mesh of the object
+ old_mesh = obj.data
+ obj.data = solid_mesh
+
+ # Remove the old mesh from memory
+ bpy.data.meshes.remove(old_mesh)
+
+ # ── Re-run the export color pipeline so the viewport shows exactly ──
+ # ── what filament/color the 3MF exporter will assign to each tri. ──
+ scene = context.scene
+ palette_rgbs_linear = np.array([item.color for item in scene.stablegen_print_palette], dtype=np.float32)
+ palette_rgbs = [tuple(c) for c in linear_to_srgb_numpy(palette_rgbs_linear)]
+
+ color_layer = solid_mesh.color_attributes.get("SG_PrintPreview")
+ if palette_rgbs and color_layer:
+ solid_mesh.calc_loop_triangles()
+
+ n_loops = len(solid_mesh.loops)
+ loop_colors = np.empty(n_loops * 4, dtype=np.float32)
+ color_layer.data.foreach_get("color", loop_colors)
+ loop_colors = loop_colors.reshape((-1, 4))
+
+ n_tris = len(solid_mesh.loop_triangles)
+ tri_loops = np.empty(n_tris * 3, dtype=np.int32)
+ solid_mesh.loop_triangles.foreach_get("loops", tri_loops)
+ tri_loops = tri_loops.reshape((-1, 3))
+
+ face_colors_rgb = loop_colors[tri_loops].mean(axis=1)[:, :3]
+ if color_layer.data_type == 'BYTE_COLOR':
+ face_colors_rgb = srgb_to_linear_numpy(face_colors_rgb)
+
+ # Convert linear face colors to sRGB for matching/mixing
+ face_colors_srgb = linear_to_srgb_numpy(face_colors_rgb)
+
+ is_dithered = getattr(scene, "stablegen_print_dithered", True)
+ if is_dithered:
+ mode, channel_indices = classify_filaments(palette_rgbs)
+ if mode == 'solid':
+ fil_rgbs = np.array(palette_rgbs, dtype=np.float32)
+ demands = solve_color_mixing_numpy(fil_rgbs, face_colors_srgb)
+
+ # Reconstruct mixed color using the chosen mixing model
+ model_formula = getattr(scene, "stablegen_print_solver_formula", 'KUBELKA_MUNK')
+ if model_formula == 'KUBELKA_MUNK':
+ scat_weight = getattr(scene, "stablegen_print_scattering_weight", 10.0)
+ fil_val = fil_rgbs.max(axis=1)
+ fil_min = fil_rgbs.min(axis=1)
+ fil_sat = np.zeros_like(fil_val)
+ mask = fil_val > 1e-5
+ fil_sat[mask] = (fil_val[mask] - fil_min[mask]) / fil_val[mask]
+ S_fil = 1.0 + scat_weight * (1.0 - fil_sat) * fil_val
+ S_fil = S_fil[:, None]
+ R_clip = np.clip(fil_rgbs, 0.001, 0.999)
+ K_fil = S_fil * ((1.0 - R_clip)**2) / (2.0 * R_clip)
+
+ K_mix = np.dot(demands, K_fil)
+ S_mix = np.dot(demands, S_fil)
+ ratio = K_mix / S_mix
+ mixed_srgb = 1.0 + ratio - np.sqrt(ratio**2 + 2.0 * ratio)
+ elif model_formula == 'ADDITIVE':
+ mixed_srgb = np.dot(demands, fil_rgbs)
+ else: # SUBTRACTIVE
+ mixed_srgb = 1.0 - np.dot(demands, 1.0 - fil_rgbs)
+ else:
+ mixed_srgb = np.empty_like(face_colors_srgb)
+ fil_rgbs = np.array([palette_rgbs[idx] for idx in channel_indices], dtype=np.float32)
+ for i in range(len(face_colors_srgb)):
+ r, g, b = face_colors_srgb[i] * 255.0
+ fractions = decompose_subtractive(r, g, b, mode, palette_rgbs, channel_indices)
+ mixed_srgb[i] = np.clip(1.0 - sum(fractions[j] * (1.0 - fil_rgbs[j]) for j in range(len(fractions))), 0.0, 1.0)
+
+ mapped_colors = srgb_to_linear_numpy(mixed_srgb)
+ else:
+ # Solid Mode Quantization
+ palette_arr = np.array(palette_rgbs, dtype=np.float32)
+ chroma_threshold = getattr(scene, "stablegen_print_chroma_threshold", 0.35)
+ material_indices = _match_colors_hsv(face_colors_srgb, palette_rgbs, chroma_threshold=chroma_threshold)
+
+ smoothing_passes = getattr(scene, "stablegen_print_smoothing", 2)
+ if smoothing_passes > 0:
+ tri_verts = np.empty(n_tris * 3, dtype=np.int32)
+ solid_mesh.loop_triangles.foreach_get("vertices", tri_verts)
+ tri_verts = tri_verts.reshape((-1, 3))
+ material_indices = _smooth_colors_vectorized(
+ tri_verts, material_indices + 1,
+ len(solid_mesh.vertices), len(palette_rgbs),
+ iterations=smoothing_passes
+ ) - 1
+
+ mapped_srgb = palette_arr[material_indices]
+ mapped_colors = srgb_to_linear_numpy(mapped_srgb)
+
+ # Map quantized colors and write back into SG_PrintPreview
+ if color_layer.data_type != 'FLOAT_COLOR':
+ solid_mesh.color_attributes.remove(color_layer)
+ color_layer = solid_mesh.color_attributes.new(
+ name="SG_PrintPreview",
+ type='FLOAT_COLOR',
+ domain='CORNER',
+ )
+
+ mapped_rgba = np.ones((n_tris, 4), dtype=np.float32)
+ mapped_rgba[:, :3] = mapped_colors
+
+ all_loop_colors = np.ones((n_loops, 4), dtype=np.float32)
+ all_loop_colors[tri_loops[:, 0]] = mapped_rgba
+ all_loop_colors[tri_loops[:, 1]] = mapped_rgba
+ all_loop_colors[tri_loops[:, 2]] = mapped_rgba
+ color_layer.data.foreach_set("color", all_loop_colors.ravel())
+
+ # Switch viewport shading to show the updated color attribute
+ for area in context.screen.areas:
+ if area.type == 'VIEW_3D':
+ for space in area.spaces:
+ if space.type == 'VIEW_3D':
+ try:
+ space.shading.type = 'SOLID'
+ space.shading.color_type = 'VERTEX'
+ try:
+ space.shading.light = 'FLAT'
+ except Exception:
+ pass
+ solid_mesh.color_attributes.active = color_layer
+ if hasattr(solid_mesh, "attributes"):
+ solid_mesh.attributes.active_color = color_layer
+ except TypeError:
+ try:
+ space.shading.type = 'SOLID'
+ space.shading.color_type = 'ATTRIBUTE'
+ space.shading.attribute_name = "SG_PrintPreview"
+ try:
+ space.shading.light = 'FLAT'
+ except Exception:
+ pass
+ except Exception:
+ pass
+ except Exception:
+ pass
+
+ print(f"[StableGen Debug] Export color preview: {n_tris} tris, {len(palette_rgbs)} palette colors.")
+
+ self.report({'INFO'}, f"Successfully solidified {obj.name} in-place. Viewport shows export color assignment.")
+ return {'FINISHED'}
+ except Exception as e:
+ self.report({'ERROR'}, f"Solidification failed: {e}")
+ import traceback
+ traceback.print_exc()
+ return {'CANCELLED'}
+
+
# ─── Registration list ───────────────────────────────────────────────────
debug_classes = [
@@ -839,4 +1081,5 @@ debug_classes = [
SG_OT_DebugFeatherPreview,
SG_OT_DebugUVSeamViz,
SG_OT_DebugRestoreMaterial,
+ SG_OT_DebugMakeSolid,
]
diff --git a/stablegen/mesh_gen/trellis2.py b/stablegen/mesh_gen/trellis2.py
index 2f2d057..4e52d63 100644
--- a/stablegen/mesh_gen/trellis2.py
+++ b/stablegen/mesh_gen/trellis2.py
@@ -199,10 +199,14 @@ class Trellis2Generate(bpy.types.Operator):
gen_dirs = get_generation_dirs(context)
revision_dir = gen_dirs.get("revision", "")
+ # Read parameters for background processing
+ decimate_method = getattr(scene, 'trellis2_decimate_method', 'server')
+ target_faces = getattr(scene, 'trellis2_decimation', 1000000)
+
# Start generation in background thread
self._thread = threading.Thread(
target=self._run_trellis2,
- args=(context, image_path, gen_from, revision_dir),
+ args=(context, image_path, gen_from, revision_dir, decimate_method, target_faces),
daemon=True
)
self._thread.start()
@@ -346,15 +350,49 @@ class Trellis2Generate(bpy.types.Operator):
# Import GLB into Blender
bpy.ops.import_scene.gltf(filepath=glb_path)
+ # --- Clean hierarchy, unparent meshes, and remove GLTF/GLB structural empties ---
+ imported_objects = [obj for obj in context.selected_objects]
+ mesh_objects = [obj for obj in imported_objects if obj.type == 'MESH']
+ empty_objects = [obj for obj in imported_objects if obj.type == 'EMPTY']
+
+ if mesh_objects:
+ # 1. Unparent meshes while preserving their world space transforms and clearing broken custom normals
+ for obj in mesh_objects:
+ # Save world matrix
+ world_mat = obj.matrix_world.copy()
+ # Set the object as active so the operator can work on it
+ bpy.context.view_layer.objects.active = obj
+ # Clear custom split normals using the official operator to fix broken custom normals & convex shadowing artifacts
+ try:
+ bpy.ops.mesh.customdata_custom_splitnormals_clear()
+ except Exception as err:
+ print(f"[TRELLIS2] Warning: Could not clear custom normals on {obj.name}: {err}")
+ # Unparent
+ obj.parent = None
+ # Restore world matrix
+ obj.matrix_world = world_mat
+
+ # 2. Delete the structural empties (e.g. "world", "geometry_0")
+ if empty_objects:
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in empty_objects:
+ obj.select_set(True)
+ bpy.ops.object.delete()
+ print(f"[TRELLIS2] Cleaned up {len(empty_objects)} GLB parent empty objects")
+
+ # 3. Reselect only the imported mesh objects for downstream processing
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in mesh_objects:
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = mesh_objects[0]
+
# --- Normalise imported mesh to a reasonable Blender-unit size ---
target_bu = getattr(context.scene, 'trellis2_import_scale', 2.0)
if target_bu > 0:
- imported_objects = [obj for obj in context.selected_objects]
- if imported_objects:
- # Compute combined world-space bounding box across all
- # imported objects (meshes, empties, armatures …).
+ imported_meshes = [obj for obj in context.selected_objects if obj.type == 'MESH']
+ if imported_meshes:
all_corners = []
- for obj in imported_objects:
+ for obj in imported_meshes:
for corner in obj.bound_box:
all_corners.append(obj.matrix_world @ mathutils.Vector(corner))
if all_corners:
@@ -368,24 +406,84 @@ class Trellis2Generate(bpy.types.Operator):
)
if extent > 1e-6:
scale_factor = target_bu / extent
- # Find the root objects (those without an imported parent)
- roots = [o for o in imported_objects if o.parent not in imported_objects]
- for root in roots:
- root.scale *= scale_factor
+ for obj in imported_meshes:
+ obj.scale *= scale_factor
# Apply scale so downstream code sees unit scale
bpy.ops.object.select_all(action='DESELECT')
- for obj in imported_objects:
+ for obj in imported_meshes:
obj.select_set(True)
- bpy.context.view_layer.objects.active = imported_objects[0]
+ bpy.context.view_layer.objects.active = imported_meshes[0]
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
print(f"[TRELLIS2] Scaled mesh to {target_bu} BU (factor {scale_factor:.4f})")
+ # --- Solidification ---
+ solidify_mesh = getattr(context.scene, 'trellis2_solidify', False)
+ if solidify_mesh:
+ from ..texturing.print_export import _make_solid_mesh_object
+ imported_meshes = [obj for obj in context.selected_objects if obj.type == 'MESH']
+ for obj in imported_meshes:
+ try:
+ print(f"[TRELLIS2] Solidifying mesh: {obj.name} before decimation/retopology...")
+ solid_mesh = _make_solid_mesh_object(obj)
+ old_mesh = obj.data
+ obj.data = solid_mesh
+ bpy.data.meshes.remove(old_mesh)
+ print(f"[TRELLIS2] Solidified mesh: {obj.name} successfully")
+ except Exception as e:
+ print(f"[TRELLIS2] Error solidifying mesh {obj.name}: {e}")
+
+ # --- Local Decimation & Retopology ---
+ decimate_method = getattr(context.scene, 'trellis2_decimate_method', 'server')
+
+ remesh_method = getattr(context.scene, 'trellis2_remesh_method', 'qdc')
+
+ imported_meshes = [obj for obj in context.selected_objects if obj.type == 'MESH']
+ if imported_meshes:
+ # 1. Fallback decimation on main thread if background decimation was requested but didn't run
+ if decimate_method == 'collapse' and not getattr(self, '_trimesh_decimated', False):
+ import trimesh
+ import numpy as np
+ import bmesh
+
+ target_faces = context.scene.trellis2_decimation
+ for obj in imported_meshes:
+ mesh = obj.data
+ vertices = np.empty(len(mesh.vertices) * 3, dtype=np.float32)
+ mesh.vertices.foreach_get("co", vertices)
+ vertices = vertices.reshape((-1, 3))
+
+ bm = bmesh.new()
+ bm.from_mesh(mesh)
+ bmesh.ops.triangulate(bm, faces=bm.faces)
+
+ faces = np.empty(len(bm.faces) * 3, dtype=np.int32)
+ for i, face in enumerate(bm.faces):
+ faces[i*3 : (i+1)*3] = [v.index for v in face.verts]
+ bm.free()
+
+ t_mesh = trimesh.Trimesh(vertices=vertices, faces=faces.reshape((-1, 3)))
+ if len(t_mesh.faces) > target_faces:
+ print(f"[TRELLIS2] Main thread fallback trimesh decimation: {len(t_mesh.faces)} -> {target_faces}")
+ decimated = t_mesh.simplify_quadric_decimation(face_count=target_faces)
+ mesh.clear_geometry()
+ mesh.from_pydata(decimated.vertices, [], decimated.faces.tolist())
+ mesh.update()
+
+ # 2. Local remeshing retopology
+ if remesh_method == 'quadriflow':
+ self._perform_retopology(context, imported_meshes, remesh_method)
+
# --- Apply shading mode to imported meshes ---
_shade_mode = getattr(context.scene, 'trellis2_shade_mode', 'flat')
if _shade_mode == 'smooth':
bpy.ops.object.shade_smooth()
+ elif _shade_mode == 'flat':
+ bpy.ops.object.shade_flat()
elif _shade_mode == 'auto_smooth':
- bpy.ops.object.shade_auto_smooth()
+ if hasattr(bpy.ops.object, "shade_auto_smooth"):
+ bpy.ops.object.shade_auto_smooth()
+ else:
+ bpy.ops.object.shade_smooth()
# --- Optional studio lighting for native PBR textures ---
tex_mode = getattr(self, '_texture_mode', 'native')
@@ -492,6 +590,20 @@ class Trellis2Generate(bpy.types.Operator):
"""Create a three-point studio lighting setup around the imported mesh."""
return setup_studio_lighting(context, scale=import_scale)
+ def _perform_retopology(self, context, meshes, remesh_method):
+ """Perform high-quality local retopology on imported meshes.
+
+ Applies shrinkwrap projection to recover fine details from the high-poly source mesh.
+ """
+ def progress_cb(pct, status_text):
+ self._overall_stage = "Local Processing"
+ self._phase_stage = status_text
+ self._phase_progress = pct
+ self._current_phase = self._total_phases
+ self._update_overall()
+
+ perform_local_retopology(context, meshes, remesh_method, progress_cb=progress_cb)
+
def _schedule_texture_generation(self, context):
"""Defer texture generation via a timer so Blender can digest the new cameras.
@@ -586,7 +698,46 @@ class Trellis2Generate(bpy.types.Operator):
bpy.app.timers.register(_deferred_generate, first_interval=0.5)
bpy.app.timers.register(_pipeline_watcher, first_interval=2.0)
- def _run_trellis2(self, context, image_path, gen_from, revision_dir):
+ def _run_trimesh_decimation(self, glb_bytes, target_faces):
+ """Runs the trimesh decimation directly inside Blender's python (on the background thread)."""
+ import io
+ import trimesh
+
+ try:
+ print(f"[TRELLIS2] Starting trimesh decimation in Blender's python (target: {target_faces} faces)...")
+ # Load glb from bytes using an in-memory file-like object
+ glb_file = io.BytesIO(glb_bytes)
+ scene = trimesh.load(glb_file, file_type='glb')
+
+ if scene.is_empty:
+ print("[TRELLIS2] Scene is empty")
+ return None
+
+ simplified_any = False
+ for name, geom in list(scene.geometry.items()):
+ if isinstance(geom, trimesh.Trimesh):
+ orig_faces = len(geom.faces)
+ if orig_faces > target_faces:
+ print(f"[TRELLIS2] Simplifying {name} directly in Blender Python: {orig_faces} -> {target_faces} faces")
+ scene.geometry[name] = geom.simplify_quadric_decimation(face_count=target_faces)
+ simplified_any = True
+ else:
+ print(f"[TRELLIS2] Skipping {name}: already has {orig_faces} faces (target {target_faces})")
+
+ if simplified_any:
+ # Export to bytes
+ out_bytes = scene.export(file_type='glb')
+ return out_bytes
+ else:
+ return glb_bytes
+
+ except Exception as e:
+ print(f"[TRELLIS2] Error during trimesh decimation: {e}")
+ import traceback
+ traceback.print_exc()
+ raise e
+
+ def _run_trellis2(self, context, image_path, gen_from, revision_dir, decimate_method, target_faces):
"""Background thread: runs the TRELLIS.2 pipeline.
If *gen_from* is ``'prompt'`` the method first generates an input
@@ -754,10 +905,325 @@ class Trellis2Generate(bpy.types.Operator):
if isinstance(result, dict) and "error" in result:
self._error = result["error"]
else:
+ self._trimesh_decimated = False
+ if decimate_method == 'collapse':
+ self._detail_stage = "Decimating mesh via trimesh"
+ self._phase_stage = "Trimesh decimation"
+ self._phase_progress = 90
+ self._update_overall()
+
+ try:
+ decimated_bytes = self._run_trimesh_decimation(result, target_faces)
+ if decimated_bytes:
+ result = decimated_bytes
+ self._trimesh_decimated = True
+ print("[TRELLIS2] Background trimesh decimation completed successfully")
+ except Exception as dec_err:
+ print(f"[TRELLIS2] Background trimesh decimation failed: {dec_err}")
+ # Fallback: result is unmodified raw GLB
self._glb_data = result
except Exception as e:
if self._cancelled:
return # Swallow exceptions caused by cancel-time WS close
self._error = str(e)
- traceback.print_exc()
\ No newline at end of file
+ traceback.print_exc()
+
+
+# ---------------------------------------------------------------------------
+# Standalone Local Post-Processing & Retopology Utilities
+# ---------------------------------------------------------------------------
+
+def perform_local_retopology(context, meshes, remesh_method, progress_cb=None):
+ """Perform high-quality local retopology on meshes.
+
+ Applies shrinkwrap projection to recover fine details from the high-poly source mesh.
+ """
+ import tempfile
+ import subprocess
+ import math
+ import os
+ import traceback
+
+ print(f"[StableGen] Starting local retopology solver: remesh={remesh_method}")
+ wm = context.window_manager
+ wm.progress_begin(0, 100)
+
+ try:
+ for obj_idx, obj in enumerate(meshes):
+ if obj.type != 'MESH':
+ continue
+
+ def update_progress(pct, status_text):
+ base = (obj_idx / len(meshes)) * 100
+ span = (1 / len(meshes)) * 100
+ overall_pct = base + (pct / 100) * span
+
+ wm.progress_update(overall_pct)
+ context.workspace.status_text_set(f"StableGen [Local Retopo]: {status_text} ({int(overall_pct)}%)")
+
+ if progress_cb:
+ progress_cb(pct, status_text)
+
+ # Force Blender to redraw all panels and viewports immediately
+ try:
+ bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
+ except Exception:
+ pass
+
+ # 1. Duplicate original high-detail mesh as reference for shrinkwrap projection
+ update_progress(10, "Preserving high-detail reference...")
+ high_poly = obj.copy()
+ high_poly.data = obj.data.copy()
+ high_poly.name = f"{obj.name}_HighPoly_Reference"
+ context.collection.objects.link(high_poly)
+ high_poly.hide_set(True) # Hide reference mesh
+
+ # Set active and select the low-poly target mesh
+ bpy.ops.object.select_all(action='DESELECT')
+ obj.select_set(True)
+ context.view_layer.objects.active = obj
+
+ # 2. Solver Setup
+ target_faces = context.scene.trellis2_decimation
+
+
+ def run_quadriflow(faces_count):
+ if faces_count > 30000:
+ print(f"[StableGen] Capping Quadriflow target faces from {faces_count} to 30000 for stability")
+ faces_count = 30000
+ print(f"[StableGen] Running native C++ Quadriflow solver (target faces: {faces_count})")
+ res = {'CANCELLED'}
+ try:
+ res = bpy.ops.object.quadriflow_remesh(
+ target_faces=faces_count,
+ use_mesh_symmetry=False,
+ use_preserve_sharp=False,
+ use_preserve_boundary=False
+ )
+ except Exception as q_err:
+ print(f"[StableGen] Native Quadriflow custom call failed, retrying with simple signature: {q_err}")
+ res = bpy.ops.object.quadriflow_remesh(target_faces=faces_count)
+
+ if 'FINISHED' not in res:
+ raise RuntimeError(f"Quadriflow operator returned non-finished status: {res}")
+
+ def run_solver(faces_count):
+ if remesh_method == 'quadriflow':
+ run_quadriflow(faces_count)
+
+ # --- Local Remeshing Solver Stage ---
+ update_progress(50, f"Executing {remesh_method} retopology solver...")
+ try:
+ run_solver(target_faces)
+ except Exception as solve_err:
+ print(f"[StableGen] Solver failed directly on mesh: {solve_err}. Attempting high-resolution OpenVDB Voxel Repair healing...")
+
+ target_bu = getattr(context.scene, 'trellis2_import_scale', 2.0)
+ voxel_size = max(0.002, target_bu / 512.0)
+ print(f"[StableGen] Healing mesh with OpenVDB Voxel Remesh (size: {voxel_size:.4f})")
+
+ obj.data.remesh_voxel_size = voxel_size
+ res_vr = {'CANCELLED'}
+ try:
+ res_vr = bpy.ops.object.voxel_remesh()
+ except Exception as remesh_err:
+ print(f"[StableGen] OpenVDB Voxel Remesh healing failed: {remesh_err}")
+
+ # Retry solver on the healed mesh
+ print("[StableGen] Retrying solver execution on healed manifold mesh...")
+ try:
+ run_solver(target_faces)
+ except Exception as retry_err:
+ print(f"[StableGen] Solver failed even after voxel healing: {retry_err}")
+ if target_faces > 30000:
+ stable_target = 20000
+ print(f"[StableGen] Retrying with a mathematically stable target count of {stable_target} quads...")
+ try:
+ run_solver(stable_target)
+ except Exception as final_err:
+ print(f"[StableGen] Fatal: Solver failed even at stable target: {final_err}")
+ else:
+ print(f"[StableGen] Fatal: Solver execution failed: {retry_err}")
+
+ # 4. Detail Projection back from HighPoly_Reference via temporary SHRINKWRAP modifier
+ update_progress(80, "Projecting high-detail reference back...")
+ print("[StableGen] Snapping quad grid and projecting high-detail reference details back")
+ sw_mod = obj.modifiers.new(name="SG_Shrinkwrap", type='SHRINKWRAP')
+ sw_mod.target = high_poly
+ sw_mod.wrap_method = 'NEAREST_SURFACEPOINT'
+ sw_mod.wrap_mode = 'ON_SURFACE'
+
+ bpy.ops.object.select_all(action='DESELECT')
+ obj.select_set(True)
+ context.view_layer.objects.active = obj
+ try:
+ bpy.ops.object.modifier_apply(modifier=sw_mod.name)
+ except Exception as sw_err:
+ print(f"[StableGen] Warning: Detail projection shrinkwrap application failed: {sw_err}")
+
+ # 5. Clean up HighPoly_Reference duplicate mesh
+ update_progress(95, "Cleaning up reference assets...")
+ bpy.ops.object.select_all(action='DESELECT')
+ high_poly.select_set(True)
+ try:
+ bpy.ops.object.delete()
+ print(f"[StableGen] Retopology completed successfully for object: {obj.name}")
+ except Exception as del_err:
+ print(f"[StableGen] Warning: Could not delete high-poly reference: {del_err}")
+
+ # Reselect the final low-poly mesh
+ bpy.ops.object.select_all(action='DESELECT')
+ obj.select_set(True)
+ context.view_layer.objects.active = obj
+ update_progress(100, "Local retopology completed!")
+
+ finally:
+ wm.progress_end()
+ context.workspace.status_text_set(None)
+
+
+class StableGenLocalPostProcess(bpy.types.Operator):
+ """Run local post-processing (decimation and/or retopology) on the active mesh"""
+ bl_idname = "object.stablegen_local_postprocess"
+ bl_label = "Run Local Post-Processing"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ @classmethod
+ def poll(cls, context):
+ return context.active_object and context.active_object.type == 'MESH'
+
+ def execute(self, context):
+ scene = context.scene
+ decimate_method = getattr(scene, 'trellis2_decimate_method', 'server')
+ remesh_method = getattr(scene, 'trellis2_remesh_method', 'qdc')
+ solidify = getattr(scene, 'trellis2_solidify', False)
+
+ # 1. Check if all post-processing options are disabled/none
+ if decimate_method == 'none' and remesh_method == 'none' and not solidify:
+ self.report({'WARNING'}, "No local post-processing is enabled (Decimation, Retopology, and Solidification are all disabled/set to None).")
+ return {'CANCELLED'}
+
+ # 2. Error if set to server-side post-processing
+ if decimate_method == 'server' or remesh_method == 'qdc':
+ self.report({'ERROR'}, "Server-side processing cannot be run locally. Please select a local decimation/remesh method.")
+ return {'CANCELLED'}
+
+ obj = context.active_object
+ if not obj or obj.type != 'MESH':
+ self.report({'ERROR'}, "No active mesh object.")
+ return {'CANCELLED'}
+
+ target_faces = scene.trellis2_decimation
+ do_decimate = (decimate_method == 'collapse')
+
+ print(f"[StableGen] Running manual local post-processing on {obj.name}: decimate={decimate_method}, remesh={remesh_method}, solidify={solidify}, target={target_faces}")
+
+ # Switch to object mode
+ if obj.mode != 'OBJECT':
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+ # 3. Run solidification locally on the main thread first if enabled
+ if solidify:
+ from ..texturing.print_export import _make_solid_mesh_object
+ try:
+ print(f"[StableGen] Solidifying active mesh: {obj.name}...")
+ solid_mesh = _make_solid_mesh_object(obj)
+ old_mesh = obj.data
+ obj.data = solid_mesh
+ bpy.data.meshes.remove(old_mesh)
+ print(f"[StableGen] Solidification completed for {obj.name}")
+ except Exception as e:
+ self.report({'ERROR'}, f"Failed to solidify mesh: {e}")
+ return {'CANCELLED'}
+
+
+ # If we need local decimation, run it asynchronously
+ if do_decimate:
+ import numpy as np
+ import bmesh
+
+ print(f"[StableGen] Starting async trimesh decimation for {obj.name}...")
+
+ # Extract mesh data on main thread
+ mesh = obj.data
+ vertices = np.empty(len(mesh.vertices) * 3, dtype=np.float32)
+ mesh.vertices.foreach_get("co", vertices)
+ vertices = vertices.reshape((-1, 3))
+
+ bm = bmesh.new()
+ bm.from_mesh(mesh)
+ bmesh.ops.triangulate(bm, faces=bm.faces)
+
+ faces = np.empty(len(bm.faces) * 3, dtype=np.int32)
+ for i, face in enumerate(bm.faces):
+ faces[i*3 : (i+1)*3] = [v.index for v in face.verts]
+ bm.free()
+
+ faces = faces.reshape((-1, 3))
+
+ # Define worker and callback
+ def bg_decimate_work():
+ import trimesh
+ t_mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
+ orig_faces = len(t_mesh.faces)
+ if orig_faces > target_faces:
+ decimated = t_mesh.simplify_quadric_decimation(face_count=target_faces)
+ return {
+ "vertices": decimated.vertices.tolist(),
+ "faces": decimated.faces.tolist(),
+ "success": True
+ }
+ return {"success": False}
+
+ def on_decimate_done(result):
+ if not result:
+ print("[StableGen] Async decimation failed or was aborted.")
+ return
+
+ # Check if object still exists
+ if not obj or obj.name not in bpy.context.scene.objects:
+ print("[StableGen] Active mesh object no longer exists.")
+ return
+
+ if result.get("success"):
+ mesh = obj.data
+ mesh.clear_geometry()
+ mesh.from_pydata(result["vertices"], [], result["faces"])
+ mesh.update()
+ print(f"[StableGen] Async decimation written back successfully.")
+ else:
+ print(f"[StableGen] Mesh already has fewer faces than target. Bypassed decimation.")
+
+ # Post-decimation stage (retopology)
+ try:
+ if remesh_method == 'quadriflow':
+ perform_local_retopology(bpy.context, [obj], remesh_method)
+ bpy.context.workspace.status_text_set(None)
+ # Trigger viewport redraw
+ for area in bpy.context.screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+ except Exception as post_err:
+ print(f"[StableGen] Error in post-decimation stage: {post_err}")
+
+ # Run async decimation
+ from ..core.state import _run_async
+ bpy.context.workspace.status_text_set("StableGen: Decimating mesh in background...")
+ _run_async(bg_decimate_work, on_decimate_done)
+ self.report({'INFO'}, "Trimesh decimation started in the background...")
+ return {'FINISHED'}
+
+ else:
+ # No background decimation needed, run retopology synchronously on main thread
+ try:
+ if remesh_method == 'quadriflow':
+ perform_local_retopology(context, [obj], remesh_method)
+
+ self.report({'INFO'}, "Local post-processing completed successfully!")
+ return {'FINISHED'}
+ except Exception as e:
+ self.report({'ERROR'}, f"Failed to run local post-processing: {e}")
+ import traceback
+ traceback.print_exc()
+ return {'CANCELLED'}
\ No newline at end of file
diff --git a/stablegen/mesh_gen/workflows.py b/stablegen/mesh_gen/workflows.py
index 53a0cca..4fe3701 100644
--- a/stablegen/mesh_gen/workflows.py
+++ b/stablegen/mesh_gen/workflows.py
@@ -223,6 +223,8 @@ class _Trellis2WorkflowMixin:
'get_conditioning': '4',
'image_to_shape': '5',
'shape_to_textured_mesh': '6',
+ 'process_mesh': '8',
+ 'rasterize_pbr': '9',
'export_glb': '7',
}
export_node_key = 'export_glb'
@@ -248,7 +250,7 @@ class _Trellis2WorkflowMixin:
prompt[NODES['get_conditioning']]["inputs"]["image"] = [NODES['input_image'], 0]
prompt[NODES['get_conditioning']]["inputs"]["mask"] = [NODES['input_image'], 1]
else:
- prompt[NODES['remove_bg']]["inputs"]["low_vram"] = False
+ prompt[NODES['remove_bg']]["inputs"]["low_vram"] = True
# Configure conditioning
prompt[NODES['get_conditioning']]["inputs"]["background_color"] = scene.trellis2_background_color
@@ -268,32 +270,56 @@ class _Trellis2WorkflowMixin:
# When post-processing is disabled, maximize the decimation target
# and disable remeshing so the user gets the rawest possible mesh.
use_pp = getattr(scene, 'trellis2_post_processing_enabled', True)
+ decimate_method = getattr(scene, 'trellis2_decimate_method', 'server')
+ remesh_method = getattr(scene, 'trellis2_remesh_method', 'qdc')
if skip_texture:
- # Configure simplify node
- if use_pp:
- prompt[NODES['simplify']]["inputs"]["target_face_count"] = scene.trellis2_decimation
- prompt[NODES['simplify']]["inputs"]["remesh"] = scene.trellis2_remesh
+ bypass_server_simplify = (not use_pp) or (remesh_method != 'qdc' and decimate_method != 'server')
+ if bypass_server_simplify:
+ # Bypass simplify node entirely: connect export directly to shape generation
+ prompt[NODES['export_trimesh']]["inputs"]["trimesh"] = [NODES['image_to_shape'], 0]
+ # Remove the simplify node from the prompt
+ simplify_id = NODES.get('simplify')
+ if simplify_id and simplify_id in prompt:
+ del prompt[simplify_id]
else:
- # Raw mesh — max faces, no remesh
- prompt[NODES['simplify']]["inputs"]["target_face_count"] = 5000000
- prompt[NODES['simplify']]["inputs"]["remesh"] = False
- prompt[NODES['simplify']]["inputs"]["fill_holes"] = False
+ # Post-processing is enabled and uses server-side QDC or decimation
+ if remesh_method == 'qdc':
+ # Server QDC handles both decimation and remeshing
+ prompt[NODES['simplify']]["inputs"]["target_face_count"] = scene.trellis2_decimation
+ prompt[NODES['simplify']]["inputs"]["remesh"] = True
+ elif decimate_method == 'server':
+ # Server decimation only (no server remesh)
+ prompt[NODES['simplify']]["inputs"]["target_face_count"] = scene.trellis2_decimation
+ prompt[NODES['simplify']]["inputs"]["remesh"] = False
+ prompt[NODES['simplify']]["inputs"]["fill_holes"] = False
prompt[NODES['export_trimesh']]["inputs"]["filename_prefix"] = unique_prefix
else:
# Configure texture generation
prompt[NODES['shape_to_textured_mesh']]["inputs"]["seed"] = seed
prompt[NODES['shape_to_textured_mesh']]["inputs"]["tex_guidance_strength"] = scene.trellis2_tex_guidance
prompt[NODES['shape_to_textured_mesh']]["inputs"]["tex_sampling_steps"] = scene.trellis2_tex_steps
-
- # Configure GLB export
- if use_pp:
- prompt[NODES['export_glb']]["inputs"]["decimation_target"] = scene.trellis2_decimation
- prompt[NODES['export_glb']]["inputs"]["remesh"] = scene.trellis2_remesh
+
+ # Configure GLB export via process/rasterize/export pipeline
+ decimate_method = getattr(scene, 'trellis2_decimate_method', 'server')
+ remesh_method = getattr(scene, 'trellis2_remesh_method', 'qdc')
+
+ bypass_server_process = (not use_pp) or (remesh_method != 'qdc' and decimate_method != 'server')
+ if bypass_server_process:
+ # Local decimation and/or local remeshing, or post-processing disabled: bypass server process_mesh entirely
+ prompt[NODES['rasterize_pbr']]["inputs"]["trimesh"] = [NODES['image_to_shape'], 0]
+ process_id = NODES.get('process_mesh')
+ if process_id and process_id in prompt:
+ del prompt[process_id]
else:
- prompt[NODES['export_glb']]["inputs"]["decimation_target"] = 5000000
- prompt[NODES['export_glb']]["inputs"]["remesh"] = False
- prompt[NODES['export_glb']]["inputs"]["texture_size"] = scene.trellis2_texture_size
+ if remesh_method == 'qdc':
+ prompt[NODES['process_mesh']]["inputs"]["target_face_count"] = scene.trellis2_decimation
+ prompt[NODES['process_mesh']]["inputs"]["remesh"] = "on"
+ elif decimate_method == 'server':
+ prompt[NODES['process_mesh']]["inputs"]["target_face_count"] = scene.trellis2_decimation
+ prompt[NODES['process_mesh']]["inputs"]["remesh"] = "off"
+
+ prompt[NODES['rasterize_pbr']]["inputs"]["texture_size"] = scene.trellis2_texture_size
prompt[NODES['export_glb']]["inputs"]["filename_prefix"] = unique_prefix
# Save prompt for debugging
@@ -331,27 +357,29 @@ class _Trellis2WorkflowMixin:
# Weights approximate actual time spent per node
if skip_texture:
NODE_PROGRESS = {
- NODES['input_image']: 2,
- NODES['load_models']: 3,
- NODES['get_conditioning']: 25,
- NODES['image_to_shape']: 80,
- NODES['simplify']: 90,
- NODES['export_trimesh']: 98,
+ NODES['input_image']: 1,
+ NODES['load_models']: 2,
+ NODES['get_conditioning']: 8,
+ NODES['image_to_shape']: 10,
+ NODES['simplify']: 85,
+ NODES['export_trimesh']: 95,
}
if not skip_bg:
- NODE_PROGRESS[NODES['remove_bg']] = 12
+ NODE_PROGRESS[NODES['remove_bg']] = 5
else:
# Full textured pipeline (single submission)
NODE_PROGRESS = {
- NODES['input_image']: 2,
- NODES['load_models']: 3,
- NODES['get_conditioning']: 18,
- NODES['image_to_shape']: 55,
- NODES['shape_to_textured_mesh']: 85,
+ NODES['input_image']: 1,
+ NODES['load_models']: 2,
+ NODES['get_conditioning']: 8,
+ NODES['image_to_shape']: 10,
+ NODES['shape_to_textured_mesh']: 50,
+ NODES['process_mesh']: 85,
+ NODES['rasterize_pbr']: 92,
NODES['export_glb']: 98,
}
if not skip_bg:
- NODE_PROGRESS[NODES['remove_bg']] = 10
+ NODE_PROGRESS[NODES['remove_bg']] = 5
# Wait for execution to complete via WebSocket
# Also capture 'executed' events which may contain the output path
@@ -366,6 +394,8 @@ class _Trellis2WorkflowMixin:
'get_conditioning': 'Conditioning',
'image_to_shape': 'Generating Shape',
'shape_to_textured_mesh': 'Generating Texture',
+ 'process_mesh': 'Processing Mesh',
+ 'rasterize_pbr': 'Rasterizing PBR',
'simplify': 'Simplifying Mesh',
'export_trimesh': 'Exporting Mesh',
'export_glb': 'Exporting GLB',
@@ -378,12 +408,16 @@ class _Trellis2WorkflowMixin:
_ss_steps = scene.trellis2_ss_steps
_shape_steps = scene.trellis2_shape_steps
_tex_steps = getattr(scene, 'trellis2_tex_steps', 0)
+ _resolution = getattr(scene, 'trellis2_resolution', '1024_cascade')
+ _is_cascade = _resolution in ('1024_cascade', '1536_cascade')
_current_exec_node = None # node-key of the currently executing node
+ _current_exec_node_id = None # node-id of the currently executing node
# Track accumulated sub-phases within a node so we can
# compute a node-internal overall progress.
_sub_phase_idx = 0 # resets when the executing node changes
_sub_phase_count = 1 # how many sub-phases this node has
+ _prev_p_value = 0 # track previous step value to detect restarts
while True:
try:
@@ -427,22 +461,25 @@ class _Trellis2WorkflowMixin:
self.operator._phase_stage = f"TRELLIS.2: {node_label}"
# Update progress based on node weight
if node_id in NODE_PROGRESS:
- self.operator._phase_progress = NODE_PROGRESS[node_id]
+ self.operator._phase_progress = max(self.operator._phase_progress, NODE_PROGRESS[node_id])
if hasattr(self.operator, '_update_overall'):
self.operator._update_overall()
self.operator._detail_stage = node_label
self.operator._detail_progress = 0
- # Reset sub-phase tracking for the new node
- _current_exec_node = node_key
- _sub_phase_idx = 0
- if node_key == 'image_to_shape':
- # SS sampling + shape sampling = 2 sub-phases
- _sub_phase_count = 2
- elif node_key == 'shape_to_textured_mesh':
- _sub_phase_count = 1
- else:
- _sub_phase_count = 1
+ # Reset sub-phase tracking for the new node if not already transitioned
+ if node_id != _current_exec_node_id:
+ _current_exec_node = node_key
+ _current_exec_node_id = node_id
+ _sub_phase_idx = 0
+ _prev_p_value = 0
+ if node_key == 'image_to_shape':
+ # SS sampling + SLat base (+ SLat cascade if cascade resolution)
+ _sub_phase_count = 3 if _is_cascade else 2
+ elif node_key == 'shape_to_textured_mesh':
+ _sub_phase_count = 1
+ else:
+ _sub_phase_count = 1
elif message['type'] == 'executed':
# Capture output from export node (newer ComfyUI versions)
@@ -473,48 +510,101 @@ class _Trellis2WorkflowMixin:
# Within-node progress (sampler steps).
# TRELLIS.2 nodes may emit separate runs of progress
# events for each internal sampling phase. We detect
- # the sub-phase by matching ``max`` against known step
- # counts (SS, shape, texture).
+ # the sub-phase transition by checking if the progress
+ # value decreased (restarted), which works even when the
+ # step counts (max) of different sub-phases are identical.
p_data = message['data']
+ # Only process progress for the currently executing node to prevent
+ # stray progress events from corrupting our stateful sub-phase tracking.
+ p_node = p_data.get('node')
+ # If the progress event is for a new node, transition to it immediately.
+ # This prevents timing races where the 'executing' event is delayed.
+ if p_node and p_node != _current_exec_node_id and p_node in NODE_PROGRESS:
+ _current_exec_node_id = p_node
+ node_names = {v: k for k, v in NODES.items()}
+ _current_exec_node = node_names.get(p_node, p_node)
+ node_label = NODE_LABELS.get(_current_exec_node, _current_exec_node)
+ print(f"[TRELLIS2] Early transition to node {_current_exec_node} via progress event")
+ self.operator._phase_stage = f"TRELLIS.2: {node_label}"
+ self.operator._detail_stage = node_label
+ self.operator._detail_progress = 0
+
+ # Reset sub-phase tracking
+ _sub_phase_idx = 0
+ _prev_p_value = 0
+ if _current_exec_node == 'image_to_shape':
+ _sub_phase_count = 3 if _is_cascade else 2
+ else:
+ _sub_phase_count = 1
+
+ if p_node and p_node != _current_exec_node_id:
+ continue
+
p_value = p_data['value']
p_max = p_data['max']
+
+ # Filter out any progress updates that do not match the expected sampler steps.
+ # This eliminates high-level node progress (p_max=3) and stray tiled convolution tqdm progress (e.g. p_max=5 or p_max=37).
+ if _current_exec_node == 'image_to_shape':
+ if p_max not in (_ss_steps, _shape_steps):
+ continue
+ elif _current_exec_node == 'shape_to_textured_mesh':
+ if p_max != _tex_steps:
+ continue
+
step_progress = (p_value / p_max) * 100 if p_max else 0
+ # Detect sub-phase transition
+ if p_value < _prev_p_value:
+ _sub_phase_idx = min(_sub_phase_idx + 1, _sub_phase_count - 1)
+ print(f"[TRELLIS2] Sub-phase restart detected. Transitioning to sub-phase index {_sub_phase_idx}")
+ _prev_p_value = p_value
+
# ── Sub-phase identification ──
sub_label = ""
if _current_exec_node == 'image_to_shape':
- if p_max == _ss_steps:
+ if _sub_phase_idx == 0:
sub_label = "Sampling SS"
- # First sub-phase: reset index if we see it again
- if _sub_phase_idx == 0 or p_value == 1:
- _sub_phase_idx = 0
- elif p_max == _shape_steps:
- sub_label = "Sampling Shape SLat"
- if _sub_phase_idx < 1:
- _sub_phase_idx = 1
+ elif _sub_phase_idx == 1:
+ sub_label = "Sampling Shape SLat LR" if _is_cascade else "Sampling Shape SLat"
else:
- # Unknown max — show generic label
- sub_label = "Sampling"
+ sub_label = "Sampling Shape SLat HR"
elif _current_exec_node == 'shape_to_textured_mesh':
- if p_max == _tex_steps:
- sub_label = "Sampling Texture"
- else:
- sub_label = "Sampling"
+ sub_label = "Sampling Texture"
else:
sub_label = "Processing"
- # Compute node-internal overall progress accounting for sub-phases
- if _sub_phase_count > 1:
- node_overall = ((_sub_phase_idx + step_progress / 100.0)
- / _sub_phase_count) * 100.0
+ # Compute node-internal overall progress accounting for weighted sub-phases.
+ # SS sampling is very fast, SLat Base is medium, SLat Cascade is slow.
+ if _current_exec_node == 'image_to_shape':
+ sub_weights = [10, 40, 50] if _is_cascade else [15, 85]
else:
- node_overall = step_progress
+ sub_weights = [100]
+
+ idx = min(_sub_phase_idx, len(sub_weights) - 1)
+ completed_progress = sum(sub_weights[:idx])
+ current_weight = sub_weights[idx]
+ node_overall = completed_progress + (step_progress / 100.0) * current_weight
if step_progress != 0:
- self.operator._detail_progress = node_overall
+ self.operator._detail_progress = step_progress
self.operator._detail_stage = (
f"{sub_label}: Step {p_value}/{p_max}"
)
+ # Interpolate the overall phase progress dynamically based on node_overall
+ if _current_exec_node_id in NODE_PROGRESS:
+ base_pct = NODE_PROGRESS[_current_exec_node_id]
+ sorted_pcts = sorted(list(NODE_PROGRESS.values()))
+ try:
+ idx = sorted_pcts.index(base_pct)
+ next_pct = sorted_pcts[idx + 1] if idx + 1 < len(sorted_pcts) else 100
+ except (ValueError, IndexError):
+ next_pct = base_pct + 10 # fallback
+ span = next_pct - base_pct
+ new_phase_pct = base_pct + (node_overall / 100.0) * span
+ self.operator._phase_progress = max(self.operator._phase_progress, new_phase_pct)
+ if hasattr(self.operator, '_update_overall'):
+ self.operator._update_overall()
print(f"[TRELLIS2] {sub_label}: Step {p_value}/{p_max} ({step_progress:.0f}%)")
elif message['type'] == 'execution_error':
diff --git a/stablegen/texturing/print_export.py b/stablegen/texturing/print_export.py
new file mode 100644
index 0000000..50d32cc
--- /dev/null
+++ b/stablegen/texturing/print_export.py
@@ -0,0 +1,3092 @@
+"""Export operators for 3D printing (STL, 3MF with multi-color support).
+
+The 3MF exporter uses the baked texture to produce per-triangle material
+assignments for multi-color / multi-filament printing (OrcaSlicer-FullSpectrum
+and similar slicers). Colors are quantised via k-means clustering so that
+each face maps to one of *N* filament colours.
+"""
+
+import colorsys
+import math
+import os
+import random
+import zipfile
+import xml.etree.ElementTree as ET
+
+import bpy # pylint: disable=import-error
+from ..utils import get_dir_path, sg_modal_active
+from ..core import ADDON_PKG, get_addon_prefs
+
+NS_3MF = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
+NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02"
+NS_REL = "http://schemas.openxmlformats.org/package/2006/relationships"
+NS_CT = "http://schemas.openxmlformats.org/package/2006/content-types"
+
+
+# ── Palette Definition & Operators ───────────────────────────────────────
+
+class StableGenPaletteColor(bpy.types.PropertyGroup):
+ def _update_color(self, context):
+ from ..core.callbacks import update_palette_color
+ update_palette_color(self, context)
+
+ color: bpy.props.FloatVectorProperty(
+ name="Color",
+ subtype='COLOR',
+ size=3,
+ min=0.0, max=1.0,
+ default=(0.5, 0.5, 0.5),
+ description="Filament Color",
+ update=_update_color
+ )
+ name: bpy.props.StringProperty(
+ name="Name",
+ default="Filament"
+ )
+
+
+def prepopulate_palette(scene):
+ if not hasattr(scene, "stablegen_print_palette") or len(scene.stablegen_print_palette) > 0:
+ return
+
+ cyan = (0.0, 1.0, 1.0)
+ magenta = (1.0, 0.0, 1.0)
+ yellow = (1.0, 1.0, 0.0)
+ white = (1.0, 1.0, 1.0)
+
+ colors_info = [
+ ("Cyan", cyan),
+ ("Magenta", magenta),
+ ("Yellow", yellow),
+ ("White", white),
+ ]
+
+ for name, col in colors_info:
+ item = scene.stablegen_print_palette.add()
+ item.name = name
+ item.color = col
+
+
+def _find_closest_palette_color(color, palette_rgbs):
+ """Find the index of the closest color in the palette (Euclidean distance)."""
+ best_dist = float('inf')
+ best_idx = 0
+ for idx, p_color in enumerate(palette_rgbs):
+ dist = sum((color[j] - p_color[j]) ** 2 for j in range(3))
+ if dist < best_dist:
+ best_dist = dist
+ best_idx = idx
+ return best_idx
+
+
+class StableGenAddPaletteColor(bpy.types.Operator):
+ """Add a new filament color to the print palette."""
+ bl_idname = "stablegen.add_palette_color"
+ bl_label = "Add Color"
+ bl_options = {'UNDO'}
+
+ def execute(self, context):
+ scene = context.scene
+ item = scene.stablegen_print_palette.add()
+ item.color = (random.random(), random.random(), random.random())
+ item.name = f"Filament {len(scene.stablegen_print_palette)}"
+ scene.stablegen_print_palette_index = len(scene.stablegen_print_palette) - 1
+ scene.stablegen_print_preset = 'CUSTOM'
+ return {'FINISHED'}
+
+
+class StableGenRemovePaletteColor(bpy.types.Operator):
+ """Remove the selected filament color from the print palette."""
+ bl_idname = "stablegen.remove_palette_color"
+ bl_label = "Remove Color"
+ bl_options = {'UNDO'}
+
+ def execute(self, context):
+ scene = context.scene
+ idx = scene.stablegen_print_palette_index
+ if 0 <= idx < len(scene.stablegen_print_palette):
+ scene.stablegen_print_palette.remove(idx)
+ scene.stablegen_print_palette_index = max(0, idx - 1)
+ scene.stablegen_print_preset = 'CUSTOM'
+ return {'FINISHED'}
+
+
+class StableGenPreviewQuantization(bpy.types.Operator):
+ """Preview the quantized palette colors on the active mesh object."""
+ bl_idname = "object.stablegen_preview_quantization"
+ bl_label = "Preview Palette Colors"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ @classmethod
+ def poll(cls, context):
+ return context.active_object and context.active_object.type == 'MESH'
+
+ def execute(self, context):
+ obj = context.active_object
+ scene = context.scene
+
+ if not scene.stablegen_print_palette:
+ prepopulate_palette(scene)
+
+ import numpy as np
+ palette_rgbs_linear = np.array([item.color for item in scene.stablegen_print_palette], dtype=np.float32)
+ palette_rgbs = [tuple(c) for c in linear_to_srgb_numpy(palette_rgbs_linear)]
+ if not palette_rgbs:
+ self.report({'WARNING'}, "No colors defined in the print palette.")
+ return {'CANCELLED'}
+
+ image = _find_texture_image(obj)
+
+ # Get triangulated mesh temporarily to read UVs and map colors
+ temp, eval_obj = _get_triangulated_mesh(obj, apply_transforms=False)
+ try:
+ import numpy as np
+
+ # Collect face colors
+ if image:
+ face_colors = _collect_face_colors(temp, image)[:, :3]
+ else:
+ # If no image, check for a color layer other than SG_PrintPreview first
+ color_layer = None
+ for attr in temp.color_attributes:
+ if attr.name != "SG_PrintPreview":
+ color_layer = attr
+ break
+ if not color_layer:
+ color_layer = temp.color_attributes.get("SG_PrintPreview")
+
+ if color_layer:
+ n_loops = len(temp.loops)
+ loop_colors = np.empty(n_loops * 4, dtype=np.float32)
+ color_layer.data.foreach_get("color", loop_colors)
+ loop_colors = loop_colors.reshape((-1, 4))
+
+ n_tris = len(temp.loop_triangles)
+ tri_loops = np.empty(n_tris * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("loops", tri_loops)
+ tri_loops = tri_loops.reshape((-1, 3))
+
+ face_colors = loop_colors[tri_loops].mean(axis=1)[:, :3]
+ if color_layer.data_type == 'BYTE_COLOR':
+ face_colors = srgb_to_linear_numpy(face_colors)
+ else:
+ face_colors = np.ones((len(temp.loop_triangles), 3), dtype=np.float32)
+
+ face_colors_srgb = face_colors # texture already in srgb
+
+ if getattr(scene, "stablegen_print_dithered", True):
+ # Dithered Mode: compute physical mixed colors
+ mode, channel_indices = classify_filaments(palette_rgbs)
+ if mode == 'solid':
+ # Fallback: Frank-Wolfe general solver on all palette colors
+ fil_rgbs = np.array(palette_rgbs, dtype=np.float32)
+ demands = solve_color_mixing_numpy(fil_rgbs, face_colors_srgb)
+
+ # Reconstruct mixed color using the chosen mixing model
+ model_formula = getattr(scene, "stablegen_print_solver_formula", 'KUBELKA_MUNK')
+ if model_formula == 'KUBELKA_MUNK':
+ scat_weight = getattr(scene, "stablegen_print_scattering_weight", 10.0)
+ fil_val = fil_rgbs.max(axis=1)
+ fil_min = fil_rgbs.min(axis=1)
+ fil_sat = np.zeros_like(fil_val)
+ mask = fil_val > 1e-5
+ fil_sat[mask] = (fil_val[mask] - fil_min[mask]) / fil_val[mask]
+ S_fil = 1.0 + scat_weight * (1.0 - fil_sat) * fil_val
+ S_fil = S_fil[:, None]
+ R_clip = np.clip(fil_rgbs, 0.001, 0.999)
+ K_fil = S_fil * ((1.0 - R_clip)**2) / (2.0 * R_clip)
+
+ K_mix = np.dot(demands, K_fil)
+ S_mix = np.dot(demands, S_fil)
+ ratio = K_mix / S_mix
+ mixed_srgb = 1.0 + ratio - np.sqrt(ratio**2 + 2.0 * ratio)
+ elif model_formula == 'ADDITIVE':
+ mixed_srgb = np.dot(demands, fil_rgbs)
+ else: # SUBTRACTIVE
+ mixed_srgb = 1.0 - np.dot(demands, 1.0 - fil_rgbs)
+ else:
+ # standard dithered subtractive formula
+ mixed_srgb = np.empty_like(face_colors_srgb)
+ fil_rgbs = np.array([palette_rgbs[idx] for idx in channel_indices], dtype=np.float32)
+ for i in range(len(face_colors_srgb)):
+ r, g, b = face_colors_srgb[i] * 255.0
+ fractions = decompose_subtractive(r, g, b, mode, palette_rgbs, channel_indices)
+ mixed_srgb[i] = np.clip(1.0 - sum(fractions[j] * (1.0 - fil_rgbs[j]) for j in range(len(fractions))), 0.0, 1.0)
+
+ # Convert the sRGB mixed colors back to linear for Blender color attribute
+ mapped_colors = srgb_to_linear_numpy(mixed_srgb)
+ else:
+ # Solid Mode: match to the closest physical filament in the palette
+ palette_arr = np.array(palette_rgbs, dtype=np.float32) # (K, 3)
+
+ # Vectorized closest color matching
+ best_idx = _match_colors_hsv(
+ face_colors_srgb, palette_rgbs,
+ chroma_threshold=getattr(scene, "stablegen_print_chroma_threshold", 0.35)
+ )
+
+ # Apply majority-vote smoothing (island cleanup)
+ smoothing_passes = getattr(scene, "stablegen_print_smoothing", 2)
+ if smoothing_passes > 0:
+ n_tris = len(temp.loop_triangles)
+ tri_verts = np.empty(n_tris * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("vertices", tri_verts)
+ tri_verts = tri_verts.reshape((-1, 3))
+
+ best_idx_smoothed = _smooth_colors_vectorized(
+ tri_verts, best_idx + 1, len(temp.vertices), len(palette_rgbs), iterations=smoothing_passes
+ )
+ best_idx = best_idx_smoothed - 1
+
+ mapped_srgb = palette_arr[best_idx] # (N, 3)
+ mapped_colors = srgb_to_linear_numpy(mapped_srgb)
+
+ finally:
+ eval_obj.to_mesh_clear()
+
+ # Debug logging to inspect mapped color ranges
+ if len(mapped_colors) > 0:
+ print(f"[StableGen Preview Debug] mode={mode if getattr(scene, 'stablegen_print_dithered', True) else 'solid'}")
+ print(f" palette_rgbs={palette_rgbs}")
+ print(f" mapped_colors min={mapped_colors.min(axis=0)}, max={mapped_colors.max(axis=0)}, mean={mapped_colors.mean(axis=0)}")
+
+ # Apply the mapped colors to a Color Attribute layer on the actual mesh data (obj.data)
+ mesh = obj.data
+ color_layer = mesh.color_attributes.get("SG_PrintPreview")
+ if color_layer and color_layer.data_type != 'FLOAT_COLOR':
+ mesh.color_attributes.remove(color_layer)
+ color_layer = None
+
+ if not color_layer:
+ color_layer = mesh.color_attributes.new(
+ name="SG_PrintPreview",
+ type='FLOAT_COLOR',
+ domain='CORNER',
+ )
+
+ mesh.calc_loop_triangles()
+ if len(mesh.loop_triangles) != len(mapped_colors):
+ self.report({'ERROR'}, "Mesh triangle count mismatch. Try applying modifiers first.")
+ return {'CANCELLED'}
+
+ # Assign to loop corners vectorially
+ n_loops = len(mesh.loops)
+ loop_colors = np.ones((n_loops, 4), dtype=np.float32) # RGBA
+
+ tri_loops = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int32)
+ mesh.loop_triangles.foreach_get("loops", tri_loops)
+ tri_loops = tri_loops.reshape((-1, 3))
+
+ mapped_colors_rgba = np.ones((len(mapped_colors), 4), dtype=np.float32)
+ mapped_colors_rgba[:, :3] = mapped_colors
+
+ loop_colors[tri_loops] = mapped_colors_rgba[:, None, :]
+
+ color_layer.data.foreach_set("color", loop_colors.ravel())
+
+ # Switch viewport shading color mode to show the Color Attribute
+ for area in context.screen.areas:
+ if area.type == 'VIEW_3D':
+ for space in area.spaces:
+ if space.type == 'VIEW_3D':
+ try:
+ # Switch shading type to SOLID to display color attributes
+ space.shading.type = 'SOLID'
+ space.shading.color_type = 'VERTEX'
+ try:
+ space.shading.light = 'FLAT'
+ except Exception:
+ pass
+ if hasattr(mesh, "color_attributes"):
+ mesh.color_attributes.active = color_layer
+ if hasattr(mesh, "attributes"):
+ mesh.attributes.active_color = color_layer
+ except TypeError:
+ # Fallback to Blender 4.x: set to ATTRIBUTE and set attribute_name
+ try:
+ space.shading.type = 'SOLID'
+ space.shading.color_type = 'ATTRIBUTE'
+ space.shading.attribute_name = "SG_PrintPreview"
+ try:
+ space.shading.light = 'FLAT'
+ except Exception:
+ pass
+ except Exception:
+ pass
+ except Exception:
+ pass
+
+ self.report({'INFO'}, f"Color preview applied.")
+ return {'FINISHED'}
+
+
+class StableGenClearQuantizationPreview(bpy.types.Operator):
+ """Clear the quantized color preview and restore material display."""
+ bl_idname = "object.stablegen_clear_quantization_preview"
+ bl_label = "Clear Preview"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ @classmethod
+ def poll(cls, context):
+ return context.active_object and context.active_object.type == 'MESH'
+
+ def execute(self, context):
+ preview_obj = bpy.data.objects.get("SG_SlicedPreview")
+ if preview_obj:
+ orig_name = preview_obj.get("original_name")
+ orig_obj = None
+ if orig_name:
+ orig_obj = bpy.data.objects.get(orig_name)
+
+ preview_mesh = preview_obj.data
+ bpy.data.objects.remove(preview_obj, do_unlink=True)
+ if preview_mesh:
+ bpy.data.meshes.remove(preview_mesh, do_unlink=True)
+
+ if orig_obj:
+ orig_obj.hide_viewport = False
+ orig_obj.hide_set(False)
+ for select_obj in context.selected_objects:
+ select_obj.select_set(False)
+ orig_obj.select_set(True)
+ context.view_layer.objects.active = orig_obj
+
+ color_layer = orig_obj.data.color_attributes.get("SG_PrintPreview")
+ if color_layer:
+ orig_obj.data.color_attributes.remove(color_layer)
+ else:
+ obj = context.active_object
+ if obj and obj.type == 'MESH':
+ color_layer = obj.data.color_attributes.get("SG_PrintPreview")
+ if color_layer:
+ obj.data.color_attributes.remove(color_layer)
+
+ # Restore viewport shading to material
+ for area in context.screen.areas:
+ if area.type == 'VIEW_3D':
+ for space in area.spaces:
+ if space.type == 'VIEW_3D':
+ shading = space.shading
+ is_our_shading = False
+
+ # Blender 4.x check
+ if getattr(shading, "color_type", "") == 'ATTRIBUTE':
+ if getattr(shading, "attribute_name", "") == "SG_PrintPreview":
+ is_our_shading = True
+ # Blender 5.x check
+ elif getattr(shading, "color_type", "") == 'VERTEX':
+ is_our_shading = True
+
+ if is_our_shading:
+ try:
+ shading.color_type = 'MATERIAL'
+ shading.type = 'MATERIAL' # Switch back to Material Preview mode
+ try:
+ shading.light = 'STUDIO'
+ except Exception:
+ pass
+ except Exception:
+ pass
+
+def _preview_sliced_worker(all_raw_verts, all_raw_tris, face_colors_srgb, unique_keys, unique_colors_arr,
+ palette_rgbs, mode, channel_indices, h_target, LH, n_layers, cyan_idx, n_channels,
+ z_min, scale_factor, is_dithered, chroma_threshold, smoothing_passes, status,
+ solver_settings=None):
+ try:
+ import numpy as np
+ import math
+
+ if not is_dithered:
+ status["stage"] = "Matching solid colors"
+ status["progress"] = 20.0
+
+ best_idx = _match_colors_hsv(
+ face_colors_srgb, palette_rgbs,
+ chroma_threshold=chroma_threshold
+ )
+
+ if smoothing_passes > 0:
+ status["stage"] = "Smoothing color islands"
+ status["progress"] = 50.0
+ best_idx_smoothed = _smooth_colors_vectorized(
+ all_raw_tris, best_idx + 1, len(all_raw_verts), len(palette_rgbs), iterations=smoothing_passes
+ )
+ best_idx = best_idx_smoothed - 1
+
+ status["stage"] = "Finalizing mesh structure"
+ status["progress"] = 90.0
+
+ final_verts = all_raw_verts.tolist()
+ final_tris = all_raw_tris.tolist()
+ final_paint = best_idx.tolist()
+ else:
+ scaled_verts = all_raw_verts.copy()
+ scaled_verts[:, 0] *= scale_factor
+ scaled_verts[:, 1] *= scale_factor
+ scaled_verts[:, 2] = (scaled_verts[:, 2] - z_min) * scale_factor
+
+ status["stage"] = "Calculating mixing demands"
+ status["progress"] = 10.0
+
+ if mode == 'solid':
+ fil_rgbs = np.array(palette_rgbs, dtype=np.float32)
+ if solver_settings is None:
+ solver_settings = {}
+ iters = solver_settings.get("iterations", 80)
+ init_m = solver_settings.get("init_method", 'CLOSEST')
+ formula = solver_settings.get("model_formula", 'KUBELKA_MUNK')
+ s_weight = solver_settings.get("scat_weight", 10.0)
+ p_weight = solver_settings.get("penalty_weight", 1.0)
+
+ demands = solve_color_mixing_numpy(
+ 1.0 - fil_rgbs, 1.0 - unique_colors_arr,
+ iterations=iters,
+ init_method=init_m,
+ model_formula=formula,
+ scat_weight=s_weight,
+ penalty_weight=p_weight
+ )
+ else:
+ demands = np.empty((len(unique_colors_arr), n_channels), dtype=np.float32)
+ for idx, color in enumerate(unique_colors_arr):
+ if status.get("cancel_requested", False):
+ return
+ r, g, b = round(color[0] * 255.0), round(color[1] * 255.0), round(color[2] * 255.0)
+ demands[idx] = decompose_subtractive(r, g, b, mode, palette_rgbs, channel_indices)
+
+ status["stage"] = "Generating color sequences"
+ status["progress"] = 30.0
+
+ color_seqs = {}
+ unique_colors_set2 = [tuple(round(c * 255.0) for c in color) for color in unique_colors_arr]
+ for idx, color_key in enumerate(unique_colors_set2):
+ if status.get("cancel_requested", False):
+ return
+ row = demands[idx]
+ total = sum(max(0.0, d) for d in row)
+ seq = [0] * n_layers
+ if total < 0.001:
+ if cyan_idx >= 0:
+ nc = min(3, n_channels - cyan_idx)
+ for li in range(n_layers):
+ seq[li] = cyan_idx + (li % nc)
+ else:
+ for li in range(n_layers):
+ seq[li] = li % n_channels
+ else:
+ frac = [max(0.0, d) / total for d in row]
+ placed = [0] * n_channels
+ for li in range(n_layers):
+ best_ch = 0
+ best_d = -float('inf')
+ for ch in range(n_channels):
+ if frac[ch] < 0.001:
+ continue
+ d = frac[ch] * (li + 1) - placed[ch]
+ tie_break = d + ch * 1e-6 + (1e-7 if li % n_channels == ch else 0.0)
+ if tie_break > best_d:
+ best_d = tie_break
+ best_ch = ch
+ seq[li] = best_ch
+ placed[best_ch] += 1
+ color_seqs[color_key] = seq
+
+ status["stage"] = "Clipping triangles crossing layers"
+ status["progress"] = 50.0
+
+ clipped_tris = []
+ ZOFF = LH / 2
+
+ total_tris_count = len(all_raw_tris)
+ for fi in range(total_tris_count):
+ if status.get("cancel_requested", False):
+ return
+ if fi % max(1, total_tris_count // 10) == 0:
+ status["progress"] = 50.0 + (fi / total_tris_count) * 30.0
+
+ t_idx = all_raw_tris[fi]
+ v1, v2, v3 = scaled_verts[t_idx[0]], scaled_verts[t_idx[1]], scaled_verts[t_idx[2]]
+ fz_min = min(v1[2], v2[2], v3[2])
+ fz_max = max(v1[2], v2[2], v3[2])
+ tri = [list(v1), list(v2), list(v3)]
+
+ li_start = max(0, int(math.floor((fz_min - ZOFF) / LH)))
+ li_end = min(n_layers - 1, int(math.ceil((fz_max - ZOFF) / LH)))
+
+ color_key = unique_keys[fi]
+ seq = color_seqs[color_key]
+
+ if li_start == li_end or li_start >= n_layers:
+ cz = (fz_min + fz_max) / 2
+ li2 = max(0, min(n_layers - 1, int(math.floor((cz - ZOFF) / LH))))
+ clipped_tris.append((tri, seq[li2]))
+ else:
+ for li in range(li_start, li_end + 1):
+ if li >= n_layers:
+ break
+ zB = ZOFF + li * LH
+ zT = ZOFF + (li + 1) * LH
+ sub_tris = cTZ(tri, zB, zT)
+ for st in sub_tris:
+ clipped_tris.append((st, seq[li]))
+
+ status["stage"] = "Welding coplanar slice vertices"
+ status["progress"] = 80.0
+
+ weld_map = {}
+ welded_verts = []
+ welded_tris = []
+ paint_arr = []
+
+ total_clipped_tris = len(clipped_tris)
+ for idx, (tri, filament_idx) in enumerate(clipped_tris):
+ if status.get("cancel_requested", False):
+ return
+ if idx % max(1, total_clipped_tris // 10) == 0:
+ status["progress"] = 80.0 + (idx / total_clipped_tris) * 15.0
+
+ tri_idx = []
+ for pt in tri:
+ key = (round(pt[0], 6), round(pt[1], 6), round(pt[2], 6))
+ if key not in weld_map:
+ weld_map[key] = len(welded_verts)
+ welded_verts.append(pt)
+ tri_idx.append(weld_map[key])
+ welded_tris.append(tri_idx)
+ global_filament_idx = channel_indices[filament_idx]
+ paint_arr.append(global_filament_idx)
+
+ status["stage"] = "Scaling geometry coordinates"
+ status["progress"] = 95.0
+
+ final_verts = []
+ for pt in welded_verts:
+ bx = pt[0] / scale_factor
+ by = pt[1] / scale_factor
+ bz = (pt[2] / scale_factor) + z_min
+ final_verts.append((bx, by, bz))
+
+ final_tris = welded_tris
+ final_paint = paint_arr
+
+ status["result"] = (final_verts, final_tris, final_paint)
+ status["done"] = True
+ except Exception as e:
+ status["error"] = e
+ status["done"] = True
+
+
+class StableGenPreviewSliced(bpy.types.Operator):
+ """Slice and dither the active mesh, and preview the actual 3D printed layers in the viewport."""
+ bl_idname = "object.stablegen_preview_sliced"
+ bl_label = "Preview Slices"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ _timer = None
+ _thread = None
+ _thread_status = None
+ _progress = 0.0
+ _stage = ""
+ _obj = None
+
+ @classmethod
+ def poll(cls, context):
+ return context.active_object and context.active_object.type == 'MESH' and not sg_modal_active(context)
+
+ def execute(self, context):
+ obj = context.active_object
+ scene = context.scene
+ self._obj = obj
+
+ if not scene.stablegen_print_palette:
+ prepopulate_palette(scene)
+
+ import numpy as np
+ palette_rgbs_linear = np.array([item.color for item in scene.stablegen_print_palette], dtype=np.float32)
+ palette_rgbs = [tuple(c) for c in linear_to_srgb_numpy(palette_rgbs_linear)]
+ if not palette_rgbs:
+ self.report({'WARNING'}, "No colors defined in the print palette.")
+ return {'CANCELLED'}
+
+ import numpy as np
+ import math
+ import threading
+
+ # 1. Clear any existing preview object
+ existing_preview = bpy.data.objects.get("SG_SlicedPreview")
+ if existing_preview:
+ orig_name = existing_preview.get("original_name")
+ if orig_name:
+ orig_obj = bpy.data.objects.get(orig_name)
+ if orig_obj:
+ orig_obj.hide_viewport = False
+ orig_obj.hide_set(False)
+ preview_mesh = existing_preview.data
+ bpy.data.objects.remove(existing_preview, do_unlink=True)
+ if preview_mesh:
+ bpy.data.meshes.remove(preview_mesh, do_unlink=True)
+
+ # 2. Extract geometry and colors (Fast, must run on main thread)
+ image = _find_texture_image(obj)
+ temp, eval_obj = _get_triangulated_mesh(obj, apply_transforms=False)
+ try:
+ n_v = len(temp.vertices)
+ v_co = np.empty(n_v * 3, dtype=np.float32)
+ temp.vertices.foreach_get("co", v_co)
+ all_raw_verts = v_co.reshape((-1, 3))
+
+ if image:
+ face_colors = _collect_face_colors(temp, image)[:, :3]
+ else:
+ color_layer = None
+ for attr in temp.color_attributes:
+ if attr.name != "SG_PrintPreview":
+ color_layer = attr
+ break
+ if not color_layer:
+ color_layer = temp.color_attributes.get("SG_PrintPreview")
+
+ if color_layer:
+ n_loops = len(temp.loops)
+ loop_colors = np.empty(n_loops * 4, dtype=np.float32)
+ color_layer.data.foreach_get("color", loop_colors)
+ loop_colors = loop_colors.reshape((-1, 4))
+
+ n_tris = len(temp.loop_triangles)
+ tri_loops = np.empty(n_tris * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("loops", tri_loops)
+ tri_loops = tri_loops.reshape((-1, 3))
+
+ face_colors = loop_colors[tri_loops].mean(axis=1)[:, :3]
+ if color_layer.data_type == 'BYTE_COLOR':
+ face_colors = srgb_to_linear_numpy(face_colors)
+ else:
+ face_colors = np.ones((len(temp.loop_triangles), 3), dtype=np.float32)
+
+ t_idx = np.empty(len(temp.loop_triangles) * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("vertices", t_idx)
+ all_raw_tris = t_idx.reshape((-1, 3))
+ finally:
+ eval_obj.to_mesh_clear()
+
+ h_target = scene.stablegen_print_model_height
+ LH = scene.stablegen_print_layer_height
+ n_layers = max(1, int(math.ceil(h_target / LH)))
+
+ face_colors_srgb = face_colors
+ q = 8
+ face_colors_q = np.clip(np.round(face_colors_srgb * 255.0 / q) * q, 0, 255).astype(np.int32)
+ unique_keys = [tuple(c) for c in face_colors_q]
+ unique_colors_set = sorted(list(set(unique_keys)))
+ unique_colors_arr = np.array(unique_colors_set, dtype=np.float32) / 255.0
+
+ mode, channel_indices = classify_filaments(palette_rgbs)
+ n_channels = len(channel_indices)
+
+ cyan_idx = -1
+ if mode != 'solid':
+ for ci, p_idx in enumerate(channel_indices):
+ if scene.stablegen_print_palette[p_idx].name == "Cyan":
+ cyan_idx = ci
+ break
+
+ z_min, z_max = all_raw_verts[:, 2].min(), all_raw_verts[:, 2].max()
+ h_blender = z_max - z_min
+ if h_blender < 1e-5:
+ h_blender = 1.0
+ scale_factor = h_target / h_blender
+
+ is_dithered = getattr(scene, "stablegen_print_dithered", True)
+ chroma_threshold = getattr(scene, "stablegen_print_chroma_threshold", 0.35)
+ smoothing_passes = getattr(scene, "stablegen_print_smoothing", 2)
+
+ # Collect advanced solver settings on the main thread (thread-safe)
+ solver_settings = {
+ "init_method": getattr(scene, "stablegen_print_solver_init", 'CLOSEST'),
+ "iterations": getattr(scene, "stablegen_print_solver_steps", 80),
+ "model_formula": getattr(scene, "stablegen_print_solver_formula", 'KUBELKA_MUNK'),
+ "scat_weight": getattr(scene, "stablegen_print_scattering_weight", 10.0),
+ "penalty_weight": getattr(scene, "stablegen_print_saturation_penalty", 1.0),
+ }
+
+ self._thread_status = {
+ "progress": 0.0,
+ "stage": "Starting worker thread",
+ "done": False,
+ "cancel_requested": False
+ }
+ self._thread = threading.Thread(
+ target=_preview_sliced_worker,
+ args=(
+ all_raw_verts, all_raw_tris, face_colors_srgb, unique_keys, unique_colors_arr,
+ palette_rgbs, mode, channel_indices, h_target, LH, n_layers, cyan_idx, n_channels,
+ z_min, scale_factor, is_dithered, chroma_threshold, smoothing_passes, self._thread_status,
+ solver_settings
+ ),
+ daemon=True
+ )
+ self._thread.start()
+
+ context.window_manager.modal_handler_add(self)
+ self._timer = context.window_manager.event_timer_add(0.1, window=context.window)
+ return {'RUNNING_MODAL'}
+
+ def modal(self, context, event):
+ if event.type == 'TIMER':
+ for window in context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type in ('PROPERTIES', 'VIEW_3D'):
+ area.tag_redraw()
+
+ status = self._thread_status
+ if status.get("cancel_requested", False):
+ self.report({'INFO'}, "Preview slices generation cancelled.")
+ self.cleanup(context)
+ return {'FINISHED'}
+
+ if status.get("done", False):
+ if "error" in status:
+ err = status["error"]
+ self.report({'ERROR'}, f"Preview slices failed: {err}")
+ import traceback
+ traceback.print_exc()
+ self.cleanup(context)
+ return {'CANCELLED'}
+
+ # Success
+ final_verts, final_tris, final_paint = status["result"]
+ self.create_preview_object(context, final_verts, final_tris, final_paint)
+ self.cleanup(context)
+ return {'FINISHED'}
+
+ self._progress = status.get("progress", 0.0)
+ self._stage = status.get("stage", "Processing")
+
+ return {'PASS_THROUGH'}
+
+ def cleanup(self, context):
+ if hasattr(self, "_timer") and self._timer:
+ context.window_manager.event_timer_remove(self._timer)
+ self._timer = None
+
+ def create_preview_object(self, context, final_verts, final_tris, final_paint):
+ obj = self._obj
+ scene = context.scene
+
+ import numpy as np
+ palette_rgbs_linear = np.array([item.color for item in scene.stablegen_print_palette], dtype=np.float32)
+ palette_rgbs = [tuple(c) for c in linear_to_srgb_numpy(palette_rgbs_linear)]
+
+ # Create the preview object
+ preview_mesh = bpy.data.meshes.new("SG_SlicedPreviewMesh")
+ preview_mesh.from_pydata(final_verts, [], final_tris)
+ preview_mesh.update()
+
+ color_layer = preview_mesh.color_attributes.new("SG_PrintPreview", 'BYTE_COLOR', 'CORNER')
+ loop_colors = np.empty(len(preview_mesh.loops) * 4, dtype=np.float32)
+
+ for face_idx, face in enumerate(preview_mesh.polygons):
+ filament_idx = final_paint[face_idx]
+ srgb = palette_rgbs[filament_idx]
+ for loop_idx in face.loop_indices:
+ loop_colors[loop_idx * 4 : loop_idx * 4 + 3] = srgb
+ loop_colors[loop_idx * 4 + 3] = 1.0
+
+ color_layer.data.foreach_set("color", loop_colors)
+
+ preview_obj = bpy.data.objects.new("SG_SlicedPreview", preview_mesh)
+ preview_obj.matrix_world = obj.matrix_world
+ preview_obj["original_name"] = obj.name
+
+ context.collection.objects.link(preview_obj)
+
+ obj.hide_viewport = True
+ obj.hide_set(True)
+
+ for select_obj in context.selected_objects:
+ select_obj.select_set(False)
+ preview_obj.select_set(True)
+ context.view_layer.objects.active = preview_obj
+
+ for area in context.screen.areas:
+ if area.type == 'VIEW_3D':
+ for space in area.spaces:
+ if space.type == 'VIEW_3D':
+ try:
+ # Switch shading type to SOLID to display color attributes
+ space.shading.type = 'SOLID'
+ space.shading.color_type = 'VERTEX'
+ try:
+ space.shading.light = 'FLAT'
+ except Exception:
+ pass
+ if hasattr(preview_mesh, "color_attributes"):
+ preview_mesh.color_attributes.active = color_layer
+ if hasattr(preview_mesh, "attributes"):
+ preview_mesh.attributes.active_color = color_layer
+ except TypeError:
+ # Fallback to Blender 4.x: set to ATTRIBUTE and set attribute_name
+ try:
+ space.shading.type = 'SOLID'
+ space.shading.color_type = 'ATTRIBUTE'
+ space.shading.attribute_name = "SG_PrintPreview"
+ try:
+ space.shading.light = 'FLAT'
+ except Exception:
+ pass
+ except Exception:
+ pass
+ except Exception:
+ pass
+
+ self.report({'INFO'}, "Sliced preview generated.")
+
+
+class StableGenPreviewSlicedCancel(bpy.types.Operator):
+ """Cancel the active sliced preview generation."""
+ bl_idname = "object.stablegen_preview_sliced_cancel"
+ bl_label = "Cancel Preview Slices"
+ bl_options = {'INTERNAL'}
+
+ def execute(self, context):
+ op = next(
+ (op for win in context.window_manager.windows
+ for op in win.modal_operators
+ if op.bl_idname == 'OBJECT_OT_stablegen_preview_sliced'),
+ None
+ )
+ if op and hasattr(op, "_thread_status") and op._thread_status:
+ op._thread_status["cancel_requested"] = True
+ self.report({'INFO'}, "Cancellation requested...")
+ return {'FINISHED'}
+
+
+# ── helpers ──────────────────────────────────────────────────────────────
+
+def _rgb_to_hsv_numpy(rgb):
+ """Vectorized RGB to HSV conversion in NumPy."""
+ import numpy as np
+ r, g, b = rgb[:, 0], rgb[:, 1], rgb[:, 2]
+ max_val = np.max(rgb, axis=1)
+ min_val = np.min(rgb, axis=1)
+ delta = max_val - min_val
+
+ h = np.zeros_like(max_val)
+ mask = delta > 0.0001
+
+ # Red is max
+ mask_r = mask & (max_val == r)
+ h[mask_r] = ((g[mask_r] - b[mask_r]) / delta[mask_r]) % 6.0
+
+ # Green is max
+ mask_g = mask & (max_val == g)
+ h[mask_g] = ((b[mask_g] - r[mask_g]) / delta[mask_g]) + 2.0
+
+ # Blue is max
+ mask_b = mask & (max_val == b)
+ h[mask_b] = ((r[mask_b] - g[mask_b]) / delta[mask_b]) + 4.0
+
+ h = (h / 6.0) % 1.0
+ s = np.zeros_like(max_val)
+ s[mask] = delta[mask] / max_val[mask]
+ v = max_val
+
+ return np.stack([h, s, v], axis=1)
+
+
+def linear_to_srgb_numpy(linear_arr):
+ """Vectorized conversion from linear RGB to sRGB in NumPy."""
+ import numpy as np
+ srgb = np.where(
+ linear_arr <= 0.0031308,
+ linear_arr * 12.92,
+ 1.055 * np.power(np.maximum(linear_arr, 0.0), 1.0 / 2.4) - 0.055
+ )
+ return np.clip(srgb, 0.0, 1.0)
+
+
+def srgb_to_linear_numpy(srgb_arr):
+ """Vectorized conversion from sRGB to linear RGB in NumPy."""
+ import numpy as np
+ linear = np.where(
+ srgb_arr <= 0.04045,
+ srgb_arr / 12.92,
+ np.power((srgb_arr + 0.055) / 1.055, 2.4)
+ )
+ return np.clip(linear, 0.0, 1.0)
+
+
+def classify_filaments(palette_rgbs):
+ """Classifies a list of physical filament RGBs into subtractive preset roles.
+
+ Returns (mode, channel_indices) where:
+ mode: 'cmy', 'wcmy', 'kcmy', 'wkcmy', '2c', or 'solid'
+ channel_indices: list of indices mapping role order to palette_rgbs indices
+ """
+ n = len(palette_rgbs)
+ if n == 0:
+ return 'solid', []
+
+ targets = {
+ 'W': (1.0, 1.0, 1.0),
+ 'K': (0.0, 0.0, 0.0),
+ 'C': (0.0, 1.0, 1.0),
+ 'M': (1.0, 0.0, 1.0),
+ 'Y': (1.0, 1.0, 0.0)
+ }
+
+ def dist(rgb1, rgb2):
+ return sum((rgb1[i] - rgb2[i])**2 for i in range(3))
+
+ matched = {}
+ remaining_indices = list(range(n))
+
+ for role in ['W', 'K', 'C', 'M', 'Y']:
+ if not remaining_indices:
+ break
+ target = targets[role]
+ best_idx = min(remaining_indices, key=lambda idx: dist(palette_rgbs[idx], target))
+ threshold = 0.05 if role in ['W', 'K'] else 0.25
+ if dist(palette_rgbs[best_idx], target) < threshold:
+ matched[role] = best_idx
+ remaining_indices.remove(best_idx)
+
+ has_c = 'C' in matched
+ has_m = 'M' in matched
+ has_y = 'Y' in matched
+ has_w = 'W' in matched
+ has_k = 'K' in matched
+
+ # If there are spools in the palette that didn't match a standard role,
+ # force the general solver to ensure no colors are ignored!
+ if len(matched) < n:
+ return 'solid', list(range(n))
+
+ if has_c and has_m and has_y:
+ if has_w and has_k:
+ return 'wkcmy', [matched['W'], matched['K'], matched['C'], matched['M'], matched['Y']]
+ elif has_w:
+ return 'wcmy', [matched['W'], matched['C'], matched['M'], matched['Y']]
+ elif has_k:
+ return 'kcmy', [matched['K'], matched['C'], matched['M'], matched['Y']]
+ else:
+ return 'cmy', [matched['C'], matched['M'], matched['Y']]
+
+ if n == 2:
+ return '2c', [0, 1]
+
+ return 'solid', list(range(n))
+
+
+def decompose_subtractive(r, g, b, mode, palette_rgbs, channel_indices):
+ """Calculates physical filament fractions using Primed3D's subtractive mixing models.
+
+ r, g, b are standard sRGB values in [0, 255].
+ """
+ if mode == 'cmy':
+ return [1.0 - r/255.0, 1.0 - g/255.0, 1.0 - b/255.0]
+ elif mode == 'wcmy':
+ cd = 1.0 - r/255.0
+ md = 1.0 - g/255.0
+ yd = 1.0 - b/255.0
+ kd = min(cd, md, yd)
+ wd = 1.0 - max(cd, md, yd)
+ k3 = kd / 3.0
+ return [wd, cd - kd + k3, md - kd + k3, yd - kd + k3]
+ elif mode == 'kcmy':
+ cd = 1.0 - r/255.0
+ md = 1.0 - g/255.0
+ yd = 1.0 - b/255.0
+ k_max = min(cd, md, yd)
+ chroma = max(cd, md, yd) - k_max
+ k_thresh = max(0.0, (k_max - 0.35) / 0.65)
+ k_scale = (1.0 - chroma * 0.7) * k_thresh
+ kd = k_max * k_scale
+ return [kd, cd - kd, md - kd, yd - kd]
+ elif mode == 'wkcmy':
+ cd = 1.0 - r/255.0
+ md = 1.0 - g/255.0
+ yd = 1.0 - b/255.0
+ k_max = min(cd, md, yd)
+ chroma = max(cd, md, yd) - k_max
+ k_scale = 1.0 - chroma * 0.7
+ kd = k_max * k_scale
+ wd = 1.0 - max(cd, md, yd)
+ return [wd, kd, cd - kd, md - kd, yd - kd]
+ elif mode == '2c':
+ spool_a = palette_rgbs[channel_indices[0]]
+ spool_b = palette_rgbs[channel_indices[1]]
+ ar, ag, ab_ = int(round(spool_a[0]*255)), int(round(spool_a[1]*255)), int(round(spool_a[2]*255))
+ br, bg, bb = int(round(spool_b[0]*255)), int(round(spool_b[1]*255)), int(round(spool_b[2]*255))
+ d_r, d_g, d_b = br - ar, bg - ag, bb - ab_
+ dot2 = d_r*d_r + d_g*d_g + d_b*d_b
+ if dot2 < 1:
+ return [0.5, 0.5]
+ t = max(0.0, min(1.0, ((r - ar) * d_r + (g - ag) * d_g + (b - ab_) * d_b) / dot2))
+ return [1.0 - t, t]
+ return []
+
+
+def solve_color_mixing_numpy(fil_rgbs, target_rgbs, iterations=None, init_method=None, model_formula=None, scat_weight=None, penalty_weight=None):
+ """Vectorized Frank-Wolfe optimization solver for arbitrary filament mixing.
+
+ Supports Linear Additive, Linear Subtractive, and physical Kubelka-Munk models
+ with configurable convergence steps, initialization method, and scattering weights.
+ """
+ import numpy as np
+ import bpy
+
+ U = target_rgbs.shape[0]
+ N = fil_rgbs.shape[0]
+ if N == 0:
+ return np.zeros((U, 0), dtype=np.float32)
+
+ # Read dynamic configuration from Blender scene if context is available
+ scene = getattr(bpy.context, "scene", None)
+
+ if init_method is None:
+ init_method = getattr(scene, "stablegen_print_solver_init", 'CLOSEST') if scene else 'CLOSEST'
+ if iterations is None:
+ iterations = getattr(scene, "stablegen_print_solver_steps", 80) if scene else 80
+ if model_formula is None:
+ model_formula = getattr(scene, "stablegen_print_solver_formula", 'KUBELKA_MUNK') if scene else 'KUBELKA_MUNK'
+ if scat_weight is None:
+ scat_weight = getattr(scene, "stablegen_print_scattering_weight", 10.0) if scene else 10.0
+ if penalty_weight is None:
+ penalty_weight = getattr(scene, "stablegen_print_saturation_penalty", 1.0) if scene else 1.0
+
+
+ # 1. Precompute absorption K and scattering S for Kubelka-Munk
+ fil_val = fil_rgbs.max(axis=1)
+ fil_min = fil_rgbs.min(axis=1)
+ fil_sat = np.zeros_like(fil_val)
+ mask = fil_val > 1e-5
+ fil_sat[mask] = (fil_val[mask] - fil_min[mask]) / fil_val[mask]
+
+ # Precompute target saturation for one-sided saturation penalty
+ target_val = target_rgbs.max(axis=1)
+ target_min = target_rgbs.min(axis=1)
+ target_sat = np.zeros_like(target_val)
+ t_mask = target_val > 1e-5
+ target_sat[t_mask] = (target_val[t_mask] - target_min[t_mask]) / target_val[t_mask]
+
+ # Scattering: base of 1.0, up to scat_weight for bright desaturated spools
+ S_filaments = 1.0 + scat_weight * (1.0 - fil_sat) * fil_val # (N,)
+ S_filaments = S_filaments[:, None] # (N, 1)
+
+ R_clip = np.clip(fil_rgbs, 0.001, 0.999)
+ K_filaments = S_filaments * ((1.0 - R_clip)**2) / (2.0 * R_clip) # (N, 3)
+
+ # Target values to match
+ target_rgbs = np.clip(target_rgbs, 0.001, 0.999)
+
+ # Initialize fractions
+ if init_method == 'CLOSEST':
+ # Compute reflectances of single filaments to find the best initial guess
+ if model_formula == 'KUBELKA_MUNK':
+ ratio_fil = K_filaments / S_filaments # (N, 3)
+ R_fil = 1.0 + ratio_fil - np.sqrt(ratio_fil**2 + 2.0 * ratio_fil) # (N, 3)
+ else:
+ R_fil = fil_rgbs
+
+ dists = np.sum((R_fil[:, None, :] - target_rgbs[None, :, :])**2, axis=2) # (N, U)
+
+ # Apply one-sided saturation penalty to initial distances
+ if penalty_weight > 0.0:
+ diff = target_sat[None, :] - fil_sat[:, None]
+ penalties = penalty_weight * target_sat[None, :] * np.maximum(0.0, diff)
+ dists = dists + penalties
+
+ best_init = np.argmin(dists, axis=0) # (U,)
+
+ f = np.zeros((U, N), dtype=np.float32)
+ f[np.arange(U), best_init] = 1.0
+ else: # EQUAL
+ f = np.full((U, N), 1.0 / N, dtype=np.float32)
+
+ for step in range(iterations):
+ gamma = 2.0 / (step + 3)
+ errors = np.empty((N, U), dtype=np.float32)
+
+ for i in range(N):
+ f_cand = f * (1.0 - gamma)
+ f_cand[:, i] += gamma
+
+ if model_formula == 'KUBELKA_MUNK':
+ K_mix = np.dot(f_cand, K_filaments) # (U, 3)
+ S_mix = np.dot(f_cand, S_filaments) # (U, 3)
+ ratio = K_mix / S_mix
+ R_cand = 1.0 + ratio - np.sqrt(ratio**2 + 2.0 * ratio)
+ elif model_formula == 'ADDITIVE':
+ R_cand = np.dot(f_cand, fil_rgbs)
+ else: # SUBTRACTIVE
+ R_cand = 1.0 - np.dot(f_cand, 1.0 - fil_rgbs)
+
+ base_err = np.sum((R_cand - target_rgbs)**2, axis=1)
+
+ # Apply one-sided saturation penalty
+ if penalty_weight > 0.0:
+ pen = penalty_weight * target_sat * np.maximum(0.0, target_sat - fil_sat[i])
+ errors[i] = base_err + pen
+ else:
+ errors[i] = base_err
+
+ best_i = np.argmin(errors, axis=0) # (U,)
+
+ f *= (1.0 - gamma)
+ f[np.arange(U), best_i] += gamma
+
+ # Apply FDM-specific pruning to eliminate tiny noisy fractions below 8%
+ threshold = 0.08
+ row_sums = f.sum(axis=1, keepdims=True)
+ row_sums[row_sums == 0] = 1.0
+ f_frac = f / row_sums
+ f_frac[f_frac < threshold] = 0.0
+
+ new_sums = f_frac.sum(axis=1, keepdims=True)
+ zero_mask = (new_sums == 0).ravel()
+ if np.any(zero_mask):
+ max_indices = np.argmax(f, axis=1)
+ f_frac[zero_mask, max_indices[zero_mask]] = 1.0
+ new_sums[zero_mask] = 1.0
+
+ return f_frac / new_sums
+
+
+def lv(a, b, z):
+ """Linear interpolation of vertex coordinates at intersection height z."""
+ # Lexicographically sort endpoints to ensure deterministic interpolation order on shared edges
+ if (a[2], a[0], a[1]) > (b[2], b[0], b[1]):
+ a, b = b, a
+ d = b[2] - a[2]
+ if abs(d) < 1e-12:
+ return [a[0], a[1], z]
+ t = (z - a[2]) / d
+ return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]), z]
+
+
+def cP(poly, z, ab):
+ """Clips a polygon against a horizontal plane z. Keep vertices on correct side (ab)."""
+ o = []
+ n_pts = len(poly)
+ for i in range(n_pts):
+ c = poly[i]
+ n = poly[(i + 1) % n_pts]
+ cI = (c[2] >= z - 1e-8) if ab else (c[2] <= z + 1e-8)
+ nI = (n[2] >= z - 1e-8) if ab else (n[2] <= z + 1e-8)
+ if cI:
+ o.append(c)
+ if not nI:
+ o.append(lv(c, n, z))
+ elif nI:
+ o.append(lv(c, n, z))
+ return o
+
+
+def cPs(ps, z, ab):
+ """Clips a list of polygons against plane z."""
+ o = []
+ for p in ps:
+ c = cP(p, z, ab)
+ if len(c) >= 3:
+ o.append(c)
+ return o
+
+
+def cTZ(tri, zB, zT):
+ """Clips a triangle into horizontal band [zB, zT]. Returns sub-triangles."""
+ ps = [tri]
+ ps = cPs(ps, zB, True)
+ ps = cPs(ps, zT, False)
+ o = []
+ for p in ps:
+ if len(p) < 3:
+ continue
+ for i in range(1, len(p) - 1):
+ o.append([p[0], p[i], p[i+1]])
+ return o
+
+
+def _match_colors_hsv(face_rgbs, palette_rgbs, chroma_threshold=0.35):
+ """Perceptual color matching using HSV space distance with warped saturation and category gates."""
+ import numpy as np
+ hsv_faces = _rgb_to_hsv_numpy(face_rgbs)
+ hsv_palette = _rgb_to_hsv_numpy(np.array(palette_rgbs, dtype=np.float32))
+
+ h1, s1, v1 = hsv_faces[:, 0, None], hsv_faces[:, 1, None], hsv_faces[:, 2, None] # (N, 1)
+ h2, s2, v2 = hsv_palette[None, :, 0], hsv_palette[None, :, 1], hsv_palette[None, :, 2] # (1, K)
+
+ # Warp Saturation to reflect human chromatic boundaries
+ # This maps e.g. S=0.6 to S_warped=0.93 (chromatic), but S=0.25 to S_warped=0.58 (neutral)
+ def warp_s(s):
+ return 1.0 - (1.0 - s) ** 3
+
+ s1_w = warp_s(s1)
+ s2_w = warp_s(s2)
+
+ # Circular Hue difference
+ dh = np.abs(h1 - h2)
+ dh = np.minimum(dh, 1.0 - dh)
+
+ ds = s1_w - s2_w
+ dv = v1 - v2
+
+ # Highly prioritize Hue matching for chromatic colors
+ # We use a large hue weight if both colors are somewhat chromatic
+ # but scale it down if either color is truly neutral (achromatic)
+ chromatic_gate = np.minimum(s1, s2)
+ hue_weight = 15.0 * np.clip(chromatic_gate / 0.15, 0.0, 1.0)
+
+ # We also penalize matching between different saturation classes (chromatic vs neutral)
+ # class 1: S >= chroma_threshold (chromatic), class 0: S < chroma_threshold (neutral)
+ c1 = (s1 >= chroma_threshold).astype(np.float32)
+ c2 = (s2 >= chroma_threshold).astype(np.float32)
+ class_penalty = 1.0 * np.abs(c1 - c2)
+
+ # HSV distance formula
+ dists = hue_weight * (dh ** 2) + 1.0 * (ds ** 2) + 0.5 * (dv ** 2) + class_penalty
+ return np.argmin(dists, axis=1)
+
+
+def _smooth_colors_vectorized(tris, paint_colors, V, K, iterations=1):
+ """Majority vote smoothing on mesh faces using shared vertices."""
+ import numpy as np
+ if iterations <= 0 or len(tris) == 0:
+ return paint_colors
+
+ T = len(tris)
+ smoothed = paint_colors.copy()
+
+ for _ in range(iterations):
+ # Create one-hot counts for each face
+ face_one_hot = np.zeros((T, K), dtype=np.float32)
+ face_one_hot[np.arange(T), smoothed - 1] = 1.0
+
+ # Accumulate face color one-hots at vertices
+ v_color_counts = np.zeros((V, K), dtype=np.float32)
+ np.add.at(v_color_counts, tris[:, 0], face_one_hot)
+ np.add.at(v_color_counts, tris[:, 1], face_one_hot)
+ np.add.at(v_color_counts, tris[:, 2], face_one_hot)
+
+ # Sum vertex counts for each triangle
+ tri_votes = (v_color_counts[tris[:, 0]] +
+ v_color_counts[tris[:, 1]] +
+ v_color_counts[tris[:, 2]])
+
+ # Determine majority color (1-based index)
+ smoothed = np.argmax(tri_votes, axis=1) + 1
+
+ return smoothed
+
+
+def _get_triangulated_mesh(obj, apply_transforms):
+ """Return a copy of *obj* triangulated, in world-space if requested.
+
+ Returns ``(mesh, eval_obj)``. The caller **must** call
+ ``eval_obj.to_mesh_clear()`` to free the temporary mesh.
+ """
+ deps = bpy.context.evaluated_depsgraph_get()
+ eval_obj = obj.evaluated_get(deps)
+ temp = eval_obj.to_mesh()
+ temp.calc_loop_triangles()
+ if apply_transforms:
+ mat = obj.matrix_world
+ temp.transform(mat)
+ return temp, eval_obj
+
+
+def _find_texture_image(obj):
+ """Locate the best colour texture image in the object's material.
+
+ The bake pipeline appends a ``{name}_baked`` material — iterate in
+ *reverse* so that the baked material is examined first.
+
+ Order of preference within each material:
+ 1. ``TEX_IMAGE`` connected to Principled BSDF Base Color.
+ 2. Any ``TEX_IMAGE`` node present in the material.
+ """
+ if not obj.data.materials:
+ return None
+ for mat in reversed(obj.data.materials):
+ if mat and mat.use_nodes:
+ nodes = mat.node_tree.nodes
+ for node in nodes:
+ if node.type == 'BSDF_PRINCIPLED':
+ bc = node.inputs.get("Base Color")
+ if bc and bc.links:
+ src = bc.links[0].from_node
+ if src.type == 'TEX_IMAGE' and src.image:
+ return src.image
+ for node in nodes:
+ if node.type == 'TEX_IMAGE' and node.image:
+ return node.image
+ return None
+
+
+def _sample_image_pixel(image, u, v):
+ """Return RGBA tuple sampled from *image* at normalized UV *u*, *v*."""
+ if not image or image.size[0] == 0 or image.size[1] == 0:
+ return (0.5, 0.5, 0.5, 1.0)
+ w, h = image.size
+ u = u - math.floor(u)
+ v = v - math.floor(v)
+ px = min(int(u * w), w - 1)
+ py = min(int(v * h), h - 1)
+ idx = (py * w + px) * 4
+ pixels = image.pixels
+ if idx + 3 >= len(pixels):
+ return (0.5, 0.5, 0.5, 1.0)
+ return (pixels[idx], pixels[idx + 1], pixels[idx + 2], pixels[idx + 3])
+
+
+def _kmeans_quantize(colors, k, max_iter=30):
+ """Quantize a list of RGBA *colors* into *k* clusters via k-means.
+
+ Returns ``(assignments, centroids)`` where *assignments* is an
+ ``int`` index per input colour and *centroids* is a list of
+ ``(r, g, b)`` tuples.
+ """
+ n = len(colors)
+ if n == 0:
+ return [], []
+ k = max(1, min(k, n))
+ rgb = [c[:3] for c in colors]
+
+ # k-means++ initialisation
+ centroids = [random.choice(rgb)]
+ for _ in range(1, k):
+ dists = []
+ for c in rgb:
+ d = min(sum((c[j] - cen[j]) ** 2 for j in range(3)) for cen in centroids)
+ dists.append(d)
+ total = sum(dists)
+ if total == 0:
+ centroids.append(random.choice(rgb))
+ continue
+ r = random.random() * total
+ cumulative = 0.0
+ chosen = rgb[-1]
+ for i, d in enumerate(dists):
+ cumulative += d
+ if cumulative >= r:
+ chosen = rgb[i]
+ break
+ centroids.append(chosen)
+
+ assignments = [0] * n
+ for _ in range(max_iter):
+ changed = False
+ for i, c in enumerate(rgb):
+ best_d = sum((c[j] - centroids[0][j]) ** 2 for j in range(3))
+ best = 0
+ for ci in range(1, k):
+ d = sum((c[j] - centroids[ci][j]) ** 2 for j in range(3))
+ if d < best_d:
+ best_d = d
+ best = ci
+ if assignments[i] != best:
+ assignments[i] = best
+ changed = True
+ if not changed:
+ break
+ sums = [(0.0, 0.0, 0.0) for _ in range(k)]
+ counts = [0] * k
+ for i, c in enumerate(rgb):
+ ci = assignments[i]
+ s = sums[ci]
+ sums[ci] = (s[0] + c[0], s[1] + c[1], s[2] + c[2])
+ counts[ci] += 1
+ centroids = []
+ for ci in range(k):
+ if counts[ci]:
+ centroids.append(tuple(v / counts[ci] for v in sums[ci]))
+ else:
+ centroids.append((0.5, 0.5, 0.5))
+ return assignments, centroids
+
+
+def _rgb_to_hex(rgb):
+ """Convert a ``(r, g, b)`` float triple to an sRGB hex string."""
+ def _clamp(v):
+ return max(0, min(255, int(round(v * 255))))
+ return f"#{_clamp(rgb[0]):02x}{_clamp(rgb[1]):02x}{_clamp(rgb[2]):02x}"
+
+
+# ── 3MF XML construction ─────────────────────────────────────────────────
+
+def _xml_with_xmlns(element, xmlns_uri, extra_ns=None):
+ """Serialize an Element to a UTF-8 XML string with ``xmlns``.
+
+ *extra_ns* is an optional ``(prefix, uri)`` pair added as an
+ additional ``xmlns:prefix="uri"`` declaration on the root.
+ """
+ raw = ET.tostring(element, encoding='unicode')
+ tag = element.tag.split('}')[-1]
+ pos = raw.index(f'<{tag}')
+ gt = raw.index('>', pos)
+ ns_decl = f' xmlns="{xmlns_uri}"'
+ if extra_ns:
+ ns_decl += f' xmlns:{extra_ns[0]}="{extra_ns[1]}"'
+ out = raw[:gt] + ns_decl + raw[gt:]
+ return '<?xml version="1.0" encoding="UTF-8"?>\n' + out
+
+
+def _build_model_settings_element(parent_id, child_ids_and_extruders):
+ """Build a ``<config>`` Element tree for model_settings.config.
+
+ Structure:
+ <config>
+ <object id="PARENT_ID">
+ <part id="CHILD_ID" subtype="normal_part">
+ <metadata key="name" value="Part_{CHILD_ID}"/>
+ <!-- No extruder key: paint_color on triangles maps directly to
+ global filament IDs. Setting an explicit extruder here causes
+ the slicer to offset all paint_color values through the part's
+ base extruder, which remaps every triangle to Filament 1. -->
+ </part>
+ ...
+ </object>
+ </config>
+ """
+ config = ET.Element('config')
+ obj_el = ET.SubElement(config, 'object')
+ obj_el.set('id', str(parent_id))
+
+ for child_id, _extruder in child_ids_and_extruders:
+ part_el = ET.SubElement(obj_el, 'part')
+ part_el.set('id', str(child_id))
+ part_el.set('subtype', 'normal_part')
+
+ meta_name = ET.SubElement(part_el, 'metadata')
+ meta_name.set('key', 'name')
+ meta_name.set('value', f'Part_{child_id}')
+ # Intentionally omit extruder metadata — paint_color already encodes
+ # the global filament index directly via (filament_id << 2).
+
+ return config
+
+
+
+def _xml_to_string(element):
+ """Serialize an Element to a UTF-8 XML string."""
+ raw = ET.tostring(element, encoding='unicode')
+ return '<?xml version="1.0" encoding="UTF-8"?>\n' + raw
+
+
+def _build_model_element(verts_arr, tris_arr, paint_arr, palette, global_to_extruder=None):
+ """Build a ``<model>`` XML string using a single object wrapped in components.
+
+ This ensures that the mesh is exported as a single, perfectly manifold object,
+ while maintaining the component wrapper structure expected by OrcaSlicer/Bambu Studio
+ to prevent circular reference crashes in model_settings.config.
+ """
+ import numpy as np
+
+ resources_parts = []
+
+ # ── Geometry Mesh Object (ID 1) ──
+ geom_obj_id = 1
+ resources_parts.append(f'<object id="{geom_obj_id}" type="model">')
+
+ # Format vertices
+ verts_strs = [f'<vertex x="{v[0]:.6f}" y="{v[1]:.6f}" z="{v[2]:.6f}"/>' for v in verts_arr]
+
+ # Format triangles, adding the paint_color attribute if assigned
+ def get_paint_color_hex(ext_id):
+ if ext_id == 0:
+ return "0"
+ elif ext_id == 1:
+ return "4"
+ elif ext_id == 2:
+ return "8"
+ else:
+ n = ext_id - 3
+ chunks = []
+ while n >= 15:
+ chunks.append("F")
+ n -= 15
+ chunks.append(f"{n:X}")
+ return "".join(reversed(chunks)) + "C"
+
+ tris_strs = []
+ for i, tri in enumerate(tris_arr):
+ # 1-based index in global_palette
+ seq_ext = int(paint_arr[i])
+ if global_to_extruder and seq_ext in global_to_extruder:
+ ext_id = global_to_extruder[seq_ext]
+ else:
+ ext_id = seq_ext
+
+ pc_str = get_paint_color_hex(ext_id)
+ tris_strs.append(f'<triangle v1="{tri[0]}" v2="{tri[1]}" v3="{tri[2]}" paint_color="{pc_str}"/>')
+
+ resources_parts.append(f'<mesh><vertices>{"".join(verts_strs)}</vertices><triangles>{"".join(tris_strs)}</triangles></mesh>')
+ resources_parts.append('</object>')
+
+ # ── Parent Assembly Object with Component (ID 2) ──
+ parent_obj_id = 2
+ resources_parts.append(f'<object id="{parent_obj_id}" type="model"><components>')
+ resources_parts.append(f'<component objectid="{geom_obj_id}"/>')
+ resources_parts.append('</components></object>')
+
+ resources_xml = "".join(resources_parts)
+ build_xml = f'<build><item objectid="{parent_obj_id}"/></build>'
+
+ model_xml = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<model unit="millimeter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021">'
+ f'<resources>{resources_xml}</resources>'
+ f'{build_xml}'
+ '</model>'
+ )
+
+ parent_id = parent_obj_id
+ child_ids_and_extruders = [(geom_obj_id, 1)]
+ return model_xml, parent_id, child_ids_and_extruders
+
+
+def _write_3mf_archive(filepath, model_element_or_str, model_settings_element=None, project_settings_json=None, prusa_config=None, prusa_model_config=None):
+ """Package the model XML into a 3MF (ZIP) archive."""
+ if isinstance(model_element_or_str, str):
+ model_str = model_element_or_str
+ else:
+ model_str = _xml_with_xmlns(model_element_or_str, NS_3MF,
+ extra_ns=('m', NS_MAT))
+
+ ct = ET.Element('Types')
+ ET.SubElement(ct, 'Default', {
+ 'Extension': 'rels',
+ 'ContentType': 'application/vnd.openxmlformats-package.relationships+xml',
+ })
+ ET.SubElement(ct, 'Default', {
+ 'Extension': 'model',
+ 'ContentType': 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml',
+ })
+ if model_settings_element is not None or project_settings_json is not None:
+ ET.SubElement(ct, 'Default', {
+ 'Extension': 'config',
+ 'ContentType': 'application/xml',
+ })
+ ct_str = _xml_with_xmlns(ct, NS_CT)
+
+ rels = ET.Element('Relationships')
+ ET.SubElement(rels, 'Relationship', {
+ 'Target': '/3D/3dmodel.model',
+ 'Id': 'rel1',
+ 'Type': 'http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel',
+ })
+ rels_str = _xml_with_xmlns(rels, NS_REL)
+
+ with zipfile.ZipFile(filepath, 'w', zipfile.ZIP_DEFLATED) as zf:
+ zf.writestr('[Content_Types].xml', ct_str)
+ zf.writestr('_rels/.rels', rels_str)
+ zf.writestr('3D/3dmodel.model', model_str)
+ if model_settings_element is not None:
+ settings_str = _xml_to_string(model_settings_element)
+ zf.writestr('Metadata/model_settings.config', settings_str)
+ if project_settings_json is not None:
+ zf.writestr('Metadata/project_settings.config', project_settings_json)
+ slice_info_str = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<config>\n'
+ ' <header>\n'
+ ' <header_item key="X-BBL-Client-Type" value="slicer"/>\n'
+ ' <header_item key="X-BBL-Client-Version" value=""/>\n'
+ ' </header>\n'
+ '</config>'
+ )
+ zf.writestr('Metadata/slice_info.config', slice_info_str)
+ if prusa_config is not None:
+ zf.writestr('Metadata/Slic3r_PE.config', prusa_config)
+ if prusa_model_config is not None:
+ zf.writestr('Metadata/Slic3r_PE_model.config', prusa_model_config)
+
+
+def _collect_face_colors(mesh, image):
+ """Sample texture colour at the centre of each loop triangle using optimized NumPy vectorization.
+
+ Prefers the ``BakeUV`` channel (created by the bake pipeline);
+ falls back to the active UV layer, then to any available UV layer.
+ """
+ import numpy as np
+
+ if not mesh.loop_triangles or not mesh.uv_layers:
+ return np.ones((len(mesh.loop_triangles), 4), dtype=np.float32) * 0.5
+
+ uv_layer = mesh.uv_layers.get("BakeUV")
+ if uv_layer is None:
+ uv_layer = mesh.uv_layers.active
+ if uv_layer is None and mesh.uv_layers:
+ uv_layer = mesh.uv_layers[0]
+ if uv_layer is None:
+ return np.ones((len(mesh.loop_triangles), 4), dtype=np.float32) * 0.5
+
+ # Force load image pixels if not already loaded in memory
+ try:
+ if len(image.pixels) > 0:
+ _ = image.pixels[0]
+ except Exception as e:
+ print(f"[StableGen 3MF] Warning: could not force load image pixels: {e}")
+
+ # 1. Fetch entire image pixels to numpy array once (extremely fast)
+ w, h = image.size
+ pixels = np.empty(w * h * 4, dtype=np.float32)
+ image.pixels.foreach_get(pixels)
+ pixels = pixels.reshape((h, w, 4))
+
+ # 2. Fetch all UVs
+ n_loops = len(uv_layer.data)
+ uv_data = np.empty(n_loops * 2, dtype=np.float32)
+ uv_layer.data.foreach_get("uv", uv_data)
+ uvs = uv_data.reshape((-1, 2))
+
+ # 3. Fetch all loop triangle indices
+ n_tris = len(mesh.loop_triangles)
+ tri_loops = np.empty(n_tris * 3, dtype=np.int32)
+ mesh.loop_triangles.foreach_get("loops", tri_loops)
+ tri_loops = tri_loops.reshape((-1, 3))
+
+ # 4. Compute average UV per triangle vectorially
+ avg_uvs = uvs[tri_loops].mean(axis=1) # (n_tris, 2)
+
+ # 5. Map UVs to pixel coordinates
+ u = avg_uvs[:, 0]
+ v = avg_uvs[:, 1]
+
+ # Handle wrapping
+ u = u - np.floor(u)
+ v = v - np.floor(v)
+
+ px = np.clip((u * w).astype(np.int32), 0, w - 1)
+ py = np.clip((v * h).astype(np.int32), 0, h - 1)
+
+ # 6. Sample colors at once using advanced indexing
+ face_colors = pixels[py, px].copy() # (n_tris, 4)
+
+ # Determine color space of the image.
+ # If the colorspace settings are 'Non-Color' or 'Raw' and the image is not a float/HDR texture,
+ # the pixels in image.pixels are raw sRGB values, not linear.
+ # In all other cases (e.g. standard 'sRGB', or 'Linear'), image.pixels are linear Rec. 709/sRGB floats.
+ is_linear = True
+ cs_name = "unknown"
+ if hasattr(image, "colorspace_settings"):
+ cs_name = image.colorspace_settings.name
+ cs_name_lower = cs_name.lower()
+ if cs_name_lower in ('non-color', 'raw'):
+ is_float = getattr(image, "is_float", False)
+ if not is_float:
+ is_linear = False
+
+ print(f"[StableGen 3MF] Texture '{image.name}' color space settings: '{cs_name}', interpreted as {'Linear' if is_linear else 'sRGB'}")
+
+ if not is_linear:
+ # Convert sRGB raw image pixels to linear space for consistent downstream behavior
+ face_colors[:, :3] = srgb_to_linear_numpy(face_colors[:, :3])
+
+ # Debug: print color range
+ uniq = set(tuple(round(float(c), 2) for c in col[:3]) for col in face_colors[:1000]) # Sample a subset for performance
+ print(f"[StableGen 3MF] Sampled {len(face_colors)} faces, found {len(uniq)}+ unique color values")
+
+ return face_colors
+
+
+
+def _make_solid_mesh_object(obj, fill_gaps=True, visible_faces=None):
+ import bmesh
+ from mathutils.bvhtree import BVHTree
+ import numpy as np
+ import mathutils
+ import math
+ import bpy
+ import time
+
+ t_start = time.perf_counter()
+ temp, eval_obj = _get_triangulated_mesh(obj, apply_transforms=False)
+ try:
+ bm = bmesh.new()
+ bm.from_mesh(temp)
+
+ # Weld overlapping/duplicate vertices to resolve topological disconnects on boundaries
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0001)
+
+ bm.faces.ensure_lookup_table()
+ bm.edges.ensure_lookup_table()
+ bm.verts.ensure_lookup_table()
+
+ color_lay = bm.loops.layers.color.get("SG_PrintPreview")
+
+ def get_avg_color(loops, color_lay):
+ if not color_lay:
+ return (0.5, 0.5, 0.5, 1.0)
+ r, g, b, a = 0.0, 0.0, 0.0, 0.0
+ n = len(loops)
+ for loop in loops:
+ c = loop[color_lay]
+ r += c[0]
+ g += c[1]
+ b += c[2]
+ if len(c) > 3:
+ a += c[3]
+ else:
+ a += 1.0
+ return (r / n, g / n, b / n, a / n)
+
+ t0 = time.perf_counter()
+ face_info = []
+ for f in bm.faces:
+ center = f.calc_center_median()
+ avg_color = get_avg_color(f.loops, color_lay)
+ face_info.append((center, avg_color, f.index))
+ print(f"[StableGen Make Solid] Collected face info in {time.perf_counter() - t0:.4f}s")
+
+ if visible_faces is None:
+ t0 = time.perf_counter()
+ bvh = BVHTree.FromBMesh(bm)
+ print(f"[StableGen Make Solid] Built BVH in {time.perf_counter() - t0:.4f}s")
+
+ verts_co = np.empty(len(temp.vertices) * 3, dtype=np.float32)
+ temp.vertices.foreach_get("co", verts_co)
+ verts_co = verts_co.reshape((-1, 3))
+
+ xmin, ymin, zmin = verts_co.min(axis=0)
+ xmax, ymax, zmax = verts_co.max(axis=0)
+
+ cx = (xmin + xmax) * 0.5
+ cy = (ymin + ymax) * 0.5
+ cz = (zmin + zmax) * 0.5
+
+ radius = max(xmax - xmin, ymax - ymin) * 0.5 * 1.25
+ z_top = zmax + (zmax - zmin) * 0.25
+ z_bottom = zmin
+
+ # Precompute cylinder angle offsets (ordered by proximity to 0.0)
+ raycast_count = 12
+ if hasattr(bpy, "context") and bpy.context and hasattr(bpy.context, "scene") and bpy.context.scene:
+ raycast_count = getattr(bpy.context.scene, "stablegen_print_raycast_count", 12)
+
+ angle_offsets = [0.0]
+ step = 2.0 * math.pi / raycast_count
+ i = 1
+ while len(angle_offsets) < raycast_count:
+ angle_offsets.append(i * step)
+ if len(angle_offsets) < raycast_count:
+ angle_offsets.append(-i * step)
+ i += 1
+
+ t0 = time.perf_counter()
+ visible_faces = set()
+
+ for f in bm.faces:
+ C = f.calc_center_median()
+ is_visible = False
+
+ # Check top point first (useful fallback for upper surface concavities)
+ P_top = mathutils.Vector((C.x, C.y, z_top))
+ direction = C - P_top
+ dist = direction.length
+ if dist > 1e-6:
+ direction.normalize()
+ hit_loc, hit_normal, hit_idx, hit_dist = bvh.ray_cast(P_top, direction)
+ if hit_loc is not None and hit_idx == f.index:
+ is_visible = True
+
+ if not is_visible:
+ dx = C.x - cx
+ dy = C.y - cy
+ dist_xy = math.sqrt(dx*dx + dy*dy)
+ if dist_xy < 1e-6:
+ dx, dy = 1.0, 0.0
+ dist_xy = 1.0
+ nx = dx / dist_xy
+ ny = dy / dist_xy
+ base_angle = math.atan2(ny, nx)
+
+ heights = [C.z, (C.z + z_bottom) * 0.5, z_bottom, (C.z + z_top) * 0.5, z_top]
+
+ for h in heights:
+ pz = max(h, z_bottom)
+ for offset in angle_offsets:
+ angle = base_angle + offset
+ px = cx + radius * math.cos(angle)
+ py = cy + radius * math.sin(angle)
+ P = mathutils.Vector((px, py, pz))
+
+ direction = C - P
+ dist = direction.length
+ if dist < 1e-6:
+ continue
+ direction.normalize()
+
+ hit_loc, hit_normal, hit_idx, hit_dist = bvh.ray_cast(P, direction)
+ if hit_loc is not None and hit_idx == f.index:
+ is_visible = True
+ break
+ if is_visible:
+ break
+
+ if is_visible:
+ visible_faces.add(f.index)
+ print(f"[StableGen Make Solid] Checked face visibility ({len(bm.faces)} faces) in {time.perf_counter() - t0:.4f}s")
+
+ t0 = time.perf_counter()
+ faces_to_delete = [f for f in bm.faces if f.index not in visible_faces]
+ bmesh.ops.delete(bm, geom=faces_to_delete, context='FACES')
+
+ bm.faces.ensure_lookup_table()
+ bm.edges.ensure_lookup_table()
+ bm.verts.ensure_lookup_table()
+
+ loose_edges = [e for e in bm.edges if not e.link_faces]
+ if loose_edges:
+ bmesh.ops.delete(bm, geom=loose_edges, context='EDGES')
+ loose_verts = [v for v in bm.verts if not v.link_edges]
+ if loose_verts:
+ bmesh.ops.delete(bm, geom=loose_verts, context='VERTS')
+
+ bm.faces.ensure_lookup_table()
+ bm.edges.ensure_lookup_table()
+ bm.verts.ensure_lookup_table()
+ print(f"[StableGen Make Solid] Deleted invisible geometry in {time.perf_counter() - t0:.4f}s")
+
+ if fill_gaps:
+ t0 = time.perf_counter()
+ visible_centers = {tuple(round(c, 4) for c in f.calc_center_median()) for f in bm.faces}
+
+ # 2. Identify all boundary edges after deletion
+ boundary_edges = [e for e in bm.edges if e.is_boundary]
+ print(f"[StableGen Make Solid] Identified {len(boundary_edges)} boundary edges in {time.perf_counter() - t0:.4f}s")
+
+ # 3. Walk and trace all boundary edge loops to create new cap faces directly (incredibly fast)
+ t0 = time.perf_counter()
+ new_faces = []
+
+ # Map each boundary edge to its desired directed transition (v -> u)
+ # to ensure that the cap face traverses the edge in the opposite direction
+ # of the adjacent face (achieving a consistent winding order and correct outward normal).
+ directed_transitions = []
+ for e in boundary_edges:
+ f = e.link_faces[0]
+ target_loop = None
+ for l in f.loops:
+ if l.edge == e:
+ target_loop = l
+ break
+ if target_loop:
+ u = target_loop.vert
+ v = target_loop.link_loop_next.vert
+ directed_transitions.append((v, u, e))
+
+ # Group directed transitions by their start vertex
+ from collections import defaultdict
+ vert_to_transitions = defaultdict(list)
+ for trans in directed_transitions:
+ v_start, v_end, e = trans
+ vert_to_transitions[v_start].append(trans)
+
+ directed_edges_set = set(directed_transitions)
+ while directed_edges_set:
+ start_trans = directed_edges_set.pop()
+ v_start, v_next, e = start_trans
+
+ loop_verts = [v_start]
+ visited_verts_set = {v_start}
+ v_curr = v_next
+
+ while True:
+ # Cycle detection: split complex/bowtie networks into separate simple faces
+ if v_curr in visited_verts_set:
+ idx = loop_verts.index(v_curr)
+ cycle = loop_verts[idx:]
+ if len(cycle) >= 3:
+ try:
+ nf = bm.faces.new(cycle)
+ new_faces.append(nf)
+ except Exception:
+ pass
+ # Remove the completed cycle from the active walk path
+ loop_verts = loop_verts[:idx]
+ visited_verts_set = set(loop_verts)
+
+ loop_verts.append(v_curr)
+ visited_verts_set.add(v_curr)
+
+ next_trans = None
+ for trans in vert_to_transitions[v_curr]:
+ if trans in directed_edges_set:
+ next_trans = trans
+ break
+ if next_trans is None:
+ # Close the remaining walk path if valid
+ if len(loop_verts) >= 3:
+ try:
+ nf = bm.faces.new(loop_verts)
+ new_faces.append(nf)
+ except Exception:
+ pass
+ break
+
+ directed_edges_set.remove(next_trans)
+ v_curr = next_trans[1]
+ print(f"[StableGen Make Solid] Traced and created {len(new_faces)} cap faces in {time.perf_counter() - t0:.4f}s")
+
+ # 5. Triangulate the newly created cap faces using beauty settings
+ t0 = time.perf_counter()
+ if new_faces:
+ try:
+ bmesh.ops.triangulate(bm, faces=new_faces, quad_method='BEAUTY', ngon_method='BEAUTY')
+ except Exception as e:
+ print(f"[StableGen Make Solid] Warning: BMesh triangulation failed: {e}")
+ print(f"[StableGen Make Solid] Triangulated new faces in {time.perf_counter() - t0:.4f}s")
+
+ # 6. Find new faces and transfer nearest colors
+ t0 = time.perf_counter()
+ final_new_faces = []
+ for f in bm.faces:
+ center_key = tuple(round(c, 4) for c in f.calc_center_median())
+ if center_key not in visible_centers:
+ final_new_faces.append(f)
+
+ if color_lay and final_new_faces:
+ valid_face_info = [info for info in face_info if info[2] in visible_faces]
+ if valid_face_info:
+ for nf in final_new_faces:
+ nf_center = nf.calc_center_median()
+ best_dist = float('inf')
+ best_color = (0.5, 0.5, 0.5, 1.0)
+ for orig_center, orig_color, _ in valid_face_info:
+ d = (orig_center - nf_center).length_squared
+ if d < best_dist:
+ best_dist = d
+ best_color = orig_color
+
+ for loop in nf.loops:
+ loop[color_lay] = best_color
+ print(f"[StableGen Make Solid] Mapped colors in {time.perf_counter() - t0:.4f}s")
+
+ # Update normals in BMesh
+ try:
+ bm.normal_update()
+ except Exception as e:
+ print(f"[StableGen Make Solid] Warning: could not update normals: {e}")
+
+ solid_mesh = bpy.data.meshes.new(f"{obj.name}_solid")
+ bm.to_mesh(solid_mesh)
+ bm.free()
+
+ solid_mesh.calc_loop_triangles()
+ print(f"[StableGen Make Solid] Total execution time: {time.perf_counter() - t_start:.4f}s")
+ return solid_mesh
+ finally:
+ eval_obj.to_mesh_clear()
+
+
+def _extract_mesh_data(obj, apply_transforms, palette_rgbs, image):
+ """Extract triangulated mesh data with per-triangle extruder IDs.
+
+ Returns ``(verts, tris, paint_colors, palette)`` where:
+ *verts* — NumPy float32 array (V, 3)
+ *tris* — NumPy int32 array (T, 3)
+ *paint_colors* — NumPy int32 array (T,) (1-based, 0 = no assignment)
+ *palette* — list of ``(hex_str, (r,g,b))``
+ """
+ import numpy as np
+ import bpy
+
+ scene = bpy.context.scene
+ make_solid = getattr(scene, "stablegen_print_make_solid", False)
+ chroma_threshold = getattr(scene, "stablegen_print_chroma_threshold", 0.35)
+
+ if make_solid:
+ if not obj.data.color_attributes.get("SG_PrintPreview"):
+ raise ValueError(f"Make Solid requires the 'SG_PrintPreview' color attribute. Run 'Preview Colors' first on {obj.name}.")
+ temp = _make_solid_mesh_object(obj)
+ eval_obj = None
+ else:
+ temp, eval_obj = _get_triangulated_mesh(obj, apply_transforms)
+
+ try:
+ n_verts = len(temp.vertices)
+ verts = np.empty(n_verts * 3, dtype=np.float32)
+ temp.vertices.foreach_get("co", verts)
+ verts = verts.reshape((-1, 3))
+
+ color_layer = temp.color_attributes.get("SG_PrintPreview")
+
+ if palette_rgbs and (color_layer or image):
+ if image and not make_solid:
+ face_colors = _collect_face_colors(temp, image)
+ elif color_layer:
+ n_loops = len(temp.loops)
+ loop_colors = np.empty(n_loops * 4, dtype=np.float32)
+ color_layer.data.foreach_get("color", loop_colors)
+ loop_colors = loop_colors.reshape((-1, 4))
+
+ n_tris = len(temp.loop_triangles)
+ tri_loops = np.empty(n_tris * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("loops", tri_loops)
+ tri_loops = tri_loops.reshape((-1, 3))
+
+ face_colors = loop_colors[tri_loops].mean(axis=1)
+ if color_layer.data_type == 'BYTE_COLOR':
+ face_colors[:, :3] = srgb_to_linear_numpy(face_colors[:, :3])
+ else:
+ face_colors = _collect_face_colors(temp, image)
+
+ face_colors_rgb = face_colors[:, :3]
+ face_colors_rgb_srgb = linear_to_srgb_numpy(face_colors_rgb)
+ material_indices = _match_colors_hsv(face_colors_rgb_srgb, palette_rgbs, chroma_threshold=chroma_threshold)
+
+ smoothing_passes = getattr(scene, "stablegen_print_smoothing", 2)
+ if smoothing_passes > 0:
+ n_tris = len(temp.loop_triangles)
+ tri_verts = np.empty(n_tris * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("vertices", tri_verts)
+ tri_verts = tri_verts.reshape((-1, 3))
+
+ material_indices = _smooth_colors_vectorized(
+ tri_verts, material_indices + 1, len(temp.vertices), len(palette_rgbs), iterations=smoothing_passes
+ ) - 1
+
+ centroids = palette_rgbs
+ else:
+ material_indices = np.zeros(len(temp.loop_triangles), dtype=np.int32)
+ centroids = [(0.7, 0.7, 0.7)]
+
+ palette = []
+ hex_lookup = {}
+ for col in centroids:
+ hex_c = _rgb_to_hex(col)
+ if hex_c not in hex_lookup:
+ hex_lookup[hex_c] = len(palette)
+ palette.append((hex_c, col))
+
+ map_arr = np.zeros(len(centroids), dtype=np.int32)
+ for ci, col in enumerate(centroids):
+ hex_c = _rgb_to_hex(col)
+ map_arr[ci] = hex_lookup.get(hex_c, 0) + 1
+
+ paint_colors = map_arr[material_indices]
+
+ n_tris = len(temp.loop_triangles)
+ tris = np.empty(n_tris * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("vertices", tris)
+ tris = tris.reshape((-1, 3))
+ finally:
+ if eval_obj is not None:
+ eval_obj.to_mesh_clear()
+ else:
+ bpy.data.meshes.remove(temp)
+
+ return verts, tris, paint_colors, palette
+
+
+# ── Operator: selection / state helpers ──────────────────────────────────
+
+class _SelectionSnapshot:
+ def __init__(self, context):
+ self.selected = list(context.selected_objects)
+ self.active = context.view_layer.objects.active
+
+ def restore(self, context):
+ bpy.ops.object.select_all(action='DESELECT')
+ for o in self.selected:
+ try:
+ o.select_set(True)
+ except ReferenceError:
+ pass
+ if self.active:
+ try:
+ context.view_layer.objects.active = self.active
+ except ReferenceError:
+ pass
+
+
+def _get_mesh_objects(context, scope):
+ if scope == 'ALL_MESH':
+ return [o for o in context.view_layer.objects
+ if o.type == 'MESH' and not o.hide_get()]
+ return [o for o in context.selected_objects if o.type == 'MESH']
+
+
+def _poll_common(context):
+ addon_prefs = get_addon_prefs(context)
+ if not addon_prefs or not os.path.exists(addon_prefs.output_dir):
+ return "Output directory not set or does not exist (check addon preferences)"
+ if sg_modal_active(context):
+ return "Another operation is in progress"
+ return None
+
+
+# ── ExportSTL ────────────────────────────────────────────────────────────
+
+class ExportSTL(bpy.types.Operator):
+ """Export selected mesh objects as STL for 3D printing."""
+ bl_idname = "object.export_stl"
+ bl_label = "Export STL"
+ bl_options = {'REGISTER'}
+
+ export_scope: bpy.props.EnumProperty(
+ name="Objects",
+ items=[
+ ('SELECTED', 'Selected', 'Export selected mesh objects'),
+ ('ALL_MESH', 'All Mesh', 'Export all visible mesh objects'),
+ ],
+ default='SELECTED',
+ )
+ apply_transforms: bpy.props.BoolProperty(
+ name="Apply Transforms",
+ description="Apply location, rotation and scale before export",
+ default=True,
+ )
+
+ @classmethod
+ def poll(cls, context):
+ msg = _poll_common(context)
+ if msg:
+ cls.poll_message_set(msg)
+ return False
+ return True
+
+ def draw(self, context):
+ self.layout.prop(self, "export_scope")
+ self.layout.prop(self, "apply_transforms")
+
+ def invoke(self, context, event):
+ return context.window_manager.invoke_props_dialog(self)
+
+ def execute(self, context):
+ meshes = _get_mesh_objects(context, self.export_scope)
+ if not meshes:
+ self.report({'ERROR'}, "No mesh objects to export.")
+ return {'CANCELLED'}
+
+ # Verify SG_PrintPreview if Make Solid is enabled
+ scene = context.scene
+ if getattr(scene, "stablegen_print_make_solid", False):
+ for o in meshes:
+ if not o.data.color_attributes.get("SG_PrintPreview"):
+ self.report({'ERROR'}, f"Make Solid requires the 'SG_PrintPreview' color attribute. Run 'Preview Colors' first on {o.name}.")
+ return {'CANCELLED'}
+
+ snap = _SelectionSnapshot(context)
+ output_dir = get_dir_path(context, "baked")
+ os.makedirs(output_dir, exist_ok=True)
+ filepath = os.path.join(output_dir, f"{meshes[0].name}.stl")
+
+ bpy.ops.object.select_all(action='DESELECT')
+ for o in meshes:
+ o.select_set(True)
+ context.view_layer.objects.active = meshes[0]
+
+ if self.apply_transforms:
+ bpy.ops.object.transform_apply(
+ location=True, rotation=True, scale=True)
+
+ solidified_mappings = {}
+ try:
+ if getattr(scene, "stablegen_print_make_solid", False):
+ for o in meshes:
+ solid_mesh = _make_solid_mesh_object(o)
+ solidified_mappings[o] = (o.data, solid_mesh)
+ o.data = solid_mesh
+
+ if hasattr(bpy.ops.wm, 'stl_export'):
+ bpy.ops.wm.stl_export(
+ filepath=filepath,
+ global_scale=1.0,
+ )
+ else:
+ bpy.ops.export_mesh.stl(
+ filepath=filepath,
+ use_selection=True,
+ ascii=False,
+ global_scale=1.0,
+ )
+ self.report({'INFO'}, f"STL exported to {filepath}")
+ except Exception as e:
+ self.report({'ERROR'}, f"STL export failed: {e}")
+ import traceback
+ traceback.print_exc()
+ snap.restore(context)
+ return {'CANCELLED'}
+ finally:
+ for o, (orig_mesh, solid_mesh) in solidified_mappings.items():
+ o.data = orig_mesh
+ bpy.data.meshes.remove(solid_mesh)
+
+ snap.restore(context)
+ return {'FINISHED'}
+
+
+# ── Asynchronous Exporter Workers ───────────────────────────────────────
+
+def _prepare_mesh_for_raycasting(obj):
+ import bmesh
+ import numpy as np
+ temp, eval_obj = _get_triangulated_mesh(obj, apply_transforms=False)
+ bm = bmesh.new()
+ bm.from_mesh(temp)
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0001)
+
+ bm.verts.ensure_lookup_table()
+ bm.faces.ensure_lookup_table()
+ coords = [v.co.copy() for v in bm.verts]
+ faces = [[v.index for v in f.verts] for f in bm.faces]
+
+ verts_co = np.array(coords, dtype=np.float32)
+ xmin, ymin, zmin = verts_co.min(axis=0)
+ xmax, ymax, zmax = verts_co.max(axis=0)
+
+ cx = (xmin + xmax) * 0.5
+ cy = (ymin + ymax) * 0.5
+
+ radius = max(xmax - xmin, ymax - ymin) * 0.5 * 1.25
+ z_top = zmax + (zmax - zmin) * 0.25
+ z_bottom = zmin
+
+ bm.free()
+ eval_obj.to_mesh_clear()
+
+ return {
+ "coords": coords,
+ "faces": faces,
+ "cx": cx,
+ "cy": cy,
+ "radius": radius,
+ "z_top": z_top,
+ "z_bottom": z_bottom
+ }
+
+
+def _raycast_visibility_worker(mesh_tasks, angle_offsets, status_dict):
+ import time
+ import math
+ import mathutils
+ from mathutils.bvhtree import BVHTree
+ import numpy as np
+
+ try:
+ results = []
+ n_tasks = len(mesh_tasks)
+ for task_idx, task in enumerate(mesh_tasks):
+ if status_dict.get("cancel_requested", False):
+ return
+
+ coords = task["coords"]
+ faces = task["faces"]
+ cx = task["cx"]
+ cy = task["cy"]
+ radius = task["radius"]
+ z_top = task["z_top"]
+ z_bottom = task["z_bottom"]
+
+ status_dict["stage"] = f"Building BVH tree ({task_idx + 1}/{n_tasks})"
+ status_dict["progress"] = (task_idx / n_tasks) * 100.0 + 5.0 / n_tasks
+
+ bvh = BVHTree.FromPolygons(coords, faces)
+
+ status_dict["stage"] = f"Raycasting visibility check ({task_idx + 1}/{n_tasks})"
+
+ visible_faces = set()
+ n_faces = len(faces)
+ progress_step = max(1, n_faces // 50)
+
+ for face_idx, f_verts in enumerate(faces):
+ if status_dict.get("cancel_requested", False):
+ return
+
+ if face_idx % progress_step == 0:
+ pct = (task_idx / n_tasks) * 100.0 + ((10.0 + (face_idx / n_faces) * 80.0) / n_tasks)
+ status_dict["progress"] = pct
+
+ v1, v2, v3 = coords[f_verts[0]], coords[f_verts[1]], coords[f_verts[2]]
+ cx_f = (v1[0] + v2[0] + v3[0]) / 3.0
+ cy_f = (v1[1] + v2[1] + v3[1]) / 3.0
+ cz_f = (v1[2] + v2[2] + v3[2]) / 3.0
+ C = mathutils.Vector((cx_f, cy_f, cz_f))
+
+ is_visible = False
+
+ P_top = mathutils.Vector((cx_f, cy_f, z_top))
+ direction = C - P_top
+ dist = direction.length
+ if dist > 1e-6:
+ direction.normalize()
+ hit_loc, hit_normal, hit_idx, hit_dist = bvh.ray_cast(P_top, direction)
+ if hit_loc is not None and hit_idx == face_idx:
+ is_visible = True
+
+ if not is_visible:
+ dx = cx_f - cx
+ dy = cy_f - cy
+ dist_xy = math.sqrt(dx*dx + dy*dy)
+ if dist_xy < 1e-6:
+ dx, dy = 1.0, 0.0
+ dist_xy = 1.0
+ nx = dx / dist_xy
+ ny = dy / dist_xy
+ base_angle = math.atan2(ny, nx)
+
+ heights = [cz_f, (cz_f + z_bottom) * 0.5, z_bottom, (cz_f + z_top) * 0.5, z_top]
+ for h in heights:
+ pz = max(h, z_bottom)
+ for offset in angle_offsets:
+ angle = base_angle + offset
+ px = cx + radius * math.cos(angle)
+ py = cy + radius * math.sin(angle)
+ P = mathutils.Vector((px, py, pz))
+
+ direction = C - P
+ dist = direction.length
+ if dist < 1e-6:
+ continue
+ direction.normalize()
+
+ hit_loc, hit_normal, hit_idx, hit_dist = bvh.ray_cast(P, direction)
+ if hit_loc is not None and hit_idx == face_idx:
+ is_visible = True
+ break
+ if is_visible:
+ break
+
+ if is_visible:
+ visible_faces.add(face_idx)
+
+ results.append(visible_faces)
+
+ status_dict["visible_faces_results"] = results
+ status_dict["progress"] = 100.0
+ status_dict["stage"] = "Visibility check completed"
+ status_dict["done"] = True
+ except Exception as e:
+ status_dict["error"] = e
+ status_dict["done"] = True
+
+
+def _export_3mf_worker(is_dithered, filepath, palette_rgbs, solid_data, dithered_data, status_dict):
+ import time
+ import math
+ import json
+ import numpy as np
+ import xml.etree.ElementTree as ET
+
+ try:
+ if not is_dithered:
+ status_dict["stage"] = "Building model XML"
+ status_dict["progress"] = 10.0
+
+ all_verts_arr = solid_data["all_verts_arr"]
+ all_tris_arr = solid_data["all_tris_arr"]
+ all_paint_arr = solid_data["all_paint_arr"]
+ global_palette = solid_data["global_palette"]
+ global_to_extruder = solid_data["global_to_extruder"]
+ parent_id = solid_data["parent_id"]
+ child_ids_and_extruders = solid_data["child_ids_and_extruders"]
+ project_settings_json = solid_data["project_settings_json"]
+ prusa_config = solid_data["prusa_config"]
+ prusa_model_config = solid_data["prusa_model_config"]
+
+ model, parent_id, child_ids_and_extruders = _build_model_element(
+ all_verts_arr, all_tris_arr, all_paint_arr, global_palette,
+ global_to_extruder=global_to_extruder
+ )
+
+ if status_dict.get("cancel_requested", False):
+ return
+
+ status_dict["stage"] = "Writing 3MF package"
+ status_dict["progress"] = 50.0
+ model_settings = _build_model_settings_element(parent_id, child_ids_and_extruders)
+
+ _write_3mf_archive(filepath, model, model_settings, project_settings_json, prusa_config, prusa_model_config)
+
+ status_dict["progress"] = 100.0
+ status_dict["stage"] = "Completed"
+ status_dict["done"] = True
+ status_dict["total_triangles"] = len(all_tris_arr)
+ return
+
+ # DITHERED MODE
+ all_raw_verts = dithered_data["all_raw_verts"]
+ all_raw_tris = dithered_data["all_raw_tris"]
+ all_raw_face_colors = dithered_data["all_raw_face_colors"]
+ h_target = dithered_data["h_target"]
+ LH = dithered_data["LH"]
+ n_layers = dithered_data["n_layers"]
+ unique_keys = dithered_data["unique_keys"]
+ unique_colors_arr = dithered_data["unique_colors_arr"]
+ mode = dithered_data["mode"]
+ channel_indices = dithered_data["channel_indices"]
+ channels_order = dithered_data["channels_order"]
+ mesh_name = dithered_data["mesh_name"]
+ cyan_idx = dithered_data["cyan_idx"]
+
+ status_dict["stage"] = "Scaling geometry"
+ status_dict["progress"] = 5.0
+
+ z_min, z_max = all_raw_verts[:, 2].min(), all_raw_verts[:, 2].max()
+ h_blender = z_max - z_min
+ if h_blender < 1e-5:
+ h_blender = 1.0
+ scale_factor = h_target / h_blender
+
+ scaled_verts = all_raw_verts.copy()
+ scaled_verts[:, 0] *= scale_factor
+ scaled_verts[:, 1] *= scale_factor
+ scaled_verts[:, 2] = (scaled_verts[:, 2] - z_min) * scale_factor
+
+ # Solve filament demands
+ status_dict["stage"] = "Calculating filament demands"
+ status_dict["progress"] = 15.0
+
+ n_channels = len(channel_indices)
+ if mode == 'solid':
+ fil_rgbs = np.array(palette_rgbs, dtype=np.float32)
+ solver_settings = dithered_data.get("solver_settings", {})
+ iters = solver_settings.get("iterations", 80)
+ init_m = solver_settings.get("init_method", 'CLOSEST')
+ formula = solver_settings.get("model_formula", 'KUBELKA_MUNK')
+ s_weight = solver_settings.get("scat_weight", 10.0)
+ p_weight = solver_settings.get("penalty_weight", 1.0)
+
+ demands = solve_color_mixing_numpy(
+ 1.0 - fil_rgbs, 1.0 - unique_colors_arr,
+ iterations=iters,
+ init_method=init_m,
+ model_formula=formula,
+ scat_weight=s_weight,
+ penalty_weight=p_weight
+ )
+ else:
+ demands = np.empty((len(unique_colors_arr), n_channels), dtype=np.float32)
+ for idx, color in enumerate(unique_colors_arr):
+ r, g, b = round(color[0] * 255.0), round(color[1] * 255.0), round(color[2] * 255.0)
+ demands[idx] = decompose_subtractive(r, g, b, mode, palette_rgbs, channel_indices)
+
+ # Build dither sequences
+ status_dict["stage"] = "Building dither sequences"
+ status_dict["progress"] = 25.0
+
+ color_seqs = {}
+ unique_colors_set = [tuple(round(c * 255.0) for c in color) for color in unique_colors_arr]
+
+ for idx, color_key in enumerate(unique_colors_set):
+ if status_dict.get("cancel_requested", False):
+ return
+ row = demands[idx]
+ total = sum(max(0.0, d) for d in row)
+ seq = [0] * n_layers
+
+ if total < 0.001:
+ if cyan_idx >= 0:
+ nc = min(3, n_channels - cyan_idx)
+ for li in range(n_layers):
+ seq[li] = cyan_idx + (li % nc)
+ else:
+ for li in range(n_layers):
+ seq[li] = li % n_channels
+ else:
+ frac = [max(0.0, d) / total for d in row]
+ placed = [0] * n_channels
+ for li in range(n_layers):
+ best_ch = 0
+ best_d = -float('inf')
+ for ch in range(n_channels):
+ if frac[ch] < 0.001:
+ continue
+ d = frac[ch] * (li + 1) - placed[ch]
+ tie_break = d + ch * 1e-6 + (1e-7 if li % n_channels == ch else 0.0)
+ if tie_break > best_d:
+ best_d = tie_break
+ best_ch = ch
+ seq[li] = best_ch
+ placed[best_ch] += 1
+ color_seqs[color_key] = seq
+
+ # Slicing and clipping
+ status_dict["stage"] = "Clipping layers"
+ status_dict["progress"] = 35.0
+
+ clipped_tris = []
+ ZOFF = LH / 2
+
+ n_raw_tris = len(all_raw_tris)
+ progress_step = max(1, n_raw_tris // 50)
+
+ for fi in range(n_raw_tris):
+ if status_dict.get("cancel_requested", False):
+ return
+
+ if fi % progress_step == 0:
+ pct = 35.0 + (fi / n_raw_tris) * 35.0 # maps to 35% - 70%
+ status_dict["progress"] = pct
+
+ t_idx = all_raw_tris[fi]
+ v1, v2, v3 = scaled_verts[t_idx[0]], scaled_verts[t_idx[1]], scaled_verts[t_idx[2]]
+ fz_min = min(v1[2], v2[2], v3[2])
+ fz_max = max(v1[2], v2[2], v3[2])
+
+ tri = [list(v1), list(v2), list(v3)]
+
+ li_start = max(0, int(math.floor((fz_min - ZOFF) / LH)))
+ li_end = min(n_layers - 1, int(math.ceil((fz_max - ZOFF) / LH)))
+
+ color_key = unique_keys[fi]
+ seq = color_seqs[color_key]
+
+ if li_start == li_end or li_start >= n_layers:
+ cz = (fz_min + fz_max) / 2
+ li2 = max(0, min(n_layers - 1, int(math.floor((cz - ZOFF) / LH))))
+ clipped_tris.append((tri, seq[li2]))
+ else:
+ for li in range(li_start, li_end + 1):
+ if li >= n_layers:
+ break
+ zB = ZOFF + li * LH
+ zT = ZOFF + (li + 1) * LH
+ sub_tris = cTZ(tri, zB, zT)
+ for st in sub_tris:
+ clipped_tris.append((st, seq[li]))
+
+ # Weld vertices
+ status_dict["stage"] = "Welding vertices"
+ status_dict["progress"] = 70.0
+
+ weld_map = {}
+ welded_verts = []
+ welded_tris = []
+ paint_arr = []
+
+ n_clipped = len(clipped_tris)
+ progress_step_w = max(1, n_clipped // 50)
+
+ for w_idx, (tri, filament_idx) in enumerate(clipped_tris):
+ if status_dict.get("cancel_requested", False):
+ return
+
+ if w_idx % progress_step_w == 0:
+ pct = 70.0 + (w_idx / n_clipped) * 15.0 # maps to 70% - 85%
+ status_dict["progress"] = pct
+
+ tri_idx = []
+ for pt in tri:
+ key = (round(pt[0], 6), round(pt[1], 6), round(pt[2], 6))
+ if key not in weld_map:
+ weld_map[key] = len(welded_verts)
+ welded_verts.append(pt)
+ tri_idx.append(weld_map[key])
+
+ if tri_idx[0] != tri_idx[1] and tri_idx[1] != tri_idx[2] and tri_idx[0] != tri_idx[2]:
+ welded_tris.append(tri_idx)
+ paint_arr.append(filament_idx)
+
+ all_verts_arr = np.array(welded_verts, dtype=np.float32)
+ all_tris_arr = np.array(welded_tris, dtype=np.int32)
+ all_paint_arr = np.array(paint_arr, dtype=np.int32)
+
+ # Build colorgroup and global mapping
+ global_palette = []
+ for p_idx in channels_order:
+ color = palette_rgbs[p_idx]
+ global_palette.append((_rgb_to_hex(color), color))
+
+ global_to_extruder = {}
+ for i in range(len(channels_order)):
+ global_to_extruder[i + 1] = channels_order[i] + 1
+
+ # Slicer settings config
+ # Slicer settings config (must preserve original palette order so paint IDs align with extruders)
+ ch_colors6 = [_rgb_to_hex(color).upper() for color in palette_rgbs]
+ project_settings_json = json.dumps({"filament_colour": ch_colors6}, indent=4)
+
+ prusa_extruder_colors = ";".join(ch_colors6)
+ prusa_nozzles = ",".join(["0.4"] * len(palette_rgbs))
+ prusa_config = f"; extruder_colour = {prusa_extruder_colors}\n; filament_colour = {prusa_extruder_colors}\n; nozzle_diameter = {prusa_nozzles}\n"
+
+ safe_n = mesh_name.replace('&', '&amp;').replace('"', '&quot;')
+ prusa_model_config = f'<?xml version="1.0" encoding="UTF-8"?>\n<config>\n <object id="2" instances_count="1">\n <metadata type="object" key="name" value="{safe_n}"/>\n <volume firstid="0" lastid="{len(all_tris_arr)-1}">\n <metadata type="volume" key="name" value="{safe_n}"/>\n <metadata type="volume" key="volume_type" value="ModelPart"/>\n <metadata type="volume" key="matrix" value="1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1"/>\n <metadata type="volume" key="extruder" value="0"/>\n </volume>\n </object>\n</config>'
+
+ shifted_paint_arr = all_paint_arr + 1
+
+ status_dict["stage"] = "Generating 3D model XML"
+ status_dict["progress"] = 85.0
+
+ model, parent_id, child_ids_and_extruders = _build_model_element(
+ all_verts_arr, all_tris_arr, shifted_paint_arr, global_palette,
+ global_to_extruder=global_to_extruder
+ )
+ model_settings = _build_model_settings_element(parent_id, child_ids_and_extruders)
+
+ status_dict["stage"] = "Writing 3MF package"
+ status_dict["progress"] = 90.0
+
+ _write_3mf_archive(filepath, model, model_settings, project_settings_json, prusa_config, prusa_model_config)
+
+ status_dict["progress"] = 100.0
+ status_dict["stage"] = "Completed"
+ status_dict["done"] = True
+ status_dict["total_triangles"] = len(all_tris_arr)
+ except Exception as e:
+ status_dict["error"] = e
+ status_dict["done"] = True
+
+
+# ── Export3MF ────────────────────────────────────────────────────────────
+
+class Export3MF(bpy.types.Operator):
+ """Export selected mesh objects as 3MF for multi-color 3D printing."""
+ bl_idname = "object.export_3mf"
+ bl_label = "Export 3MF"
+ bl_options = {'REGISTER'}
+
+ export_scope: bpy.props.EnumProperty(
+ name="Objects",
+ items=[
+ ('SELECTED', 'Selected', 'Export selected mesh objects'),
+ ('ALL_MESH', 'All Mesh', 'Export all visible mesh objects'),
+ ],
+ default='SELECTED',
+ )
+ apply_transforms: bpy.props.BoolProperty(
+ name="Apply Transforms",
+ description="Apply location, rotation and scale before export",
+ default=True,
+ )
+
+ _timer = None
+ _thread = None
+ _thread_status = None
+ _snap = None
+ _progress = 0.0
+ _stage = ""
+ _temp_solid_meshes = None
+ _solidified_mappings = None
+ _phase = ""
+ _prepared_tasks = None
+ _meshes = None
+ _filepath = ""
+ _palette_rgbs = None
+ _is_dithered = False
+
+ @classmethod
+ def poll(cls, context):
+ msg = _poll_common(context)
+ if msg:
+ cls.poll_message_set(msg)
+ return False
+ return True
+
+ def draw(self, context):
+ self.layout.prop(self, "export_scope")
+ self.layout.prop(self, "apply_transforms")
+
+ def invoke(self, context, event):
+ return context.window_manager.invoke_props_dialog(self)
+
+ def execute(self, context):
+ meshes = _get_mesh_objects(context, self.export_scope)
+ if not meshes:
+ self.report({'ERROR'}, "No mesh objects to export.")
+ return {'CANCELLED'}
+
+ scene = context.scene
+ if not scene.stablegen_print_palette:
+ prepopulate_palette(scene)
+
+ import numpy as np
+ palette_rgbs_linear = np.array([item.color for item in scene.stablegen_print_palette], dtype=np.float32)
+ palette_rgbs = [tuple(c) for c in linear_to_srgb_numpy(palette_rgbs_linear)]
+ if not palette_rgbs:
+ self.report({'ERROR'}, "Print color palette is empty.")
+ return {'CANCELLED'}
+
+ # Verify SG_PrintPreview if Make Solid is enabled
+ make_solid = getattr(scene, "stablegen_print_make_solid", False)
+ if make_solid:
+ for o in meshes:
+ if not o.data.color_attributes.get("SG_PrintPreview"):
+ self.report({'ERROR'}, f"Make Solid requires the 'SG_PrintPreview' color attribute. Run 'Preview Colors' first on {o.name}.")
+ return {'CANCELLED'}
+
+ self._snap = _SelectionSnapshot(context)
+ self._meshes = meshes
+ self._palette_rgbs = palette_rgbs
+ self._is_dithered = getattr(scene, "stablegen_print_dithered", True)
+ self._temp_solid_meshes = []
+ self._solidified_mappings = {}
+
+ output_dir = get_dir_path(context, "baked")
+ os.makedirs(output_dir, exist_ok=True)
+ self._filepath = os.path.join(output_dir, f"{meshes[0].name}.3mf")
+
+ if self.apply_transforms:
+ bpy.ops.object.select_all(action='DESELECT')
+ for o in meshes:
+ o.select_set(True)
+ context.view_layer.objects.active = meshes[0]
+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
+
+ self._progress = 0.0
+ self._stage = "Initializing"
+
+ if make_solid:
+ self._phase = 'RAYCASTING'
+ self._stage = "Preparing raycast tasks"
+
+ self._prepared_tasks = []
+ try:
+ for obj in meshes:
+ task = _prepare_mesh_for_raycasting(obj)
+ self._prepared_tasks.append(task)
+ except Exception as e:
+ self.report({'ERROR'}, f"Failed to prepare meshes for raycasting: {e}")
+ self._snap.restore(context)
+ return {'CANCELLED'}
+
+ import math
+ raycast_count = getattr(context.scene, "stablegen_print_raycast_count", 12)
+ angle_offsets = [0.0]
+ step = 2.0 * math.pi / raycast_count
+ i = 1
+ while len(angle_offsets) < raycast_count:
+ angle_offsets.append(i * step)
+ if len(angle_offsets) < raycast_count:
+ angle_offsets.append(-i * step)
+ i += 1
+
+ import threading
+ self._thread_status = {
+ "progress": 0.0,
+ "stage": "Starting visibility check",
+ "done": False,
+ "cancel_requested": False
+ }
+ self._thread = threading.Thread(
+ target=_raycast_visibility_worker,
+ args=(self._prepared_tasks, angle_offsets, self._thread_status),
+ daemon=True
+ )
+ self._thread.start()
+ else:
+ self._phase = 'EXPORTING'
+ self._stage = "Extracting mesh data"
+
+ success = self._start_exporting_worker(context)
+ if not success:
+ self._snap.restore(context)
+ return {'CANCELLED'}
+
+ context.window_manager.modal_handler_add(self)
+ self._timer = context.window_manager.event_timer_add(0.1, window=context.window)
+ return {'RUNNING_MODAL'}
+
+ def _start_exporting_worker(self, context):
+ scene = context.scene
+ orig_make_solid = scene.stablegen_print_make_solid
+ scene.stablegen_print_make_solid = False
+
+ try:
+ import numpy as np
+ import threading
+ import math
+
+ solid_data = {}
+ dithered_data = {}
+
+ if not self._is_dithered:
+ # ── SOLID MODE Extraction ──
+ all_verts = []
+ all_tris = []
+ all_paint = []
+ global_palette = []
+
+ for obj in self._meshes:
+ image = _find_texture_image(obj)
+ verts, tris, paint_colors, palette = _extract_mesh_data(
+ obj, apply_transforms=False,
+ palette_rgbs=self._palette_rgbs, image=image,
+ )
+
+ base_vi = sum(v.shape[0] for v in all_verts) if all_verts else 0
+ all_verts.append(verts)
+ all_tris.append(tris + base_vi)
+ all_paint.append(paint_colors)
+
+ for hex_c, rgb in palette:
+ if hex_c not in {c for c, _ in global_palette}:
+ global_palette.append((hex_c, rgb))
+
+ if not all_tris:
+ self.report({'ERROR'}, "No valid mesh data extracted.")
+ return False
+
+ all_verts_arr = np.concatenate(all_verts, axis=0)
+ all_tris_arr = np.concatenate(all_tris, axis=0)
+ all_paint_arr = np.concatenate(all_paint, axis=0)
+
+ global_to_extruder = {}
+ for seq_ext in range(1, len(global_palette) + 1):
+ hex_c = global_palette[seq_ext - 1][0]
+ p_idx = -1
+ for idx, item in enumerate(scene.stablegen_print_palette):
+ if _rgb_to_hex(item.color).upper() == hex_c.upper():
+ p_idx = idx
+ break
+ global_to_extruder[seq_ext] = p_idx + 1 if p_idx != -1 else seq_ext
+
+ import json
+ ch_colors6 = [_rgb_to_hex(rgb).upper() for rgb in self._palette_rgbs]
+ project_settings_json = json.dumps({"filament_colour": ch_colors6}, indent=4)
+
+ prusa_extruder_colors = ";".join(ch_colors6)
+ prusa_nozzles = ",".join(["0.4"] * len(self._palette_rgbs))
+ prusa_config = f"; extruder_colour = {prusa_extruder_colors}\n; filament_colour = {prusa_extruder_colors}\n; nozzle_diameter = {prusa_nozzles}\n"
+
+ safe_n = self._meshes[0].name.replace('&', '&amp;').replace('"', '&quot;')
+ prusa_model_config = f'<?xml version="1.0" encoding="UTF-8"?>\n<config>\n <object id="2" instances_count="1">\n <metadata type="object" key="name" value="{safe_n}"/>\n <volume firstid="0" lastid="{len(all_tris_arr)-1}">\n <metadata type="volume" key="name" value="{safe_n}"/>\n <metadata type="volume" key="volume_type" value="ModelPart"/>\n <metadata type="volume" key="matrix" value="1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1"/>\n <metadata type="volume" key="extruder" value="0"/>\n </volume>\n </object>\n</config>'
+
+ geom_obj_id = 1
+ parent_obj_id = 2
+
+ solid_data = {
+ "all_verts_arr": all_verts_arr,
+ "all_tris_arr": all_tris_arr,
+ "all_paint_arr": all_paint_arr,
+ "global_palette": global_palette,
+ "global_to_extruder": global_to_extruder,
+ "parent_id": parent_obj_id,
+ "child_ids_and_extruders": [(geom_obj_id, 1)],
+ "project_settings_json": project_settings_json,
+ "prusa_config": prusa_config,
+ "prusa_model_config": prusa_model_config
+ }
+ else:
+ # ── DITHERED MODE Extraction ──
+ raw_verts_list = []
+ raw_tris_list = []
+ raw_face_colors_list = []
+
+ for obj in self._meshes:
+ image = _find_texture_image(obj)
+ temp, eval_obj = _get_triangulated_mesh(obj, apply_transforms=False)
+
+ try:
+ n_v = len(temp.vertices)
+ v_co = np.empty(n_v * 3, dtype=np.float32)
+ temp.vertices.foreach_get("co", v_co)
+ v_co = v_co.reshape((-1, 3))
+
+ if image:
+ face_colors = _collect_face_colors(temp, image)[:, :3]
+ else:
+ color_layer = temp.color_attributes.get("SG_PrintPreview")
+ if color_layer:
+ n_loops = len(temp.loops)
+ loop_colors = np.empty(n_loops * 4, dtype=np.float32)
+ color_layer.data.foreach_get("color", loop_colors)
+ loop_colors = loop_colors.reshape((-1, 4))
+
+ n_tris = len(temp.loop_triangles)
+ tri_loops = np.empty(n_tris * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("loops", tri_loops)
+ tri_loops = tri_loops.reshape((-1, 3))
+
+ face_colors = loop_colors[tri_loops].mean(axis=1)[:, :3]
+ if color_layer.data_type == 'BYTE_COLOR':
+ face_colors = srgb_to_linear_numpy(face_colors)
+ else:
+ face_colors = np.ones((len(temp.loop_triangles), 3), dtype=np.float32)
+
+ t_idx = np.empty(len(temp.loop_triangles) * 3, dtype=np.int32)
+ temp.loop_triangles.foreach_get("vertices", t_idx)
+ t_idx = t_idx.reshape((-1, 3))
+
+ base_vi = sum(v.shape[0] for v in raw_verts_list) if raw_verts_list else 0
+ raw_verts_list.append(v_co)
+ raw_tris_list.append(t_idx + base_vi)
+ raw_face_colors_list.append(face_colors)
+ finally:
+ eval_obj.to_mesh_clear()
+
+ all_raw_verts = np.concatenate(raw_verts_list, axis=0)
+ all_raw_tris = np.concatenate(raw_tris_list, axis=0)
+ all_raw_face_colors = np.concatenate(raw_face_colors_list, axis=0)
+
+ h_target = scene.stablegen_print_model_height
+ LH = scene.stablegen_print_layer_height
+ n_layers = max(1, int(math.ceil(h_target / LH)))
+
+ face_colors_srgb = all_raw_face_colors
+ q = 8
+ face_colors_q = np.clip(np.round(face_colors_srgb * 255.0 / q) * q, 0, 255).astype(np.int32)
+ unique_keys = [tuple(c) for c in face_colors_q]
+ unique_colors_set = sorted(list(set(unique_keys)))
+ unique_colors_arr = np.array(unique_colors_set, dtype=np.float32) / 255.0
+
+ mode, channel_indices = classify_filaments(self._palette_rgbs)
+
+ if mode == 'solid':
+ channels_order = list(range(len(self._palette_rgbs)))
+ else:
+ channels_order = channel_indices
+
+ cyan_idx = -1
+ if mode != 'solid':
+ for ci, p_idx in enumerate(channel_indices):
+ if scene.stablegen_print_palette[p_idx].name == "Cyan":
+ cyan_idx = ci
+ break
+
+ dithered_data = {
+ "all_raw_verts": all_raw_verts,
+ "all_raw_tris": all_raw_tris,
+ "all_raw_face_colors": all_raw_face_colors,
+ "h_target": h_target,
+ "LH": LH,
+ "n_layers": n_layers,
+ "unique_keys": unique_keys,
+ "unique_colors_arr": unique_colors_arr,
+ "mode": mode,
+ "channel_indices": channel_indices,
+ "channels_order": channels_order,
+ "mesh_name": self._meshes[0].name,
+ "cyan_idx": cyan_idx,
+ "solver_settings": {
+ "init_method": getattr(scene, "stablegen_print_solver_init", 'CLOSEST'),
+ "iterations": getattr(scene, "stablegen_print_solver_steps", 80),
+ "model_formula": getattr(scene, "stablegen_print_solver_formula", 'KUBELKA_MUNK'),
+ "scat_weight": getattr(scene, "stablegen_print_scattering_weight", 10.0),
+ "penalty_weight": getattr(scene, "stablegen_print_saturation_penalty", 1.0),
+ }
+ }
+
+ self._thread_status = {
+ "progress": 0.0,
+ "stage": "Starting export worker",
+ "done": False,
+ "cancel_requested": False
+ }
+ self._thread = threading.Thread(
+ target=_export_3mf_worker,
+ args=(self._is_dithered, self._filepath, self._palette_rgbs, solid_data, dithered_data, self._thread_status),
+ daemon=True
+ )
+ self._thread.start()
+ return True
+
+ except Exception as e:
+ self.report({'ERROR'}, f"Failed to start export thread: {e}")
+ import traceback
+ traceback.print_exc()
+ return False
+ finally:
+ scene.stablegen_print_make_solid = orig_make_solid
+
+ def modal(self, context, event):
+ if event.type == 'TIMER':
+ for window in context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type in ('PROPERTIES', 'VIEW_3D'):
+ area.tag_redraw()
+
+ status = self._thread_status
+ if status.get("cancel_requested", False):
+ self.report({'INFO'}, "Export cancelled by user.")
+ self.cleanup(context)
+ return {'FINISHED'}
+
+ if status.get("done", False):
+ if "error" in status:
+ err = status["error"]
+ self.report({'ERROR'}, f"3MF export failed: {err}")
+ import traceback
+ print(f"[StableGen 3MF] Error details:")
+ if isinstance(err, Exception):
+ traceback.print_exception(type(err), err, err.__traceback__)
+ else:
+ print(err)
+ self.cleanup(context)
+ return {'CANCELLED'}
+
+ if self._phase == 'RAYCASTING':
+ self._phase = 'EXPORTING'
+ self._stage = "Raycasting completed. Starting export..."
+
+ visible_faces_results = status["visible_faces_results"]
+ fill_gaps = getattr(context.scene, "stablegen_print_fill_gaps", True)
+
+ try:
+ for idx, obj in enumerate(self._meshes):
+ vis_faces = visible_faces_results[idx]
+ solid_mesh = _make_solid_mesh_object(obj, fill_gaps=fill_gaps, visible_faces=vis_faces)
+ self._temp_solid_meshes.append(solid_mesh)
+
+ self._solidified_mappings[obj] = (obj.data, solid_mesh)
+ obj.data = solid_mesh
+
+ success = self._start_exporting_worker(context)
+ if not success:
+ self.cleanup(context)
+ return {'CANCELLED'}
+
+ except Exception as e:
+ self.report({'ERROR'}, f"Failed to solidify meshes: {e}")
+ import traceback
+ traceback.print_exc()
+ self.cleanup(context)
+ return {'CANCELLED'}
+ else:
+ n_extruders = len(self._palette_rgbs)
+ total_tris = status.get("total_triangles", 0)
+ self.report({'INFO'},
+ f"3MF exported to {self._filepath} "
+ f"({n_extruders} extruder{'' if n_extruders == 1 else 's'}, "
+ f"{total_tris} triangles)")
+ self.cleanup(context)
+ return {'FINISHED'}
+
+ self._progress = status.get("progress", 0.0)
+ self._stage = status.get("stage", "Processing")
+
+ return {'PASS_THROUGH'}
+
+ def cleanup(self, context):
+ if hasattr(self, "_snap") and self._snap:
+ self._snap.restore(context)
+
+ if hasattr(self, "_solidified_mappings") and self._solidified_mappings:
+ for obj, (orig_mesh, solid_mesh) in self._solidified_mappings.items():
+ obj.data = orig_mesh
+ try:
+ bpy.data.meshes.remove(solid_mesh)
+ except Exception as e:
+ print(f"[StableGen 3MF] Warning: could not remove solid mesh {solid_mesh.name}: {e}")
+
+ if hasattr(self, "_timer") and self._timer:
+ context.window_manager.event_timer_remove(self._timer)
+ self._timer = None
+
+
+class Export3MFCancel(bpy.types.Operator):
+ """Cancel the active 3MF export process."""
+ bl_idname = "object.export_3mf_cancel"
+ bl_label = "Cancel 3MF Export"
+ bl_options = {'INTERNAL'}
+
+ def execute(self, context):
+ export_op = next(
+ (op for win in context.window_manager.windows
+ for op in win.modal_operators
+ if op.bl_idname == 'OBJECT_OT_export_3mf'),
+ None
+ )
+ if export_op:
+ if hasattr(export_op, "_thread_status") and export_op._thread_status:
+ export_op._thread_status["cancel_requested"] = True
+ self.report({'INFO'}, "Requesting cancellation of 3MF export...")
+ else:
+ self.report({'WARNING'}, "Export operator has no active thread status.")
+ else:
+ self.report({'WARNING'}, "No active 3MF export operator found.")
+ return {'FINISHED'}
+
diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.py
index e221072..25d177e 100644
--- a/stablegen/texturing/projection.py
+++ b/stablegen/texturing/projection.py
@@ -1287,7 +1287,8 @@ def project_image(context, to_project, mat_id, stop_index=1000000):
_bake_visibility_weights(context, to_project, cameras, mat_id)
# Switch to Cycles (needed for Raycast shader node on all versions)
- context.scene.render.engine = 'CYCLES'
+ if context.scene.render.engine != 'CYCLES':
+ context.scene.render.engine = 'CYCLES'
# Force CPU + OSL only for Blender < 5.1 (native Raycast nodes don't need it)
if bpy.app.version < (5, 1, 0):
context.scene.cycles.device = 'CPU'
diff --git a/stablegen/texturing/rendering.py b/stablegen/texturing/rendering.py
index 82e7f52..8981601 100644
--- a/stablegen/texturing/rendering.py
+++ b/stablegen/texturing/rendering.py
@@ -215,7 +215,8 @@ def render_edge_feather_mask(context, to_export, camera, camera_index, feather_w
world.use_nodes = False
# ── Render settings ─────────────────────────────────────────────────────
- context.scene.render.engine = 'CYCLES'
+ if context.scene.render.engine != 'CYCLES':
+ context.scene.render.engine = 'CYCLES'
context.scene.render.film_transparent = False
context.scene.cycles.samples = 1
bpy.context.scene.display_settings.display_device = 'sRGB'
@@ -276,7 +277,8 @@ def render_edge_feather_mask(context, to_export, camera, camera_index, feather_w
# ── Restore render / world settings ─────────────────────────────────────
context.scene.camera = original_camera
- context.scene.render.engine = original_engine
+ if context.scene.render.engine != original_engine:
+ context.scene.render.engine = original_engine
context.scene.render.film_transparent = original_transparent
context.scene.cycles.samples = original_samples
bpy.context.scene.view_settings.view_transform = original_view_transform
@@ -726,7 +728,8 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
world.use_nodes = False
# Switch to CYCLES render engine (needed for emission pass rendering)
- context.scene.render.engine = 'CYCLES'
+ if context.scene.render.engine != 'CYCLES':
+ context.scene.render.engine = 'CYCLES'
# Force CPU + OSL only for Blender < 5.1 (native Raycast nodes don't need it)
if bpy.app.version < (5, 1, 0):
if hasattr(context.scene.cycles, 'shading_system'):
@@ -810,7 +813,8 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
cv2.imwrite(final_path, expanded_mask_u8)
# Restore original settings
- context.scene.render.engine = original_engine
+ if context.scene.render.engine != original_engine:
+ context.scene.render.engine = original_engine
context.scene.render.film_transparent = original_film_transparent
context.scene.render.use_compositing = original_use_compositing
context.scene.render.filepath = original_filepath
@@ -907,7 +911,8 @@ def export_render(context, camera_id=None, output_dir=None, filename=None):
original_use_compositing = context.scene.render.use_compositing
# Switch to WORKBENCH render engine and configure settings
- context.scene.render.engine = 'BLENDER_WORKBENCH'
+ if context.scene.render.engine != 'BLENDER_WORKBENCH':
+ context.scene.render.engine = 'BLENDER_WORKBENCH'
# Configure Workbench for a flat, consistent look if needed
context.scene.display.shading.light = 'STUDIO'
context.scene.display.shading.color_type = 'SINGLE'
@@ -955,7 +960,8 @@ def export_render(context, camera_id=None, output_dir=None, filename=None):
# Restore original render settings
- context.scene.render.engine = original_engine
+ if context.scene.render.engine != original_engine:
+ context.scene.render.engine = original_engine
context.scene.display.shading.light = original_workbench_settings['lighting']
context.scene.display.shading.color_type = original_workbench_settings['color_type']
context.scene.render.filepath = original_render_filepath
@@ -992,7 +998,8 @@ def export_viewport(context, camera_id=None, output_dir=None, filename=None):
original_image_settings = context.scene.render.image_settings.file_format
# Switch to WORKBENCH render engine for consistent viewport shading
- context.scene.render.engine = 'BLENDER_WORKBENCH'
+ if context.scene.render.engine != 'BLENDER_WORKBENCH':
+ context.scene.render.engine = 'BLENDER_WORKBENCH'
# Find a viewport
viewport_area = None
@@ -1018,7 +1025,8 @@ def export_viewport(context, camera_id=None, output_dir=None, filename=None):
if not (viewport_area and viewport_region and viewport_space and viewport_region_3d and viewport_window):
print("[StableGen] Viewport render failed: no VIEW_3D area found.")
- context.scene.render.engine = original_engine
+ if context.scene.render.engine != original_engine:
+ context.scene.render.engine = original_engine
return
# Store viewport settings
@@ -1053,7 +1061,8 @@ def export_viewport(context, camera_id=None, output_dir=None, filename=None):
viewport_space.overlay.show_overlays = original_overlay_show
# Restore original render settings
- context.scene.render.engine = original_engine
+ if context.scene.render.engine != original_engine:
+ context.scene.render.engine = original_engine
context.scene.render.filepath = original_render_filepath
context.scene.render.image_settings.file_format = original_image_settings
@@ -1522,7 +1531,8 @@ class SwitchMaterial(bpy.types.Operator):
return {'FINISHED'}
def prepare_baking(context):
- bpy.context.scene.render.engine = 'CYCLES'
+ if bpy.context.scene.render.engine != 'CYCLES':
+ bpy.context.scene.render.engine = 'CYCLES'
# Force CPU + OSL only for Blender < 5.1 (native Raycast nodes don't need it)
if bpy.app.version < (5, 1, 0):
if hasattr(bpy.context.scene.cycles, 'shading_system'):
@@ -1915,6 +1925,48 @@ def _find_pbr_bake_sources(mat):
return sources
+def _has_pbr_channels(mat):
+ """Check if the material contains any PBR channels other than base_color,
+ and that a Principled BSDF is actually active/wired to the material output.
+ """
+ if not mat or not mat.use_nodes:
+ return False
+
+ nodes = mat.node_tree.nodes
+ output_node = None
+ for n in nodes:
+ if n.type == 'OUTPUT_MATERIAL':
+ output_node = n
+ break
+
+ if not output_node or not output_node.inputs["Surface"].links:
+ return False
+
+ # Check if a node is (or leads to) an active Principled BSDF
+ def check_is_pbr_active(node, visited=None):
+ if visited is None:
+ visited = set()
+ if node in visited:
+ return False
+ visited.add(node)
+
+ if node.type == 'BSDF_PRINCIPLED':
+ return True
+ if node.type == 'MIX_SHADER':
+ for inp in node.inputs:
+ if inp.links:
+ if check_is_pbr_active(inp.links[0].from_node, visited):
+ return True
+ return False
+
+ from_node = output_node.inputs["Surface"].links[0].from_node
+ if not check_is_pbr_active(from_node):
+ return False
+
+ sources = _find_pbr_bake_sources(mat)
+ return any(ch in sources for ch in ('roughness', 'metallic', 'normal', 'emission', 'height', 'ao'))
+
+
def _restore_materials(obj, original_materials, original_active):
"""Restore an object's material slots back to their original state."""
obj.data.materials.clear()
@@ -2148,6 +2200,20 @@ class BakeTextures(bpy.types.Operator):
max=8192
) # type: ignore
+ samples: bpy.props.IntProperty(
+ name="Render Samples",
+ description="Number of samples to use for baking. Higher values reduce noise but take longer",
+ default=16,
+ min=1,
+ max=4096
+ ) # type: ignore
+
+ use_denoise: bpy.props.BoolProperty(
+ name="Denoise Baked Textures",
+ description="Use Cycles' built-in denoiser to clean up noise in baked textures",
+ default=True
+ ) # type: ignore
+
try_unwrap: bpy.props.EnumProperty(
name="Unwrap Method",
description="Method to unwrap UVs before baking",
@@ -2235,6 +2301,8 @@ class BakeTextures(bpy.types.Operator):
def draw(self, context):
layout = self.layout
layout.prop(self, "texture_resolution")
+ layout.prop(self, "samples")
+ layout.prop(self, "use_denoise")
layout.prop(self, "try_unwrap")
layout.prop(self, "overlap_only")
layout.prop(self, "add_material")
@@ -2272,11 +2340,18 @@ class BakeTextures(bpy.types.Operator):
"""
self.original_engine = bpy.context.scene.render.engine
- self.original_shading = bpy.context.space_data.shading.type
+ if bpy.context.space_data and hasattr(bpy.context.space_data, 'shading'):
+ self.original_shading = bpy.context.space_data.shading.type
+ else:
+ self.original_shading = 'SOLID'
self.original_device = bpy.context.scene.cycles.device
self.original_samples = bpy.context.scene.cycles.samples
self.original_max_bounces = bpy.context.scene.cycles.max_bounces
self.original_persistent = bpy.context.scene.render.use_persistent_data
+ if hasattr(bpy.context.scene.cycles, 'use_denoising'):
+ self.original_use_denoising = bpy.context.scene.cycles.use_denoising
+ else:
+ self.original_use_denoising = False
# Save Cycles compute_device_type so we can restore after GPU bake
try:
self._original_compute_device_type = (
@@ -2285,17 +2360,22 @@ class BakeTextures(bpy.types.Operator):
except Exception:
self._original_compute_device_type = None
# Set render engine to CYCLES (required for baking)
- bpy.context.scene.render.engine = 'CYCLES'
- # Switch to Solid shading to avoid conflicts with Rendered mode
- # (Rendered viewport + bake = crash). Solid is engine-independent
+ if bpy.context.scene.render.engine != 'CYCLES':
+ bpy.context.scene.render.engine = 'CYCLES'
+ # Switch to Solid shading in ALL viewports to avoid conflicts with Rendered mode
+ # (Rendered viewport + bake = crash). Solid is engine-independent
# and won't cause pink textures like Material Preview (EEVEE) does.
- for area in context.screen.areas:
- if area.type == 'VIEW_3D':
- for space in area.spaces:
- if space.type == 'VIEW_3D':
- space.shading.type = 'SOLID'
- break
+ for window in context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ for space in area.spaces:
+ if space.type == 'VIEW_3D':
+ space.shading.type = 'SOLID'
prepare_baking(context)
+ # Apply user's custom bake samples and denoising configuration
+ bpy.context.scene.cycles.samples = self.samples
+ if hasattr(bpy.context.scene.cycles, 'use_denoising'):
+ bpy.context.scene.cycles.use_denoising = self.use_denoise
# Start modal operation
context.window_manager.modal_handler_add(self)
@@ -2368,7 +2448,12 @@ class BakeTextures(bpy.types.Operator):
self._progress = 100
elif self._phase == 'bake':
- if self.bake_pbr:
+ # Fall back to standard color/diffuse bake if PBR channels are absent
+ has_pbr = False
+ if self.bake_pbr and obj.active_material:
+ has_pbr = _has_pbr_channels(obj.active_material)
+
+ if has_pbr:
# PBR mode bakes BaseColor via EMIT — skip the
# redundant DIFFUSE bake entirely.
self._progress = 100
@@ -2381,6 +2466,19 @@ class BakeTextures(bpy.types.Operator):
context.window_manager.event_timer_remove(self._timer)
return {'CANCELLED'}
+ # Copy fallback diffuse bake to PBR BaseColor if bake_pbr is True
+ if self.bake_pbr:
+ baked_dir = get_dir_path(context, "baked")
+ src_path = os.path.join(baked_dir, f"{obj.name}.png")
+ dst_path = os.path.join(baked_dir, f"{obj.name}_BaseColor.png")
+ if os.path.exists(src_path):
+ import shutil
+ try:
+ shutil.copy(src_path, dst_path)
+ print(f"[StableGen] Copied fallback diffuse bake to PBR BaseColor: {dst_path}")
+ except Exception as e:
+ print(f"[StableGen] Failed to copy fallback diffuse bake to PBR BaseColor: {e}")
+
# NEW: optionally flatten into the projection material so you can keep refining
if self.flatten_for_refine:
try:
@@ -2417,7 +2515,7 @@ class BakeTextures(bpy.types.Operator):
self._phase = 'bake_pbr'
self._pbr_queue = []
for obj in self._objects:
- if obj.active_material:
+ if obj.active_material and _has_pbr_channels(obj.active_material):
for ch in _find_pbr_bake_sources(obj.active_material):
self._pbr_queue.append((obj, ch))
self._pbr_queue_idx = 0
@@ -2436,28 +2534,66 @@ class BakeTextures(bpy.types.Operator):
self._current_index = 0
else:
context.window_manager.event_timer_remove(self._timer)
- bpy.context.scene.render.engine = self.original_engine
- bpy.context.scene.cycles.device = self.original_device
- bpy.context.scene.cycles.samples = self.original_samples
- bpy.context.scene.cycles.max_bounces = self.original_max_bounces
- bpy.context.scene.render.use_persistent_data = self.original_persistent
- # Restore Cycles compute_device_type
- if self._original_compute_device_type is not None:
+
+ # Capture original settings in local variables to avoid closures referencing self,
+ # as self (the operator instance) may be destroyed by Blender when modal exits.
+ orig_engine = str(self.original_engine)
+ orig_device = str(self.original_device)
+ orig_samples = int(self.original_samples)
+ orig_max_bounces = int(self.original_max_bounces)
+ orig_persistent = bool(self.original_persistent)
+ orig_use_denoising = bool(self.original_use_denoising)
+ orig_compute_device = self._original_compute_device_type
+ if orig_compute_device is not None:
+ orig_compute_device = str(orig_compute_device)
+ orig_shading = str(self.original_shading)
+
+ # Define defer restore function to run outside modal loop
+ def defer_restore():
try:
- bpy.context.preferences.addons['cycles'].preferences.compute_device_type = (
- self._original_compute_device_type
- )
- except Exception:
- pass
- # Restore original viewport shading
- for area in context.screen.areas:
- if area.type == 'VIEW_3D':
- for space in area.spaces:
- if space.type == 'VIEW_3D':
- space.shading.type = self.original_shading
- break
+ # 1. Disable Cycles persistent data to release caches
+ bpy.context.scene.render.use_persistent_data = False
+
+ # 2. Switch Cycles to CPU device to free GPU contexts and memory
+ bpy.context.scene.cycles.device = 'CPU'
+
+ # 3. Update view layer to ensure Cycles releases everything
+ bpy.context.view_layer.update()
+
+ # 4. Now restore the render engine
+ if bpy.context.scene.render.engine != orig_engine:
+ bpy.context.scene.render.engine = orig_engine
+
+ # 5. Restore other scene/Cycles settings
+ bpy.context.scene.cycles.device = orig_device
+ bpy.context.scene.cycles.samples = orig_samples
+ bpy.context.scene.cycles.max_bounces = orig_max_bounces
+ bpy.context.scene.render.use_persistent_data = orig_persistent
+ if hasattr(bpy.context.scene.cycles, 'use_denoising'):
+ bpy.context.scene.cycles.use_denoising = orig_use_denoising
+ if orig_compute_device is not None:
+ try:
+ bpy.context.preferences.addons['cycles'].preferences.compute_device_type = orig_compute_device
+ except Exception:
+ pass
+
+ # 6. Restore original viewport shading in all screens
+ for window in bpy.context.window_manager.windows:
+ for area in window.screen.areas:
+ if area.type == 'VIEW_3D':
+ for space in area.spaces:
+ if space.type == 'VIEW_3D':
+ space.shading.type = orig_shading
+ break
+ remove_empty_dirs(bpy.context)
+ except Exception as e:
+ print(f"[StableGen] Error in defer_restore: {e}")
+ return None
+
+ import bpy
+ bpy.app.timers.register(defer_restore, first_interval=0.2)
+
self.report({'INFO'}, "Textures baked successfully.")
- remove_empty_dirs(context)
return {'FINISHED'}
return {'PASS_THROUGH'}
@@ -2479,12 +2615,10 @@ class BakeTextures(bpy.types.Operator):
nodes.remove(node)
# Assign the new material to all faces
- obj.active_material_index = len(obj.material_slots) - 1
- bpy.context.view_layer.objects.active = obj
- bpy.ops.object.mode_set(mode='EDIT')
- bpy.ops.mesh.select_all(action='SELECT')
- bpy.ops.object.material_slot_assign()
- bpy.ops.object.mode_set(mode='OBJECT')
+ slot_idx = len(obj.material_slots) - 1
+ obj.active_material_index = slot_idx
+ obj.data.polygons.foreach_set("material_index", [slot_idx] * len(obj.data.polygons))
+ obj.data.update()
# Output node
output_node = nodes.new("ShaderNodeOutputMaterial")
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index 2479240..0484302 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -5,6 +5,7 @@ import bpy # pylint: disable=import-error
import mathutils # pylint: disable=import-error
import math
from ..utils import sg_modal_active
+from ..core import get_addon_prefs
from .presets import PRESETS, GEN_PARAMETERS
from . import queue as _queue_mod
@@ -531,72 +532,75 @@ class StableGenPanel(bpy.types.Panel):
row.operator("stablegen.delete_preset", text="Delete", icon="TRASH")
# --- Scene Queue ---
- queue_box = layout.box()
- queue_col = queue_box.column()
- wm = context.window_manager
- show_queue = getattr(wm, 'sg_show_queue', False)
- queue_header = queue_col.row()
- queue_header.prop(wm, "sg_show_queue",
- text=f"Scene Queue ({len(wm.sg_scene_queue)})",
- icon="TRIA_DOWN" if show_queue else "TRIA_RIGHT",
- emboss=False)
- if _queue_mod._queue_processing:
- status_text = "Exporting GIF..." if _queue_mod._queue_phase == 'exporting_gif' else "Processing..."
- queue_header.label(text=status_text, icon="SORTTIME")
-
- if show_queue:
- queue_content = queue_col.box()
- row = queue_content.row()
- row.template_list("SG_UL_SceneQueueList", "",
- wm, "sg_scene_queue",
- wm, "sg_scene_queue_index",
- rows=3)
- col = row.column(align=True)
- col.operator("stablegen.queue_move_up", text="", icon="TRIA_UP")
- col.operator("stablegen.queue_move_down", text="", icon="TRIA_DOWN")
- col.separator()
- col.operator("stablegen.queue_remove", text="", icon="REMOVE")
-
- btn_row = queue_content.row(align=True)
- btn_row.operator("stablegen.queue_add", text="Add Scene", icon="ADD")
- btn_row.operator("stablegen.queue_open_result", text="Open", icon="FILE_BLEND")
- btn_row2 = queue_content.row(align=True)
- btn_row2.operator("stablegen.queue_invalidate", text="Reset", icon="LOOP_BACK")
- btn_row2.operator("stablegen.queue_clear", text="Clear", icon="TRASH")
-
- process_row = queue_content.row()
+ from ..core import get_addon_prefs
+ prefs = get_addon_prefs(context)
+ if prefs and getattr(prefs, "enable_scene_queue", False):
+ queue_box = layout.box()
+ queue_col = queue_box.column()
+ wm = context.window_manager
+ show_queue = getattr(wm, 'sg_show_queue', False)
+ queue_header = queue_col.row()
+ queue_header.prop(wm, "sg_show_queue",
+ text=f"Scene Queue ({len(wm.sg_scene_queue)})",
+ icon="TRIA_DOWN" if show_queue else "TRIA_RIGHT",
+ emboss=False)
if _queue_mod._queue_processing:
- process_row.alert = True
- process_row.operator("stablegen.queue_process", text="Cancel Queue", icon="CANCEL")
- else:
- process_row.operator("stablegen.queue_process", text="Process Queue", icon="PLAY")
- process_row.enabled = len(wm.sg_scene_queue) > 0
-
- # ── GIF Export settings ──
- gif_box = queue_content.box()
- gif_row = gif_box.row()
- gif_row.prop(wm, "sg_queue_gif_export", text="Export Orbit GIF/MP4")
- if getattr(wm, 'sg_queue_gif_export', False):
- gif_col = gif_box.column(align=True)
- row = gif_col.row(align=True)
- row.prop(wm, "sg_queue_gif_duration")
- row.prop(wm, "sg_queue_gif_fps")
- row = gif_col.row(align=True)
- row.prop(wm, "sg_queue_gif_resolution")
- row.prop(wm, "sg_queue_gif_samples")
- gif_col.prop(wm, "sg_queue_gif_engine")
- gif_col.prop(wm, "sg_queue_gif_interpolation")
- gif_col.separator()
- gif_col.prop(wm, "sg_queue_gif_use_hdri")
- if getattr(wm, 'sg_queue_gif_use_hdri', False):
- gif_col.prop(wm, "sg_queue_gif_hdri_path")
- gif_col.prop(wm, "sg_queue_gif_hdri_strength")
- gif_col.prop(wm, "sg_queue_gif_hdri_rotation")
- gif_col.prop(wm, "sg_queue_gif_env_mode")
- gif_col.prop(wm, "sg_queue_gif_denoiser")
- if bpy.app.version >= (5, 1, 0) and getattr(wm, 'sg_queue_gif_engine', 'CYCLES') == 'CYCLES':
- gif_col.prop(wm, "sg_queue_gif_use_gpu")
- gif_col.prop(wm, "sg_queue_gif_also_no_pbr")
+ status_text = "Exporting GIF..." if _queue_mod._queue_phase == 'exporting_gif' else "Processing..."
+ queue_header.label(text=status_text, icon="SORTTIME")
+
+ if show_queue:
+ queue_content = queue_col.box()
+ row = queue_content.row()
+ row.template_list("SG_UL_SceneQueueList", "",
+ wm, "sg_scene_queue",
+ wm, "sg_scene_queue_index",
+ rows=3)
+ col = row.column(align=True)
+ col.operator("stablegen.queue_move_up", text="", icon="TRIA_UP")
+ col.operator("stablegen.queue_move_down", text="", icon="TRIA_DOWN")
+ col.separator()
+ col.operator("stablegen.queue_remove", text="", icon="REMOVE")
+
+ btn_row = queue_content.row(align=True)
+ btn_row.operator("stablegen.queue_add", text="Add Scene", icon="ADD")
+ btn_row.operator("stablegen.queue_open_result", text="Open", icon="FILE_BLEND")
+ btn_row2 = queue_content.row(align=True)
+ btn_row2.operator("stablegen.queue_invalidate", text="Reset", icon="LOOP_BACK")
+ btn_row2.operator("stablegen.queue_clear", text="Clear", icon="TRASH")
+
+ process_row = queue_content.row()
+ if _queue_mod._queue_processing:
+ process_row.alert = True
+ process_row.operator("stablegen.queue_process", text="Cancel Queue", icon="CANCEL")
+ else:
+ process_row.operator("stablegen.queue_process", text="Process Queue", icon="PLAY")
+ process_row.enabled = len(wm.sg_scene_queue) > 0
+
+ # ── GIF Export settings ──
+ gif_box = queue_content.box()
+ gif_row = gif_box.row()
+ gif_row.prop(wm, "sg_queue_gif_export", text="Export Orbit GIF/MP4")
+ if getattr(wm, 'sg_queue_gif_export', False):
+ gif_col = gif_box.column(align=True)
+ row = gif_col.row(align=True)
+ row.prop(wm, "sg_queue_gif_duration")
+ row.prop(wm, "sg_queue_gif_fps")
+ row = gif_col.row(align=True)
+ row.prop(wm, "sg_queue_gif_resolution")
+ row.prop(wm, "sg_queue_gif_samples")
+ gif_col.prop(wm, "sg_queue_gif_engine")
+ gif_col.prop(wm, "sg_queue_gif_interpolation")
+ gif_col.separator()
+ gif_col.prop(wm, "sg_queue_gif_use_hdri")
+ if getattr(wm, 'sg_queue_gif_use_hdri', False):
+ gif_col.prop(wm, "sg_queue_gif_hdri_path")
+ gif_col.prop(wm, "sg_queue_gif_hdri_strength")
+ gif_col.prop(wm, "sg_queue_gif_hdri_rotation")
+ gif_col.prop(wm, "sg_queue_gif_env_mode")
+ gif_col.prop(wm, "sg_queue_gif_denoiser")
+ if bpy.app.version >= (5, 1, 0) and getattr(wm, 'sg_queue_gif_engine', 'CYCLES') == 'CYCLES':
+ gif_col.prop(wm, "sg_queue_gif_use_gpu")
+ gif_col.prop(wm, "sg_queue_gif_also_no_pbr")
# --- Main Parameters section ---
if not hasattr(scene, 'show_generation_params'):
@@ -810,10 +814,35 @@ class StableGenPanel(bpy.types.Panel):
row.prop(scene, "trellis2_post_processing_enabled", text="Enable Post-Processing", toggle=True, icon="MOD_DECIM")
if scene.trellis2_post_processing_enabled:
+ dec_method = getattr(scene, 'trellis2_decimate_method', 'server')
+ rem_method = getattr(scene, 'trellis2_remesh_method', 'qdc')
+
row = content_box.row()
- row.prop(scene, "trellis2_decimation", text="Decimation Target")
+ row.prop(scene, "trellis2_decimate_method", text="Decimation Method")
+
+ show_target = (dec_method in ('server', 'collapse')) or (rem_method in ('qdc', 'quadriflow'))
+ if show_target:
+ if dec_method in ('server', 'collapse') and rem_method in ('qdc', 'quadriflow'):
+ label_text = "Target Face Count"
+ elif dec_method in ('server', 'collapse'):
+ label_text = "Decimation Target"
+ else:
+ label_text = "Remesh Face Target"
+
+ row = content_box.row()
+ row.prop(scene, "trellis2_decimation", text=label_text)
+
+ row = content_box.row()
+ row.prop(scene, "trellis2_remesh_method", text="Remesh Method")
+
+ if rem_method == 'quadriflow':
+ row = content_box.row()
+ row.label(text="Note: Quadriflow is experimental and might produce artifacts.", icon="WARNING")
+
row = content_box.row()
- row.prop(scene, "trellis2_remesh", text="Remesh", toggle=True, icon="MOD_REMESH")
+ row.prop(scene, "trellis2_solidify", text="Solidify Mesh")
+
+
content_box.separator()
@@ -1926,6 +1955,9 @@ class StableGenPanel(bpy.types.Panel):
row = tools_box.row()
row.operator("object.stablegen_mirror_reproject", text="Mirror Last Projection", icon="MOD_MIRROR")
+ if width_mode == 'narrow':
+ row = tools_box.row()
+ row.operator("object.stablegen_local_postprocess", text="Run Local Post-Processing", icon="MODIFIER")
# --- Debug Tools ---
prefs = context.preferences.addons.get(_ADDON_PKG)
@@ -1960,6 +1992,9 @@ class StableGenPanel(bpy.types.Panel):
row = debug_box.row()
op2 = row.operator("stablegen.debug_feather_preview", text="Feather Preview", icon="MOD_SMOOTH")
+ row = debug_box.row()
+ row.operator("stablegen.debug_make_solid", text="Debug Make Solid", icon="MOD_REMESH")
+
# --- Narrow panel hint ---
if width_mode == 'narrow':
hint_row = layout.row()
@@ -1967,4 +2002,157 @@ class StableGenPanel(bpy.types.Panel):
hint_row.label(text="Widen panel for side-by-side layout", icon="INFO")
layout.separator()
+
+
+class StableGenPrintPanel(bpy.types.Panel):
+ """Creates the 3D Printing panel for the StableGen addon."""
+ bl_label = "StableGen 3D Printing"
+ bl_idname = "OBJECT_PT_stablegen_print"
+ bl_space_type = "VIEW_3D"
+ bl_region_type = "UI"
+ bl_category = "StableGen Print"
+ bl_context = "objectmode"
+ bl_ui_units_x = 600
+
+ @classmethod
+ def poll(cls, context):
+ prefs = get_addon_prefs(context)
+ return bool(prefs and prefs.enable_print_tab)
+
+ def draw(self, context):
+ layout = self.layout
+ scene = context.scene
+
+ region = context.region
+ width = region.width
+ width_mode = 'narrow' if width < 420 else 'wide'
+
+ # Check if 3MF export is running
+ export_op = next(
+ (op for win in context.window_manager.windows
+ for op in win.modal_operators
+ if op.bl_idname == 'OBJECT_OT_export_3mf'),
+ None
+ )
+
+ # Check if Preview Slices is running
+ preview_sliced_op = next(
+ (op for win in context.window_manager.windows
+ for op in win.modal_operators
+ if op.bl_idname == 'OBJECT_OT_stablegen_preview_sliced'),
+ None
+ )
+
+ if export_op:
+ # Draw progress bar and cancel button
+ progress_col = layout.column()
+ stage_text = f"{getattr(export_op, '_stage', 'Exporting 3MF')} ({getattr(export_op, '_progress', 0.0):.0f}%)"
+ progress = getattr(export_op, '_progress', 0.0) / 100.0
+ progress_col.progress(text=stage_text, factor=max(0.0, min(progress, 1.0)))
+ progress_col.operator("object.export_3mf_cancel", text="Cancel Export", icon="CANCEL")
+
+ # Disable inputs for the rest of the panel
+ main_layout = layout.column()
+ main_layout.enabled = False
+ elif preview_sliced_op:
+ # Draw progress bar and cancel button
+ progress_col = layout.column()
+ stage_text = f"{getattr(preview_sliced_op, '_stage', 'Previewing Slices')} ({getattr(preview_sliced_op, '_progress', 0.0):.0f}%)"
+ progress = getattr(preview_sliced_op, '_progress', 0.0) / 100.0
+ progress_col.progress(text=stage_text, factor=max(0.0, min(progress, 1.0)))
+ progress_col.operator("object.stablegen_preview_sliced_cancel", text="Cancel Preview", icon="CANCEL")
+
+ # Disable inputs for the rest of the panel
+ main_layout = layout.column()
+ main_layout.enabled = False
+ else:
+ main_layout = layout
+
+ box = main_layout.box()
+ row = box.row()
+ row.alignment = 'CENTER'
+ row.label(text="Multi-Color 3D Print Palette", icon="COLOR")
+
+ row = box.row()
+ row.prop(scene, "stablegen_print_preset", text="Preset")
+
+ palette = scene.stablegen_print_palette
+ if len(palette) > 0:
+ for i in range(0, len(palette), 2):
+ row = box.row()
+
+ # Column 1
+ item1 = palette[i]
+ col1 = row.column()
+ sub_row1 = col1.row(align=True)
+ is_selected1 = (scene.stablegen_print_palette_index == i)
+ icon1 = 'CHECKBOX_HLT' if is_selected1 else 'CHECKBOX_DEHLT'
+ op1 = sub_row1.operator("wm.context_set_int", text="", icon=icon1, emboss=True)
+ op1.data_path = "scene.stablegen_print_palette_index"
+ op1.value = i
+ sub_row1.prop(item1, "color", text="")
+
+ # Column 2
+ col2 = row.column()
+ if i + 1 < len(palette):
+ item2 = palette[i+1]
+ sub_row2 = col2.row(align=True)
+ is_selected2 = (scene.stablegen_print_palette_index == i + 1)
+ icon2 = 'CHECKBOX_HLT' if is_selected2 else 'CHECKBOX_DEHLT'
+ op2 = sub_row2.operator("wm.context_set_int", text="", icon=icon2, emboss=True)
+ op2.data_path = "scene.stablegen_print_palette_index"
+ op2.value = i + 1
+ sub_row2.prop(item2, "color", text="")
+ else:
+ col2.label(text="")
+ else:
+ box.label(text="No colors in palette. Click 'Add Color' to start.", icon="INFO")
+
+ row = box.row(align=True)
+ row.operator("stablegen.add_palette_color", text="Add Color", icon="ADD")
+ if len(palette) > 0:
+ row.operator("stablegen.remove_palette_color", text="Remove Selected", icon="REMOVE")
+
+ row = box.row()
+ row.prop(scene, "stablegen_print_dithered", text="Dithered (Full Spectrum)")
+
+ if scene.stablegen_print_dithered:
+ row = box.row()
+ row.prop(scene, "stablegen_print_model_height", text="Model Height (mm)")
+ row = box.row()
+ row.prop(scene, "stablegen_print_layer_height", text="Layer Height (mm)")
+
+ row = box.row()
+ row.prop(scene, "stablegen_print_smoothing", text="Island Cleanup", slider=True)
+
+ row = box.row()
+ row.prop(scene, "stablegen_print_chroma_threshold", text="Chroma Threshold", slider=True)
+
+ row = box.row()
+ row.prop(scene, "stablegen_print_make_solid", text="Make Solid", icon="MOD_REMESH")
+ if scene.stablegen_print_make_solid:
+ row = box.row()
+ row.prop(scene, "stablegen_print_raycast_count", text="Raycast Angles")
+
+ # Advanced Solver Settings
+ row = box.row()
+ row.prop(scene, "stablegen_print_show_advanced", text="Advanced Solver Settings", icon="TRIA_DOWN" if scene.stablegen_print_show_advanced else "TRIA_RIGHT")
+ if scene.stablegen_print_show_advanced:
+ adv_box = box.box()
+ adv_box.prop(scene, "stablegen_print_solver_formula", text="Model")
+ adv_box.prop(scene, "stablegen_print_solver_init", text="Init Method")
+ adv_box.prop(scene, "stablegen_print_solver_steps", text="Steps")
+ adv_box.prop(scene, "stablegen_print_saturation_penalty", text="Saturation Penalty", slider=True)
+ if scene.stablegen_print_solver_formula == 'KUBELKA_MUNK':
+ adv_box.prop(scene, "stablegen_print_scattering_weight", text="Opaque Scattering")
+
+ row = box.row(align=True)
+ row.operator("object.stablegen_preview_quantization", text="Preview Colors", icon="COLOR")
+ row.operator("object.stablegen_preview_sliced", text="Preview Slices", icon="MOD_DECIM")
+ row.operator("object.stablegen_clear_quantization_preview", text="Clear Preview", icon="X")
+
+ row = box.row(align=True)
+ row.operator("object.export_stl", text="Export STL", icon="EXPORT")
+ row.operator("object.export_3mf", text="Export 3MF", icon="EXPORT")
+
diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.py
index 25899f7..aa90ce8 100644
--- a/stablegen/ui/presets.py
+++ b/stablegen/ui/presets.py
@@ -28,14 +28,14 @@ PRESETS = {
"LOCAL REFINE": {"description": "Uses the SDXL local edit mode to improve detail / refine specific areas. Use new set of cameras or a single camera pointed at the area you want to refine.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "local_edit", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.10000000149011612, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "original_render", "sequential_desaturate_factor": 0.10000000149011612, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": True, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05, "visibility_vignette": True, "visibility_vignette_width": 0.3, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "pbr_decomposition": False, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
"LOCAL EDIT (QWEN)": {"description": "Uses Qwen to make targeted edits to specific areas. Point cameras at what you want to change — you can alter colors, style, rewrite text, add details, and more. Untouched areas are preserved.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "qwen_generation_method": "local_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": False, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": False, "refine_angle_ramp_active": False, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05, "visibility_vignette": True, "visibility_vignette_width": 0.1, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6, "refine_edge_feather_projection": True, "refine_edge_feather_width": 15, "refine_edge_feather_softness": 1.0, "pbr_decomposition": False, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
"REFINE (QWEN)": {"description": "Uses Qwen to restyle or globally modify the entire existing texture. Applies changes uniformly across all camera views — ideal for changing the overall color scheme, art style, or surface appearance.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "qwen_generation_method": "refine", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": False, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": False, "pbr_decomposition": False, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
- "DEFAULT (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and SDXL to generate a textured mesh. Optimized for general object generation. May not work ideally for the cases which have their specialized presets.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 75.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 85.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.10000000149011612, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "trellis2_input", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "sdxl", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 10, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": False, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "auto", "trellis2_attn_backend": "auto", "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 7.5, "trellis2_tex_steps": 12, "trellis2_max_tokens": 32768, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": False, "trellis2_max_elevation": 1.2216999530792236, "trellis2_min_elevation": -1.0471975803375244, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": False, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
- "TRELLIS.2 (MESH ONLY)": {"description": "Uses TRELLIS.2 to generate a mesh without texturing. Useful when you only need geometry or plan to texture manually.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 75.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 85.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.10000000149011612, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "trellis2_input", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "none", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 10, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": False, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "auto", "trellis2_attn_backend": "auto", "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 7.5, "trellis2_tex_steps": 12, "trellis2_max_tokens": 32768, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": False, "trellis2_max_elevation": 1.2216999530792236, "trellis2_min_elevation": -1.0471975803375244, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": False, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
- "CHARACTERS (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and SDXL to generate a textured mesh. Optimized settings for generating characters. Will not texture bottom facing faces.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 75.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 85.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.10000000149011612, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "trellis2_input", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "sdxl", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "auto", "trellis2_attn_backend": "auto", "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 7.5, "trellis2_tex_steps": 12, "trellis2_max_tokens": 32768, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": False, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
- "ARCHITECTURE (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and SDXL to generate a textured mesh. Optimized settings for architecture, and other models with flat walls and sharp angles.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 85.0, "weight_exponent": 10.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "separate", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": False, "sequential_custom_camera_order": "", "sequential_factor": 0.75, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "trellis2_input", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 0.800000011920929, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": False, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "sdxl", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "auto", "trellis2_attn_backend": "auto", "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 7.5, "trellis2_tex_steps": 12, "trellis2_max_tokens": 32768, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": False, "trellis2_max_elevation": 1.2216999530792236, "trellis2_min_elevation": -1.0471975803375244, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": False, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
- "QWEN PRECISE (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Precise detail when camera overlap is good. Relies on context renders plus the prompt.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "auto", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 7.5, "trellis2_tex_steps": 12, "trellis2_max_tokens": 32768, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": True, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
- "QWEN SAFE (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Safer fallback when coverage is limited. Uses TRELLIS.2 input image as sequential style reference for global coherence.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 6.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "auto", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 7.5, "trellis2_tex_steps": 12, "trellis2_max_tokens": 32768, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
- "QWEN ALT (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Uses ADDITIONAL context renders with TRELLIS.2 style transfer for consistency. Good general-purpose Qwen pipeline.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": True, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "ADDITIONAL", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "auto", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 7.5, "trellis2_tex_steps": 12, "trellis2_max_tokens": 32768, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
- "QWEN VORONOI (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Voronoi projection with exponent 1000 for hard camera segmentation during generation, then resets to 15 for softer blending.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 1000.0, "weight_exponent_generation_only": True, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": True, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "auto", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 7.5, "trellis2_tex_steps": 12, "trellis2_max_tokens": 32768, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
+ "DEFAULT (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and SDXL to generate a textured mesh. Optimized for general object generation. May not work ideally for the cases which have their specialized presets.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 75.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 85.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.10000000149011612, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "trellis2_input", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "sdxl", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 10, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": False, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": False, "trellis2_max_elevation": 1.2216999530792236, "trellis2_min_elevation": -1.0471975803375244, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": False, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
+ "TRELLIS.2 (MESH ONLY)": {"description": "Uses TRELLIS.2 to generate a mesh without texturing. Useful when you only need geometry or plan to texture manually.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 75.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 85.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.10000000149011612, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "trellis2_input", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "none", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 10, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": False, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": False, "trellis2_max_elevation": 1.2216999530792236, "trellis2_min_elevation": -1.0471975803375244, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": False, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
+ "CHARACTERS (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and SDXL to generate a textured mesh. Optimized settings for generating characters. Will not texture bottom facing faces.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 75.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 85.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.10000000149011612, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "trellis2_input", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "sdxl", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": False, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
+ "ARCHITECTURE (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and SDXL to generate a textured mesh. Optimized settings for architecture, and other models with flat walls and sharp angles.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 85.0, "weight_exponent": 10.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "separate", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": False, "sequential_custom_camera_order": "", "sequential_factor": 0.75, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "trellis2_input", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 0.800000011920929, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": False, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 5.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "sdxl", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": False, "trellis2_max_elevation": 1.2216999530792236, "trellis2_min_elevation": -1.0471975803375244, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": False, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},
+ "QWEN PRECISE (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Precise detail when camera overlap is good. Relies on context renders plus the prompt.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": True, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
+ "QWEN SAFE (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Safer fallback when coverage is limited. Uses TRELLIS.2 input image as sequential style reference for global coherence.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 6.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
+ "QWEN ALT (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Uses ADDITIONAL context renders with TRELLIS.2 style transfer for consistency. Good general-purpose Qwen pipeline.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": True, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": False, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "ADDITIONAL", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
+ "QWEN VORONOI (MESH + TEXTURE)": {"description": "Uses TRELLIS.2 and Qwen Image Edit to generate a textured mesh. Voronoi projection with exponent 1000 for hard camera segmentation during generation, then resets to 15 for softer blending.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 1000.0, "weight_exponent_generation_only": True, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "reinhard", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "auto_rescale_target_mp": 1.0, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.800000011920929, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_voronoi_mode": True, "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_prompt_gray_background": True, "qwen_rescale_alignment": True, "qwen_generation_method": "generate", "qwen_refine_use_prev_ref": False, "qwen_refine_use_depth": False, "qwen_timestep_zero_ref": False, "refine_angle_ramp_active": True, "refine_angle_ramp_pos_0": 0.0, "refine_angle_ramp_pos_1": 0.05000000074505806, "visibility_vignette": True, "visibility_vignette_width": 0.15000000596046448, "visibility_vignette_softness": 1.0, "visibility_vignette_blur": False, "sg_silhouette_margin": 3, "sg_silhouette_depth": 0.05000000074505806, "sg_silhouette_rays": "4", "refine_feather_ramp_pos_0": 0.0, "refine_feather_ramp_pos_1": 0.6000000238418579, "refine_edge_feather_projection": True, "refine_edge_feather_width": 30, "refine_edge_feather_softness": 1.0, "trellis2_texture_mode": "qwen_image_edit", "trellis2_initial_image_arch": "sdxl", "trellis2_camera_count": 8, "trellis2_placement_mode": "normal_weighted", "trellis2_auto_prompts": True, "trellis2_exclude_bottom": True, "trellis2_exclude_bottom_angle": 1.5533000230789185, "trellis2_auto_aspect": "per_camera", "trellis2_occlusion_mode": "none", "trellis2_consider_existing": False, "trellis2_delete_cameras": False, "trellis2_coverage_target": 0.949999988079071, "trellis2_max_auto_cameras": 12, "trellis2_fan_angle": 90.0, "trellis2_resolution": "1024_cascade", "trellis2_precision": "bf16", "trellis2_attn_backend": "auto", "trellis2_seed": 0, "trellis2_ss_guidance": 7.5, "trellis2_ss_steps": 12, "trellis2_shape_guidance": 7.5, "trellis2_shape_steps": 12, "trellis2_tex_guidance": 3.0, "trellis2_tex_steps": 12, "trellis2_max_tokens": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": "qdc", "trellis2_post_processing_enabled": True, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "trellis2_max_elevation": 0.8726646259971648, "trellis2_min_elevation": -0.8726646259971648, "trellis2_auto_lighting": True, "use_ipadapter": False, "sequential_ipadapter_regenerate_wo_controlnet": False, "allow_modify_existing_textures": False, "ask_object_prompts": True, "weight_exponent_mask": False, "mask_blocky": False, "architecture_mode": "trellis2", "use_camera_prompts": True, "sg_use_custom_camera_order": False, "pbr_decomposition": False, "generation_mode": "standard", "texture_objects": "all", "use_flux_lora": True, "qwen_use_trellis2_style": True, "qwen_trellis2_style_initial_only": False, "trellis2_skip_texture": True, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},
}
# Global list of all generation parameter names to check for a preset.
@@ -160,6 +160,8 @@ GEN_PARAMETERS = [
"trellis2_texture_size",
"trellis2_decimation",
"trellis2_remesh",
+ "trellis2_decimate_method",
+ "trellis2_remesh_method",
"trellis2_post_processing_enabled",
"trellis2_bg_removal",
@@ -238,17 +240,22 @@ def get_preset_items(self, context):
items.append(('CUSTOM', 'Custom', 'Custom configuration'))
return items
+def normalize_value(key, value):
+ if key == "trellis2_remesh" and isinstance(value, bool):
+ return "qdc" if value else "none"
+ return value
+
def update_parameters(self, context):
scene = context.scene
# Build a dictionary of current parameter values
- current = {key: getattr(scene, key) for key in GEN_PARAMETERS if hasattr(scene, key)}
+ current = {key: normalize_value(key, getattr(scene, key)) for key in GEN_PARAMETERS if hasattr(scene, key)}
# Compare current values with every stock preset's stored values
for name, preset in PRESETS.items():
# First check regular parameters
if all(
(lambda v1, v2: math.isclose(v1, v2, rel_tol=1e-7, abs_tol=0.0) if isinstance(v1, (int, float)) and isinstance(v2, (int, float)) else v1 == v2)
- (current.get(key), preset.get(key))
+ (current.get(key), normalize_value(key, preset.get(key)))
for key in GEN_PARAMETERS if key in preset
):
units_match = True
@@ -394,6 +401,31 @@ class ApplyPreset(bpy.types.Operator):
for key, value in values.items():
if key not in ["controlnet_units", "lora_units", "description"] and hasattr(context.scene, key):
try:
+ if key == "trellis2_decimate_method" and value == "planar":
+ setattr(context.scene, "trellis2_decimate_method", "none")
+ continue
+ if key == "trellis2_remesh":
+ if isinstance(value, bool):
+ legacy_str = "qdc" if value else "none"
+ else:
+ legacy_str = value
+ setattr(context.scene, "trellis2_remesh", legacy_str)
+ if legacy_str == "qdc":
+ setattr(context.scene, "trellis2_decimate_method", "server")
+ setattr(context.scene, "trellis2_remesh_method", "qdc")
+ elif legacy_str in ("none", "decimate_planar"):
+ setattr(context.scene, "trellis2_decimate_method", "none")
+ setattr(context.scene, "trellis2_remesh_method", "none")
+ elif legacy_str == "decimate_collapse":
+ setattr(context.scene, "trellis2_decimate_method", "collapse")
+ setattr(context.scene, "trellis2_remesh_method", "none")
+ elif legacy_str == "quadriflow":
+ setattr(context.scene, "trellis2_decimate_method", "none")
+ setattr(context.scene, "trellis2_remesh_method", "quadriflow")
+ elif legacy_str == "instant_meshes":
+ setattr(context.scene, "trellis2_decimate_method", "none")
+ setattr(context.scene, "trellis2_remesh_method", "quadriflow")
+ continue
setattr(context.scene, key, value)
except (TypeError, AttributeError):
# Dynamic enum values (e.g. trellis2_input) may not
diff --git a/stablegen/util/workflow_templates.py b/stablegen/util/workflow_templates.py
index 0ae401a..4e93f59 100644
--- a/stablegen/util/workflow_templates.py
+++ b/stablegen/util/workflow_templates.py
@@ -1704,7 +1704,8 @@ prompt_text_trellis2 = """
"inputs": {
"model_config": ["2", 0],
"conditioning": ["4", 0],
- "shape_result": ["5", 0],
+ "shape_slat": ["5", 1],
+ "subs": ["5", 2],
"seed": 0,
"tex_guidance_strength": 7.5,
"tex_sampling_steps": 12
@@ -1714,17 +1715,47 @@ prompt_text_trellis2 = """
"title": "Shape to Textured Mesh"
}
},
+ "8": {
+ "inputs": {
+ "trimesh": ["5", 0],
+ "remesh": "on",
+ "remesh_band": 1.0,
+ "remove_inner_faces": false,
+ "floater_threshold": 0.001,
+ "target_face_count": 100000,
+ "weld_vertices": true,
+ "weld_digits": 4,
+ "chart_cone_angle": 90.0,
+ "chart_refine_iterations": 0,
+ "chart_global_iterations": 1,
+ "chart_smooth_strength": 1
+ },
+ "class_type": "Trellis2ProcessMesh",
+ "_meta": {
+ "title": "Process Mesh"
+ }
+ },
+ "9": {
+ "inputs": {
+ "trimesh": ["8", 0],
+ "voxelgrid": ["6", 0],
+ "original_mesh": ["5", 0],
+ "texture_size": 4096
+ },
+ "class_type": "Trellis2RasterizePBR",
+ "_meta": {
+ "title": "Rasterize PBR"
+ }
+ },
"7": {
"inputs": {
- "voxelgrid_path": ["6", 1],
- "decimation_target": 100000,
- "texture_size": 4096,
- "remesh": true,
- "filename_prefix": "trellis2"
+ "trimesh": ["9", 0],
+ "filename_prefix": "trellis2",
+ "file_format": "glb"
},
- "class_type": "Trellis2ExportGLB",
+ "class_type": "Trellis2ExportTrimesh",
"_meta": {
- "title": "Export GLB"
+ "title": "Export Trimesh"
}
}
}
@@ -1793,7 +1824,7 @@ prompt_text_trellis2_shape_only = """
},
"6": {
"inputs": {
- "trimesh": ["5", 1],
+ "trimesh": ["5", 0],
"target_face_count": 100000,
"fill_holes": false,
"remesh": false,