Skip to content

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

feat: scene queue, prompt separator, compositor safety, qwen presets, pbr progress

sakalond24f4bfff5198
diff --git a/installer.py b/installer.py
index 4604106..2a9e2a8 100644
--- a/installer.py
+++ b/installer.py
@@ -325,6 +325,30 @@ _PATCH_TRELLIS_UNLOAD_TEX_REPLACE = (
' print(f"[TRELLIS2] Texture pipeline offloaded", file=sys.stderr)\n'
)
+# Patch for stages.py: clean up IPC tensor files from previous generations
+# inside _save_to_disk so they don't accumulate and fill the disk.
+_PATCH_TRELLIS_TEMP_CLEANUP_ANCHOR = (
+ "def _save_to_disk(data, prefix):\n"
+ " path = os.path.join(_get_temp_dir(), f'{prefix}_{uuid.uuid4().hex[:8]}.pt')\n"
+ " torch.save(data, path)\n"
+ " return {'_tensor_file': path}"
+)
+
+_PATCH_TRELLIS_TEMP_CLEANUP_REPLACE = (
+ "def _save_to_disk(data, prefix):\n"
+ " import glob as _glob\n"
+ " temp_dir = _get_temp_dir()\n"
+ " # StableGen patch: clean up files from previous generations\n"
+ " for _old in _glob.glob(os.path.join(temp_dir, f'{prefix}_*.pt')):\n"
+ " try:\n"
+ " os.remove(_old)\n"
+ " except OSError:\n"
+ " pass\n"
+ " path = os.path.join(temp_dir, f'{prefix}_{uuid.uuid4().hex[:8]}.pt')\n"
+ " torch.save(data, path)\n"
+ " return {'_tensor_file': path}"
+)
+
# --- Configuration: Dependencies Data ---
# Sizes are in MB.
DEPENDENCIES: Dict[str, Dict[str, Any]] = {
@@ -592,6 +616,13 @@ DEPENDENCIES: Dict[str, Dict[str, Any]] = {
"patch": _PATCH_TRELLIS_UNLOAD_TEX_REPLACE,
"mode": "replace",
},
+ {
+ "file": "nodes/trellis_utils/stages.py",
+ "marker": "# StableGen patch: clean up files from previous generations",
+ "anchor": _PATCH_TRELLIS_TEMP_CLEANUP_ANCHOR,
+ "patch": _PATCH_TRELLIS_TEMP_CLEANUP_REPLACE,
+ "mode": "replace",
+ },
]
},
# --- VLM Emission (Grounding DINO + SAM 2) ---
diff --git a/stablegen/__init__.py b/stablegen/__init__.py
index 3ed24b2..d0909e5 100644
--- a/stablegen/__init__.py
+++ b/stablegen/__init__.py
@@ -1,6 +1,7 @@
""" This script registers the addon. """
import bpy # pylint: disable=import-error
from .stablegen import StableGenPanel, ApplyPreset, SavePreset, DeletePreset, get_preset_items, update_parameters, ResetQwenPrompt
+from .stablegen import SG_UL_SceneQueueList, SceneQueueAdd, SceneQueueRemove, SceneQueueClear, SceneQueueMoveUp, SceneQueueMoveDown, SceneQueueOpenResult, SceneQueueProcess
from .render_tools import BakeTextures, AddCameras, CloneCamera, MirrorCamera, ToggleCameraLabels, SwitchMaterial, ExportOrbitGIF, ExportForGameEngine, CollectCameraPrompts, CameraPromptItem, CameraOrderItem, SG_UL_CameraOrderList, SyncCameraOrder, MoveCameraOrder, ApplyCameraOrderPreset
from .debug_tools import debug_classes as _debug_classes
from .utils import AddHDRI, ApplyModifiers, CurvesToMesh
@@ -48,6 +49,14 @@ classes = [
Regenerate,
MirrorReproject,
Trellis2Generate,
+ SG_UL_SceneQueueList,
+ SceneQueueAdd,
+ SceneQueueRemove,
+ SceneQueueClear,
+ SceneQueueMoveUp,
+ SceneQueueMoveDown,
+ SceneQueueOpenResult,
+ SceneQueueProcess,
]
# Global caches for model lists fetched via API
@@ -1441,6 +1450,137 @@ class RemoveLoRAUnit(bpy.types.Operator):
self.report({'WARNING'}, "No LoRA unit selected or list is empty.")
return {'CANCELLED'}
+# ── Scene Queue persistence (JSON file in output dir) ─────────────────
+_SG_QUEUE_FILENAME = "sg_scene_queue.json"
+
+def _sg_queue_filepath():
+ """Return the path to the queue JSON file.
+
+ Uses the addon output_dir if set; otherwise falls back to a
+ `.stablegen` folder next to the addon package.
+ """
+ try:
+ prefs = bpy.context.preferences.addons.get(__package__)
+ if prefs and prefs.preferences.output_dir:
+ d = bpy.path.abspath(prefs.preferences.output_dir)
+ if os.path.isdir(d):
+ return os.path.join(d, _SG_QUEUE_FILENAME)
+ except Exception:
+ pass
+ # Fallback: <addon_dir>/.stablegen/
+ fallback = os.path.join(os.path.dirname(__file__), ".stablegen")
+ os.makedirs(fallback, exist_ok=True)
+ return os.path.join(fallback, _SG_QUEUE_FILENAME)
+
+
+def _sg_queue_save(processing=False, current_idx=0, phase='idle'):
+ """Serialize the scene queue + processing state to a JSON file on disk."""
+ wm = bpy.context.window_manager
+ if not hasattr(wm, 'sg_scene_queue'):
+ return
+ items = [{"label": it.label,
+ "scene_name": it.scene_name,
+ "blend_file": it.blend_file,
+ "prompt": it.prompt,
+ "negative_prompt": it.negative_prompt,
+ "status": it.status,
+ "retries": it.retries}
+ for it in wm.sg_scene_queue]
+ # GIF export settings (persist across .blend switches)
+ gif_settings = {}
+ _GIF_KEYS = (
+ 'sg_queue_gif_export', 'sg_queue_gif_duration', 'sg_queue_gif_fps',
+ 'sg_queue_gif_resolution', 'sg_queue_gif_samples', 'sg_queue_gif_engine',
+ 'sg_queue_gif_interpolation', 'sg_queue_gif_use_hdri',
+ 'sg_queue_gif_hdri_path', 'sg_queue_gif_hdri_strength',
+ 'sg_queue_gif_hdri_rotation', 'sg_queue_gif_env_mode',
+ 'sg_queue_gif_shadow_plane', 'sg_queue_gif_denoiser',
+ )
+ for key in _GIF_KEYS:
+ if hasattr(wm, key):
+ gif_settings[key] = getattr(wm, key)
+
+ data = {
+ "items": items,
+ "processing": processing,
+ "current_idx": current_idx,
+ "phase": phase,
+ "gif_settings": gif_settings,
+ }
+ try:
+ fp = _sg_queue_filepath()
+ with open(fp, 'w', encoding='utf-8') as f:
+ json.dump(data, f)
+ except Exception as e:
+ print(f"[Queue] save error: {e}")
+
+
+def _sg_queue_load():
+ """Restore the scene queue from the JSON file on disk.
+
+ If the JSON indicates that queue processing was active (e.g. after a
+ .blend switch), automatically resume.
+ """
+ wm = bpy.context.window_manager
+ if not hasattr(wm, 'sg_scene_queue'):
+ return
+ fp = _sg_queue_filepath()
+ if not os.path.isfile(fp):
+ return
+ try:
+ with open(fp, 'r', encoding='utf-8') as f:
+ raw = json.load(f)
+
+ # Support both old (list) and new (dict) format
+ if isinstance(raw, list):
+ items = raw
+ meta = {}
+ else:
+ items = raw.get("items", [])
+ meta = raw
+
+ wm.sg_scene_queue.clear()
+ for entry in items:
+ new_item = wm.sg_scene_queue.add()
+ new_item.label = entry.get("label", "")
+ new_item.scene_name = entry.get("scene_name", "")
+ new_item.blend_file = entry.get("blend_file", "")
+ new_item.prompt = entry.get("prompt", "")
+ new_item.negative_prompt = entry.get("negative_prompt", "")
+ new_item.status = entry.get("status", "pending")
+ new_item.retries = entry.get("retries", 0)
+ wm.sg_scene_queue_index = min(0, len(wm.sg_scene_queue) - 1)
+
+ # Restore GIF export settings
+ gif_settings = meta.get("gif_settings", {})
+ for key, value in gif_settings.items():
+ if hasattr(wm, key):
+ try:
+ setattr(wm, key, value)
+ except Exception:
+ pass
+
+ # Auto-resume processing if it was active (e.g. after a blend switch)
+ if meta.get("processing", False):
+ try:
+ from .stablegen import _resume_queue
+ idx = meta.get("current_idx", 0)
+ _resume_queue(idx)
+ print(f"[Queue] Auto-resuming from item {idx}")
+ except Exception as e:
+ print(f"[Queue] Failed to auto-resume: {e}")
+ except Exception as e:
+ print(f"[Queue] Failed to restore queue: {e}")
+
+
+@persistent
+def _sg_queue_load_handler(dummy):
+ """load_post handler: restore the queue when a .blend is opened."""
+ def _deferred():
+ _sg_queue_load()
+ return None
+ bpy.app.timers.register(_deferred, first_interval=0.3)
+
# load handler to set default ControlNet and LoRA units on first load
@persistent
def load_handler(dummy):
@@ -1529,7 +1669,17 @@ def load_handler(dummy):
_pending_checkpoint_refresh_architecture = current_architecture
bpy.app.timers.register(_refresh_checkpoint_for_architecture, first_interval=0.2)
-classes_to_append = [CheckServerStatus, RefreshCheckpointList, RefreshLoRAList, STABLEGEN_UL_ControlNetMappingList, ControlNetModelMappingItem, RefreshControlNetMappings, StableGenAddonPreferences, ControlNetUnit, LoRAUnit, AddControlNetUnit, RemoveControlNetUnit, AddLoRAUnit, RemoveLoRAUnit]
+class SceneQueueItem(bpy.types.PropertyGroup):
+ """A single item in the scene generation queue."""
+ label: bpy.props.StringProperty(name="Label", default="") # type: ignore # user display name
+ scene_name: bpy.props.StringProperty(name="Scene", default="") # type: ignore
+ blend_file: bpy.props.StringProperty(name="Blend File", default="") # type: ignore # path to .blend COPY
+ prompt: bpy.props.StringProperty(name="Prompt", default="") # type: ignore # display-only
+ negative_prompt: bpy.props.StringProperty(name="Negative Prompt", default="") # type: ignore
+ status: bpy.props.StringProperty(name="Status", default="pending") # type: ignore
+ retries: bpy.props.IntProperty(name="Retries", default=0) # type: ignore # how many times this item has been retried
+
+classes_to_append = [CheckServerStatus, RefreshCheckpointList, RefreshLoRAList, STABLEGEN_UL_ControlNetMappingList, ControlNetModelMappingItem, RefreshControlNetMappings, StableGenAddonPreferences, ControlNetUnit, LoRAUnit, AddControlNetUnit, RemoveControlNetUnit, AddLoRAUnit, RemoveLoRAUnit, SceneQueueItem]
for cls in classes_to_append:
classes.append(cls)
for cls in _debug_classes:
@@ -1543,6 +1693,91 @@ def register():
for cls in classes:
bpy.utils.register_class(cls)
+ # --- Scene Queue properties (on WindowManager so they're global) ---
+ bpy.types.WindowManager.sg_scene_queue = bpy.props.CollectionProperty(
+ type=SceneQueueItem,
+ name="Scene Queue"
+ )
+ bpy.types.WindowManager.sg_scene_queue_index = bpy.props.IntProperty(
+ name="Queue Index", default=0
+ )
+ bpy.types.WindowManager.sg_show_queue = bpy.props.BoolProperty(
+ name="Show Queue", default=False
+ )
+
+ # --- Queue GIF Export settings (global, applied to all items) ---
+ bpy.types.WindowManager.sg_queue_gif_export = bpy.props.BoolProperty(
+ name="Export GIF After Each Item", default=False,
+ description="Automatically export an orbit GIF/MP4 after each queue item completes"
+ )
+ bpy.types.WindowManager.sg_queue_gif_duration = bpy.props.FloatProperty(
+ name="Duration (s)", default=5.0, min=0.1, max=60.0,
+ description="Duration of the 360-degree orbit"
+ )
+ bpy.types.WindowManager.sg_queue_gif_fps = bpy.props.IntProperty(
+ name="FPS", default=24, min=1, max=60,
+ description="Frames per second"
+ )
+ bpy.types.WindowManager.sg_queue_gif_resolution = bpy.props.IntProperty(
+ name="Resolution %", default=50, min=10, max=100, subtype='PERCENTAGE',
+ description="Percentage of scene render resolution"
+ )
+ bpy.types.WindowManager.sg_queue_gif_samples = bpy.props.IntProperty(
+ name="Samples", default=32, min=1, max=4096,
+ description="Render samples per frame"
+ )
+ bpy.types.WindowManager.sg_queue_gif_engine = bpy.props.EnumProperty(
+ name="Engine",
+ items=[
+ ('BLENDER_WORKBENCH', "Workbench", ""),
+ ('EEVEE', "Eevee", ""),
+ ('CYCLES', "Cycles", ""),
+ ],
+ default='CYCLES'
+ )
+ bpy.types.WindowManager.sg_queue_gif_interpolation = bpy.props.EnumProperty(
+ name="Rotation Curve",
+ items=[
+ ('LINEAR', "Linear", "Constant speed"),
+ ('BEZIER', "Ease In/Out", "Smooth acceleration"),
+ ],
+ default='LINEAR'
+ )
+ bpy.types.WindowManager.sg_queue_gif_use_hdri = bpy.props.BoolProperty(
+ name="HDRI Environment", default=False
+ )
+ bpy.types.WindowManager.sg_queue_gif_hdri_path = bpy.props.StringProperty(
+ name="HDRI File",
+ description="Path to the HDRI image file (.hdr / .exr). "
+ "Applied via AddHDRI before each GIF export",
+ default="",
+ subtype='FILE_PATH',
+ )
+ bpy.types.WindowManager.sg_queue_gif_hdri_strength = bpy.props.FloatProperty(
+ name="HDRI Strength",
+ description="Brightness of the HDRI environment lighting",
+ default=1.0, min=0.01, max=10.0,
+ )
+ bpy.types.WindowManager.sg_queue_gif_hdri_rotation = bpy.props.FloatProperty(
+ name="HDRI Rotation", default=0.0, min=0.0, max=360.0, subtype='ANGLE'
+ )
+ bpy.types.WindowManager.sg_queue_gif_env_mode = bpy.props.EnumProperty(
+ name="Environment Mode",
+ items=[
+ ('FIXED', "Fixed", ""),
+ ('LOCKED', "Locked", ""),
+ ('COUNTER', "Counter-Rotate", ""),
+ ('ENV_ONLY', "Environment Only", ""),
+ ],
+ default='FIXED'
+ )
+ bpy.types.WindowManager.sg_queue_gif_shadow_plane = bpy.props.BoolProperty(
+ name="Ground Shadow", default=False
+ )
+ bpy.types.WindowManager.sg_queue_gif_denoiser = bpy.props.BoolProperty(
+ name="Denoise", default=True
+ )
+
def initial_refresh():
print("StableGen: Performing initial model list refresh...")
try:
@@ -1560,6 +1795,7 @@ def register():
print("StableGen: Server address not set, skipping initial refresh.")
# Run load handler to set defaults
load_handler(None)
+ _sg_queue_load()
except Exception as e:
# Catch potential errors during startup refresh
print(f"StableGen: Error during initial refresh: {e}")
@@ -1570,7 +1806,7 @@ def register():
bpy.types.Scene.comfyui_prompt = bpy.props.StringProperty(
name="ComfyUI Prompt",
- description="Enter the text prompt for ComfyUI generation",
+ description="Text prompt for generation. Use || to separate generation (left) from texturing (right) prompt",
default="gold cube",
update=update_parameters
)
@@ -1937,6 +2173,11 @@ def register():
default='idle',
update=update_parameters
)
+ bpy.types.Scene.sg_last_gen_error = bpy.props.BoolProperty(
+ name="Last Generation Error",
+ description="True if the most recent generation ended with an error",
+ default=False,
+ )
bpy.types.Scene.generation_progress = bpy.props.FloatProperty(
name="Generation Progress",
description="Current progress of image generation",
@@ -2870,6 +3111,7 @@ def register():
bpy.types.Scene.controlnet_units_index = bpy.props.IntProperty(default=0)
bpy.types.Scene.lora_units_index = bpy.props.IntProperty(default=0)
bpy.app.handlers.load_post.append(load_handler)
+ bpy.app.handlers.load_post.append(_sg_queue_load_handler)
# --- TRELLIS.2 Properties ---
bpy.types.Scene.trellis2_available = bpy.props.BoolProperty(
@@ -3549,6 +3791,7 @@ def unregister():
del bpy.types.Scene.refine_prompt
del bpy.types.Scene.refine_upscale_method
del bpy.types.Scene.generation_status
+ del bpy.types.Scene.sg_last_gen_error
del bpy.types.Scene.generation_progress
del bpy.types.Scene.overwrite_material
del bpy.types.Scene.bake_visibility_weights
@@ -3697,13 +3940,33 @@ def unregister():
if hasattr(bpy.types.Scene, prop):
delattr(bpy.types.Scene, prop)
+ # --- Scene Queue cleanup ---
+ if hasattr(bpy.types.WindowManager, 'sg_scene_queue'):
+ del bpy.types.WindowManager.sg_scene_queue
+ if hasattr(bpy.types.WindowManager, 'sg_scene_queue_index'):
+ del bpy.types.WindowManager.sg_scene_queue_index
+ if hasattr(bpy.types.WindowManager, 'sg_show_queue'):
+ del bpy.types.WindowManager.sg_show_queue
+
+ 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',
+ 'sg_queue_gif_interpolation', 'sg_queue_gif_use_hdri',
+ 'sg_queue_gif_hdri_path', 'sg_queue_gif_hdri_strength',
+ 'sg_queue_gif_hdri_rotation', 'sg_queue_gif_env_mode',
+ 'sg_queue_gif_shadow_plane', 'sg_queue_gif_denoiser',
+ ):
+ if hasattr(bpy.types.WindowManager, attr):
+ delattr(bpy.types.WindowManager, attr)
+
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
# Remove the load handler for default controlnet unit
if load_handler in bpy.app.handlers.load_post:
bpy.app.handlers.load_post.remove(load_handler)
-
+ if _sg_queue_load_handler in bpy.app.handlers.load_post:
+ bpy.app.handlers.load_post.remove(_sg_queue_load_handler)
if __name__ == "__main__":
register()
diff --git a/stablegen/generator.py b/stablegen/generator.py
index 8695cb8..cc9e386 100644
--- a/stablegen/generator.py
+++ b/stablegen/generator.py
@@ -625,6 +625,7 @@ class ComfyUIGenerate(bpy.types.Operator):
context.scene.generation_status = 'running'
+ context.scene.sg_last_gen_error = False
ComfyUIGenerate._is_running = True
print("Executing ComfyUI Generation")
@@ -673,6 +674,7 @@ class ComfyUIGenerate(bpy.types.Operator):
if not self._cameras:
self.report({'ERROR'}, "No cameras found in the scene.")
context.scene.generation_status = 'idle'
+ context.scene.sg_last_gen_error = True
ComfyUIGenerate._is_running = False
return {'CANCELLED'}
# Sort cameras by name
@@ -719,6 +721,7 @@ class ComfyUIGenerate(bpy.types.Operator):
if not controlnet_units and not (context.scene.use_flux_lora and context.scene.model_architecture == 'flux1') and context.scene.model_architecture != 'flux2_klein':
self.report({'ERROR'}, "At least one ControlNet unit is required to run the operator.")
context.scene.generation_status = 'idle'
+ context.scene.sg_last_gen_error = True
ComfyUIGenerate._is_running = False
return {'CANCELLED'}
@@ -739,6 +742,7 @@ class ComfyUIGenerate(bpy.types.Operator):
if not self._to_texture:
self.report({'ERROR'}, "No mesh objects selected for texturing.")
context.scene.generation_status = 'idle'
+ context.scene.sg_last_gen_error = True
ComfyUIGenerate._is_running = False
return {'CANCELLED'}
else: # all
@@ -757,6 +761,7 @@ class ComfyUIGenerate(bpy.types.Operator):
if not has_buffer and len(obj.data.uv_layers) >= 8:
self.report({'ERROR'}, "Not enough UV map slots. Please remove at least 1 UV map to free a slot for the projection buffer.")
context.scene.generation_status = 'idle'
+ context.scene.sg_last_gen_error = True
ComfyUIGenerate._is_running = False
return {'CANCELLED'}
@@ -927,6 +932,7 @@ class ComfyUIGenerate(bpy.types.Operator):
if self._error == "'25'" or self._error == "'111'" or self._error == "'5'":
# Probably canceled by user, quietly return
context.scene.generation_status = 'idle'
+ context.scene.sg_last_gen_error = True
self.report({'WARNING'}, "Generation cancelled.")
_sg_restore_square_display(context.scene)
_sg_ensure_crop_overlay()
@@ -939,6 +945,7 @@ class ComfyUIGenerate(bpy.types.Operator):
_sg_restore_label_overlay()
remove_empty_dirs(context)
context.scene.generation_status = 'idle'
+ context.scene.sg_last_gen_error = True
return {'CANCELLED'}
if not context.scene.generation_mode == 'project_only':
self.report({'INFO'}, "Generation complete.")
@@ -999,6 +1006,7 @@ class ComfyUIGenerate(bpy.types.Operator):
_sg_ensure_crop_overlay()
_sg_restore_label_overlay()
context.scene.generation_status = 'idle'
+ context.scene.sg_last_gen_error = False
# Clear output directories which are not needed anymore
addon_prefs = context.preferences.addons[__package__].preferences
# Save blend file in the output directory if enabled
@@ -1394,6 +1402,7 @@ class ComfyUIGenerate(bpy.types.Operator):
# Get info for the previous render and mask
render_info = self._get_uploaded_image_info(context, "inpaint", subtype="render", camera_id=self._current_image)
mask_info = self._get_uploaded_image_info(context, "inpaint", subtype="visibility", camera_id=self._current_image)
+
if context.scene.model_architecture == 'flux1':
image = self.workflow_manager.refine_flux(context, controlnet_info=controlnet_info, render_info=render_info, mask_info=mask_info, ipadapter_ref_info=ipadapter_ref_info)
elif context.scene.model_architecture == 'qwen_image_edit':
@@ -1413,7 +1422,9 @@ class ComfyUIGenerate(bpy.types.Operator):
image = self.workflow_manager.generate(context, controlnet_info=controlnet_info, ipadapter_ref_info=ipadapter_ref_info)
if image == {"error": "conn_failed"}:
- return # Error message already set
+ if not self._error:
+ self._error = "Connection to ComfyUI server failed."
+ return # Error message set
if (context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein') and
context.scene.generation_method == 'sequential' and
@@ -1433,7 +1444,7 @@ class ComfyUIGenerate(bpy.types.Operator):
with open(image_path, 'wb') as f:
f.write(image)
-
+
# Use hack to re-generate the image using IPAdapter to match IPAdapter style
if camera_id == 0 and (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate' or context.scene.generation_method in ('refine', 'local_edit'))\
and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate and not context.scene.use_ipadapter and context.scene.sequential_ipadapter_mode == 'first':
@@ -2924,6 +2935,8 @@ class ComfyUIGenerate(bpy.types.Operator):
original_engine = bpy.context.scene.render.engine
original_view_transform = bpy.context.scene.view_settings.view_transform
original_film_transparent = bpy.context.scene.render.film_transparent
+ original_use_compositing = bpy.context.scene.render.use_compositing
+ original_filepath = bpy.context.scene.render.filepath
# Set animation frame to 1
bpy.context.scene.frame_set(1)
@@ -2949,7 +2962,8 @@ class ComfyUIGenerate(bpy.types.Operator):
# Enable depth pass in the render settings
view_layer.use_pass_z = True
- # Use the compositor to save the depth pass
+ # Enable compositor pipeline (may have been disabled by prior GIF export)
+ bpy.context.scene.render.use_compositing = True
bpy.context.scene.use_nodes = True
node_tree = get_compositor_node_tree(bpy.context.scene)
nodes = node_tree.nodes
@@ -2995,6 +3009,8 @@ class ComfyUIGenerate(bpy.types.Operator):
bpy.context.scene.render.engine = original_engine
bpy.context.scene.view_settings.view_transform = original_view_transform
bpy.context.scene.render.film_transparent = original_film_transparent
+ bpy.context.scene.render.use_compositing = original_use_compositing
+ bpy.context.scene.render.filepath = original_filepath
view_layer.use_pass_z = original_pass_z
def export_normal(self, context, camera_id=None):
@@ -3021,10 +3037,13 @@ class ComfyUIGenerate(bpy.types.Operator):
original_engine = bpy.context.scene.render.engine
original_view_transform = bpy.context.scene.view_settings.view_transform
original_film_transparent = bpy.context.scene.render.film_transparent
+ original_use_compositing = bpy.context.scene.render.use_compositing
+ original_filepath = bpy.context.scene.render.filepath
bpy.context.scene.render.engine = get_eevee_engine_id()
bpy.context.scene.view_settings.view_transform = 'Raw'
bpy.context.scene.render.film_transparent = True
+ bpy.context.scene.render.use_compositing = True
bpy.context.scene.use_nodes = True
# Clear existing nodes.
@@ -3063,6 +3082,8 @@ class ComfyUIGenerate(bpy.types.Operator):
bpy.context.scene.render.engine = original_engine
bpy.context.scene.view_settings.view_transform = original_view_transform
bpy.context.scene.render.film_transparent = original_film_transparent
+ bpy.context.scene.render.use_compositing = original_use_compositing
+ bpy.context.scene.render.filepath = original_filepath
view_layer.use_pass_normal = original_pass_normal
@@ -3708,6 +3729,7 @@ class Trellis2Generate(bpy.types.Operator):
return {'CANCELLED'}
Trellis2Generate._is_running = True
+ context.scene.sg_last_gen_error = False
self._error = None
self._glb_data = None
self._progress = 0.0
@@ -3725,7 +3747,7 @@ class Trellis2Generate(bpy.types.Operator):
# 3-tier progress init
has_txt2img = (gen_from == 'prompt')
- has_texturing = (tex_mode in ('sdxl', 'flux1', 'qwen_image_edit'))
+ has_texturing = (tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'))
if has_txt2img and has_texturing:
self._total_phases = 3
self._phase_layout = 'txt2img+trellis+texturing'
@@ -3852,15 +3874,18 @@ class Trellis2Generate(bpy.types.Operator):
# User cancelled — exit silently (no error toast)
if was_cancelled:
context.scene.generation_status = 'idle'
+ context.scene.sg_last_gen_error = True
return {'FINISHED'}
if self._error:
self.report({'ERROR'}, f"TRELLIS.2 error: {self._error}")
+ context.scene.sg_last_gen_error = True
return {'CANCELLED'}
if self._glb_data is None or (isinstance(self._glb_data, dict) and "error" in self._glb_data):
error_msg = self._glb_data.get("error", "Unknown error") if isinstance(self._glb_data, dict) else "No data received"
self.report({'ERROR'}, f"TRELLIS.2 failed: {error_msg}")
+ context.scene.sg_last_gen_error = True
return {'CANCELLED'}
# Surface mesh-corruption warning to the user (set by workflows.py
@@ -3935,7 +3960,7 @@ class Trellis2Generate(bpy.types.Operator):
self._setup_studio_lighting(context, target_bu)
# --- Phase 3: If diffusion texturing, auto-place cameras + start generation ---
- if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit'):
+ if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'):
# Place cameras NOW (while operator context is still valid)
camera_count = getattr(context.scene, 'trellis2_camera_count', 8)
imported_objects = [obj for obj in context.selected_objects]
@@ -3950,6 +3975,11 @@ class Trellis2Generate(bpy.types.Operator):
# consistent reference direction for sorting and auto-prompts.
# TRELLIS.2 always imports meshes in standard orientation so the
# viewport should match.
+ # Find the 3D viewport area + WINDOW region so add_cameras
+ # gets a full context (region_data etc.) even when invoked
+ # from a timer-driven modal callback.
+ _v3d_area = None
+ _v3d_region = None
for area in context.screen.areas:
if area.type == 'VIEW_3D':
for space in area.spaces:
@@ -3961,6 +3991,11 @@ class Trellis2Generate(bpy.types.Operator):
(0.7071068, 0.7071068, 0.0, 0.0)
)
rv3d.view_perspective = 'PERSP'
+ _v3d_area = area
+ for reg in area.regions:
+ if reg.type == 'WINDOW':
+ _v3d_region = reg
+ break
break
try:
@@ -3985,8 +4020,14 @@ class Trellis2Generate(bpy.types.Operator):
_cam_kwargs['max_auto_cameras'] = getattr(context.scene, 'trellis2_max_auto_cameras', 12)
if _pm == 'fan_from_camera':
_cam_kwargs['fan_angle'] = getattr(context.scene, 'trellis2_fan_angle', 90.0)
- bpy.ops.object.add_cameras(**_cam_kwargs)
- print(f"[TRELLIS2] Placed {camera_count} cameras ({_pm})")
+
+ # Use temp_override so add_cameras gets proper region_data
+ 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)
+
except Exception as cam_err:
print(f"[TRELLIS2] Warning: Camera placement failed: {cam_err}")
traceback.print_exc()
@@ -4062,9 +4103,9 @@ class Trellis2Generate(bpy.types.Operator):
print(f"[TRELLIS2] Pre-texturing flush warning: {flush_err}")
bpy.ops.object.select_all(action='DESELECT')
- for obj in bpy.context.scene.objects:
- if obj.type == 'CAMERA':
- obj.select_set(True)
+ scene_cams = [obj for obj in bpy.context.scene.objects if obj.type == 'CAMERA']
+ for obj in scene_cams:
+ obj.select_set(True)
bpy.ops.object.test_stable('INVOKE_DEFAULT')
print("[TRELLIS2] Texture generation started")
diff --git a/stablegen/render_tools.py b/stablegen/render_tools.py
index b0fd8cc..bd58146 100644
--- a/stablegen/render_tools.py
+++ b/stablegen/render_tools.py
@@ -160,6 +160,8 @@ def render_edge_feather_mask(context, to_export, camera, camera_index, feather_w
original_transparent = context.scene.render.film_transparent
original_samples = context.scene.cycles.samples
original_view_transform = bpy.context.scene.view_settings.view_transform
+ original_use_compositing = context.scene.render.use_compositing
+ original_filepath = context.scene.render.filepath
world = context.scene.world
if not world:
@@ -232,6 +234,7 @@ def render_edge_feather_mask(context, to_export, camera, camera_index, feather_w
view_layer.use_pass_environment = True
# ── Compositor ──────────────────────────────────────────────────────────
+ context.scene.render.use_compositing = True
context.scene.use_nodes = True
node_tree = get_compositor_node_tree(context.scene)
comp_nodes = node_tree.nodes
@@ -285,6 +288,8 @@ def render_edge_feather_mask(context, to_export, camera, camera_index, feather_w
context.scene.render.film_transparent = original_transparent
context.scene.cycles.samples = original_samples
bpy.context.scene.view_settings.view_transform = original_view_transform
+ context.scene.render.use_compositing = original_use_compositing
+ context.scene.render.filepath = original_filepath
world.use_nodes = original_use_nodes
world.color = original_color
if original_bg_node_color is not None and world.node_tree:
@@ -701,6 +706,8 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
# Store original settings
original_engine = context.scene.render.engine
original_film_transparent = context.scene.render.film_transparent
+ original_use_compositing = context.scene.render.use_compositing
+ original_filepath = context.scene.render.filepath
original_use_nodes = world.use_nodes
original_color = world.color.copy()
original_bg_node_color = None
@@ -754,6 +761,7 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
# Set up compositor nodes
+ context.scene.render.use_compositing = True
context.scene.use_nodes = True
node_tree = get_compositor_node_tree(context.scene)
nodes = node_tree.nodes
@@ -812,6 +820,8 @@ def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.
# Restore original settings
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
world.use_nodes = original_use_nodes
world.color = original_color
if original_bg_node_color is not None and world.node_tree:
@@ -902,6 +912,7 @@ def export_render(context, camera_id=None, output_dir=None, filename=None):
}
original_render_filepath = context.scene.render.filepath
original_image_settings = context.scene.render.image_settings.file_format
+ original_use_compositing = context.scene.render.use_compositing
# Switch to WORKBENCH render engine and configure settings
context.scene.render.engine = 'BLENDER_WORKBENCH'
@@ -916,6 +927,7 @@ def export_render(context, camera_id=None, output_dir=None, filename=None):
render_layer.use_pass_combined = True
# Set up output nodes (Compositor setup remains the same)
+ context.scene.render.use_compositing = True
context.scene.use_nodes = True
node_tree = get_compositor_node_tree(context.scene)
nodes = node_tree.nodes
@@ -956,6 +968,7 @@ def export_render(context, camera_id=None, output_dir=None, filename=None):
context.scene.display.shading.color_type = original_workbench_settings['color_type']
context.scene.render.filepath = original_render_filepath
context.scene.render.image_settings.file_format = original_image_settings
+ context.scene.render.use_compositing = original_use_compositing
print(f"Render saved to: {os.path.join(output_dir, output_file)}0001.png") # Blender adds frame number
@@ -2769,6 +2782,17 @@ class AddCameras(bpy.types.Operator):
layout.prop(self, "consider_existing")
def draw_callback(self, context):
+ # Guard against operator being freed while draw handler is still registered
+ try:
+ _ = self._occ_phase # probe attribute access
+ except ReferenceError:
+ # Operator freed — remove the dangling draw handler
+ if AddCameras._draw_handle:
+ bpy.types.SpaceView3D.draw_handler_remove(
+ AddCameras._draw_handle, 'WINDOW')
+ AddCameras._draw_handle = None
+ return
+
# ── Occlusion progress display ───────────────────────────────────
if self._occ_phase:
font_id = 0
@@ -2907,7 +2931,11 @@ class AddCameras(bpy.types.Operator):
# only the manual modes (orbit_ring, fan_from_camera) need this.
if is_auto_mode:
# Placeholder – auto branch overrides center_location from verts
- center_location = context.region_data.view_location.copy()
+ rv3d = getattr(context, 'region_data', None)
+ if rv3d is not None:
+ center_location = rv3d.view_location.copy()
+ else:
+ center_location = mathutils.Vector((0.0, 0.0, 0.0))
elif self.center_type == 'object':
obj = context.object
cursor_loc = context.scene.cursor.location.copy()
@@ -2918,14 +2946,21 @@ class AddCameras(bpy.types.Operator):
context.scene.cursor.location = cursor_loc
center_location = obj.matrix_world.translation + obj.matrix_world.to_3x3() @ (center_location - obj.matrix_world.translation)
else:
- center_location = context.region_data.view_location.copy()
+ rv3d = getattr(context, 'region_data', None)
+ if rv3d is not None:
+ center_location = rv3d.view_location.copy()
+ else:
+ center_location = mathutils.Vector((0.0, 0.0, 0.0))
# --- Set or create reference camera ---
self._initial_camera = context.scene.camera
using_viewport_ref = False
if not self._initial_camera and not is_auto_mode:
# Manual modes: create a camera from the viewport as Camera_0
- rv3d = context.region_data
+ rv3d = getattr(context, 'region_data', None)
+ if rv3d is None:
+ self.report({'ERROR'}, "No 3D viewport available for camera placement")
+ return {'CANCELLED'}
cam_data = bpy.data.cameras.new(name='Camera_0')
cam_obj = bpy.data.objects.new('Camera_0', cam_data)
context.collection.objects.link(cam_obj)
@@ -5826,41 +5861,58 @@ class ExportOrbitGIF(bpy.types.Operator):
break
if env_tex is None:
- # No HDRI world set up — create a procedural sky fallback
- print("[StableGen] Orbit GIF: No HDRI found, creating sky fallback")
- tree.nodes.clear()
-
- tex_coord = tree.nodes.new("ShaderNodeTexCoord")
+ # No HDRI world set up — create a *separate* procedural sky world
+ # so the original world node tree is never destroyed.
+ print("[StableGen] Orbit GIF: No HDRI found, creating sky fallback "
+ "(original world preserved)")
+ fallback_world = bpy.data.worlds.new("SG_OrbitSkyFallback")
+ fallback_world.use_nodes = True
+ fb_tree = fallback_world.node_tree
+ fb_tree.nodes.clear()
+
+ tex_coord = fb_tree.nodes.new("ShaderNodeTexCoord")
tex_coord.location = (-800, 300)
- mapping = tree.nodes.new("ShaderNodeMapping")
+ mapping = fb_tree.nodes.new("ShaderNodeMapping")
mapping.location = (-600, 300)
mapping.inputs["Rotation"].default_value[2] = self.hdri_rotation
self._env_mapping_node = mapping
- sky_tex = tree.nodes.new("ShaderNodeTexSky")
+ sky_tex = fb_tree.nodes.new("ShaderNodeTexSky")
sky_tex.location = (-300, 300)
- sky_tex.sky_type = 'NISHITA'
- sky_tex.sun_elevation = math.radians(30)
- sky_tex.sun_rotation = math.radians(45)
+ # Set sky type — Blender 5.x replaced 'NISHITA' with new names
+ for sky_type in ('NISHITA', 'HOSEK_WILKIE', 'PREETHAM'):
+ try:
+ sky_tex.sky_type = sky_type
+ break
+ except TypeError:
+ continue
+ # Sun attributes vary by sky type / version
+ try:
+ sky_tex.sun_elevation = math.radians(30)
+ sky_tex.sun_rotation = math.radians(45)
+ except AttributeError:
+ pass
- bg_node = tree.nodes.new("ShaderNodeBackground")
+ bg_node = fb_tree.nodes.new("ShaderNodeBackground")
bg_node.location = (0, 300)
- output_node = tree.nodes.new("ShaderNodeOutputWorld")
+ output_node = fb_tree.nodes.new("ShaderNodeOutputWorld")
output_node.location = (200, 300)
- tree.links.new(tex_coord.outputs["Generated"],
+ fb_tree.links.new(tex_coord.outputs["Generated"],
mapping.inputs["Vector"])
- tree.links.new(mapping.outputs["Vector"],
+ fb_tree.links.new(mapping.outputs["Vector"],
sky_tex.inputs["Vector"])
- tree.links.new(sky_tex.outputs["Color"],
+ fb_tree.links.new(sky_tex.outputs["Color"],
bg_node.inputs["Color"])
- tree.links.new(bg_node.outputs["Background"],
+ fb_tree.links.new(bg_node.outputs["Background"],
output_node.inputs["Surface"])
- # Track that we created the fallback so cleanup can remove it
+ # Swap the scene world to the fallback; original is stored for restore
+ context.scene.world = fallback_world
self._original_world_data['created_fallback'] = True
+ self._original_world_data['fallback_world'] = fallback_world
return
# ── Inject Mapping node before the Environment Texture ────────
@@ -6059,6 +6111,23 @@ class ExportOrbitGIF(bpy.types.Operator):
render = scene.render
cycles = scene.cycles # Get cycles settings
+ # When called via EXEC_DEFAULT (e.g. from the queue) invoke()
+ # is skipped, so initialise paths / temp dir here if needed.
+ if not self._temp_dir:
+ try:
+ revision_dir = get_dir_path(context, "revision")
+ os.makedirs(revision_dir, exist_ok=True)
+ self._output_path = os.path.join(revision_dir, "orbit.gif")
+ self._output_path_mp4 = os.path.join(revision_dir, "orbit.mp4")
+ except Exception as e:
+ self.report({'ERROR'}, f"Could not determine output directory: {e}")
+ return {'CANCELLED'}
+ try:
+ self._temp_dir = tempfile.mkdtemp(prefix="blender_gif_")
+ except Exception as e:
+ self.report({'ERROR'}, f"Could not create temporary directory: {e}")
+ return {'CANCELLED'}
+
# Store Initial Settings
self._initial_settings = {
'frame_start': scene.frame_start,
@@ -6135,6 +6204,7 @@ class ExportOrbitGIF(bpy.types.Operator):
# Start Rendering
self._rendering = True
+ ExportOrbitGIF._rendering = True # class-level flag for external polling
self._cancelled = False # Reset cancellation flag
self._frame_paths.clear() # Clear list for new render
self._handle_complete = bpy.app.handlers.render_complete.append(self.render_complete_handler)
@@ -6284,48 +6354,61 @@ class ExportOrbitGIF(bpy.types.Operator):
if self._original_world_data:
try:
world = self._original_world_data['world_ref']
- if world and world.name in bpy.data.worlds:
- # Remove HDRI animation keyframes
+
+ if self._original_world_data.get('created_fallback'):
+ # We swapped in a separate fallback world — restore original
+ fallback_world = self._original_world_data.get(
+ 'fallback_world')
+
+ # Clean up animation data on the fallback world
+ if (fallback_world and fallback_world.node_tree
+ and fallback_world.node_tree.animation_data):
+ action = fallback_world.node_tree.animation_data.action
+ if action and action.name in bpy.data.actions:
+ bpy.data.actions.remove(action)
+ fallback_world.node_tree.animation_data_clear()
+
+ # Restore the original world
+ if world and world.name in bpy.data.worlds:
+ bpy.context.scene.world = world
+ # Remove the temporary fallback world datablock
+ if (fallback_world
+ and fallback_world.name in bpy.data.worlds):
+ bpy.data.worlds.remove(fallback_world)
+ elif world and world.name in bpy.data.worlds:
+ # Remove HDRI animation keyframes on the original world
if world.node_tree and world.node_tree.animation_data:
action = world.node_tree.animation_data.action
if action and action.name in bpy.data.actions:
bpy.data.actions.remove(action)
world.node_tree.animation_data_clear()
- if self._original_world_data.get('created_fallback'):
- # We created a whole sky fallback — restore original
- world.use_nodes = self._original_world_data['use_nodes']
- world.color = self._original_world_data['color']
- if not self._original_world_data['use_nodes']:
- if world.node_tree:
- world.node_tree.nodes.clear()
- else:
- # We injected SG_OrbitMapping + SG_OrbitTexCoord
- # into the existing tree. Remove them and restore
- # the original vector link.
- tree = world.node_tree
- if tree:
- # Find the env tex and restore its vector input
- env_tex = None
- for node in tree.nodes:
- if node.type == 'TEX_ENVIRONMENT':
- env_tex = node
- break
+ # We injected SG_OrbitMapping + SG_OrbitTexCoord
+ # into the existing tree. Remove them and restore
+ # the original vector link.
+ tree = world.node_tree
+ if tree:
+ # Find the env tex and restore its vector input
+ env_tex = None
+ for node in tree.nodes:
+ if node.type == 'TEX_ENVIRONMENT':
+ env_tex = node
+ break
- orig_socket = self._original_world_data.get(
- 'env_vec_from_socket')
- if env_tex and orig_socket:
- tree.links.new(orig_socket,
- env_tex.inputs["Vector"])
- elif env_tex:
- # Had no vector link originally — just remove
- for link in list(env_tex.inputs["Vector"].links):
- tree.links.remove(link)
-
- # Remove injected nodes
- for name in ("SG_OrbitMapping", "SG_OrbitTexCoord"):
- if name in tree.nodes:
- tree.nodes.remove(tree.nodes[name])
+ orig_socket = self._original_world_data.get(
+ 'env_vec_from_socket')
+ if env_tex and orig_socket:
+ tree.links.new(orig_socket,
+ env_tex.inputs["Vector"])
+ elif env_tex:
+ # Had no vector link originally — just remove
+ for link in list(env_tex.inputs["Vector"].links):
+ tree.links.remove(link)
+
+ # Remove injected nodes
+ for name in ("SG_OrbitMapping", "SG_OrbitTexCoord"):
+ if name in tree.nodes:
+ tree.nodes.remove(tree.nodes[name])
except Exception as e:
print(f"Warning: Could not restore world environment: {e}")
self._original_world_data = None
@@ -6333,6 +6416,7 @@ class ExportOrbitGIF(bpy.types.Operator):
self._rendering = False # Ensure rendering flag is reset
+ ExportOrbitGIF._rendering = False # class-level flag for external polling
self._cancelled = False # Reset cancellation flag
# Clean up temporary directory if it exists
diff --git a/stablegen/stablegen.py b/stablegen/stablegen.py
index 888057f..a47ae48 100644
--- a/stablegen/stablegen.py
+++ b/stablegen/stablegen.py
@@ -39,6 +39,10 @@ PRESETS = {
"DEFAULT (MODEL + 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_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_vram_mode": "disk_offload", "trellis2_attn_backend": "flash_attn", "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": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_low_vram": False, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_fill_holes": True, "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, "apply_bsdf": 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 (MODEL + 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_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_vram_mode": "disk_offload", "trellis2_attn_backend": "flash_attn", "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": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_low_vram": False, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_fill_holes": True, "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "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, "apply_bsdf": 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 (MODEL + 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_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_vram_mode": "disk_offload", "trellis2_attn_backend": "flash_attn", "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": 49152, "trellis2_texture_size": 4096, "trellis2_decimation": 1000000, "trellis2_remesh": True, "trellis2_post_processing_enabled": True, "trellis2_low_vram": False, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_fill_holes": True, "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, "apply_bsdf": 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 (MODEL + 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_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_vram_mode": "disk_offload", "trellis2_attn_backend": "flash_attn", "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_low_vram": False, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_fill_holes": True, "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "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, "apply_bsdf": 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 (MODEL + 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": True, "sequential_ipadapter_mode": "trellis2_input", "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_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_vram_mode": "disk_offload", "trellis2_attn_backend": "flash_attn", "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_low_vram": False, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_fill_holes": True, "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "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, "apply_bsdf": 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 ALT (MODEL + 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_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_vram_mode": "disk_offload", "trellis2_attn_backend": "flash_attn", "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_low_vram": False, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_fill_holes": True, "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "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, "apply_bsdf": 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 VORONOI (MODEL + 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_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_vram_mode": "disk_offload", "trellis2_attn_backend": "flash_attn", "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_low_vram": False, "trellis2_bg_removal": "auto", "trellis2_background_color": "black", "trellis2_fill_holes": True, "trellis2_import_scale": 2.0, "trellis2_clamp_elevation": True, "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, "apply_bsdf": 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}]},
}
# Global list of all generation parameter names to check for a preset.
@@ -418,43 +422,88 @@ class StableGenPanel(bpy.types.Panel):
action_row.operator("object.test_stable", text="Cancel Texturing", icon="CANCEL")
progress_col = layout.column()
- # Compute overall from scene pipeline props + ComfyUI progress
- phase_start = getattr(scene, 'trellis2_pipeline_phase_start_pct', 65.0)
- phase_weight = 100.0 - phase_start
- comfy_progress = getattr(comfy_tex_op, '_progress', 0) / 100.0
- total_imgs = getattr(comfy_tex_op, '_total_images', 0)
- cur_img_idx = getattr(comfy_tex_op, '_current_image', 0)
- if total_imgs > 1:
- comfy_overall = (cur_img_idx + comfy_progress) / total_imgs
+ pbr_active = getattr(comfy_tex_op, '_pbr_active', False)
+ if pbr_active:
+ # PBR decomposition sub-phase
+ pbr_step = getattr(comfy_tex_op, '_pbr_step', 0)
+ pbr_total = max(getattr(comfy_tex_op, '_pbr_total_steps', 1), 1)
+ pbr_cam = getattr(comfy_tex_op, '_pbr_cam', 0)
+ pbr_cam_total = max(getattr(comfy_tex_op, '_pbr_cam_total', 1), 1)
+ cam_frac = pbr_cam / pbr_cam_total
+ stage_text = getattr(comfy_tex_op, '_stage', 'PBR Decomposition')
+
+ # Bar 1 — Current model (camera progress)
+ progress_col.progress(text=stage_text, factor=max(0.0, min(cam_frac, 1.0)))
+ # Bar 2 — PBR step N/M
+ pbr_factor = max(0.0, min(((pbr_step - 1) + cam_frac) / pbr_total, 1.0))
+ progress_col.progress(text=f"PBR: Step {pbr_step}/{pbr_total}", factor=pbr_factor)
else:
- comfy_overall = comfy_progress
- overall_pct = phase_start + comfy_overall * phase_weight
- overall_pct = max(0.0, min(overall_pct, 100.0))
-
- total_phases = getattr(scene, 'trellis2_pipeline_total_phases', 3)
- # Bar 1 — Overall
- progress_col.progress(
- text=f"Phase {total_phases}/{total_phases}: Texturing ({overall_pct:.0f}%)",
- factor=max(0.0, min(overall_pct / 100.0, 1.0))
- )
+ # Normal texturing progress
+ # Compute overall from scene pipeline props + ComfyUI progress
+ phase_start = getattr(scene, 'trellis2_pipeline_phase_start_pct', 65.0)
+ phase_weight = 100.0 - phase_start
+ comfy_progress = getattr(comfy_tex_op, '_progress', 0) / 100.0
+ total_imgs = getattr(comfy_tex_op, '_total_images', 0)
+ cur_img_idx = getattr(comfy_tex_op, '_current_image', 0)
+ if total_imgs > 1:
+ comfy_overall = (cur_img_idx + comfy_progress) / total_imgs
+ else:
+ comfy_overall = comfy_progress
+ overall_pct = phase_start + comfy_overall * phase_weight
+ overall_pct = max(0.0, min(overall_pct, 100.0))
- # Bar 2 — Per-image (same as normal ComfyUI bar)
- stage = getattr(comfy_tex_op, '_stage', 'Generating')
- img_pct = getattr(comfy_tex_op, '_progress', 0)
- progress_col.progress(
- text=f"{stage} ({img_pct:.0f}%)",
- factor=max(0.0, min(img_pct / 100.0, 1.0))
- )
+ total_phases = getattr(scene, 'trellis2_pipeline_total_phases', 3)
+ # Bar 1 — Overall
+ progress_col.progress(
+ text=f"Phase {total_phases}/{total_phases}: Texturing ({overall_pct:.0f}%)",
+ factor=max(0.0, min(overall_pct / 100.0, 1.0))
+ )
- # Bar 3 — Image N/M (same as normal ComfyUI overall bar)
- if total_imgs > 1:
- cur_img = min(cur_img_idx + 1, total_imgs)
- img_overall = max(0.0, min(comfy_overall, 1.0))
+ # Bar 2 — Per-image (same as normal ComfyUI bar)
+ stage = getattr(comfy_tex_op, '_stage', 'Generating')
+ img_pct = getattr(comfy_tex_op, '_progress', 0)
progress_col.progress(
- text=f"Overall: Image {cur_img}/{total_imgs}",
- factor=img_overall
+ text=f"{stage} ({img_pct:.0f}%)",
+ factor=max(0.0, min(img_pct / 100.0, 1.0))
)
+ # Bar 3 — Image N/M (same as normal ComfyUI overall bar)
+ if total_imgs > 1:
+ cur_img = min(cur_img_idx + 1, total_imgs)
+ img_overall = max(0.0, min(comfy_overall, 1.0))
+ progress_col.progress(
+ text=f"Overall: Image {cur_img}/{total_imgs}",
+ factor=img_overall
+ )
+
+ elif comfy_tex_op and scene.generation_status == 'running':
+ # Standalone ComfyUIGenerate (e.g. Reproject with PBR)
+ # outside the TRELLIS.2 pipeline.
+ action_row.operator("object.test_stable", text="Cancel Generation", icon="CANCEL")
+ progress_col = layout.column()
+ raw_progress = getattr(comfy_tex_op, '_progress', 0) / 100.0
+ pbr_active = getattr(comfy_tex_op, '_pbr_active', False)
+
+ if pbr_active:
+ pbr_step = getattr(comfy_tex_op, '_pbr_step', 0)
+ pbr_total = max(getattr(comfy_tex_op, '_pbr_total_steps', 1), 1)
+ pbr_cam = getattr(comfy_tex_op, '_pbr_cam', 0)
+ pbr_cam_total = max(getattr(comfy_tex_op, '_pbr_cam_total', 1), 1)
+ cam_frac = pbr_cam / pbr_cam_total
+ stage_text = getattr(comfy_tex_op, '_stage', 'PBR Decomposition')
+ progress_col.progress(text=stage_text, factor=max(0.0, min(cam_frac, 1.0)))
+ pbr_factor = max(0.0, min(((pbr_step - 1) + cam_frac) / pbr_total, 1.0))
+ progress_col.progress(text=f"PBR: Step {pbr_step}/{pbr_total}", factor=pbr_factor)
+ else:
+ progress_text = f"{getattr(comfy_tex_op, '_stage', 'Generating')} ({getattr(comfy_tex_op, '_progress', 0):.0f}%)"
+ progress_col.progress(text=progress_text, factor=max(0.0, min(raw_progress, 1.0)))
+ total_images = getattr(comfy_tex_op, '_total_images', 0)
+ if total_images > 1:
+ current_image_idx = getattr(comfy_tex_op, '_current_image', 0)
+ overall_progress = (current_image_idx + max(0.0, min(raw_progress, 1.0))) / total_images if total_images > 0 else 0
+ cur_img = min(current_image_idx + 1, total_images)
+ progress_col.progress(text=f"Overall: Image {cur_img}/{total_images}", factor=max(0.0, min(overall_progress, 1.0)))
+
elif scene.trellis2_generate_from == 'image' and not scene.trellis2_input_image:
action_row.operator("object.trellis2_generate", text="Select an image first", icon="ERROR")
action_row.enabled = False
@@ -600,6 +649,69 @@ class StableGenPanel(bpy.types.Panel):
if not is_stock_preset and scene.stablegen_preset != "DEFAULT":
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_processing:
+ status_text = "Exporting GIF..." if _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_clear", text="Clear", icon="TRASH")
+ btn_row.operator("stablegen.queue_open_result", text="Open Result", icon="FILE_BLEND")
+
+ process_row = queue_content.row()
+ if _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_shadow_plane")
+ gif_col.prop(wm, "sg_queue_gif_denoiser")
# --- Main Parameters section ---
if not hasattr(scene, 'show_generation_params'):
@@ -658,10 +770,10 @@ class StableGenPanel(bpy.types.Panel):
split.label(text="Texture Mode:")
split.prop(scene, "trellis2_texture_mode", text="")
- # Prompt + native/none: show initial-image architecture & checkpoint
+ # Prompt + native: show initial-image architecture & checkpoint
_prompt_native = (
scene.trellis2_generate_from == 'prompt'
- and trellis2_tex_mode in ('native', 'none')
+ and trellis2_tex_mode == 'native'
)
if _prompt_native:
split = params_container.split(factor=0.5)
@@ -1885,6 +1997,15 @@ class ApplyPreset(bpy.types.Operator):
if preset in PRESETS:
values = PRESETS[preset]
+ # Apply architecture_mode first so dynamic enums that
+ # depend on it (e.g. sequential_ipadapter_mode) are valid
+ # when their values are set in the main loop.
+ if "architecture_mode" in values and hasattr(context.scene, "architecture_mode"):
+ try:
+ setattr(context.scene, "architecture_mode", values["architecture_mode"])
+ except (TypeError, AttributeError):
+ pass
+
# Apply regular parameters
skipped = []
for key, value in values.items():
@@ -2069,3 +2190,793 @@ class DeletePreset(bpy.types.Operator):
else:
self.report({'WARNING'}, "Preset not found.")
return {'CANCELLED'}
+
+
+# =====================================================================
+# Scene Queue System
+# =====================================================================
+# Allows users to queue multiple Blender scenes for unattended batch
+# processing. Each queued scene is processed in order — the manager
+# switches to the scene, invokes the appropriate generation operator
+# (TRELLIS.2 or standard texturing), waits for completion, optionally
+# saves a .blend copy, then advances to the next item.
+
+_queue_timer = None # Reference to the active timer callback
+_queue_processing = False # Global flag: queue is being processed
+_queue_current_idx = 0 # Index of the currently-processing item
+_queue_phase = 'idle' # 'idle' | 'switching' | 'running' | 'settling' | 'waiting_texturing' | 'exporting_gif'
+_queue_settle_deadline = 0.0 # monotonic time after which 'settling' may finish
+_queue_force_reload = False # Force re-open of the .blend on next idle tick (for retries)
+_queue_texturing_seen = False # Set True once generation_status='running' is observed during settling
+_QUEUE_MAX_RETRIES = 3 # how many times a failed item is retried
+
+
+class SG_UL_SceneQueueList(bpy.types.UIList):
+ """UIList for the scene generation queue."""
+ bl_idname = "SG_UL_SceneQueueList"
+
+ def draw_item(self, context, layout, data, item, icon, active_data, active_property, index):
+ if self.layout_type in {'DEFAULT', 'COMPACT'}:
+ row = layout.row(align=True)
+
+ # Label (or scene name as fallback)
+ display = item.label if item.label else item.scene_name
+ row.label(text=display, icon='SCENE_DATA')
+
+ # Status icon + retry indicator
+ if item.status == 'done':
+ row.label(text="", icon='CHECKMARK')
+ elif item.status == 'error':
+ retry_txt = f"x{item.retries}" if item.retries else ""
+ row.label(text=retry_txt, icon='ERROR')
+ elif item.status == 'processing':
+ retry_txt = f"#{item.retries + 1}" if item.retries else ""
+ row.label(text=retry_txt, icon='SORTTIME')
+ elif self.layout_type == 'GRID':
+ layout.alignment = 'CENTER'
+ display = item.label if item.label else item.scene_name
+ layout.label(text=display, icon='SCENE_DATA')
+
+
+def _persist_queue():
+ """Write the queue + processing state to a JSON file on disk."""
+ try:
+ from . import _sg_queue_save
+ _sg_queue_save(
+ processing=_queue_processing,
+ current_idx=_queue_current_idx,
+ phase=_queue_phase,
+ )
+ except Exception:
+ pass
+
+
+def _resume_queue(idx):
+ """Resume queue processing from *idx* (called after a .blend switch).
+
+ This is invoked by ``_sg_queue_load()`` in ``__init__.py`` when the
+ JSON file indicates that processing was active.
+ """
+ global _queue_processing, _queue_current_idx, _queue_phase, _queue_timer
+
+ _queue_processing = True
+ _queue_current_idx = idx
+ _queue_phase = 'idle'
+
+ # Avoid duplicate timers
+ if _queue_timer is not None:
+ try:
+ bpy.app.timers.unregister(_queue_tick)
+ except Exception:
+ pass
+
+ _queue_timer = bpy.app.timers.register(_queue_tick, first_interval=1.5)
+ print(f"[Queue] Resumed processing from item {idx}")
+ _tag_redraw()
+
+
+class SceneQueueAdd(bpy.types.Operator):
+ """Add the current scene to the generation queue.
+
+ Saves a *copy* of the current .blend into ``<output_dir>/queue_jobs/``.
+ The queue item points at that copy so the original file is never
+ modified by queue processing.
+ """
+ bl_idname = "stablegen.queue_add"
+ bl_label = "Add to Queue"
+ bl_description = "Snapshot the current .blend and add the scene to the batch queue"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ item_label: bpy.props.StringProperty(
+ name="Name",
+ description="A short label for this queue entry",
+ default="",
+ ) # type: ignore
+
+ @classmethod
+ def poll(cls, context):
+ return not _queue_processing
+
+ def invoke(self, context, event):
+ scene = context.scene
+ cur_prompt = getattr(scene, 'comfyui_prompt', '')
+ # Pre-fill with a truncated prompt
+ self.item_label = (cur_prompt[:40]) if cur_prompt else scene.name
+ return context.window_manager.invoke_props_dialog(self, width=350)
+
+ def draw(self, context):
+ layout = self.layout
+ layout.prop(self, "item_label")
+
+ def execute(self, context):
+ import time
+
+ wm = context.window_manager
+ scene = context.scene
+ scene_name = scene.name
+ cur_prompt = getattr(scene, 'comfyui_prompt', '')
+ cur_neg = getattr(scene, 'comfyui_negative_prompt', '')
+ label = self.item_label.strip() or scene_name
+
+ # Determine queue_jobs directory
+ prefs = context.preferences.addons.get(__package__)
+ output_dir = ''
+ if prefs:
+ output_dir = bpy.path.abspath(prefs.preferences.output_dir or '')
+ if not output_dir or not os.path.isdir(output_dir):
+ self.report({'ERROR'}, "Set an Output Directory in StableGen preferences first.")
+ return {'CANCELLED'}
+
+ jobs_dir = os.path.join(output_dir, "queue_jobs")
+ os.makedirs(jobs_dir, exist_ok=True)
+
+ # Build filename from the user-provided label
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
+ safe_label = label.replace(" ", "_").replace("/", "_").replace("\\", "_")
+ # Truncate to keep filenames reasonable
+ safe_label = safe_label[:60]
+ copy_name = f"{safe_label}_{timestamp}.blend"
+ copy_path = os.path.join(jobs_dir, copy_name)
+
+ # Save a copy — current file stays active & untouched
+ try:
+ bpy.ops.wm.save_as_mainfile(filepath=copy_path, copy=True)
+ except Exception as e:
+ self.report({'ERROR'}, f"Failed to save queue snapshot: {e}")
+ return {'CANCELLED'}
+
+ new_item = wm.sg_scene_queue.add()
+ new_item.label = label
+ new_item.scene_name = scene_name
+ new_item.blend_file = copy_path
+ new_item.prompt = cur_prompt
+ new_item.negative_prompt = cur_neg
+ new_item.status = 'pending'
+ wm.sg_scene_queue_index = len(wm.sg_scene_queue) - 1
+ _persist_queue()
+
+ self.report({'INFO'}, f"Queued '{label}' ({copy_name})")
+ return {'FINISHED'}
+
+
+class SceneQueueRemove(bpy.types.Operator):
+ """Remove the selected scene from the queue"""
+ bl_idname = "stablegen.queue_remove"
+ bl_label = "Remove from Queue"
+
+ @classmethod
+ def poll(cls, context):
+ wm = context.window_manager
+ return not _queue_processing and len(wm.sg_scene_queue) > 0
+
+ def invoke(self, context, event):
+ wm = context.window_manager
+ idx = wm.sg_scene_queue_index
+ if 0 <= idx < len(wm.sg_scene_queue):
+ item = wm.sg_scene_queue[idx]
+ display = item.label or item.scene_name
+ # Show a confirmation popup
+ return context.window_manager.invoke_confirm(self, event,
+ message=f"Remove '{display}' from queue?",
+ confirm_text="Remove")
+ return {'CANCELLED'}
+
+ def execute(self, context):
+ wm = context.window_manager
+ idx = wm.sg_scene_queue_index
+ if 0 <= idx < len(wm.sg_scene_queue):
+ item = wm.sg_scene_queue[idx]
+ display = item.label or item.scene_name
+ # Delete the snapshot .blend if the item hasn't been processed
+ if item.status != 'done' and item.blend_file:
+ try:
+ blend_path = item.blend_file
+ if os.path.isfile(blend_path):
+ os.remove(blend_path)
+ print(f"[Queue] Deleted snapshot: {blend_path}")
+ except Exception as e:
+ print(f"[Queue] Could not delete snapshot: {e}")
+ wm.sg_scene_queue.remove(idx)
+ wm.sg_scene_queue_index = min(idx, len(wm.sg_scene_queue) - 1)
+ _persist_queue()
+ self.report({'INFO'}, f"Removed '{display}' from queue.")
+ return {'FINISHED'}
+
+
+class SceneQueueClear(bpy.types.Operator):
+ """Clear the entire queue"""
+ bl_idname = "stablegen.queue_clear"
+ bl_label = "Clear Queue"
+
+ @classmethod
+ def poll(cls, context):
+ wm = context.window_manager
+ return not _queue_processing and len(wm.sg_scene_queue) > 0
+
+ def invoke(self, context, event):
+ wm = context.window_manager
+ count = len(wm.sg_scene_queue)
+ return context.window_manager.invoke_confirm(self, event,
+ message=f"Clear all {count} item(s) from queue?",
+ confirm_text="Clear All")
+
+ def execute(self, context):
+ wm = context.window_manager
+ # Delete snapshot .blends for unprocessed items
+ for item in wm.sg_scene_queue:
+ if item.status != 'done' and item.blend_file:
+ try:
+ if os.path.isfile(item.blend_file):
+ os.remove(item.blend_file)
+ print(f"[Queue] Deleted snapshot: {item.blend_file}")
+ except Exception as e:
+ print(f"[Queue] Could not delete snapshot: {e}")
+ wm.sg_scene_queue.clear()
+ wm.sg_scene_queue_index = 0
+ _persist_queue()
+ self.report({'INFO'}, "Queue cleared.")
+ return {'FINISHED'}
+
+
+class SceneQueueMoveUp(bpy.types.Operator):
+ """Move the selected queue item up"""
+ bl_idname = "stablegen.queue_move_up"
+ bl_label = "Move Up"
+
+ @classmethod
+ def poll(cls, context):
+ wm = context.window_manager
+ return not _queue_processing and wm.sg_scene_queue_index > 0
+
+ def execute(self, context):
+ wm = context.window_manager
+ idx = wm.sg_scene_queue_index
+ wm.sg_scene_queue.move(idx, idx - 1)
+ wm.sg_scene_queue_index -= 1
+ return {'FINISHED'}
+
+
+class SceneQueueMoveDown(bpy.types.Operator):
+ """Move the selected queue item down"""
+ bl_idname = "stablegen.queue_move_down"
+ bl_label = "Move Down"
+
+ @classmethod
+ def poll(cls, context):
+ wm = context.window_manager
+ return (not _queue_processing
+ and wm.sg_scene_queue_index < len(wm.sg_scene_queue) - 1)
+
+ def execute(self, context):
+ wm = context.window_manager
+ idx = wm.sg_scene_queue_index
+ wm.sg_scene_queue.move(idx, idx + 1)
+ wm.sg_scene_queue_index += 1
+ return {'FINISHED'}
+
+
+class SceneQueueOpenResult(bpy.types.Operator):
+ """Open the processed .blend copy for the selected queue item"""
+ bl_idname = "stablegen.queue_open_result"
+ bl_label = "Open Result"
+ bl_description = "Open the .blend snapshot of the selected processed queue item"
+
+ @classmethod
+ def poll(cls, context):
+ wm = context.window_manager
+ idx = wm.sg_scene_queue_index
+ if idx < 0 or idx >= len(wm.sg_scene_queue):
+ return False
+ item = wm.sg_scene_queue[idx]
+ return item.status == 'done' and item.blend_file and os.path.isfile(item.blend_file)
+
+ def execute(self, context):
+ wm = context.window_manager
+ item = wm.sg_scene_queue[wm.sg_scene_queue_index]
+ filepath = item.blend_file
+ try:
+ bpy.ops.wm.open_mainfile(filepath=filepath)
+ except Exception as e:
+ self.report({'ERROR'}, f"Failed to open result: {e}")
+ return {'CANCELLED'}
+ return {'FINISHED'}
+
+
+class SceneQueueProcess(bpy.types.Operator):
+ """Start or cancel batch processing of the scene queue"""
+ bl_idname = "stablegen.queue_process"
+ bl_label = "Process Queue"
+ bl_description = "Process all queued scenes sequentially"
+
+ @classmethod
+ def poll(cls, context):
+ wm = context.window_manager
+ if _queue_processing:
+ return True # Allow clicking to cancel
+ return len(wm.sg_scene_queue) > 0
+
+ def execute(self, context):
+ global _queue_processing, _queue_timer, _queue_current_idx, _queue_phase
+
+ if _queue_processing:
+ # Cancel
+ _queue_processing = False
+ _queue_phase = 'idle'
+ _persist_queue() # Save stopped state so load_post won't auto-resume
+ print("[Queue] Cancelled by user.")
+ self.report({'WARNING'}, "Queue processing cancelled.")
+ return {'FINISHED'}
+
+ # Reset statuses
+ wm = context.window_manager
+ for item in wm.sg_scene_queue:
+ if item.status != 'done':
+ item.status = 'pending'
+
+ _queue_processing = True
+ _queue_current_idx = 0
+ _queue_phase = 'idle'
+
+ # Find first pending item
+ while _queue_current_idx < len(wm.sg_scene_queue):
+ if wm.sg_scene_queue[_queue_current_idx].status == 'pending':
+ break
+ _queue_current_idx += 1
+
+ if _queue_current_idx >= len(wm.sg_scene_queue):
+ _queue_processing = False
+ self.report({'INFO'}, "No pending items in queue.")
+ return {'FINISHED'}
+
+ # Start the timer-based queue driver
+ _queue_timer = bpy.app.timers.register(_queue_tick, first_interval=0.5)
+ self.report({'INFO'}, f"Queue processing started ({len(wm.sg_scene_queue)} items).")
+ return {'FINISHED'}
+
+
+def _queue_tick():
+ """Timer callback that drives queue advancement.
+
+ Returns:
+ float: Seconds until next tick, or None to stop.
+ """
+ import time as _time
+ global _queue_processing, _queue_current_idx, _queue_phase, _queue_timer
+ global _queue_settle_deadline, _queue_force_reload, _queue_texturing_seen
+
+ if not _queue_processing:
+ _queue_phase = 'idle'
+ _queue_timer = None
+ _tag_redraw()
+ return None # Stop timer
+
+ wm = bpy.context.window_manager
+ queue = wm.sg_scene_queue
+
+ if _queue_current_idx >= len(queue):
+ # All done
+ _queue_processing = False
+ _queue_phase = 'idle'
+ _queue_timer = None
+ print("[Queue] All items processed.")
+ _tag_redraw()
+ return None
+
+ item = queue[_queue_current_idx]
+
+ # ── Phase: IDLE → switch to the next scene and start ──
+ if _queue_phase == 'idle':
+ # Verify the item belongs to the currently-open .blend
+ current_blend = bpy.data.filepath or "<unsaved>"
+ need_open = (item.blend_file and item.blend_file != current_blend)
+
+ # On retry, always re-open the .blend to restore clean state
+ is_retry_reload = False
+ if _queue_force_reload and item.blend_file:
+ need_open = True
+ is_retry_reload = True
+ _queue_force_reload = False
+
+ if need_open:
+ # Need to open a different .blend file
+ target = item.blend_file
+ if not os.path.isfile(target):
+ print(f"[Queue] Blend file not found: {target} — skipping.")
+ item.status = 'error'
+ _queue_current_idx += 1
+ _persist_queue()
+ _tag_redraw()
+ return 0.5
+
+ # Save current file first so nothing is lost — BUT skip save
+ # on retry reloads; we want to discard dirty state and revert
+ # to the original clean copy.
+ if bpy.data.filepath and not is_retry_reload:
+ try:
+ bpy.ops.wm.save_mainfile()
+ except Exception as e:
+ print(f"[Queue] Warning: could not save current file: {e}")
+
+ # Persist state so the load_post handler can resume after
+ # the new file is opened.
+ _persist_queue()
+ print(f"[Queue] Opening '{os.path.basename(target)}' for item "
+ f"'{item.scene_name}'...")
+
+ # Open the target file. After this call the current WM
+ # data (and our timer) are gone — the load_post handler
+ # will restore the queue and call _resume_queue().
+ try:
+ bpy.ops.wm.open_mainfile(filepath=target)
+ except Exception as e:
+ print(f"[Queue] Failed to open '{target}': {e}")
+ # Can't recover gracefully — stop processing
+ _queue_processing = False
+ _queue_phase = 'idle'
+ _queue_timer = None
+ _persist_queue()
+ _tag_redraw()
+ return None # Stop timer — load_post will restart it
+
+ scene_ref = bpy.data.scenes.get(item.scene_name)
+ if not scene_ref:
+ print(f"[Queue] Scene '{item.scene_name}' not found — skipping.")
+ item.status = 'error'
+ _queue_current_idx += 1
+ _tag_redraw()
+ return 0.5 # Try next immediately
+
+ # Switch to the target scene
+ bpy.context.window.scene = scene_ref
+ item.status = 'processing'
+ _queue_phase = 'switching'
+ print(f"[Queue] Switched to scene '{item.scene_name}'")
+ _tag_redraw()
+ return 1.0 # Give Blender a moment to digest
+
+ # ── Phase: SWITCHING → invoke the generation operator ──
+ if _queue_phase == 'switching':
+ scene_ref = bpy.context.scene
+ arch_mode = getattr(scene_ref, 'architecture_mode', 'sdxl')
+
+ # Clear the error flag before invoking
+ scene_ref.sg_last_gen_error = False
+
+ # Disable interactive elements for unattended batch
+ if arch_mode == 'trellis2':
+ scene_ref.trellis2_preview_gallery_enabled = False
+
+ try:
+ if arch_mode == 'trellis2':
+ bpy.ops.object.trellis2_generate('INVOKE_DEFAULT')
+ print(f"[Queue] Invoked trellis2_generate for '{item.scene_name}'")
+ else:
+ # Standard texturing — select all cameras first
+ bpy.ops.object.select_all(action='DESELECT')
+ for obj in scene_ref.objects:
+ if obj.type == 'CAMERA':
+ obj.select_set(True)
+ bpy.ops.object.test_stable('INVOKE_DEFAULT')
+ print(f"[Queue] Invoked test_stable for '{item.scene_name}'")
+ _queue_phase = 'running'
+ except Exception as e:
+ print(f"[Queue] Failed to invoke operator for '{item.scene_name}': {e}")
+ _queue_handle_failure(item, str(e))
+ _tag_redraw()
+ return 1.5
+
+ # ── Phase: RUNNING → poll for completion ──
+ if _queue_phase == 'running':
+ from .generator import Trellis2Generate, ComfyUIGenerate
+ scene_ref = bpy.context.scene
+ arch_mode = getattr(scene_ref, 'architecture_mode', 'sdxl')
+
+ if arch_mode == 'trellis2':
+ trellis_running = Trellis2Generate._is_running
+ gen_err = getattr(scene_ref, 'sg_last_gen_error', False)
+ tex_mode = getattr(scene_ref, 'trellis2_texture_mode', 'native')
+ pipe_active = getattr(scene_ref, 'trellis2_pipeline_active', False)
+ gen_status = getattr(scene_ref, 'generation_status', 'idle')
+ # TRELLIS.2: wait for the operator to finish
+ if trellis_running:
+ return 1.0 # Still running
+
+ # Check if Trellis2 itself failed
+ if gen_err:
+ print(f"[Queue] TRELLIS.2 generation failed for '{item.scene_name}'")
+ _queue_handle_failure(item, "TRELLIS.2 generation failed")
+ return 0.5
+
+ # Trellis2Generate finished — enter settling phase to wait for
+ # _schedule_texture_generation / _deferred_generate to fire.
+ if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'):
+ _queue_phase = 'settling'
+ _queue_settle_deadline = _time.monotonic() + 15.0 # generous: server may need VRAM flush
+ _queue_texturing_seen = False
+ print(f"[Queue] TRELLIS.2 mesh done, entering settling (tex_mode='{tex_mode}'), "
+ f"waiting for texturing to start (up to 15 s)...")
+ else:
+ # Native texture mode — mesh only, done
+ print(f"[Queue] tex_mode='{tex_mode}' — no diffusion texturing, finishing item")
+ _queue_finish_item(item)
+ return 1.0
+ else:
+ # Standard texturing
+ gen_status = getattr(scene_ref, 'generation_status', 'idle')
+ if gen_status in ('idle', 'waiting'):
+ if getattr(scene_ref, 'sg_last_gen_error', False):
+ _queue_handle_failure(item, "Generation failed")
+ return 0.5
+ _queue_finish_item(item)
+ return 0.5
+ return 1.0 # Still running
+
+ # ── Phase: SETTLING → wait for TRELLIS.2 chained texturing to start ──
+ if _queue_phase == 'settling':
+ scene_ref = bpy.context.scene
+ pipeline_active = getattr(scene_ref, 'trellis2_pipeline_active', False)
+ gen_status = getattr(scene_ref, 'generation_status', 'idle')
+ if pipeline_active or gen_status == 'running':
+ _queue_texturing_seen = True
+
+ if _queue_texturing_seen:
+ if gen_status == 'running' or pipeline_active:
+ # Texturing is actively running — transition
+ _queue_phase = 'waiting_texturing'
+ print(f"[Queue] Texturing confirmed running, waiting for completion...")
+ return 1.0
+ else:
+ # Texturing already completed (fast finish during settling)
+ if getattr(scene_ref, 'sg_last_gen_error', False):
+ _queue_handle_failure(item, "Texturing failed")
+ else:
+ _queue_finish_item(item)
+ return 0.5
+
+ # Texturing hasn't appeared yet — wait until deadline
+ if _time.monotonic() >= _queue_settle_deadline:
+ print(f"[Queue] Texturing never started for '{item.scene_name}' (timeout)")
+ _queue_handle_failure(item, "Diffusion texturing failed to start")
+ return 0.5
+
+ return 1.0 # Still settling
+
+ # ── Phase: WAITING_TEXTURING → poll chained ComfyUIGenerate ──
+ if _queue_phase == 'waiting_texturing':
+ scene_ref = bpy.context.scene
+ gen_status = getattr(scene_ref, 'generation_status', 'idle')
+ pipeline_active = getattr(scene_ref, 'trellis2_pipeline_active', False)
+ gen_err = getattr(scene_ref, 'sg_last_gen_error', False)
+
+ if gen_status in ('idle', 'waiting') and not pipeline_active:
+ if getattr(scene_ref, 'sg_last_gen_error', False):
+ _queue_handle_failure(item, "Texturing failed")
+ return 0.5
+ _queue_finish_item(item)
+ return 0.5
+ return 1.0 # Still running
+
+ # ── Phase: EXPORTING_GIF → poll ExportOrbitGIF completion ──
+ if _queue_phase == 'exporting_gif':
+ from .render_tools import ExportOrbitGIF
+ if ExportOrbitGIF._rendering:
+ return 1.0 # Still rendering frames
+ # GIF export finished — save and advance
+ print("[Queue] GIF export completed")
+ _queue_save_and_advance(item)
+ return 0.5
+
+ return 1.0
+
+
+def _queue_handle_failure(item, reason):
+ """Handle a failed queue item — retry if under the limit, else mark as error."""
+ global _queue_current_idx, _queue_phase, _queue_processing, _queue_timer
+ global _queue_force_reload
+
+ item.retries += 1
+ if item.retries < _QUEUE_MAX_RETRIES:
+ item.status = 'pending'
+ _queue_phase = 'idle' # Will re-attempt on next tick
+ _queue_force_reload = True # Force re-open to restore clean .blend state
+ print(f"[Queue] Retrying '{item.label or item.scene_name}' "
+ f"(attempt {item.retries + 1}/{_QUEUE_MAX_RETRIES}): {reason}")
+ else:
+ item.status = 'error'
+ print(f"[Queue] '{item.label or item.scene_name}' failed after "
+ f"{_QUEUE_MAX_RETRIES} attempts: {reason}")
+ _queue_current_idx += 1
+ # Find next pending
+ wm = bpy.context.window_manager
+ while _queue_current_idx < len(wm.sg_scene_queue):
+ if wm.sg_scene_queue[_queue_current_idx].status == 'pending':
+ break
+ _queue_current_idx += 1
+ if _queue_current_idx >= len(wm.sg_scene_queue):
+ _queue_processing = False
+ _queue_phase = 'idle'
+ _queue_timer = None
+ print("[Queue] All queue items processed.")
+ else:
+ _queue_phase = 'idle'
+ _persist_queue()
+ _tag_redraw()
+
+
+def _queue_finish_item(item):
+ """Mark the current queue item as done and advance to the next.
+
+ If GIF export is enabled, starts the orbit GIF export first and
+ defers the save+advance to the ``exporting_gif`` phase handler.
+ """
+ global _queue_current_idx, _queue_phase, _queue_processing, _queue_timer
+
+ item.status = 'done'
+ print(f"[Queue] Finished '{item.scene_name}'")
+
+ # ── Optional GIF export before saving ──
+ wm = bpy.context.window_manager
+ if getattr(wm, 'sg_queue_gif_export', False):
+ if _queue_start_gif_export():
+ _queue_phase = 'exporting_gif'
+ print("[Queue] GIF export started — deferring save until export finishes")
+ _tag_redraw()
+ return # save + advance will happen in the 'exporting_gif' handler
+
+ # No GIF (or export failed to start) — save and advance immediately
+ _queue_save_and_advance(item)
+
+
+def _queue_start_gif_export():
+ """Try to invoke ExportOrbitGIF with current WM settings.
+
+ Returns True if the operator was successfully started.
+ """
+ from .render_tools import ExportOrbitGIF
+
+ scene = bpy.context.scene
+
+ # ── Always use the first camera (Camera_0 or lowest-numbered) ──
+ cameras = sorted(
+ [o for o in scene.objects if o.type == 'CAMERA'],
+ key=lambda c: c.name,
+ )
+ if not cameras:
+ print("[Queue] No cameras in scene — skipping GIF export")
+ return False
+ scene.camera = cameras[0]
+ print(f"[Queue] GIF export: using camera '{cameras[0].name}'")
+
+ # ── Ensure an active mesh/empty exists (poll requirement) ──
+ vl = bpy.context.view_layer
+ active = vl.objects.active
+ if not active or active.type not in {'MESH', 'EMPTY'}:
+ for obj in scene.objects:
+ if obj.type == 'MESH':
+ vl.objects.active = obj
+ obj.select_set(True)
+ print(f"[Queue] GIF export: activated mesh '{obj.name}'")
+ break
+ else:
+ print("[Queue] No mesh in scene — skipping GIF export")
+ return False
+
+ wm = bpy.context.window_manager
+
+ # ── Explicitly apply HDRI from the queue's file path (if set) ──
+ hdri_path = getattr(wm, 'sg_queue_gif_hdri_path', '')
+ hdri_strength = getattr(wm, 'sg_queue_gif_hdri_strength', 1.0)
+ use_hdri = getattr(wm, 'sg_queue_gif_use_hdri', False)
+
+ if use_hdri and hdri_path:
+ import os as _os
+ resolved = bpy.path.abspath(hdri_path)
+ if _os.path.isfile(resolved):
+ try:
+ bpy.ops.object.add_hdri(hdri_path=resolved,
+ strength=hdri_strength)
+ print(f"[Queue] Applied HDRI: {resolved} "
+ f"(strength={hdri_strength:.2f})")
+ except Exception as e:
+ print(f"[Queue] AddHDRI failed: {e} — continuing anyway")
+ else:
+ print(f"[Queue] HDRI file not found: {resolved} — skipping HDRI")
+
+ kwargs = {
+ 'duration': getattr(wm, 'sg_queue_gif_duration', 5.0),
+ 'frame_rate': getattr(wm, 'sg_queue_gif_fps', 24),
+ 'resolution_percentage': getattr(wm, 'sg_queue_gif_resolution', 50),
+ 'samples': getattr(wm, 'sg_queue_gif_samples', 32),
+ 'engine': getattr(wm, 'sg_queue_gif_engine', 'CYCLES'),
+ 'interpolation': getattr(wm, 'sg_queue_gif_interpolation', 'LINEAR'),
+ 'use_hdri': use_hdri,
+ 'hdri_rotation': getattr(wm, 'sg_queue_gif_hdri_rotation', 0.0),
+ 'env_mode': getattr(wm, 'sg_queue_gif_env_mode', 'FIXED'),
+ 'use_shadow_plane': getattr(wm, 'sg_queue_gif_shadow_plane', False),
+ 'use_denoiser': getattr(wm, 'sg_queue_gif_denoiser', True),
+ }
+
+ # Build a temp_override so the modal operator has a proper window
+ window = bpy.context.window
+ if not window:
+ for w in wm.windows:
+ window = w
+ break
+ if not window:
+ print("[Queue] No window available — skipping GIF export")
+ return False
+
+ try:
+ with bpy.context.temp_override(window=window):
+ result = bpy.ops.object.export_orbit_gif('EXEC_DEFAULT', **kwargs)
+ if 'RUNNING_MODAL' in result:
+ print(f"[Queue] GIF export started successfully")
+ return True
+ print(f"[Queue] GIF export returned {result} — skipping")
+ return False
+ except Exception as e:
+ print(f"[Queue] GIF export failed to start: {e}")
+ import traceback; traceback.print_exc()
+ return False
+
+
+def _queue_save_and_advance(item):
+ """Save the current .blend and advance to the next queue item."""
+ global _queue_current_idx, _queue_phase, _queue_processing, _queue_timer
+
+ # Save the result in-place on the queue copy .blend
+ if bpy.data.filepath:
+ try:
+ bpy.ops.wm.save_mainfile()
+ print(f"[Queue] Saved result: {bpy.data.filepath}")
+ except Exception as e:
+ print(f"[Queue] Save warning: {e}")
+
+ # Advance to next pending item
+ _queue_current_idx += 1
+ wm = bpy.context.window_manager
+ while _queue_current_idx < len(wm.sg_scene_queue):
+ if wm.sg_scene_queue[_queue_current_idx].status == 'pending':
+ break
+ _queue_current_idx += 1
+
+ if _queue_current_idx >= len(wm.sg_scene_queue):
+ _queue_processing = False
+ _queue_phase = 'idle'
+ _queue_timer = None
+ print("[Queue] All queue items processed.")
+ else:
+ _queue_phase = 'idle' # Will switch to next scene on next tick
+
+ _persist_queue()
+ _tag_redraw()
+
+
+def _tag_redraw():
+ """Redraw all 3D viewports so the queue UI updates."""
+ try:
+ for window in bpy.context.window_manager.windows:
+ for area in window.screen.areas:
+ area.tag_redraw()
+ except Exception:
+ pass
diff --git a/stablegen/utils.py b/stablegen/utils.py
index 4dfa06e..f558708 100644
--- a/stablegen/utils.py
+++ b/stablegen/utils.py
@@ -354,7 +354,7 @@ def get_file_path(context, file_type, subtype=None, filename=None, camera_id=Non
if subtype == "render":
filename = f"ctx_render{camera_id}{frame_suffix}" if not filename else filename
elif subtype == "visibility":
- filename = f"render{camera_id}_visibility{frame_suffix}" if not filename else filename
+ filename = f"ctx_render{camera_id}_visibility{frame_suffix}" if not filename else filename
return os.path.join(base_dir, f"{filename}.png")
elif file_type == "uv_inpaint" and subtype:
diff --git a/stablegen/workflows.py b/stablegen/workflows.py
index 0d2a986..b716290 100644
--- a/stablegen/workflows.py
+++ b/stablegen/workflows.py
@@ -18,6 +18,30 @@ from io import BytesIO
import numpy as np
from PIL import Image
+
+def _texturing_prompt(scene):
+ """Return the texturing portion of the prompt (after ``||`` if present).
+
+ Users can write ``generation prompt || texturing prompt`` to give a
+ different prompt to the per-camera texturing step. When the separator
+ is absent the full prompt is returned unchanged.
+ """
+ raw = scene.comfyui_prompt
+ if '||' in raw:
+ return raw.split('||', 1)[1].strip()
+ return raw
+
+
+def _generation_prompt(scene):
+ """Return the generation portion of the prompt (before ``||`` if present).
+
+ See :func:`_texturing_prompt` for the separator convention.
+ """
+ raw = scene.comfyui_prompt
+ if '||' in raw:
+ return raw.split('||', 1)[0].strip()
+ return raw
+
class WorkflowManager:
def __init__(self, operator):
"""
@@ -468,7 +492,7 @@ class WorkflowManager:
prompt[NODES['style_map_loader']]['inputs']['image'] = style_image_info['name']
# Fallback to TRELLIS.2 input image as style
- if not style_image_info and getattr(context.scene, 'qwen_use_trellis2_style', False):
+ if not style_image_info and getattr(context.scene, 'architecture_mode', '') == 'trellis2' and getattr(context.scene, 'qwen_use_trellis2_style', False):
t2_path = getattr(context.scene, 'trellis2_last_input_image', '')
if t2_path and os.path.exists(bpy.path.abspath(t2_path)):
style_image_info = self.operator._get_uploaded_image_info(context, "custom", filename=bpy.path.abspath(t2_path))
@@ -496,7 +520,7 @@ class WorkflowManager:
del prompt[NODES['neg_prompt']]['inputs']['image3']
# --- Prompt ---
- user_prompt = context.scene.comfyui_prompt
+ user_prompt = _texturing_prompt(context.scene)
final_prompt = f"Modify image1 to {user_prompt}"
if depth_info:
final_prompt += ". Use image3 as depth map reference."
@@ -576,7 +600,7 @@ class WorkflowManager:
prompt[NODES['guidance_map_loader']]['inputs']['image'] = guidance_map_info['name']
# --- Configure Style Image (Image 2) and Prompts ---
- user_prompt = context.scene.comfyui_prompt
+ user_prompt = _texturing_prompt(context.scene)
style_image_info = None
context_render_info = None
context_mode = context.scene.qwen_context_render_mode
@@ -645,13 +669,13 @@ class WorkflowManager:
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
else: # Additional mode
if context.scene.qwen_use_custom_prompts:
- pos_prompt_text = ()
+ pos_prompt_text = (context.scene.qwen_custom_prompt_seq_additional if not is_initial_image else context.scene.qwen_custom_prompt_initial).format(main_prompt=user_prompt)
else:
pos_prompt_text = self._get_qwen_default_prompts(context, is_initial_image).format(main_prompt=user_prompt)
prompt[NODES['pos_prompt']]['inputs']['prompt'] = pos_prompt_text
# Case 1b: TRELLIS.2 input image as style (when no external style configured)
- elif getattr(context.scene, 'qwen_use_trellis2_style', False):
+ elif getattr(context.scene, 'architecture_mode', '') == 'trellis2' and getattr(context.scene, 'qwen_use_trellis2_style', False):
use_t2_this_frame = True
if not is_initial_image and getattr(context.scene, 'qwen_trellis2_style_initial_only', False):
# Initial-only mode: fall back to sequential style for subsequent frames
@@ -699,10 +723,19 @@ class WorkflowManager:
# Case 3: First image of a sequence, or separate generation, or no style source in sequential
if style_image_info is None:
- # No style image is provided. For the first image, we remove image2 entirely.
+ # No style image is provided — remove the style loader node and
+ # its reference from the prompt encoders.
del prompt[NODES['style_map_loader']]
- del prompt[NODES['pos_prompt']]['inputs']['image2']
- del prompt[NODES['neg_prompt']]['inputs']['image2']
+ if context_mode == 'ADDITIONAL' and not is_initial_image:
+ # In ADDITIONAL mode the context/style loader IDs were swapped
+ # above, so the style loader now sits on the node that image3
+ # originally pointed to. Remove image3 (dangling after the
+ # delete) but keep image2 (the context render).
+ for nid in (NODES['pos_prompt'], NODES['neg_prompt']):
+ prompt[nid]['inputs'].pop('image3', None)
+ else:
+ del prompt[NODES['pos_prompt']]['inputs']['image2']
+ del prompt[NODES['neg_prompt']]['inputs']['image2']
if context.scene.qwen_use_custom_prompts:
pos_prompt_text = (context.scene.qwen_custom_prompt_initial if is_initial_image else context.scene.qwen_custom_prompt_seq_none).format(main_prompt=user_prompt)
else:
@@ -859,7 +892,7 @@ class WorkflowManager:
prompt[NODES['clip_loader']]['inputs']['clip_name'] = "qwen_3_8b_fp8mixed.safetensors"
# --- Base user prompt + camera injection ---
- user_prompt = context.scene.comfyui_prompt
+ user_prompt = _texturing_prompt(context.scene)
camera_suffix = ""
if (context.scene.use_camera_prompts
and self.operator._cameras
@@ -937,7 +970,7 @@ class WorkflowManager:
prompt[NODES['pos_prompt']]['inputs']['text'] = pos_prompt_text
# Case 1b: TRELLIS.2 input image as style
- if not style_image_info and getattr(context.scene, 'qwen_use_trellis2_style', False):
+ if not style_image_info and getattr(context.scene, 'architecture_mode', '') == 'trellis2' and getattr(context.scene, 'qwen_use_trellis2_style', False):
use_t2 = True
if not is_initial_image and getattr(context.scene, 'qwen_trellis2_style_initial_only', False):
use_t2 = False
@@ -1111,6 +1144,36 @@ class WorkflowManager:
except Exception:
return None, None
+ @staticmethod
+ def _cleanup_trellis2_temp_files():
+ """Remove TRELLIS2 IPC temp directories and voxelgrid cache files.
+
+ The ComfyUI-TRELLIS2 custom node saves intermediate tensors and
+ voxelgrid data to disk but never deletes them, gradually filling
+ the system temp directory. This method cleans up both locations.
+ """
+ import tempfile
+ import glob
+ import shutil
+
+ tmp_root = tempfile.gettempdir()
+
+ # IPC tensor directories: <tempdir>/trellis2_*/
+ for d in glob.glob(os.path.join(tmp_root, 'trellis2_*')):
+ if os.path.isdir(d):
+ try:
+ shutil.rmtree(d)
+ except OSError:
+ pass # Still locked by worker — ignore
+
+ # Voxelgrid cache (Windows: C:\tmp\trellis2_cache)
+ for cache_dir in ('/tmp/trellis2_cache', r'C:\tmp\trellis2_cache'):
+ if os.path.isdir(cache_dir):
+ try:
+ shutil.rmtree(cache_dir)
+ except OSError:
+ pass
+
def _flush_comfyui_vram(self, server_address, retries=3, label="Post-generation"):
"""Unload all models and free VRAM on the ComfyUI server.
@@ -1233,13 +1296,15 @@ class WorkflowManager:
# Double-check here in case the property wasn't synced yet.
if getattr(scene, 'architecture_mode', '') == 'trellis2':
tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
- if tex_mode not in ('sdxl', 'flux1', 'qwen_image_edit'):
+ if tex_mode not in ('sdxl', 'flux1', 'qwen_image_edit', 'flux2_klein'):
architecture = getattr(scene, 'trellis2_initial_image_arch', 'sdxl')
if architecture == 'qwen_image_edit':
prompt, save_node = self._build_qwen_txt2img(context)
elif architecture == 'flux1':
prompt, save_node = self._build_flux_txt2img(context)
+ elif architecture == 'flux2_klein':
+ prompt, save_node = self._build_klein_txt2img(context)
else:
prompt, save_node = self._build_sdxl_txt2img(context)
@@ -1293,7 +1358,7 @@ class WorkflowManager:
},
"2": {
"class_type": "CLIPTextEncode",
- "inputs": {"text": scene.comfyui_prompt, "clip": ["1", 1]}
+ "inputs": {"text": _generation_prompt(scene), "clip": ["1", 1]}
},
"3": {
"class_type": "CLIPTextEncode",
@@ -1666,6 +1731,88 @@ class WorkflowManager:
# StableDelight returns a single image
return delight_images[0] if delight_images else {"error": "StableDelight returned empty"}
+ def _build_klein_txt2img(self, context):
+ """Return (prompt_dict, save_node_id) for a minimal FLUX.2 Klein txt2img.
+
+ Uses the same node types as the full Klein multi-reference workflow
+ (UNETLoader, CLIPLoader with type flux2, VAELoader, Flux2Scheduler,
+ CFGGuider, SamplerCustomAdvanced) but without any reference images.
+ """
+ scene = context.scene
+ unet_name = scene.model_name
+
+ # Detect 9B vs 4B CLIP from model name
+ model_lower = unet_name.lower()
+ clip_name = "qwen_3_8b_fp8mixed.safetensors" if '9b' in model_lower else "qwen_3_4b.safetensors"
+
+ prompt = {
+ "1": {
+ "class_type": "UNETLoader",
+ "inputs": {"unet_name": unet_name, "weight_dtype": "default"}
+ },
+ "2": {
+ "class_type": "CLIPLoader",
+ "inputs": {"clip_name": clip_name, "type": "flux2"}
+ },
+ "3": {
+ "class_type": "VAELoader",
+ "inputs": {"vae_name": "flux2-vae.safetensors"}
+ },
+ "4": {
+ "class_type": "CLIPTextEncode",
+ "inputs": {"text": _generation_prompt(scene), "clip": ["2", 0]}
+ },
+ "5": {
+ "class_type": "CLIPTextEncode",
+ "inputs": {"text": "", "clip": ["2", 0]}
+ },
+ "6": {
+ "class_type": "EmptyFlux2LatentImage",
+ "inputs": {"width": 1024, "height": 1024, "batch_size": 1}
+ },
+ "7": {
+ "class_type": "Flux2Scheduler",
+ "inputs": {"steps": scene.steps, "width": 1024, "height": 1024}
+ },
+ "8": {
+ "class_type": "KSamplerSelect",
+ "inputs": {"sampler_name": scene.sampler}
+ },
+ "9": {
+ "class_type": "RandomNoise",
+ "inputs": {"noise_seed": scene.seed if scene.seed != 0 else random.randint(0, 2**31)}
+ },
+ "10": {
+ "class_type": "CFGGuider",
+ "inputs": {
+ "model": ["1", 0],
+ "positive": ["4", 0],
+ "negative": ["5", 0],
+ "cfg": scene.cfg
+ }
+ },
+ "11": {
+ "class_type": "SamplerCustomAdvanced",
+ "inputs": {
+ "noise": ["9", 0],
+ "guider": ["10", 0],
+ "sampler": ["8", 0],
+ "sigmas": ["7", 0],
+ "latent_image": ["6", 0]
+ }
+ },
+ "12": {
+ "class_type": "VAEDecode",
+ "inputs": {"samples": ["11", 0], "vae": ["3", 0]}
+ },
+ "13": {
+ "class_type": "SaveImageWebsocket",
+ "inputs": {"images": ["12", 0]}
+ }
+ }
+
+ return prompt, "13"
+
def _build_flux_txt2img(self, context):
"""Return (prompt_dict, save_node_id) for a minimal Flux txt2img with LoRA support."""
scene = context.scene
@@ -1693,7 +1840,7 @@ class WorkflowManager:
},
"6": {
"class_type": "CLIPTextEncode",
- "inputs": {"text": scene.comfyui_prompt, "clip": ["11", 0]}
+ "inputs": {"text": _generation_prompt(scene), "clip": ["11", 0]}
},
"26": {
"class_type": "FluxGuidance",
@@ -1796,7 +1943,7 @@ class WorkflowManager:
"12": {
"class_type": "TextEncodeQwenImageEditPlus",
"inputs": {
- "prompt": scene.comfyui_prompt,
+ "prompt": _generation_prompt(scene),
"clip": ["3", 0]
}
},
@@ -2286,6 +2433,7 @@ class WorkflowManager:
# Restore the original seed so the UI isn't silently changed
context.scene.trellis2_seed = original_seed
self._flush_comfyui_vram(server_address, label="Post-generation")
+ self._cleanup_trellis2_temp_files()
def _generate_trellis2_inner(self, context, input_image_path, server_address, client_id):
"""Inner implementation of generate_trellis2, called within a try/finally VRAM flush."""
@@ -2831,7 +2979,7 @@ class WorkflowManager:
'ipadapter_image': "237",
}
- base_prompt_text = context.scene.comfyui_prompt
+ base_prompt_text = _texturing_prompt(context.scene)
# Camera Prompt Injection
if context.scene.use_camera_prompts and context.scene.generation_method in ['separate', 'sequential', 'refine', 'local_edit'] and self.operator._cameras and self.operator._current_image < len(self.operator._cameras):
current_camera_name = self.operator._cameras[self.operator._current_image].name
@@ -3275,6 +3423,16 @@ class WorkflowManager:
if hasattr(self.operator, '_update_overall'):
self.operator._update_overall()
print(f"Progress: {progress:.1f}%")
+
+ elif message['type'] == 'execution_error':
+ error_data = message.get('data', {})
+ error_msg = error_data.get('exception_message', 'Unknown error')
+ node_id = error_data.get('node_id', '?')
+ self.operator._error = (
+ f"ComfyUI execution error (node {node_id}): {error_msg}"
+ )
+ print(f"[StableGen] {self.operator._error}")
+ break
else:
# Binary data (image)
if current_node == NODES['save_image']: # SaveImageWebsocket node
@@ -3453,7 +3611,7 @@ class WorkflowManager:
'save_image': "111"
}
- base_prompt_text = context.scene.comfyui_prompt
+ base_prompt_text = _texturing_prompt(context.scene)
# Camera Prompt Injection
if context.scene.use_camera_prompts and context.scene.generation_method in ['separate', 'sequential', 'refine', 'local_edit'] and self.operator._cameras and self.operator._current_image < len(self.operator._cameras):
current_camera_name = self.operator._cameras[self.operator._current_image].name
@@ -3468,7 +3626,7 @@ class WorkflowManager:
if context.scene.generation_method in ['refine', 'local_edit', 'uv_inpaint', 'sequential']:
prompt[NODES['pos_prompt']]["inputs"]["text"] = base_prompt_text
else:
- prompt[NODES['pos_prompt']]["inputs"]["text"] = context.scene.refine_prompt if context.scene.refine_prompt != "" else context.scene.comfyui_prompt
+ prompt[NODES['pos_prompt']]["inputs"]["text"] = context.scene.refine_prompt if context.scene.refine_prompt != "" else _texturing_prompt(context.scene)
# Set negative prompt
prompt[NODES['neg_prompt']]["inputs"]["text"] = context.scene.comfyui_negative_prompt
@@ -3586,7 +3744,7 @@ class WorkflowManager:
prompt[NODES['inpaint_conditioning']]["inputs"]["noise_mask"] = context.scene.differential_noise
# Create base UV prompt
- uv_prompt = f"seamless (UV-unwrapped texture) of {context.scene.comfyui_prompt}, consistent material continuity, no visible seams or stretching, PBR material properties"
+ uv_prompt = f"seamless (UV-unwrapped texture) of {_texturing_prompt(context.scene)}, consistent material continuity, no visible seams or stretching, PBR material properties"
uv_prompt_neg = f"seam, stitch, visible edge, texture stretching, repeating pattern, {context.scene.comfyui_negative_prompt}"
prompt[NODES['pos_prompt']]["inputs"]["text"] = uv_prompt
@@ -3597,7 +3755,7 @@ class WorkflowManager:
current_object_name = os.path.basename(render_info['name']).split('.')[0]
# Use the object-specific prompt if available
- object_prompt = self.operator._object_prompts.get(current_object_name, context.scene.comfyui_prompt)
+ object_prompt = self.operator._object_prompts.get(current_object_name, _texturing_prompt(context.scene))
if object_prompt:
uv_prompt = f"(UV-unwrapped texture) of {object_prompt}, consistent material continuity, no visible seams or stretching, PBR material properties"
uv_prompt_neg = f"seam, stitch, visible edge, texture stretching, repeating pattern, {context.scene.comfyui_negative_prompt}"
@@ -3689,7 +3847,7 @@ class WorkflowManager:
'save_image': "32" # SaveImageWebsocket
}
- base_prompt_text = context.scene.comfyui_prompt
+ base_prompt_text = _texturing_prompt(context.scene)
# Camera Prompt Injection
if context.scene.use_camera_prompts and context.scene.generation_method in ['separate', 'sequential', 'refine', 'local_edit'] and self.operator._cameras and self.operator._current_image < len(self.operator._cameras):
current_camera_name = self.operator._cameras[self.operator._current_image].name
@@ -3895,7 +4053,7 @@ class WorkflowManager:
'save_image': "32" # SaveImageWebsocket
}
- base_prompt_text = context.scene.comfyui_prompt
+ base_prompt_text = _texturing_prompt(context.scene)
# Camera Prompt Injection
if context.scene.use_camera_prompts and context.scene.generation_method in ['separate', 'sequential', 'refine', 'local_edit', 'grid'] and self.operator._cameras and self.operator._current_image < len(self.operator._cameras):
current_camera_name = self.operator._cameras[self.operator._current_image].name
@@ -4115,13 +4273,13 @@ class WorkflowManager:
prompt[NODES['inpaint_conditioning']]["inputs"]["noise_mask"] = context.scene.differential_noise
# Create UV-specific prompt
- uv_prompt = f"seamless (UV-unwrapped texture) of {context.scene.comfyui_prompt}, consistent material continuity, no visible seams or stretching"
+ uv_prompt = f"seamless (UV-unwrapped texture) of {_texturing_prompt(context.scene)}, consistent material continuity, no visible seams or stretching"
prompt[NODES['pos_prompt']]["inputs"]["text"] = uv_prompt
# Object-specific prompt if available
if render_info and 'name' in render_info:
current_object_name = os.path.basename(render_info['name']).split('.')[0]
- object_prompt = self.operator._object_prompts.get(current_object_name, context.scene.comfyui_prompt)
+ object_prompt = self.operator._object_prompts.get(current_object_name, _texturing_prompt(context.scene))
if object_prompt:
uv_prompt = f"(UV-unwrapped texture) of {object_prompt}, consistent material continuity, no visible seams or stretching"
prompt[NODES['pos_prompt']]["inputs"]["text"] = uv_prompt