Skip to content

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

add experimental qwen 2.1 turbo, moss image and fibo 2.0 architectures and tags in the panel

sakalond6fb05d5ffa37
diff --git a/stablegen/_generator_utils.py b/stablegen/_generator_utils.py
index f02b251..b66a9da 100644
--- a/stablegen/_generator_utils.py
+++ b/stablegen/_generator_utils.py
@@ -14,7 +14,7 @@ import uuid
import requests
from .timeout_config import get_timeout
-from .generation_status import reporting_upload
+from .core.generation_status import reporting_upload
def redraw_ui(context):
"""Redraws the UI to reflect changes in the operator's progress and status."""
diff --git a/stablegen/architecture_options.py b/stablegen/architecture_options.py
deleted file mode 100644
index d5118d9..0000000
--- a/stablegen/architecture_options.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Preference-gated architecture menus, retaining saved enum identifiers."""
-
-DEPRECATED_ARCHITECTURES = frozenset({'flux1', 'flux2_klein'})
-DEPRECATION_NOTICE = 'Deprecated: no longer receiving further support'
-
-# Explicit numbers match the original static enums, including their ordering.
-# Retain these numbers when filtering so existing .blend files keep their choice.
-MODEL_ARCHITECTURE_ITEMS = (
- ('sdxl', 'SDXL', 'Stable Diffusion XL', 0),
- ('flux1', 'FLUX.1 (Deprecated)', DEPRECATION_NOTICE, 1),
- ('qwen_image_edit', 'Qwen Image Edit', 'Qwen-Image-Edit checkpoints', 2),
- ('qwen_image_21', 'Qwen Image 2.1', 'Qwen-Image 2.1 checkpoints', 3),
- ('flux2_klein', 'FLUX.2 Klein (Deprecated)', DEPRECATION_NOTICE, 4),
-)
-ARCHITECTURE_ITEMS = MODEL_ARCHITECTURE_ITEMS + (
- ('trellis2', 'TRELLIS.2', 'Image to 3D mesh generation with TRELLIS.2', 5),
-)
-TRELLIS_TEXTURE_ITEMS = (
- ('none', 'None', 'Shape only, no texture generation', 0),
- ('native', 'Native (TRELLIS.2)', 'Use TRELLIS.2 built-in texture generation', 1),
-) + tuple((key, label, description, number + 2)
- for key, label, description, number in MODEL_ARCHITECTURE_ITEMS)
-
-
-def deprecated_architectures_enabled(context=None):
- try:
- from .core import get_addon_prefs
- prefs = get_addon_prefs(context)
- return bool(prefs and getattr(prefs, 'enable_deprecated_architectures', False))
- except (AttributeError, ImportError, KeyError, ReferenceError):
- return False
-
-
-_READING_SELECTION = set()
-
-
-def _architecture_items(scene, context, property_name, items):
- if deprecated_architectures_enabled(context) or property_name in _READING_SELECTION:
- return items
- # Read through RNA with the complete menu during the nested callback. This
- # avoids depending on ID-property storage, which changed in Blender 5.1.
- _READING_SELECTION.add(property_name)
- try:
- selected = getattr(scene, property_name, None)
- finally:
- _READING_SELECTION.remove(property_name)
- # A saved deprecated selection stays readable until the user replaces it or
- # opts in. This exception never offers another deprecated architecture.
- return tuple(item for item in items
- if item[0] not in DEPRECATED_ARCHITECTURES or item[0] == selected)
-
-
-def model_architecture_items(scene, context):
- return _architecture_items(scene, context, 'model_architecture', MODEL_ARCHITECTURE_ITEMS)
-
-
-def architecture_items(scene, context):
- return _architecture_items(scene, context, 'architecture_mode', ARCHITECTURE_ITEMS)
-
-
-def trellis_texture_items(scene, context):
- return _architecture_items(scene, context, 'trellis2_texture_mode', TRELLIS_TEXTURE_ITEMS)
-
-
-def trellis_initial_image_items(scene, context):
- return _architecture_items(scene, context, 'trellis2_initial_image_arch', MODEL_ARCHITECTURE_ITEMS)
-
-
-def active_deprecated_architectures(scene):
- if scene.architecture_mode != 'trellis2':
- choices = (scene.architecture_mode, scene.model_architecture)
- elif scene.trellis2_texture_mode in ('native', 'none'):
- choices = ((scene.trellis2_initial_image_arch,)
- if scene.trellis2_generate_from == 'prompt' else ())
- else:
- choices = (scene.trellis2_texture_mode,)
- return DEPRECATED_ARCHITECTURES.intersection(choices)
-
-
-def preset_uses_deprecated_architecture(preset):
- if preset.get('architecture_mode') == 'trellis2':
- texture = preset.get('trellis2_texture_mode', 'native')
- if texture in ('none', 'native'):
- return (preset.get('trellis2_generate_from', 'image') == 'prompt'
- and preset.get('trellis2_initial_image_arch') in DEPRECATED_ARCHITECTURES)
- return texture in DEPRECATED_ARCHITECTURES
- return (preset.get('architecture_mode') in DEPRECATED_ARCHITECTURES
- or preset.get('model_architecture') in DEPRECATED_ARCHITECTURES)
-
-
-def redraw_architecture_menus(self, context):
- # No scene mutation: switching the preference preserves all saved settings.
- for window in context.window_manager.windows:
- for area in window.screen.areas:
- area.tag_redraw()
diff --git a/stablegen/cameras/geometry.py b/stablegen/cameras/geometry.py
index 03330ff..a856083 100644
--- a/stablegen/cameras/geometry.py
+++ b/stablegen/cameras/geometry.py
@@ -5,6 +5,7 @@ import bpy, bmesh # pylint: disable=import-error
import numpy as np
import mathutils
from mathutils import Matrix
+from ..core.architectures import QWEN_21_ARCHITECTURES
def _existing_camera_directions(mesh_center):
"""Return unit-direction vectors from *mesh_center* toward each existing
@@ -793,8 +794,11 @@ def _resolution_from_aspect(aspect, total_px, align=8):
def _get_resolution_align(context):
"""Use each Qwen encoder's image grid for camera resolution planning."""
architecture = context.scene.model_architecture
- if architecture == 'qwen_image_21':
+ if architecture in QWEN_21_ARCHITECTURES:
return 32
+ if architecture in {'moss_image', 'fibo_edit'}:
+ # Both use 16px latent patches (8x VAE with 2x2 patchify).
+ return 16
if (architecture == 'qwen_image_edit'
and getattr(context.scene, 'qwen_rescale_alignment', False)):
return 112
diff --git a/stablegen/cameras/overlays.py b/stablegen/cameras/overlays.py
index 5e41a97..c099ca1 100644
--- a/stablegen/cameras/overlays.py
+++ b/stablegen/cameras/overlays.py
@@ -208,7 +208,15 @@ def register_overlays():
handlers.append(callback)
if not bpy.app.timers.is_registered(_tick):
bpy.app.timers.register(_tick, first_interval=.1, persistent=True)
- display_settings_changed(bpy.context.scene)
+ # Enabling the add-on in Preferences registers it with a restricted context that has no scene, so the first
+ # sync waits until registration is over.
+ bpy.app.timers.register(_sync_after_register, first_interval=0)
+
+
+def _sync_after_register():
+ if _registered:
+ display_settings_changed(bpy.context.scene)
+ return None
def unregister_overlays():
@@ -216,8 +224,9 @@ def unregister_overlays():
_registered = False
_sg_remove_crop_overlay()
_sg_hide_label_overlay()
- if bpy.app.timers.is_registered(_tick):
- bpy.app.timers.unregister(_tick)
+ for timer in (_tick, _sync_after_register):
+ if bpy.app.timers.is_registered(timer):
+ bpy.app.timers.unregister(timer)
for handlers, callback in [(bpy.app.handlers.depsgraph_update_post, _invalidate),
(bpy.app.handlers.load_pre, _load_pre),
(bpy.app.handlers.load_post, _load_post)]:
diff --git a/stablegen/cameras/placement.py b/stablegen/cameras/placement.py
index 163ade2..0f4c4b7 100644
--- a/stablegen/cameras/placement.py
+++ b/stablegen/cameras/placement.py
@@ -1378,7 +1378,7 @@ class AddCameras(bpy.types.Operator):
return True
def invoke(self, context, event):
- return context.window_manager.invoke_props_dialog(self)
+ return context.window_manager.invoke_props_dialog(self, width=480)
\ No newline at end of file
diff --git a/stablegen/core/architectures.py b/stablegen/core/architectures.py
new file mode 100644
index 0000000..999162d
--- /dev/null
+++ b/stablegen/core/architectures.py
@@ -0,0 +1,157 @@
+"""Preference-gated architecture menus, retaining saved enum identifiers."""
+
+DEPRECATED_ARCHITECTURES = frozenset({'flux1', 'flux2_klein'})
+DEPRECATION_NOTICE = 'Deprecated: no longer receiving further support'
+# Shown by default; the add-on preferences can hide them like the deprecated ones.
+EXPERIMENTAL_ARCHITECTURES = frozenset({'qwen_image_21_turbo', 'moss_image', 'fibo_edit'})
+EXPERIMENTAL_NOTICE = 'Experimental: results and settings may still change'
+
+# Explicit numbers match the original static enums, including their ordering.
+# Retain these numbers when filtering so existing .blend files keep their choice.
+# Number 5 belongs to TRELLIS.2 in ARCHITECTURE_ITEMS; later models start at 6.
+MODEL_ARCHITECTURE_ITEMS = (
+ ('sdxl', 'SDXL', 'Stable Diffusion XL', 0),
+ ('moss_image', 'MOSS Image', 'MOSS-Image diffusion models, using the SDXL inpainting workflow. ' + EXPERIMENTAL_NOTICE, 7),
+ ('flux1', 'FLUX.1', DEPRECATION_NOTICE, 1),
+ ('qwen_image_edit', 'Qwen Image Edit', 'Qwen-Image-Edit checkpoints', 2),
+ ('qwen_image_21', 'Qwen Image 2.1', 'Qwen-Image 2.1 checkpoints', 3),
+ ('qwen_image_21_turbo', 'Qwen Image 2.1 Turbo', 'Qwen-Image 2.1 Turbo checkpoints with few-step sampling. ' + EXPERIMENTAL_NOTICE, 6),
+ ('fibo_edit', 'FIBO 2.0 Edit', 'Bria FIBO 2.0 Edit, using the Qwen Image Edit workflow. ' + EXPERIMENTAL_NOTICE, 8),
+ ('flux2_klein', 'FLUX.2 Klein', DEPRECATION_NOTICE, 4),
+)
+ARCHITECTURE_ITEMS = MODEL_ARCHITECTURE_ITEMS + (
+ ('trellis2', 'TRELLIS.2', 'Image to 3D mesh generation with TRELLIS.2', 5),
+)
+DIFFUSION_ARCHITECTURES = tuple(item[0] for item in MODEL_ARCHITECTURE_ITEMS)
+
+# Architecture families. Each new backbone reuses one established StableGen
+# pipeline, so dispatch and UI checks use these groups instead of single ids.
+QWEN_21_ARCHITECTURES = frozenset({'qwen_image_21', 'qwen_image_21_turbo'})
+# Image-edit models driven by the shared Qwen guidance settings and prompts.
+QWEN_ARCHITECTURES = QWEN_21_ARCHITECTURES | {'qwen_image_edit', 'fibo_edit'}
+# Native-graph edit models that VAE-encode their first image as the output
+# canvas, so projected context moves into image 1 and guides use gray.
+CANVAS_EDIT_ARCHITECTURES = QWEN_21_ARCHITECTURES | {'fibo_edit'}
+# Reference-image edit pipelines, including the deprecated FLUX.2 Klein.
+EDIT_ARCHITECTURES = QWEN_ARCHITECTURES | {'flux2_klein'}
+# Checkpoint-style models that run the SDXL txt2img / img2img / inpaint graphs.
+SDXL_GRAPH_ARCHITECTURES = frozenset({'sdxl', 'moss_image'})
+# Models loaded through dedicated native nodes, without LoRA or CLIP skip.
+NATIVE_GRAPH_ARCHITECTURES = CANVAS_EDIT_ARCHITECTURES | {'moss_image'}
+MASKED_EDIT_ARCHITECTURES = SDXL_GRAPH_ARCHITECTURES | QWEN_ARCHITECTURES
+TRELLIS_TEXTURE_ITEMS = (
+ ('none', 'None', 'Shape only, no texture generation', 0),
+ ('native', 'Native (TRELLIS.2)', 'Use TRELLIS.2 built-in texture generation', 1),
+) + tuple((key, label, description, number + 2)
+ for key, label, description, number in MODEL_ARCHITECTURE_ITEMS)
+
+
+def _preference(context, name, default):
+ try:
+ from . import get_addon_prefs
+ prefs = get_addon_prefs(context)
+ return bool(getattr(prefs, name, default)) if prefs else default
+ except (AttributeError, ImportError, KeyError, ReferenceError):
+ return default
+
+
+def deprecated_architectures_enabled(context=None):
+ return _preference(context, 'enable_deprecated_architectures', False)
+
+
+def experimental_architectures_enabled(context=None):
+ return _preference(context, 'enable_experimental_architectures', True)
+
+
+def hidden_architectures(context=None):
+ hidden = set()
+ if not deprecated_architectures_enabled(context):
+ hidden |= DEPRECATED_ARCHITECTURES
+ if not experimental_architectures_enabled(context):
+ hidden |= EXPERIMENTAL_ARCHITECTURES
+ return hidden
+
+
+def architecture_status(identifier):
+ """'Deprecated', 'Experimental' or '' for an architecture identifier."""
+ return ('Deprecated' if identifier in DEPRECATED_ARCHITECTURES
+ else 'Experimental' if identifier in EXPERIMENTAL_ARCHITECTURES else '')
+
+
+_READING_SELECTION = set()
+
+
+def _architecture_items(scene, context, property_name, items):
+ hidden = hidden_architectures(context)
+ if not hidden or property_name in _READING_SELECTION:
+ return items
+ # Read through RNA with the complete menu during the nested callback. This
+ # avoids depending on ID-property storage, which changed in Blender 5.1.
+ _READING_SELECTION.add(property_name)
+ try:
+ selected = getattr(scene, property_name, None)
+ finally:
+ _READING_SELECTION.remove(property_name)
+ # A saved hidden selection stays readable until the user replaces it or
+ # opts in. This exception never offers another hidden architecture.
+ return tuple(item for item in items if item[0] not in hidden or item[0] == selected)
+
+
+def model_architecture_items(scene, context):
+ return _architecture_items(scene, context, 'model_architecture', MODEL_ARCHITECTURE_ITEMS)
+
+
+def architecture_items(scene, context):
+ return _architecture_items(scene, context, 'architecture_mode', ARCHITECTURE_ITEMS)
+
+
+def trellis_texture_items(scene, context):
+ return _architecture_items(scene, context, 'trellis2_texture_mode', TRELLIS_TEXTURE_ITEMS)
+
+
+def trellis_initial_image_items(scene, context):
+ return _architecture_items(scene, context, 'trellis2_initial_image_arch', MODEL_ARCHITECTURE_ITEMS)
+
+
+def active_deprecated_architectures(scene):
+ return DEPRECATED_ARCHITECTURES.intersection(_active_architectures(scene))
+
+
+def active_experimental_architectures(scene):
+ return EXPERIMENTAL_ARCHITECTURES.intersection(_active_architectures(scene))
+
+
+def _active_architectures(scene):
+ if scene.architecture_mode != 'trellis2':
+ choices = (scene.architecture_mode, scene.model_architecture)
+ elif scene.trellis2_texture_mode in ('native', 'none'):
+ choices = ((scene.trellis2_initial_image_arch,)
+ if scene.trellis2_generate_from == 'prompt' else ())
+ else:
+ choices = (scene.trellis2_texture_mode,)
+ return choices
+
+
+def _preset_architectures(preset):
+ if preset.get('architecture_mode') == 'trellis2':
+ texture = preset.get('trellis2_texture_mode', 'native')
+ if texture in ('none', 'native'):
+ return ({preset.get('trellis2_initial_image_arch')}
+ if preset.get('trellis2_generate_from', 'image') == 'prompt' else set())
+ return {texture}
+ return {preset.get('architecture_mode'), preset.get('model_architecture')}
+
+
+def preset_uses_deprecated_architecture(preset):
+ return bool(_preset_architectures(preset) & DEPRECATED_ARCHITECTURES)
+
+
+def preset_uses_experimental_architecture(preset):
+ return bool(_preset_architectures(preset) & EXPERIMENTAL_ARCHITECTURES)
+
+
+def redraw_architecture_menus(self, context):
+ # No scene mutation: switching the preference preserves all saved settings.
+ for window in context.window_manager.windows:
+ for area in window.screen.areas:
+ area.tag_redraw()
diff --git a/stablegen/core/callbacks.py b/stablegen/core/callbacks.py
index fa8ccf6..26630b6 100644
--- a/stablegen/core/callbacks.py
+++ b/stablegen/core/callbacks.py
@@ -23,6 +23,7 @@ from .server_api import (
)
from ..timeout_config import get_timeout
from ..texturing.qwen_models import QWEN_PROMPT_TEMPLATE_ITEMS
+from .architectures import DIFFUSION_ARCHITECTURES, QWEN_ARCHITECTURES
# ── Architecture-mode helpers ──────────────────────────────────────────────
@@ -30,6 +31,9 @@ from ..texturing.qwen_models import QWEN_PROMPT_TEMPLATE_ITEMS
_QWEN_DEFAULT_PROMPT_TEMPLATES = {
'qwen_image_edit': 'QWEN_EDIT_LEGACY',
'qwen_image_21': 'QWEN_21_DEFAULT',
+ 'qwen_image_21_turbo': 'QWEN_21_DEFAULT',
+ # FIBO also edits its first image, so it shares the Qwen 2.1 image roles.
+ 'fibo_edit': 'QWEN_21_DEFAULT',
}
_QWEN_PROMPT_FIELDS = (
('qwen_custom_prompt_initial', True, None),
@@ -63,9 +67,7 @@ def refresh_qwen_prompt_template_fields(scene):
global _qwen_prompt_sync_active
if _qwen_prompt_sync_active:
return
- if getattr(scene, 'model_architecture', '') not in {
- 'qwen_image_edit', 'qwen_image_21'
- }:
+ if getattr(scene, 'model_architecture', '') not in QWEN_ARCHITECTURES:
return
template_id = getattr(scene, 'qwen_prompt_template', 'CUSTOM')
if template_id == 'CUSTOM':
@@ -97,9 +99,7 @@ def update_qwen_prompt_field(self, context):
if _qwen_prompt_sync_active:
return
scene = context.scene
- if getattr(scene, 'model_architecture', '') not in {
- 'qwen_image_edit', 'qwen_image_21'
- }:
+ if getattr(scene, 'model_architecture', '') not in QWEN_ARCHITECTURES:
update_parameters(self, context)
return
@@ -168,7 +168,7 @@ def update_architecture_mode(self, context):
def _sync_trellis2_backbone(scene):
"""Pick the right diffusion backbone for the current TRELLIS.2 state."""
tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
- if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ if tex_mode in DIFFUSION_ARCHITECTURES:
target = tex_mode
elif getattr(scene, 'trellis2_generate_from', 'image') == 'prompt':
target = getattr(scene, 'trellis2_initial_image_arch', 'sdxl')
@@ -212,6 +212,20 @@ def update_trellis2_generate_from(self, context):
update_parameters(self, context)
+def update_pbr_albedo_source(self, context):
+ """Set the saturation correction to suit the chosen albedo source.
+
+ Marigold IID-Appearance desaturates and needs the correction; Marigold V2
+ already keeps the generated colors, so the correction would only dull it.
+ """
+ source = context.scene.pbr_albedo_source
+ if source == 'marigold_v2':
+ context.scene.pbr_albedo_auto_saturation = False
+ elif source == 'marigold':
+ context.scene.pbr_albedo_auto_saturation = True
+ update_parameters(self, context)
+
+
# ── Server-address change callback ────────────────────────────────────────
def update_combined(self, context):
diff --git a/stablegen/feature_flags.py b/stablegen/core/feature_flags.py
similarity index 91%
rename from stablegen/feature_flags.py
rename to stablegen/core/feature_flags.py
index 40d482a..677d9bf 100644
--- a/stablegen/feature_flags.py
+++ b/stablegen/core/feature_flags.py
@@ -31,7 +31,8 @@ def experiments_enabled(context=None):
if context is None:
import bpy
context = bpy.context
- addon = context.preferences.addons.get(__package__)
+ # The add-on package owns the preferences; this module lives in its core package.
+ addon = context.preferences.addons.get((__package__ or '').rpartition('.')[0])
return bool(addon and addon.preferences.enable_texturing_experiments)
except (AttributeError, ImportError, KeyError, ReferenceError):
return False
diff --git a/stablegen/generation_status.py b/stablegen/core/generation_status.py
similarity index 100%
rename from stablegen/generation_status.py
rename to stablegen/core/generation_status.py
diff --git a/stablegen/core/load_handlers.py b/stablegen/core/load_handlers.py
index b691b3c..5af64ed 100644
--- a/stablegen/core/load_handlers.py
+++ b/stablegen/core/load_handlers.py
@@ -11,6 +11,7 @@ import bpy # pylint: disable=import-error
from bpy.app.handlers import persistent
from . import ADDON_PKG
+from .architectures import QWEN_ARCHITECTURES
@persistent
@@ -28,7 +29,9 @@ def load_handler(dummy):
# Builds saved while Qwen-Image 2.1 shared the Qwen-Image-Edit enum need a
# one-time architecture migration. The filename is used only here for
# compatibility; new generations dispatch exclusively by architecture.
- from ..texturing.qwen_models import is_qwen_image_21_model
+ from ..texturing.qwen_models import (
+ is_qwen_image_21_model, is_qwen_image_21_turbo_model,
+ )
saved_model_name = (
getattr(scene, "sg_model_name_backup", "")
or getattr(scene, "model_name", "")
@@ -36,14 +39,17 @@ def load_handler(dummy):
if not getattr(scene, "sg_qwen_21_architecture_migrated", False):
if (getattr(scene, "model_architecture", "") == 'qwen_image_edit'
and is_qwen_image_21_model(saved_model_name)):
- scene.model_architecture = 'qwen_image_21'
+ target = ('qwen_image_21_turbo'
+ if is_qwen_image_21_turbo_model(saved_model_name)
+ else 'qwen_image_21')
+ scene.model_architecture = target
if getattr(scene, "architecture_mode", "") == 'qwen_image_edit':
- scene.architecture_mode = 'qwen_image_21'
+ scene.architecture_mode = target
elif getattr(scene, "architecture_mode", "") == 'trellis2':
if getattr(scene, "trellis2_texture_mode", "") == 'qwen_image_edit':
- scene.trellis2_texture_mode = 'qwen_image_21'
+ scene.trellis2_texture_mode = target
if getattr(scene, "trellis2_initial_image_arch", "") == 'qwen_image_edit':
- scene.trellis2_initial_image_arch = 'qwen_image_21'
+ scene.trellis2_initial_image_arch = target
print("[StableGen] Migrated saved Qwen-Image 2.1 model to its dedicated architecture.")
scene.sg_qwen_21_architecture_migrated = True
@@ -61,7 +67,7 @@ def load_handler(dummy):
current_template = getattr(
loaded_scene, "qwen_prompt_template", ""
)
- if architecture in {'qwen_image_edit', 'qwen_image_21'}:
+ if architecture in QWEN_ARCHITECTURES:
valid_templates = {
'QWEN_EDIT_LEGACY', 'QWEN_21_DEFAULT', 'CANVAS_EDIT',
'REFERENCE_RECONSTRUCTION', 'CONCISE_TRANSFER',
@@ -78,9 +84,9 @@ def load_handler(dummy):
loaded_scene.qwen_prompt_template = 'CUSTOM'
elif needs_legacy_migration:
loaded_scene.qwen_prompt_template = (
- 'QWEN_21_DEFAULT'
- if architecture == 'qwen_image_21'
- else 'QWEN_EDIT_LEGACY'
+ 'QWEN_EDIT_LEGACY'
+ if architecture == 'qwen_image_edit'
+ else 'QWEN_21_DEFAULT'
)
loaded_scene.sg_qwen_prompt_template_migrated = True
diff --git a/stablegen/core/preferences.py b/stablegen/core/preferences.py
index 118a9d8..5ad4f5e 100644
--- a/stablegen/core/preferences.py
+++ b/stablegen/core/preferences.py
@@ -10,7 +10,7 @@ Contains:
import bpy # pylint: disable=import-error
-from ..architecture_options import redraw_architecture_menus
+from .architectures import redraw_architecture_menus
from ..ui.presets import update_parameters
from ..utils import sg_modal_active
from . import ADDON_PKG
@@ -74,6 +74,13 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
update=redraw_architecture_menus,
) # type: ignore
+ enable_experimental_architectures: bpy.props.BoolProperty(
+ name="Enable Experimental Architectures",
+ description="Show Qwen Image 2.1 Turbo, MOSS Image and FIBO 2.0 Edit; these architectures are new and their results and settings may still change",
+ default=True,
+ update=redraw_architecture_menus,
+ ) # type: ignore
+
enable_texturing_experiments: bpy.props.BoolProperty(
name="Enable Experimental Texturing Features",
description="Show research controls and allow their saved settings to affect texturing; disabling keeps saved values but prevents experimental execution",
@@ -220,6 +227,7 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):
layout.prop(self, "save_blend_file")
layout.prop(self, "enable_print_tab")
layout.prop(self, "enable_texturing_experiments")
+ layout.prop(self, "enable_experimental_architectures")
layout.prop(self, "enable_deprecated_architectures")
if self.enable_deprecated_architectures:
layout.label(text="FLUX.1 and FLUX.2 Klein no longer receive support.", icon='INFO')
diff --git a/stablegen/core/properties.py b/stablegen/core/properties.py
index 3182b34..9c9fcb7 100644
--- a/stablegen/core/properties.py
+++ b/stablegen/core/properties.py
@@ -17,6 +17,7 @@ from .callbacks import (
update_trellis2_generate_from,
update_trellis2_initial_image_arch,
update_trellis2_texture_mode,
+ update_pbr_albedo_source,
update_print_preset,
update_print_dithered,
update_qwen_prompt_dependencies,
@@ -24,10 +25,10 @@ from .callbacks import (
update_qwen_prompt_template,
)
from . import ADDON_PKG
-from ..feature_flags import TEXTURING_DEFAULTS
-from ..architecture_options import (
+from .feature_flags import TEXTURING_DEFAULTS
+from .architectures import (
architecture_items, model_architecture_items,
- trellis_texture_items, trellis_initial_image_items,
+ trellis_texture_items, trellis_initial_image_items, QWEN_ARCHITECTURES,
)
from ..texturing.qwen_models import QWEN_PROMPT_TEMPLATE_ITEMS
@@ -42,7 +43,7 @@ def _get_ipadapter_mode_items(self, context):
if context:
is_local_edit = (
context.scene.generation_method == 'local_edit'
- or (context.scene.model_architecture.startswith('qwen')
+ or (context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.qwen_generation_method == 'local_edit')
)
if is_local_edit:
@@ -435,6 +436,32 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
default=True,
update=update_parameters,
)
+ bpy.types.Scene.moss_depth_control = bpy.props.BoolProperty(
+ name="Depth Control",
+ description=(
+ "Guide MOSS-Image with each camera's depth map through the color/depth "
+ "control adapter (moss_image_color_depth_control.safetensors in "
+ "models/loras). Needs ComfyUI 0.42.3 or later; without it, MOSS follows "
+ "only the prompt and any projected context"
+ ),
+ default=True,
+ update=update_parameters,
+ )
+ bpy.types.Scene.moss_depth_strength = bpy.props.FloatProperty(
+ name="Depth Strength",
+ description="Scale of the depth map's contribution. 1.0 is the trained strength",
+ default=1.0, min=0.0, max=10.0, soft_max=2.0,
+ update=update_parameters,
+ )
+ bpy.types.Scene.moss_depth_end = bpy.props.FloatProperty(
+ name="Depth End",
+ description=(
+ "Sampling fraction at which depth control stops. The adapter recommends "
+ "0.5 for rendered 3D depth maps, letting later steps refine the shapes"
+ ),
+ default=0.5, min=0.0, max=1.0,
+ update=update_parameters,
+ )
bpy.types.Scene.auto_rescale_target_mp = bpy.props.FloatProperty(
name="Target megapixels",
description=(
@@ -1834,7 +1861,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
('lighting', "Marigold IID-Lighting (Vibrant)", "Albedo from Marigold IID-Lighting \u2014 tends to produce more vibrant, saturated colours than IID-Appearance"),
('marigold_v2', "Marigold V2 (Sharp Albedo)", "Albedo from Marigold V2 at up to the Marigold V2 resolution \u2014 removes lighting while keeping fine texture detail and colour. Needs the Marigold V2 models (about 24 GB with normals) and a September 2026 or newer ComfyUI. Roughness and metallic still come from Marigold IID-Appearance"),
],
- default='marigold', update=update_parameters,
+ default='marigold', update=update_pbr_albedo_source,
)
bpy.types.Scene.pbr_normal_model = bpy.props.EnumProperty(
name="Normal Model", description="Model used to estimate the normal map",
@@ -2008,7 +2035,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,
)
bpy.types.Scene.pbr_albedo_auto_saturation = bpy.props.BoolProperty(
name="Correct Albedo Saturation",
- description="Automatically correct albedo saturation by comparing the PBR albedo against the original rendered image and boosting to match. Averaged across all cameras for uniform results by default. Recommended for Marigold IID (Flat Albedo) which tends to desaturate. Usually not needed for StableDelight or IID-Lighting",
+ description="Automatically correct albedo saturation by comparing the PBR albedo against the original rendered image and boosting to match. Averaged across all cameras for uniform results by default. Recommended for Marigold IID (Flat Albedo) which tends to desaturate. Usually not needed for StableDelight or IID-Lighting. Choosing an albedo source turns it on for Marigold IID and off for Marigold V2, which already keeps the generated colors",
default=True, update=update_parameters
)
bpy.types.Scene.pbr_albedo_saturation_mode = bpy.props.EnumProperty(
@@ -2064,6 +2091,9 @@ def unregister_properties(load_handler, _sg_queue_load_handler):
'auto_rescale',
'qwen_rescale_alignment',
'qwen_image_21_native_rgba',
+ 'moss_depth_control',
+ 'moss_depth_strength',
+ 'moss_depth_end',
'auto_rescale_target_mp',
'generation_method',
'use_ipadapter',
diff --git a/stablegen/core/server_api.py b/stablegen/core/server_api.py
index 34419e7..99879bc 100644
--- a/stablegen/core/server_api.py
+++ b/stablegen/core/server_api.py
@@ -153,6 +153,21 @@ def check_skintokens_autorig_available(server_address, timeout=1.0):
return False
+def fetch_node_info(server_address, node_class, timeout=1.0):
+ """Return a node's ``/object_info`` entry, or ``None`` if it is not installed."""
+ if not server_address:
+ return None
+ try:
+ response = requests.get(
+ f"http://{server_address}/object_info/{node_class}", timeout=timeout
+ )
+ if response.status_code == 200:
+ return response.json().get(node_class)
+ except Exception as e:
+ print(f"[StableGen] Could not query ComfyUI node {node_class}: {e}")
+ return None
+
+
# ── API data retrieval ─────────────────────────────────────────────────────
def fetch_from_comfyui_api(context, endpoint):
diff --git a/stablegen/dae_import/batch_texture.py b/stablegen/dae_import/batch_texture.py
index 296ca60..27e1f15 100644
--- a/stablegen/dae_import/batch_texture.py
+++ b/stablegen/dae_import/batch_texture.py
@@ -18,6 +18,7 @@ from .batch_manifest import (
filename_contains_model_stem,
load_batch_manifest,
)
+from ..core.architectures import EDIT_ARCHITECTURES
# Reference image filenames (checked in order)
_REF_NAMES = ('ref.png', 'ref.jpg', 'ref.jpeg')
@@ -492,7 +493,7 @@ def _do_set_ref_image():
if arch == 'sdxl':
scene.use_ipadapter = True
scene.ipadapter_image = ref
- elif arch in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ elif arch in EDIT_ARCHITECTURES:
scene.qwen_use_external_style_image = True
scene.qwen_external_style_image = ref
elif arch == 'flux1':
diff --git a/stablegen/debug_tools.py b/stablegen/debug_tools.py
index 5d51863..7cead83 100644
--- a/stablegen/debug_tools.py
+++ b/stablegen/debug_tools.py
@@ -54,6 +54,7 @@ from .mesh_gen.rig_display import (
fortune_conversion_risks,
selected_armatures_for_display,
)
+from .core.architectures import CANVAS_EDIT_ARCHITECTURES, EDIT_ARCHITECTURES, QWEN_ARCHITECTURES
# ─── Shared helpers ──────────────────────────────────────────────────────
@@ -2188,11 +2189,7 @@ _INTERACTIVE_DISCARD_BUILD_SETTINGS = (
'qwen_voronoi_mode',
)
-_MAGENTA_EDIT_ARCHITECTURES = {
- 'qwen_image_edit',
- 'qwen_image_21',
- 'flux2_klein',
-}
+_MAGENTA_EDIT_ARCHITECTURES = EDIT_ARCHITECTURES
def _copy_scene_value(value):
@@ -2572,7 +2569,7 @@ class SG_OT_InteractiveDiscardCheck(bpy.types.Operator):
)
fallback = tuple(scene.qwen_guidance_fallback_color)
background = tuple(scene.qwen_guidance_background_color)
- if scene.model_architecture == 'qwen_image_21':
+ if scene.model_architecture in CANVAS_EDIT_ARCHITECTURES:
background = (0.5, 0.5, 0.5)
# Blender's write_still render also writes to scene.render.filepath in
@@ -2973,7 +2970,7 @@ class SG_OT_DebugProjectionLine(bpy.types.Operator):
self.report({'ERROR'}, 'Current material uses baked Surface Blend weights; reproject with Boundary Crossfade or Local Unsharpen for this comparison')
return {'CANCELLED'}
if context.scene.generation_method == 'local_edit' or (
- context.scene.model_architecture.startswith('qwen')
+ context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.qwen_generation_method == 'local_edit'):
self.report({'ERROR'}, 'Line diagnostics currently require an ordinary multi-view projection, not a local edit pass')
return {'CANCELLED'}
diff --git a/stablegen/mesh_gen/trellis2.py b/stablegen/mesh_gen/trellis2.py
index a749272..030a64f 100644
--- a/stablegen/mesh_gen/trellis2.py
+++ b/stablegen/mesh_gen/trellis2.py
@@ -26,6 +26,7 @@ from .rig_display import (
record_autorig_bone_heuristic,
selected_armatures_for_display,
)
+from ..core.architectures import DIFFUSION_ARCHITECTURES
_ADDON_PKG = __package__.rsplit('.', 1)[0]
_GARMENT_STABILIZED_GROUP = "SG_GarmentStabilized"
@@ -1342,7 +1343,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', 'qwen_image_21', 'flux2_klein'))
+ has_texturing = (tex_mode in DIFFUSION_ARCHITECTURES)
has_autorig = bool(getattr(scene, 'trellis2_autorig_enabled', False))
if has_txt2img and has_autorig and has_texturing:
self._total_phases = 4
@@ -1758,7 +1759,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', 'qwen_image_21', 'flux2_klein'):
+ if tex_mode in DIFFUSION_ARCHITECTURES:
# 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]
diff --git a/stablegen/mesh_gen/workflows.py b/stablegen/mesh_gen/workflows.py
index ed455bb..bbbf212 100644
--- a/stablegen/mesh_gen/workflows.py
+++ b/stablegen/mesh_gen/workflows.py
@@ -1513,7 +1513,7 @@ class _Trellis2WorkflowMixin:
if message['type'] == 'executing':
data = message['data']
- if data['prompt_id'] == prompt_id:
+ if data.get('prompt_id') == prompt_id:
if data['node'] is None:
self.operator._phase_progress = 100
self.operator._detail_progress = 100
diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.py
index 50dce06..7387328 100644
--- a/stablegen/texturing/generator.py
+++ b/stablegen/texturing/generator.py
@@ -1,4 +1,4 @@
-from ..feature_flags import experimental_enabled
+from ..core.feature_flags import experimental_enabled
"""ComfyUI texture generation operator (core pipeline)."""
import os
@@ -31,7 +31,7 @@ from ..cameras.geometry import _SGCameraResolution, _get_camera_resolution, _get
from ..cameras.overlays import _sg_restore_square_display, _sg_remove_crop_overlay, _sg_ensure_crop_overlay, _sg_hide_label_overlay, _sg_restore_label_overlay
from .projection import project_image, reinstate_compare_nodes, _bake_visibility_weights, reset_projection_material_nodes, _is_projection_mesh, pop_svm_stack_warning, pop_eevee_attribute_warning
from .jobs import operation, RenderRequest, MainThreadOperation, run_sync
-from ..utils import get_last_material_index, get_generation_dirs, get_file_path, get_dir_path, remove_empty_dirs, get_compositor_node_tree, configure_output_node_paths, get_eevee_engine_id, sg_modal_active
+from ..utils import get_last_material_index, get_generation_dirs, get_file_path, get_dir_path, remove_empty_dirs, get_compositor_node_tree, new_compositor_math, configure_output_node_paths, get_eevee_engine_id, sg_modal_active
from ..util.mirror_color import MirrorReproject, _get_viewport_ref_np, _apply_color_match_to_file
from ..timeout_config import get_timeout
from .._generator_utils import redraw_ui, setup_studio_lighting, _pbr_setup_studio_lights, upload_image_to_comfyui
@@ -60,7 +60,8 @@ from .pose_lock import (
restore_active_texturing_frame,
set_active_texturing_frame,
)
-from ..feature_flags import active_experiments
+from ..core.feature_flags import active_experiments
+from ..core.architectures import CANVAS_EDIT_ARCHITECTURES, EDIT_ARCHITECTURES, QWEN_ARCHITECTURES
import websocket
@@ -509,7 +510,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
if context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}:
fallback = tuple(context.scene.qwen_guidance_fallback_color)
background = tuple(context.scene.qwen_guidance_background_color)
- if context.scene.model_architecture == 'qwen_image_21':
+ if context.scene.model_architecture in CANVAS_EDIT_ARCHITECTURES:
# Qwen 2.1 VAE-encodes projected context as its edit target and
# otherwise preserves a magenta canvas. Keep magenta only for
# unknown surface regions and make the outer background neutral.
@@ -849,7 +850,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
else:
print("[StableGen] Standard texturing; no research options active")
- if context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein') and not context.scene.generation_mode == 'project_only':
+ if context.scene.model_architecture in EDIT_ARCHITECTURES and not context.scene.generation_mode == 'project_only':
context.scene.generation_method = 'sequential' # Force sequential for edit models
render = bpy.context.scene.render
@@ -870,8 +871,8 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
# Qwen Image Edit's optional 112px grid follows Qwen2.5-VL; Qwen
# Image 2.1 uses Qwen3-VL and ComfyUI's native 32px image grid.
- # FLUX.2 Klein uses 16x latent downscale.
- if context.scene.model_architecture.startswith('qwen'):
+ # FLUX.2 Klein, MOSS-Image and FIBO use 16x latent downscale.
+ if context.scene.model_architecture in QWEN_ARCHITECTURES | {'moss_image'}:
align_step = _get_resolution_align(context)
elif context.scene.model_architecture == 'flux2_klein':
align_step = 16
@@ -1085,7 +1086,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
# Check if there is at least one ControlNet unit
controlnet_units = getattr(context.scene, "controlnet_units", [])
- if not controlnet_units and not (context.scene.use_flux_lora and context.scene.model_architecture == 'flux1') and context.scene.model_architecture != 'flux2_klein':
+ if not controlnet_units and not (context.scene.use_flux_lora and context.scene.model_architecture == 'flux1') and context.scene.model_architecture not in ('flux2_klein', 'moss_image'):
self.report({'ERROR'}, "At least one ControlNet unit is required. Add one in the Guidance section below.")
context.scene.generation_status = 'idle'
context.scene.sg_last_gen_error = True
@@ -1144,10 +1145,12 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._restore_texturing_pose(context)
return {'CANCELLED'}
- if not context.scene.overwrite_material or self._material_id == -1 or (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit')):
+ if not context.scene.overwrite_material or self._material_id == -1 or (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.qwen_generation_method == 'local_edit')):
self._material_id += 1
- self._controlnet_units = list(controlnet_units)
+ # MOSS-Image has no ControlNet models; skip exporting their guide maps.
+ self._controlnet_units = ([] if context.scene.model_architecture == 'moss_image'
+ else list(controlnet_units))
# Prepare for generating
if context.scene.generation_method == 'grid':
@@ -1420,7 +1423,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
applicable = (
getattr(self, '_generation_method_on_start', None) == 'sequential'
- or context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
+ or context.scene.model_architecture in EDIT_ARCHITECTURES
)
reset_angle = (
context.scene.discard_factor_after_generation
@@ -1630,9 +1633,11 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
need_depth = (
any(u["unit_type"] == "depth" for u in controlnet_units)
or (context.scene.use_flux_lora and context.scene.model_architecture == 'flux1')
- or (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
+ or (context.scene.model_architecture == 'moss_image'
+ and context.scene.moss_depth_control)
+ or (context.scene.model_architecture in EDIT_ARCHITECTURES
and context.scene.qwen_guidance_map_type == 'depth')
- or (context.scene.model_architecture.startswith('qwen')
+ or (context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.qwen_generation_method in ('refine', 'local_edit')
and context.scene.qwen_refine_use_depth)
or (getattr(context.scene, 'sg_rework_projection_guard', False)
@@ -1672,7 +1677,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
need_normal = (
any(u["unit_type"] == "normal" for u in controlnet_units)
- or (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
+ or (context.scene.model_architecture in EDIT_ARCHITECTURES
and context.scene.qwen_guidance_map_type == 'normal')
)
if need_normal and context.scene.generation_method != 'uv_inpaint':
@@ -1693,13 +1698,13 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
return
# Qwen guidance using Workbench
- if (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
+ if (context.scene.model_architecture in EDIT_ARCHITECTURES
and context.scene.qwen_guidance_map_type == 'workbench'
and context.scene.generation_method != 'uv_inpaint'):
workbench_dir = get_dir_path(context, "controlnet")["workbench"]
guide_background = (
(0.5, 0.5, 0.5)
- if context.scene.model_architecture == 'qwen_image_21'
+ if context.scene.model_architecture in CANVAS_EDIT_ARCHITECTURES
else None
)
for i, camera in enumerate(cameras):
@@ -1721,13 +1726,13 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
return
# Qwen guidance using Viewport
- elif (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
+ elif (context.scene.model_architecture in EDIT_ARCHITECTURES
and context.scene.qwen_guidance_map_type == 'viewport'
and context.scene.generation_method != 'uv_inpaint'):
viewport_dir = get_dir_path(context, "controlnet")["viewport"]
guide_background = (
(0.5, 0.5, 0.5)
- if context.scene.model_architecture == 'qwen_image_21'
+ if context.scene.model_architecture in CANVAS_EDIT_ARCHITECTURES
else None
)
for i, camera in enumerate(cameras):
@@ -1751,14 +1756,14 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
# Refine / Local Edit mode — emit images + edge feather masks
is_refine = (
context.scene.generation_method in ('refine', 'local_edit')
- or (context.scene.model_architecture.startswith('qwen')
+ or (context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.qwen_generation_method in ('refine', 'local_edit'))
)
if is_refine:
need_feather = (
context.scene.refine_edge_feather_projection
and (context.scene.generation_method == 'local_edit'
- or (context.scene.model_architecture.startswith('qwen')
+ or (context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.qwen_generation_method == 'local_edit'))
)
for i, camera in enumerate(cameras):
@@ -1909,7 +1914,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
image = self.workflow_manager.refine_flux(context, controlnet_info=controlnet_info, render_info=render_info, ipadapter_ref_info=ipadapter_ref_info)
else:
image = self.workflow_manager.refine(context, controlnet_info=controlnet_info, render_info=render_info, ipadapter_ref_info=ipadapter_ref_info)
- elif context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method in ('refine', 'local_edit'):
+ elif context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.qwen_generation_method in ('refine', 'local_edit'):
image = self.workflow_manager.generate_qwen_refine(context, camera_id=camera_id)
elif context.scene.generation_method == 'uv_inpaint':
if context.scene.model_architecture == 'flux1':
@@ -1920,7 +1925,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
if self._current_image == 0:
if context.scene.model_architecture == 'flux1':
image = self.workflow_manager.generate_flux(context, controlnet_info=controlnet_info, ipadapter_ref_info=ipadapter_ref_info)
- elif context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21'):
+ elif context.scene.model_architecture in QWEN_ARCHITECTURES:
image = self.workflow_manager.generate_qwen_edit(context, camera_id=camera_id)
elif context.scene.model_architecture == 'flux2_klein':
image = self.workflow_manager.generate_flux2_klein(context, camera_id=camera_id)
@@ -1954,7 +1959,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
)
_emit_cam = _cur_cam
with _SGCameraResolution(context, _emit_cam):
- if context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'): # export custom bg and fallback for Qwen/Klein image edit
+ if context.scene.model_architecture in EDIT_ARCHITECTURES: # export custom bg and fallback for Qwen/Klein image edit
fallback_color, background_color = self._get_qwen_context_colors(context)
yield from export_emit_image(context, self._to_texture, camera_id=self._current_image, bg_color=background_color, fallback_color=fallback_color, _steps=True)
if getattr(context.scene, 'qwen_use_confidence_context', False):
@@ -1986,7 +1991,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
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 in ('qwen_image_edit', 'qwen_image_21'):
+ elif context.scene.model_architecture in QWEN_ARCHITECTURES:
image = self.workflow_manager.generate_qwen_edit(context, camera_id=camera_id)
elif context.scene.model_architecture == 'flux2_klein':
image = self.workflow_manager.generate_flux2_klein(context, camera_id=camera_id)
@@ -1995,7 +2000,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
else: # Grid or Separate
if context.scene.model_architecture == 'flux1':
image = self.workflow_manager.generate_flux(context, controlnet_info=controlnet_info, ipadapter_ref_info=ipadapter_ref_info)
- elif context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21'):
+ elif context.scene.model_architecture in QWEN_ARCHITECTURES:
image = self.workflow_manager.generate_qwen_edit(context, camera_id=camera_id)
elif context.scene.model_architecture == 'flux2_klein':
image = self.workflow_manager.generate_flux2_klein(context, camera_id=camera_id)
@@ -2007,7 +2012,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
self._error = "Connection to ComfyUI server failed."
return # Error message set
- if (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
+ if (context.scene.model_architecture in EDIT_ARCHITECTURES
and context.scene.generation_method == 'sequential'
and self._current_image > 0
and not getattr(context.scene, 'qwen_use_confidence_context', False)
@@ -2026,7 +2031,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
with open(image_path, 'wb') as f:
f.write(image)
- if (context.scene.model_architecture.startswith('qwen')
+ if (context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.generation_method == 'sequential'
and self._current_image > 0):
fallback_color, _ = self._get_qwen_context_colors(context)
@@ -2100,7 +2105,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
else: # steps == 0, skip generation
pass # No image generation needed
- if context.scene.generation_method in ('separate', 'refine', 'local_edit', 'sequential') or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method in ('refine', 'local_edit')):
+ if context.scene.generation_method in ('separate', 'refine', 'local_edit', 'sequential') or (context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.qwen_generation_method in ('refine', 'local_edit')):
self._current_image += 1
self._threads_left -= 1
if self._threads_left > 0:
@@ -2149,62 +2154,68 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
traceback.print_exc()
return
- # ── PBR Decomposition (runs after ALL cameras are generated) ──
- if getattr(context.scene, 'pbr_decomposition', False):
- self._pbr_maps = {}
- # Collect camera images that need PBR decomposition
- camera_images = {} # cam_idx → image_path
- per_camera_missing = {} # cam_idx → set of missing map names (reproject only)
- num_cameras = len(self._cameras)
- for cam_idx in range(num_cameras):
- cam_image_path = get_file_path(
- context, "generated", camera_id=cam_idx,
- material_id=self._material_id,
- )
- if os.path.exists(cam_image_path):
- # In project_only (reproject) mode, reuse existing PBR
- # maps when all enabled maps are already on disk. This
- # avoids re-running the slow ComfyUI decomposition.
- if context.scene.generation_mode == 'project_only':
- existing, missing = self._find_existing_pbr_maps(
- context, cam_idx)
- if not missing:
- # All maps present — fully reuse
- self._ensure_raw_copies(
- context, cam_idx, existing)
- self._pbr_maps[cam_idx] = existing
- print(f"[StableGen] Reusing existing PBR maps "
- f"for camera {cam_idx}")
- continue
- # Some maps exist, some are missing — seed existing
- # maps so the batched function only generates what's
- # missing.
- if existing:
- self._ensure_raw_copies(
- context, cam_idx, existing)
- self._pbr_maps[cam_idx] = existing
- per_camera_missing[cam_idx] = missing
- print(f"[StableGen] PBR maps missing for camera "
- f"{cam_idx}: {missing}, running selective decomposition…")
- camera_images[cam_idx] = cam_image_path
- if camera_images:
- self._run_pbr_decomposition_batched(
- context, camera_images,
- per_camera_missing=per_camera_missing if per_camera_missing else None)
- if self._error:
- return
-
- # ── Batch post-processing (albedo sat/contrast, roughness scale) ──
- # Runs after ALL cameras have raw maps saved, so auto-saturation
- # can average across all cameras uniformly.
- if self._pbr_maps:
- self._apply_albedo_postprocessing_batch(context)
+ # A failed model call must end the run with an error, not leave stale maps behind silently.
+ try:
+ # ── PBR Decomposition (runs after ALL cameras are generated) ──
+ if getattr(context.scene, 'pbr_decomposition', False):
+ self._pbr_maps = {}
+ # Collect camera images that need PBR decomposition
+ camera_images = {} # cam_idx → image_path
+ per_camera_missing = {} # cam_idx → set of missing map names (reproject only)
+ num_cameras = len(self._cameras)
+ for cam_idx in range(num_cameras):
+ cam_image_path = get_file_path(
+ context, "generated", camera_id=cam_idx,
+ material_id=self._material_id,
+ )
+ if os.path.exists(cam_image_path):
+ # In project_only (reproject) mode, reuse existing PBR
+ # maps when all enabled maps are already on disk. This
+ # avoids re-running the slow ComfyUI decomposition.
+ if context.scene.generation_mode == 'project_only':
+ existing, missing = self._find_existing_pbr_maps(
+ context, cam_idx)
+ if not missing:
+ # All maps present — fully reuse
+ self._ensure_raw_copies(
+ context, cam_idx, existing)
+ self._pbr_maps[cam_idx] = existing
+ print(f"[StableGen] Reusing existing PBR maps "
+ f"for camera {cam_idx}")
+ continue
+ # Some maps exist, some are missing — seed existing
+ # maps so the batched function only generates what's
+ # missing.
+ if existing:
+ self._ensure_raw_copies(
+ context, cam_idx, existing)
+ self._pbr_maps[cam_idx] = existing
+ per_camera_missing[cam_idx] = missing
+ print(f"[StableGen] PBR maps missing for camera "
+ f"{cam_idx}: {missing}, running selective decomposition…")
+ camera_images[cam_idx] = cam_image_path
+ if camera_images:
+ self._run_pbr_decomposition_batched(
+ context, camera_images,
+ per_camera_missing=per_camera_missing if per_camera_missing else None)
+ if self._error:
+ return
- # ── Persist per-map settings hashes so future reprojects can
- # detect stale maps and only regenerate what changed. ──
- if camera_images:
- for cam_idx in camera_images:
- self._save_pbr_settings(context, cam_idx)
+ # ── Batch post-processing (albedo sat/contrast, roughness scale) ──
+ # Runs after ALL cameras have raw maps saved, so auto-saturation
+ # can average across all cameras uniformly.
+ if self._pbr_maps:
+ self._apply_albedo_postprocessing_batch(context)
+
+ # ── Persist per-map settings hashes so future reprojects can
+ # detect stale maps and only regenerate what changed. ──
+ if camera_images:
+ for cam_idx in camera_images:
+ self._save_pbr_settings(context, cam_idx)
+ except Exception as e:
+ self._error = f"PBR decomposition failed: {e}"
+ traceback.print_exc()
+ return
def image_project_callback():
if context.scene.generation_method == 'sequential':
@@ -2388,11 +2399,14 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
original_pass_z = view_layer.use_pass_z
- # Enable depth pass in the render settings
+ # Enable depth pass in the render settings. Workbench keeps Combined:
+ # it draws that image anyway, and Blender 4.5's compositor crashes on a
+ # Render Layers node when a Workbench render has no Combined pass.
for name in _RenderStateTransaction._PASS_NAMES:
if hasattr(view_layer, name):
setattr(view_layer, name, name == 'use_pass_z' or (
- use_part_ids and name in {'use_pass_object_index', 'use_pass_material_index'}))
+ use_part_ids and name in {'use_pass_object_index', 'use_pass_material_index'}) or (
+ depth_engine == 'BLENDER_WORKBENCH' and name == 'use_pass_combined'))
view_layer.use_pass_z = True
if hasattr(view_layer, 'use_pass_object_index'):
view_layer.use_pass_object_index = use_part_ids
@@ -2457,11 +2471,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
)
if actual_socket is None:
return False
- # Blender 5 removed the compositor-specific Math node idname.
- # ShaderNodeMath is the shared Math node accepted by compositor
- # trees in both the current API and supported Blender 4.x builds.
- divide = nodes.new(type="ShaderNodeMath")
- divide.operation = 'DIVIDE'
+ divide = new_compositor_math(nodes, 'DIVIDE')
divide.inputs[1].default_value = 255.0
divide.location = (200, y)
links.new(render_layers_node.outputs[actual_socket], divide.inputs[0])
@@ -2480,8 +2490,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
(obj.matrix_world @ mathutils.Vector(corner) - camera_position).length
for obj in context.view_layer.objects if obj.type == 'MESH' and not obj.hide_render
for corner in obj.bound_box]) * 1.01
- distance_node = nodes.new('ShaderNodeMath')
- distance_node.operation = 'DIVIDE'
+ distance_node = new_compositor_math(nodes, 'DIVIDE')
distance_node.inputs[1].default_value = distance_scale
links.new(render_layers_node.outputs['Depth'], distance_node.inputs[0])
distance_output = nodes.new('CompositorNodeOutputFile')
@@ -2895,7 +2904,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):
is_recent_mode_ref = (
file_type == "generated" and
context.scene.sequential_ipadapter_mode == 'recent' and
- (context.scene.sequential_ipadapter or context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'))
+ (context.scene.sequential_ipadapter or context.scene.model_architecture in EDIT_ARCHITECTURES)
)
temp_image_path = None
diff --git a/stablegen/texturing/masked_edit.py b/stablegen/texturing/masked_edit.py
index 674168b..25e016f 100644
--- a/stablegen/texturing/masked_edit.py
+++ b/stablegen/texturing/masked_edit.py
@@ -18,7 +18,9 @@ import numpy as np
from ..core import ADDON_PKG, legacy_panel_enabled
from ..utils import sg_modal_active, get_file_path
+from .pbr_emission import emission_from_hsv, emission_from_residual
from .rendering import _RenderStateTransaction
+from ..core.architectures import MASKED_EDIT_ARCHITECTURES, QWEN_ARCHITECTURES, SDXL_GRAPH_ARCHITECTURES
MASK_UV = 'SG Edit Mask UV'
COVERAGE = 'SG Masked Edit Coverage'
@@ -69,6 +71,17 @@ def output_node(material):
if n.type == 'OUTPUT_MATERIAL' and n.is_active_output), None)
+def color_input(shader):
+ """Where the colour graph enters *shader*: its Base Color (or Color), or the colour input of
+ StableGen's 'AO Multiply' node when ambient occlusion is multiplied on top. Edits enter there,
+ so the AO still darkens them and the context renders show the colour before AO."""
+ socket = shader.inputs['Base Color' if shader.type == 'BSDF_PRINCIPLED' else 'Color']
+ ao = socket.links[0].from_node if socket.links else None
+ if ao is not None and ao.type == 'MIX' and ao.label == 'AO Multiply' and ao.inputs[6].links:
+ return ao.inputs[6] # A: the colour, B is the AO factor
+ return socket
+
+
def color_socket(material):
"""Support StableGen colour graphs, baked Principled materials and emission."""
nodes, links = material.node_tree.nodes, material.node_tree.links
@@ -78,7 +91,7 @@ def color_socket(material):
socket = out.inputs['Surface'].links[0].from_socket
source = socket.node
if source.type in {'BSDF_PRINCIPLED', 'EMISSION'}:
- color = source.inputs['Base Color' if source.type == 'BSDF_PRINCIPLED' else 'Color']
+ color = color_input(source)
if color.links:
return color.links[0].from_socket
rgb = nodes.new('ShaderNodeRGB')
@@ -89,6 +102,14 @@ def color_socket(material):
return socket
+def pack_image(image):
+ """Pack *image* unless it is already packed and unchanged. Blender 4.x empties a packed image
+ whose pixels are not loaded (a fresh copy, or a mask not yet drawn) when it is packed again."""
+ if image.packed_file and not image.is_dirty:
+ return
+ image.pack()
+
+
def mask_socket(material, image, label=FROZEN):
nodes, links = material.node_tree.nodes, material.node_tree.links
uv = nodes.new('ShaderNodeUVMap')
@@ -211,7 +232,7 @@ def paint_session_valid(context):
def is_masked_edit_mode(scene):
- if scene.model_architecture.startswith('qwen'):
+ if scene.model_architecture in QWEN_ARCHITECTURES:
return scene.qwen_generation_method == 'masked_edit'
return scene.generation_method == 'masked_edit'
@@ -305,7 +326,7 @@ def finish_paint(context):
del obj['_sg_mask_paint_hidden']
del obj['_sg_mask_paint_render_hidden']
if obj.sg_edit_mask:
- obj.sg_edit_mask.pack()
+ pack_image(obj.sg_edit_mask)
if '_sg_mask_paint_selected' in context.scene:
selected = json.loads(context.scene['_sg_mask_paint_selected'])
for obj in context.view_layer.objects:
@@ -324,7 +345,7 @@ def finish_paint(context):
obj.active_material = obj.sg_mask_paint_original
obj.sg_mask_paint_original = None
if obj.sg_edit_mask:
- obj.sg_edit_mask.pack()
+ pack_image(obj.sg_edit_mask)
old_uv = obj.get('_sg_mask_old_uv', '')
if old_uv in obj.data.uv_layers:
obj.data.uv_layers.active = obj.data.uv_layers[old_uv]
@@ -646,7 +667,7 @@ def begin_layers(objects):
node.name = COVERAGE + ' Previous'
frozen = obj.sg_edit_mask.copy()
frozen.name = obj.name + ' Edit Selection Snapshot'
- frozen.pack()
+ pack_image(frozen)
mask_socket(material, frozen)
# Give the legacy local projector a colour node, retaining original shader
# separately so its lighting/PBR inputs can be restored around each layer.
@@ -654,7 +675,7 @@ def begin_layers(objects):
before = output_node(material).inputs['Surface'].links[0].from_node
material['_sg_mask_shader'] = before.name if before.type in {'BSDF_PRINCIPLED', 'EMISSION'} else ''
if before.type in {'BSDF_PRINCIPLED', 'EMISSION'}:
- material.node_tree.links.new(source, before.inputs['Base Color' if before.type == 'BSDF_PRINCIPLED' else 'Color'])
+ material.node_tree.links.new(source, color_input(before))
def resolve_layers(scene, apply):
@@ -681,10 +702,12 @@ def resolve_layers(scene, apply):
def pbr_targets(material):
- """Principled inputs that carry projected PBR maps: {'roughness'|'metallic'|'normal': input socket}.
+ """Inputs that carry projected PBR maps: {channel: input socket}.
- The normal entry is the Normal Map node's Color input. Only linked inputs are returned,
- so unlinked constant values are left alone.
+ roughness and metallic are Principled inputs, normal is the Normal Map node's Color input and
+ height the Displacement node's Height input; these are returned only when linked, so unlinked
+ constant values are left alone. emission is the Principled Emission Color, returned even when
+ unlinked: a material without an emission map is black there, and an edit may add the glow.
"""
shader = material.node_tree.nodes.get(material.get('_sg_mask_shader', ''))
if not shader or shader.type != 'BSDF_PRINCIPLED':
@@ -696,6 +719,15 @@ def pbr_targets(material):
normal = shader.inputs['Normal'].links[0].from_node if shader.inputs['Normal'].links else None
if normal and normal.type == 'NORMAL_MAP' and normal.inputs['Color'].links:
targets['normal'] = normal.inputs['Color']
+ out = output_node(material)
+ displacement = (out.inputs['Displacement'].links[0].from_node
+ if out and 'Displacement' in out.inputs and out.inputs['Displacement'].links else None)
+ if displacement and displacement.type == 'DISPLACEMENT' and displacement.inputs['Height'].links:
+ targets['height'] = displacement.inputs['Height']
+ for name in ('Emission Color', 'Emission'): # 'Emission' before Blender 4.0
+ if name in shader.inputs:
+ targets['emission'] = shader.inputs[name]
+ break
return targets
@@ -730,8 +762,9 @@ def extract_pbr_maps(manager, context, jobs, settings, progress=None):
*jobs* are dicts with 'image' (the composited edit), 'mask' (write mask), 'dir' and
'rotation' (camera-to-world 3x3); maps are written into each job's 'dir' as
- pbr-<channel>.png and listed in job['maps']. *settings* names the channels wanted and
- the models, mirroring the scene's PBR settings. Raises RuntimeError on a model error.
+ pbr-<channel>.png and listed in job['maps']. *settings* names the channels wanted
+ (albedo, roughness, metallic, normal, height, emission) and the models and emission
+ detector, mirroring the scene's PBR settings. Raises RuntimeError on a model error.
"""
from PIL import Image, ImageEnhance
import io
@@ -751,18 +784,22 @@ def extract_pbr_maps(manager, context, jobs, settings, progress=None):
passes = []
want = settings['channels']
source, normal_model = settings.get('albedo_source', 'marigold'), settings.get('normal_model', 'marigold')
+ emission = settings.get('emission', {})
+ residual_emission = 'emission' in want and emission.get('method', 'residual') == 'residual'
if 'albedo' in want and source == 'marigold_v2':
passes.append('v2_albedo')
if 'normal' in want and normal_model == 'marigold_v2':
passes.append('v2_normals')
if want & {'roughness', 'metallic'} or ('albedo' in want and source == 'marigold'):
passes.append('appearance')
- if 'albedo' in want and source == 'lighting':
+ if ('albedo' in want and source == 'lighting') or residual_emission:
passes.append('lighting')
if 'albedo' in want and source == 'delight':
passes.append('delight')
if 'normal' in want and normal_model != 'marigold_v2':
passes.append('v1_normals')
+ if 'height' in want:
+ passes.append('depth')
total = max(len(passes) * len(jobs), 1)
done = 0
@@ -775,8 +812,8 @@ def extract_pbr_maps(manager, context, jobs, settings, progress=None):
# The edit model (Qwen or SDXL) is still loaded; free it before the PBR models load.
flush('Masked Edit PBR pre-load')
- for name in passes:
- if name == 'appearance' and done and passes[0].startswith('v2'):
+ for index, name in enumerate(passes):
+ if index and passes[index - 1].startswith('v2') and not name.startswith('v2'):
# The Qwen-Image-Edit base used by Marigold V2 must leave memory for Marigold v1.
flush('Masked Edit PBR before Marigold v1')
for job in jobs:
@@ -803,14 +840,44 @@ def extract_pbr_maps(manager, context, jobs, settings, progress=None):
elif name == 'lighting':
maps = check(manager.generate_pbr_maps(context, image, model_name='prs-eth/marigold-iid-lighting-v1-1'),
'Marigold IID-Lighting')
- save(job, 'albedo', maps[0])
+ if 'albedo' in want and source == 'lighting':
+ save(job, 'albedo', maps[0])
+ if residual_emission:
+ # albedo, shading, non-diffuse residual; the residual becomes emission below
+ path = Path(job['dir']) / 'pbr-lighting-residual.png'
+ path.write_bytes(check(maps[2] if len(maps) > 2 else None, 'Marigold IID-Lighting residual'))
+ job['residual'] = str(path)
elif name == 'delight':
save(job, 'albedo', check(manager.generate_delight_map(context, image), 'StableDelight'))
elif name == 'v1_normals':
maps = check(manager.generate_pbr_maps(context, image, model_name='prs-eth/marigold-normals-lcm-v0-1'),
'Marigold normals')
save(job, 'normal', world_normals(maps[0], job['rotation']))
+ elif name == 'depth':
+ maps = check(manager.generate_pbr_maps(context, image, model_name='prs-eth/marigold-depth-lcm-v1-0'),
+ 'Marigold depth')
+ save(job, 'height', maps[0])
done += 1
+ if 'emission' in want:
+ # The same detectors as generation (pbr_emission.py), on each edited view.
+ threshold = emission.get('threshold', 0.2)
+ for job in jobs:
+ if residual_emission:
+ # Gated by the view's metallic when that map is being updated, as in generation.
+ metallic_path = job.get('maps', {}).get('metallic')
+ with Image.open(job['residual']) as residual:
+ metallic = None
+ if metallic_path:
+ with Image.open(metallic_path) as metal:
+ metallic = metal.convert('L')
+ result = emission_from_residual(residual, metallic, threshold)
+ else:
+ with Image.open(job['image']) as view:
+ result = emission_from_hsv(view, emission.get('saturation_min', 0.5),
+ emission.get('value_min', 0.85), emission.get('bloom', 5.0), threshold)
+ buf = io.BytesIO()
+ result.save(buf, format='PNG')
+ save(job, 'emission', buf.getvalue())
if 'albedo' in want and settings.get('auto_saturation'):
from .pbr import _PBRMixin
for job in jobs:
@@ -829,13 +896,15 @@ def extract_pbr_maps(manager, context, jobs, settings, progress=None):
return jobs
-def add_pbr_layers(material, layer, maps, use_albedo):
+def add_pbr_layers(material, layer, maps, use_albedo, emission_strength=2.5):
"""Layer one edited view's PBR maps over the material's existing channels.
*layer* names the view's colour mix and its projected texture (from project_view). Each
channel gets a mix with the same factor as the colour layer, so the maps change exactly
where the colour did. With *use_albedo*, the colour layer shows the edit's albedo instead
- of its lit image, matching a material whose base colour is extracted albedo.
+ of its lit image, matching a material whose base colour is extracted albedo. A material
+ without an emission map gets one that is black outside the edit, and an Emission Strength
+ of *emission_strength* if it had none.
"""
nodes, links = material.node_tree.nodes, material.node_tree.links
mix, texture = nodes.get(layer['mix']), nodes.get(layer['texture'])
@@ -854,9 +923,23 @@ def add_pbr_layers(material, layer, maps, use_albedo):
texture.image = load(maps['albedo'], 'sRGB')
added.append('albedo')
for channel, target in pbr_targets(material).items():
- if not maps.get(channel) or not target.links:
+ if not maps.get(channel):
+ continue
+ if target.links:
+ previous = target.links[0].from_socket
+ elif channel == 'emission':
+ # No emission map yet: black elsewhere (not the input's default colour, which
+ # would glow over the whole object once the strength is raised).
+ black = nodes.new('ShaderNodeRGB')
+ black.outputs[0].default_value = (0.0, 0.0, 0.0, 1.0)
+ black.label = 'Masked Edit no emission'
+ previous = black.outputs[0]
+ shader = target.node
+ strength = shader.inputs.get('Emission Strength')
+ if strength is not None and not strength.links and strength.default_value == 0.0:
+ strength.default_value = emission_strength
+ else:
continue
- previous = target.links[0].from_socket
tex = nodes.new('ShaderNodeTexImage')
tex.image = load(maps[channel], 'Non-Color')
tex.label = f'Masked Edit {channel}'
@@ -925,7 +1008,7 @@ def project_view(context, objects, camera, image_path, write_path, material_id,
coverage.node.name = COVERAGE
original_shader = nodes.get(material.get('_sg_mask_shader', ''))
if original_shader:
- links.new(mix.outputs[0], original_shader.inputs['Base Color' if original_shader.type == 'BSDF_PRINCIPLED' else 'Color'])
+ links.new(mix.outputs[0], color_input(original_shader))
links.new(original_shader.outputs[0], output_node(material).inputs['Surface'])
# Embed input assets so saving the blend preserves the edit preview.
for node in nodes:
@@ -943,7 +1026,7 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
@classmethod
def poll(cls, context):
return (cls._active is None and not sg_modal_active(context)
- and context.scene.model_architecture in {'sdxl', 'qwen_image_edit', 'qwen_image_21'}
+ and context.scene.model_architecture in MASKED_EDIT_ARCHITECTURES
and not any(o.sg_mask_original for o in context.scene.objects))
def execute(self, context):
@@ -1016,8 +1099,12 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
for obj in self.objects:
if obj.active_material.get('_sg_mask_shader'):
targets = pbr_targets(obj.active_material)
- channels |= {c for c in targets if getattr(self.scene, f'pbr_map_{c}', True)}
- if targets and self.pbr_use_albedo:
+ mapped = {c for c, socket in targets.items() if socket.links}
+ channels |= {c for c in mapped if getattr(self.scene, f'pbr_map_{c}', True)}
+ if ('emission' in targets and self.scene.pbr_decomposition
+ and self.scene.pbr_map_emission):
+ channels.add('emission') # an edit may add glow where there was none
+ if mapped and self.pbr_use_albedo:
channels.add('albedo')
self.pbr_channels = channels
type(self)._active = self
@@ -1096,7 +1183,7 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
server = context.preferences.addons[ADDON_PKG].preferences.server_address
self.uploads = {}
paths = {'render': render, 'mask': generation}
- if context.scene.model_architecture.startswith('qwen') and context.scene.sg_masked_overlay:
+ if context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.sg_masked_overlay:
paths['overlay'] = overlay
if depth:
paths['depth'] = depth
@@ -1109,7 +1196,7 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
uploaded['name'] = subfolder.rstrip('/') + '/' + uploaded['name']
self.uploads[key] = uploaded
manager = WorkflowManager(self)
- if context.scene.model_architecture.startswith('qwen'):
+ if context.scene.model_architecture in QWEN_ARCHITECTURES:
data = manager.generate_qwen_refine(context, camera_id=0, masked_edit={
'prompt': context.scene.sg_masked_prompt,
'overlay': self.uploads.get('overlay'),
@@ -1189,7 +1276,7 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
render, mask, self.current_dir,
self.scene.sg_masked_feather, self.scene.sg_masked_expand)
depth = None
- if self.scene.model_architecture.startswith('qwen') and self.scene.sg_masked_use_depth:
+ if self.scene.model_architecture in QWEN_ARCHITECTURES and self.scene.sg_masked_use_depth:
self.scene.sg_masked_status = f'Preparing depth {self.index+1}/{len(self.ranked)}: {camera.name}'
depth = render_depth_view(context, camera, self.current_dir)
self.result = self.current_dir / 'generated.png'
@@ -1245,7 +1332,12 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
scene = self.scene
settings = {'channels': set(self.pbr_channels), 'albedo_source': scene.pbr_albedo_source,
'normal_model': getattr(scene, 'pbr_normal_model', 'marigold'),
- 'auto_saturation': bool(scene.pbr_albedo_auto_saturation)}
+ 'auto_saturation': bool(scene.pbr_albedo_auto_saturation),
+ 'emission': {'method': scene.pbr_emission_method,
+ 'threshold': scene.pbr_emission_threshold,
+ 'saturation_min': scene.pbr_emission_saturation_min,
+ 'value_min': scene.pbr_emission_value_min,
+ 'bloom': scene.pbr_emission_bloom}}
self.phase = 'pbr'
self._error = ''
self._stage = 'Updating PBR Maps'
@@ -1283,7 +1375,8 @@ class SG_OT_MaskedEdit(bpy.types.Operator):
for name, layer in job['layers'].items():
obj = by_name.get(name)
if obj:
- added = add_pbr_layers(obj.active_material, layer, job.get('maps', {}), self.pbr_use_albedo)
+ added = add_pbr_layers(obj.active_material, layer, job.get('maps', {}), self.pbr_use_albedo,
+ self.scene.pbr_emission_strength)
job.setdefault('added', {})[name] = added
channels = ', '.join(sorted(self.pbr_channels))
self.report_rows.append({'status': 'pbr_updated', 'channels': sorted(self.pbr_channels),
@@ -1411,7 +1504,7 @@ def draw_masked_edit_controls(layout, context):
layout.prop(scene, 'sg_masked_feather')
if scene.pbr_decomposition:
layout.prop(scene, 'sg_masked_update_pbr')
- if scene.model_architecture.startswith('qwen'):
+ if scene.model_architecture in QWEN_ARCHITECTURES:
layout.prop(scene, 'sg_masked_overlay')
layout.prop(scene, 'sg_masked_use_depth')
layout.prop(scene, 'sg_masked_use_custom_prompt', text='Custom Guidance Prompt', toggle=True, icon='TEXT')
@@ -1421,10 +1514,10 @@ def draw_masked_edit_controls(layout, context):
row = box.row(align=True)
row.prop(scene, 'sg_masked_custom_prompt', text='')
row.operator('stablegen.reset_masked_prompt', text='', icon='FILE_REFRESH')
- elif scene.model_architecture == 'sdxl':
+ elif scene.model_architecture in SDXL_GRAPH_ARCHITECTURES:
layout.prop(scene, 'sg_masked_strength')
else:
- layout.label(text='Masked Edit supports Qwen Image Edit and SDXL.', icon='INFO')
+ layout.label(text='Masked Edit supports Qwen, FIBO, MOSS and SDXL.', icon='INFO')
layout.label(text='Uses the current model and existing cameras.')
if scene.sg_masked_status:
layout.label(text=scene.sg_masked_status)
@@ -1482,9 +1575,11 @@ def register_properties():
bpy.types.Scene.sg_masked_strength = bpy.props.FloatProperty(description="Denoising strength inside the prepared selection. Lower values preserve more of the source image; higher values allow larger changes. Selection expansion and feathering control the boundary separately.", name="Edit strength", default=0.85, min=0.05, max=1.0)
bpy.types.Scene.sg_masked_update_pbr = bpy.props.BoolProperty(
name='Update PBR Maps', default=True,
- description='On PBR materials, extract roughness, metallic and normal (and albedo, when it is the base '
- 'colour) from the edited views with the PBR map settings, so the edited region gets its new '
- 'material instead of the old surface\'s. Runs once after all views are edited')
+ description='On PBR materials, extract the material\'s maps (roughness, metallic, normal, height, and '
+ 'albedo when it is the base colour) from the edited views with the PBR map settings, so the '
+ 'edited region gets its new material instead of the old surface\'s. With Emission enabled in '
+ 'the PBR settings, glowing parts of the edit also become emission. Runs once after all views '
+ 'are edited')
bpy.types.Scene.sg_masked_status = bpy.props.StringProperty(default='')
keyconfig = bpy.context.window_manager.keyconfigs.addon
if keyconfig:
diff --git a/stablegen/texturing/moss_models.py b/stablegen/texturing/moss_models.py
new file mode 100644
index 0000000..19abb61
--- /dev/null
+++ b/stablegen/texturing/moss_models.py
@@ -0,0 +1,221 @@
+"""MOSS-Image model defaults and the SDXL-graph adapter.
+
+MOSS-Image reuses StableGen's SDXL workflows: txt2img, img2img refinement,
+classical inpainting and Differential Diffusion. The adapter below swaps only
+the model layer of a finished SDXL graph and removes the SDXL-only extensions
+(LoRA, CLIP skip, IPAdapter and ControlNet) that have no MOSS counterpart.
+
+Two ComfyUI setups are supported. ComfyUI 0.42 and later load MOSS-Image
+with the core loaders and already apply its flow shift; 0.42.3 adds the
+``MOSSImageControl`` node for the color/depth control adapter. Older servers
+use the OpenMOSS ``moss-image`` custom node, whose model needs an explicit
+``ModelSamplingSD3`` shift. The core model must not receive that node: it
+would also change the timestep multiplier.
+"""
+
+from __future__ import annotations
+
+MOSS_IMAGE_ARCHITECTURE = "moss_image"
+MOSS_IMAGE_TEXT_ENCODER = "qwen3.5_9b_int8_convrot.safetensors"
+MOSS_IMAGE_VAE = "flux2-vae_small.safetensors"
+# darask0/MOSS-Image-color-depth-control, as repacked by Comfy-Org.
+MOSS_IMAGE_CONTROL_LORA = "moss_image_color_depth_control.safetensors"
+MOSS_IMAGE_SHIFT = 5.0
+# The model card skips block 22 on the unconditional branch.
+MOSS_IMAGE_UNCOND_SKIP_LAYERS = "22"
+# Nodes that tell the two server setups apart.
+MOSS_PLUGIN_LOADER = "MOSSImageUNETLoader"
+MOSS_CONTROL_NODE = "MOSSImageControl"
+
+# Nodes removed from SDXL graphs, mapped as {output index: passthrough input}.
+_BYPASSED_NODES = {
+ "CLIPSetLastLayer": {0: "clip"},
+ "LoraLoader": {0: "model", 1: "clip"},
+ "LoraLoaderModelOnly": {0: "model"},
+ "IPAdapterUnifiedLoader": {0: "model"},
+ "IPAdapter": {0: "model"},
+ "ControlNetApplyAdvanced": {0: "positive", 1: "negative"},
+}
+_OUTPUT_NODES = {"SaveImageWebsocket", "SaveImage", "PreviewImage"}
+_SAMPLERS = {"KSampler", "KSamplerAdvanced"}
+
+
+def _is_reference(value) -> bool:
+ return (
+ isinstance(value, list)
+ and len(value) == 2
+ and isinstance(value[0], (str, int))
+ and isinstance(value[1], int)
+ )
+
+
+def _next_id(prompt, start):
+ node_id = start
+ while str(node_id) in prompt:
+ node_id += 1
+ return str(node_id)
+
+
+def _rewire(prompt, mapping, skip=()):
+ """Replace every link ``(node, output)`` found in *mapping*."""
+ for node_id, node in prompt.items():
+ if node_id in skip:
+ continue
+ inputs = node.get("inputs", {})
+ for name, value in list(inputs.items()):
+ if _is_reference(value):
+ target = mapping.get((str(value[0]), value[1]))
+ if target is not None:
+ inputs[name] = list(target)
+
+
+def _drop_unreachable(prompt):
+ """Remove nodes that no output node depends on (orphaned loaders)."""
+ reachable = set()
+ pending = [node_id for node_id, node in prompt.items()
+ if node.get("class_type") in _OUTPUT_NODES]
+ while pending:
+ node_id = str(pending.pop())
+ if node_id in reachable or node_id not in prompt:
+ continue
+ reachable.add(node_id)
+ for value in prompt[node_id].get("inputs", {}).values():
+ if _is_reference(value):
+ pending.append(str(value[0]))
+ if reachable:
+ for node_id in [node_id for node_id in prompt if node_id not in reachable]:
+ del prompt[node_id]
+
+
+def _add(prompt, start, class_type, title, inputs):
+ node_id = _next_id(prompt, start)
+ prompt[node_id] = {"inputs": inputs, "class_type": class_type, "_meta": {"title": title}}
+ return node_id
+
+
+def convert_sdxl_graph_to_moss(
+ prompt,
+ model_name: str,
+ *,
+ native: bool = True,
+ depth_image: str | None = None,
+ depth_strength: float = 1.0,
+ depth_end: float = 0.5,
+ text_encoder: str = MOSS_IMAGE_TEXT_ENCODER,
+ vae: str = MOSS_IMAGE_VAE,
+ control_lora: str = MOSS_IMAGE_CONTROL_LORA,
+):
+ """Rewrite a StableGen SDXL API graph in place to run MOSS-Image.
+
+ Every ``CheckpointLoaderSimple`` becomes a MOSS diffusion-model loader
+ with separate Qwen3.5 text-encoder and FLUX.2 VAE loaders, for the core
+ nodes (``native``) or the older custom node. SDXL-only extensions are
+ bypassed so their conditioning and model links reconnect to their inputs.
+ ``InpaintModelConditioning`` becomes a VAE encode with a latent noise
+ mask: its concat latent is the channel MOSS reads its control maps from.
+ Empty latents switch to the FLUX.2 format, and samplers get the model
+ card's unconditional layer skip. With ``depth_image`` (an uploaded image
+ name, core nodes only) the color/depth adapter conditions every sampler.
+ Returns the removed SDXL-only class types for reporting.
+ """
+ removed = []
+ for node_id, node in list(prompt.items()):
+ if node.get("class_type") != "CheckpointLoaderSimple":
+ continue
+ if native:
+ clip_id = _add(prompt, 800, "CLIPLoader", "Load MOSS-Image Qwen3.5 Text Encoder",
+ {"clip_name": text_encoder, "type": "moss_image", "device": "default"})
+ loader = "UNETLoader"
+ else:
+ clip_id = _add(prompt, 800, "MOSSImageCLIPLoader", "Load MOSS-Image Qwen3.5 Text Encoder",
+ {"clip_name": text_encoder, "device": "default"})
+ loader = MOSS_PLUGIN_LOADER
+ vae_id = _add(prompt, 800, "VAELoader", "Load MOSS-Image VAE", {"vae_name": vae})
+ prompt[node_id] = {
+ "inputs": {"unet_name": model_name, "weight_dtype": "default"},
+ "class_type": loader,
+ "_meta": {"title": "Load MOSS-Image Diffusion Model"},
+ }
+ _rewire(prompt, {(node_id, 1): (clip_id, 0), (node_id, 2): (vae_id, 0)})
+
+ # Bypass repeatedly: LoRA and ControlNet chains link to one another.
+ changed = True
+ while changed:
+ changed = False
+ for node_id, node in list(prompt.items()):
+ passthrough = _BYPASSED_NODES.get(node.get("class_type"))
+ if passthrough is None:
+ continue
+ inputs = node.get("inputs", {})
+ mapping = {
+ (node_id, output): tuple(inputs[name])
+ for output, name in passthrough.items()
+ if _is_reference(inputs.get(name))
+ }
+ del prompt[node_id]
+ _rewire(prompt, mapping)
+ removed.append(node["class_type"])
+ changed = True
+
+ for node_id, node in list(prompt.items()):
+ if node.get("class_type") != "InpaintModelConditioning":
+ continue
+ inputs = node["inputs"]
+ latent_id = _add(prompt, 840, "VAEEncode", "Encode Inpaint Image",
+ {"pixels": inputs["pixels"], "vae": inputs["vae"]})
+ if inputs.get("noise_mask", True):
+ latent_id = _add(prompt, 840, "SetLatentNoiseMask", "Inpaint Noise Mask",
+ {"samples": [latent_id, 0], "mask": inputs["mask"]})
+ del prompt[node_id]
+ _rewire(prompt, {
+ (node_id, 0): tuple(inputs["positive"]),
+ (node_id, 1): tuple(inputs["negative"]),
+ (node_id, 2): (latent_id, 0),
+ })
+
+ for node in prompt.values():
+ if node.get("class_type") == "EmptyLatentImage":
+ node["class_type"] = "EmptyFlux2LatentImage"
+ node.setdefault("_meta", {})["title"] = "Empty FLUX.2 Latent"
+
+ if depth_image and native:
+ for node_id, node in list(prompt.items()):
+ if node.get("class_type") != "UNETLoader":
+ continue
+ lora_id = _add(prompt, 860, "LoraLoaderModelOnly", "MOSS-Image Color/Depth Control Adapter",
+ {"lora_name": control_lora, "strength_model": 1.0, "model": [node_id, 0]})
+ _rewire(prompt, {(node_id, 0): (lora_id, 0)}, skip={lora_id})
+
+ for node_id, node in list(prompt.items()):
+ if node.get("class_type") not in _SAMPLERS:
+ continue
+ inputs = node["inputs"]
+ model = inputs.get("model")
+ if not native and _is_reference(model):
+ model = [_add(prompt, 820, "ModelSamplingSD3", "MOSS-Image Flow Shift",
+ {"shift": MOSS_IMAGE_SHIFT, "model": model}), 0]
+ if _is_reference(model):
+ inputs["model"] = [_add(prompt, 820, "SkipLayerGuidanceDiTSimple", "MOSS-Image Uncond Layer Skip", {
+ "double_layers": "",
+ "single_layers": MOSS_IMAGE_UNCOND_SKIP_LAYERS,
+ "start_percent": 0.0,
+ "end_percent": 1.0,
+ "model": model,
+ }), 0]
+ if depth_image and native:
+ decoder = next((n for n in prompt.values() if n.get("class_type") == "VAEDecode"), None)
+ depth_id = _add(prompt, 880, "LoadImage", "Load Depth Map", {"image": depth_image})
+ control_id = _add(prompt, 880, MOSS_CONTROL_NODE, "MOSS-Image Depth Control", {
+ "positive": inputs["positive"],
+ "negative": inputs["negative"],
+ "vae": decoder["inputs"]["vae"],
+ "depth_map": [depth_id, 0],
+ "strength": depth_strength,
+ "start_percent": 0.0,
+ "end_percent": depth_end,
+ })
+ inputs["positive"] = [control_id, 0]
+ inputs["negative"] = [control_id, 1]
+
+ _drop_unreachable(prompt)
+ return removed
diff --git a/stablegen/texturing/pbr.py b/stablegen/texturing/pbr.py
index faa7e42..3d811a2 100644
--- a/stablegen/texturing/pbr.py
+++ b/stablegen/texturing/pbr.py
@@ -18,6 +18,7 @@ from PIL import Image, ImageEnhance
import bpy # pylint: disable=import-error
from ..utils import get_file_path, get_dir_path, get_generation_dirs
from ..timeout_config import get_timeout
+from .pbr_emission import emission_from_hsv, emission_from_residual
_ADDON_PKG = __package__.rsplit('.', 1)[0]
@@ -1458,12 +1459,12 @@ class _PBRMixin:
# ── Emission extraction methods ───────────────────────────────────
def _gate_emission_residual(self, context, camera_id):
- """Gate the IID-Lighting residual with roughness/metallic to
- produce a cleaner emission map.
+ """Gate the IID-Lighting residual with metallic to produce a
+ cleaner emission map (see emission_from_residual).
- emission = residual × (1 − metallic) × roughness_mask, then
- threshold. High-metallic + low-roughness regions are likely
- specular reflections, not true emission.
+ emission = residual × (1 − metallic), then a soft threshold.
+ High-metallic regions are likely specular reflections, not true
+ emission.
"""
scene = context.scene
cam_maps = self._pbr_maps.get(camera_id, {})
@@ -1475,33 +1476,13 @@ class _PBRMixin:
threshold = getattr(scene, 'pbr_emission_threshold', 0.2)
try:
- residual = np.array(Image.open(residual_path).convert('RGB')).astype(np.float32) / 255.0
-
- # Optionally gate with metallic if available — high metallic
- # surfaces produce strong specular that isn't true emission.
+ # Gate with metallic when available (it may differ in size when
+ # tiling/super-res settings aren't identical; it is resized).
metal_path = cam_maps.get('metallic')
- if metal_path and os.path.exists(metal_path):
- metal_img = Image.open(metal_path).convert('L')
- # Resize metallic to match residual dims (they may differ
- # when tiling/super-res settings aren't identical).
- res_h, res_w = residual.shape[:2]
- if metal_img.size != (res_w, res_h):
- metal_img = metal_img.resize(
- (res_w, res_h), Image.Resampling.BILINEAR)
- metallic = np.array(metal_img).astype(np.float32) / 255.0
- gate = (1.0 - metallic)[:, :, np.newaxis]
- residual = residual * gate
-
- # Apply soft threshold — pixels below the threshold are
- # smoothly faded out rather than hard-clipped.
- luminance = np.mean(residual, axis=2)
- # Smooth fade: rescale [0, threshold] → 0, [threshold, 1] → preserved
- fade = np.clip((luminance - threshold * 0.5) / max(threshold * 0.5, 1e-6),
- 0.0, 1.0)[:, :, np.newaxis]
- emission = residual * fade
-
- emission_img = Image.fromarray(
- np.clip(emission * 255, 0, 255).astype(np.uint8), mode='RGB')
+ metal_img = (Image.open(metal_path).convert('L')
+ if metal_path and os.path.exists(metal_path) else None)
+ emission_img = emission_from_residual(
+ Image.open(residual_path), metal_img, threshold)
emission_path = get_file_path(
context, "pbr", subtype="emission",
camera_id=camera_id,
@@ -1526,42 +1507,8 @@ class _PBRMixin:
threshold = getattr(scene, 'pbr_emission_threshold', 0.3)
try:
- original = np.array(Image.open(image_path).convert('RGB'))
- rgb_f = original.astype(np.float32) / 255.0
-
- # RGB → HSV
- maxc = rgb_f.max(axis=2)
- minc = rgb_f.min(axis=2)
- delta = maxc - minc
- saturation = np.where(maxc > 1e-6, delta / maxc, 0.0)
- value = maxc
-
- # Build binary mask: high saturation AND high value
- mask = ((saturation >= sat_min) & (value >= val_min)).astype(np.float32)
-
- # Apply bloom (Gaussian blur) to soften edges
- if bloom_radius > 0:
- try:
- import cv2
- ksize = int(bloom_radius * 4) | 1 # must be odd
- mask = cv2.GaussianBlur(mask, (ksize, ksize), bloom_radius)
- except ImportError:
- # Fallback: simple box blur via PIL
- from PIL import ImageFilter
- mask_pil = Image.fromarray(
- (mask * 255).astype(np.uint8), mode='L')
- mask_pil = mask_pil.filter(
- ImageFilter.GaussianBlur(radius=bloom_radius))
- mask = np.array(mask_pil).astype(np.float32) / 255.0
-
- # Apply threshold on the blurred mask
- mask = np.where(mask > threshold, mask, 0.0)
-
- # Multiply mask by original RGB to get coloured emission
- emission = rgb_f * mask[:, :, np.newaxis]
-
- emission_img = Image.fromarray(
- np.clip(emission * 255, 0, 255).astype(np.uint8), mode='RGB')
+ emission_img = emission_from_hsv(
+ Image.open(image_path), sat_min, val_min, bloom_radius, threshold)
emission_path = get_file_path(
context, "pbr", subtype="emission",
camera_id=camera_id,
diff --git a/stablegen/texturing/pbr_emission.py b/stablegen/texturing/pbr_emission.py
new file mode 100644
index 0000000..fcadcc6
--- /dev/null
+++ b/stablegen/texturing/pbr_emission.py
@@ -0,0 +1,50 @@
+"""Emission detectors shared by PBR generation (pbr.py) and Masked Edit's PBR update.
+
+Plain numpy/OpenCV/PIL, so both pipelines produce identical maps from the same view.
+"""
+
+import cv2
+import numpy as np
+from PIL import Image
+
+
+def emission_from_residual(residual_img, metallic_img=None, threshold=0.2):
+ """Emission from the IID-Lighting non-diffuse residual (an RGB image).
+
+ *metallic_img* (an 'L' image, resized to the residual when needed)
+ suppresses the specular reflections of metal, which are not emission.
+ A soft cutoff then removes weak residual: luminance below half the
+ threshold is dropped and full strength is reached at the threshold.
+ Returns an RGB image.
+ """
+ residual = np.asarray(residual_img.convert('RGB'), np.float32) / 255.0
+ if metallic_img is not None:
+ res_h, res_w = residual.shape[:2]
+ if metallic_img.size != (res_w, res_h):
+ metallic_img = metallic_img.resize((res_w, res_h), Image.Resampling.BILINEAR)
+ metallic = np.asarray(metallic_img.convert('L'), np.float32) / 255.0
+ residual = residual * (1.0 - metallic)[:, :, np.newaxis]
+ luminance = np.mean(residual, axis=2)
+ fade = np.clip((luminance - threshold * 0.5) / max(threshold * 0.5, 1e-6),
+ 0.0, 1.0)[:, :, np.newaxis]
+ return Image.fromarray(np.clip(residual * fade * 255, 0, 255).astype(np.uint8), mode='RGB')
+
+
+def emission_from_hsv(image, sat_min=0.5, val_min=0.85, bloom=5.0, threshold=0.2):
+ """Emission from bright, saturated pixels of a generated image.
+
+ Glowing parts keep their colour intensity while normally lit surfaces
+ desaturate under bright light. The detection mask is blurred by *bloom*
+ pixels, cut at *threshold* and multiplied by the image's own colour.
+ Returns an RGB image.
+ """
+ rgb = np.asarray(image.convert('RGB'), np.float32) / 255.0
+ maxc = rgb.max(axis=2)
+ minc = rgb.min(axis=2)
+ saturation = np.where(maxc > 1e-6, (maxc - minc) / np.maximum(maxc, 1e-6), 0.0)
+ mask = ((saturation >= sat_min) & (maxc >= val_min)).astype(np.float32)
+ if bloom > 0:
+ ksize = int(bloom * 4) | 1 # must be odd
+ mask = cv2.GaussianBlur(mask, (ksize, ksize), bloom)
+ mask = np.where(mask > threshold, mask, 0.0)
+ return Image.fromarray(np.clip(rgb * mask[:, :, np.newaxis] * 255, 0, 255).astype(np.uint8), mode='RGB')
diff --git a/stablegen/texturing/print_export.py b/stablegen/texturing/print_export.py
index 65afa27..73b58c3 100644
--- a/stablegen/texturing/print_export.py
+++ b/stablegen/texturing/print_export.py
@@ -389,7 +389,9 @@ class StableGenClearQuantizationPreview(bpy.types.Operator):
pass
except Exception:
pass
-
+ return {'FINISHED'}
+
+
def _generate_blue_noise_tile(size=64, seed=42):
"""Generate a toroidal blue noise threshold tile via FFT spectral shaping.
diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.py
index 747242c..7f5001f 100644
--- a/stablegen/texturing/projection.py
+++ b/stablegen/texturing/projection.py
@@ -1,4 +1,4 @@
-from ..feature_flags import experimental_enabled
+from ..core.feature_flags import experimental_enabled
import bpy
import os
from math import atan, tan, pi
@@ -10,6 +10,7 @@ from mathutils import Matrix, Vector
from .jobs import operation
from .projection_cache import eligible as _cache_eligible, configuration as _cache_configuration, graph_state as _graph_state, asset_state as _asset_state
from .svm_budget import SVM_STACK_SIZE, estimate_svm_stack
+from ..core.architectures import EDIT_ARCHITECTURES, QWEN_21_ARCHITECTURES, QWEN_ARCHITECTURES, SDXL_GRAPH_ARCHITECTURES
_SG_BUFFER_UV_NAME = "_SG_ProjectionBuffer"
@@ -1807,7 +1808,7 @@ def project_image(
and getattr(context.scene, 'sg_silhouette_feather', 0) > 0)
if surface_blend:
if (context.scene.generation_method in {'local_edit', 'refine'}
- or (context.scene.model_architecture.startswith('qwen')
+ or (context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.qwen_generation_method == 'local_edit')):
raise ValueError('Surface Blend preview supports base multi-view projection; use Local Unsharpen for local refinement')
# A newly generated view changes the joint solution. Do not reuse a
@@ -1872,7 +1873,7 @@ def project_image(
return mult
# Compute offsets based on recursion level
- is_local_edit = (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit'))
+ is_local_edit = (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.qwen_generation_method == 'local_edit'))
if is_local_edit:
last_node_x = last_node.location[0] if last_node else 0
x_offset = 1000 + level * 800 + last_node_x + 200 if context.scene.early_priority else 1000 + level * 600 + last_node_x + 200
@@ -2535,7 +2536,7 @@ def project_image(
# Create the material
to_switch = False
- is_local_edit = (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit'))
+ is_local_edit = (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.qwen_generation_method == 'local_edit'))
if is_local_edit and not context.scene.overwrite_material:
# Copy active material
mat = obj.active_material.copy()
@@ -2630,8 +2631,8 @@ def project_image(
getattr(context.scene, 'sg_rework_projection_guard', False),
getattr(context.scene, 'qwen_use_confidence_context', False),
experimental_enabled(context.scene, 'qwen_use_projection_write_masks'),
- context.scene.model_architecture == 'sdxl',
- context.scene.model_architecture == 'qwen_image_21',
+ context.scene.model_architecture in SDXL_GRAPH_ARCHITECTURES,
+ context.scene.model_architecture in QWEN_21_ARCHITECTURES,
))
legacy_incremental_update = (
((context.scene.generation_method == 'sequential' and stop_index > 0)
@@ -2887,12 +2888,12 @@ def project_image(
return acquisition
# Voronoi mode flag: keep natural weights for non-generated cameras
- voronoi_active = (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')
+ voronoi_active = (context.scene.model_architecture in EDIT_ARCHITECTURES
and getattr(context.scene, 'qwen_voronoi_mode', False)
and context.scene.generation_method == 'sequential')
confidence_context_active = (
getattr(context.scene, 'qwen_use_confidence_context', False)
- and context.scene.model_architecture.startswith('qwen')
+ and context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.generation_method == 'sequential'
and context.scene.qwen_generation_method == 'generate'
and context.scene.qwen_context_render_mode
@@ -2991,7 +2992,7 @@ def project_image(
elif use_native_raycast:
# ── Native Raycast path (Blender 5.1+) ──
- is_local_edit_mode = (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit'))
+ is_local_edit_mode = (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.qwen_generation_method == 'local_edit'))
native_pre_factors = None
if (not is_local_edit_mode
and getattr(context.scene, 'sg_rework_acquisition_quality', False)):
@@ -3116,7 +3117,7 @@ def project_image(
is_local_edit_mode = (
context.scene.generation_method == 'local_edit'
- or (context.scene.model_architecture.startswith('qwen')
+ or (context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.qwen_generation_method == 'local_edit')
)
needs_frame_quality = (
@@ -3258,7 +3259,7 @@ def project_image(
use_qwen_write_mask = (
i > 0
and (i <= stop_index or stable_sequential)
- and context.scene.model_architecture.startswith('qwen')
+ and context.scene.model_architecture in QWEN_ARCHITECTURES
and context.scene.generation_method == 'sequential'
and context.scene.qwen_generation_method == 'generate'
and context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}
@@ -3266,11 +3267,11 @@ def project_image(
)
qwen_write_weight = None
use_sdxl_write_mask = (
- i > 0 and (i <= stop_index or stable_sequential) and (context.scene.model_architecture == 'sdxl') and (context.scene.generation_method == 'sequential')
+ i > 0 and (i <= stop_index or stable_sequential) and (context.scene.model_architecture in SDXL_GRAPH_ARCHITECTURES) and (context.scene.generation_method == 'sequential')
)
use_qwen21_generated_alpha = (
(i <= stop_index or stable_sequential)
- and context.scene.model_architecture == 'qwen_image_21'
+ and context.scene.model_architecture in QWEN_21_ARCHITECTURES
)
if (use_qwen_write_mask or use_sdxl_write_mask) and script_nodes_outputs:
current_weight = script_nodes_outputs[-1]
diff --git a/stablegen/texturing/projection_cache.py b/stablegen/texturing/projection_cache.py
index 90ce10d..661c0f9 100644
--- a/stablegen/texturing/projection_cache.py
+++ b/stablegen/texturing/projection_cache.py
@@ -4,6 +4,7 @@ import os
import hashlib
from array import array
import bpy
+from ..core.architectures import EDIT_ARCHITECTURES, QWEN_ARCHITECTURES
def _plain(value):
@@ -65,10 +66,10 @@ def eligible(scene):
# Edit passes, baked fields and joint surface solves change topology. Base
# sequential projection is shared by all texturing architectures; late
# write-mask/image resources are bound before activating their view.
- qwen = scene.model_architecture.startswith('qwen')
+ qwen = scene.model_architecture in QWEN_ARCHITECTURES
confidence = (qwen and scene.qwen_use_confidence_context
and scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'})
- voronoi = (scene.model_architecture in {'qwen_image_edit', 'qwen_image_21', 'flux2_klein'}
+ voronoi = (scene.model_architecture in EDIT_ARCHITECTURES
and scene.qwen_voronoi_mode)
surface = (scene.sg_guard_feather_method == 'SURFACE_BLEND'
and scene.sg_rework_projection_guard and scene.sg_silhouette_feather > 0)
@@ -91,7 +92,7 @@ def configuration(scene, cameras, mat_id, assets, meshes):
# the active camera is runtime state. Include each effective projection
# resolution, including the scene fallback for cameras without overrides.
from ..cameras.geometry import _get_camera_resolution
- from ..feature_flags import experimental_enabled
+ from ..core.feature_flags import experimental_enabled
prefixes = ('sg_guard_', 'sg_rework_', 'sg_silhouette_', 'sg_projection_',
'discard_', 'weight_', 'early_', 'visibility_', 'refine_',
'qwen_', 'bake_visibility', 'sg_allow_backface', 'sequential_', 'use_ipadapter',
diff --git a/stablegen/texturing/qwen_models.py b/stablegen/texturing/qwen_models.py
index 22a6342..93629b8 100644
--- a/stablegen/texturing/qwen_models.py
+++ b/stablegen/texturing/qwen_models.py
@@ -9,6 +9,18 @@ QWEN_IMAGE_21_TEXT_ENCODER = "qwen3vl_8b_w4a8.safetensors"
QWEN_IMAGE_21_VAE = "qwen_image_2.1_vae_bf16.safetensors"
QWEN_IMAGE_EDIT_ARCHITECTURE = "qwen_image_edit"
QWEN_IMAGE_21_ARCHITECTURE = "qwen_image_21"
+QWEN_IMAGE_21_TURBO_ARCHITECTURE = "qwen_image_21_turbo"
+FIBO_EDIT_ARCHITECTURE = "fibo_edit"
+# Qwen-Image 2.1 Turbo is distilled to one fixed 8-step schedule
+# (``sample_sigmas`` in its model_index.json, used by the official ComfyUI
+# templates through ManualSigmas). Standard schedulers do not reproduce it.
+QWEN_IMAGE_21_TURBO_STEPS = 8
+QWEN_IMAGE_21_TURBO_SIGMAS = (
+ "1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568, 0"
+)
+# Bria FIBO 2.0, as packaged by Comfy-Org/Fibo-2.0 for ComfyUI's core nodes.
+FIBO_TEXT_ENCODER = "qwen3vl_4b_int8_convrot.safetensors"
+FIBO_VAE = "flux2-vae.safetensors"
QWEN_IMAGE_21_RGBA_PREFIX = "This is an RGBA format image with transparency."
QWEN_IMAGE_21_RGBA_SUFFIX = (
"The image has an alpha channel and a transparent background."
@@ -73,8 +85,26 @@ def is_qwen_image_21_model(model_name: str) -> bool:
retained for filtering model choices and migrating files saved before the
dedicated architecture existed; generation dispatch uses the architecture.
"""
- normalized = (model_name or "").replace("\\", "/").rsplit("/", 1)[-1].lower()
- return bool(re.search(r"qwen[-_. ]*image[-_. ]*2[-_. ]*1(?:\D|$)", normalized))
+ return bool(re.search(r"qwen[-_. ]*image[-_. ]*2[-_. ]*1(?:\D|$)", _model_basename(model_name)))
+
+
+def is_qwen_image_21_turbo_model(model_name: str) -> bool:
+ """Return whether a Qwen-Image 2.1 model file is the few-step Turbo variant."""
+ return is_qwen_image_21_model(model_name) and "turbo" in _model_basename(model_name)
+
+
+def is_moss_image_model(model_name: str) -> bool:
+ """Return whether a diffusion model file belongs to MOSS-Image."""
+ return bool(re.search(r"moss[-_. ]*image", _model_basename(model_name)))
+
+
+def is_fibo_model(model_name: str) -> bool:
+ """Return whether a diffusion model file belongs to Bria FIBO."""
+ return "fibo" in _model_basename(model_name)
+
+
+def _model_basename(model_name: str) -> str:
+ return (model_name or "").replace("\\", "/").rsplit("/", 1)[-1].lower()
def is_qwen_architecture(architecture: str) -> bool:
@@ -82,6 +112,8 @@ def is_qwen_architecture(architecture: str) -> bool:
return architecture in {
QWEN_IMAGE_EDIT_ARCHITECTURE,
QWEN_IMAGE_21_ARCHITECTURE,
+ QWEN_IMAGE_21_TURBO_ARCHITECTURE,
+ FIBO_EDIT_ARCHITECTURE,
}
@@ -272,3 +304,14 @@ def remap_qwen_image_21_prompt(text: str, image_mapping: dict[int, int]) -> str:
converted,
flags=re.IGNORECASE,
)
+
+
+def fibo_prompt(text: str, image_mapping: dict[int, int] | None = None) -> str:
+ """Convert image references to FIBO 2.0's explicit ``<image_N>`` indices.
+
+ FIBO refers to its inputs by position only, so every reference is made
+ explicit. ``image_mapping`` renumbers them after the graph adapter has
+ moved the projected context into the first (edited) slot.
+ """
+ converted = remap_qwen_image_21_prompt(text, image_mapping or {})
+ return re.sub(r"<image([1-9]\d*)>", r"<image_\1>", converted, flags=re.IGNORECASE)
diff --git a/stablegen/texturing/rendering.py b/stablegen/texturing/rendering.py
index 74e06de..efff2c3 100644
--- a/stablegen/texturing/rendering.py
+++ b/stablegen/texturing/rendering.py
@@ -12,6 +12,7 @@ from .pose_lock import ensure_texturing_frame
from .jobs import operation, RenderRequest
from PIL import Image
import cv2
+from ..core.architectures import QWEN_ARCHITECTURES
_ADDON_PKG = __package__.rsplit('.', 1)[0]
@@ -1112,7 +1113,7 @@ def _export_emit_image_impl(context, to_export, camera_id=None, bg_color=(0.5, 0
else:
final_path = os.path.join(output_dir, f"{output_file}0001.png")
- if context.scene.visibility_vignette and (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit')):
+ if context.scene.visibility_vignette and (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.qwen_generation_method == 'local_edit')):
# Smooth edge feathering, no blocky mask
apply_vignette_to_mask(
final_path,
@@ -1827,7 +1828,7 @@ def _export_visibility_impl(context, to_export, obj=None, camera_visibility=None
# Save the image
cv2.imwrite(image_path, image)
- if context.scene.visibility_vignette and (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit')):
+ if context.scene.visibility_vignette and (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture in QWEN_ARCHITECTURES and context.scene.qwen_generation_method == 'local_edit')):
apply_vignette_to_mask(
image_path,
feather_width=context.scene.visibility_vignette_width,
@@ -3309,7 +3310,7 @@ class BakeTextures(bpy.types.Operator):
self._phase = 'unwrap'
self._total_objects = len(self._objects)
self._stage = "Preparing"
- return context.window_manager.invoke_props_dialog(self)
+ return context.window_manager.invoke_props_dialog(self, width=440)
def execute(self, context):
"""
diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.py
index 1b4bc64..3208e29 100644
--- a/stablegen/texturing/workflows.py
+++ b/stablegen/texturing/workflows.py
@@ -1,4 +1,4 @@
-from ..feature_flags import experimental_enabled
+from ..core.feature_flags import experimental_enabled
import bpy
import os
import json
@@ -19,8 +19,13 @@ from .graph_validation import (
sdxl_final_mask_reference,
)
from .qwen_models import (
+ FIBO_TEXT_ENCODER,
+ FIBO_VAE,
QWEN_IMAGE_21_TEXT_ENCODER,
+ QWEN_IMAGE_21_TURBO_SIGMAS,
+ QWEN_IMAGE_21_TURBO_STEPS,
QWEN_IMAGE_21_VAE,
+ fibo_prompt,
qwen_prepared_prompt,
qwen_image_21_prompt,
qwen_image_21_rgba_prompt,
@@ -30,6 +35,17 @@ from .qwen_models import (
from io import BytesIO
import numpy as np
from PIL import Image
+from ..core.architectures import (
+ CANVAS_EDIT_ARCHITECTURES, DIFFUSION_ARCHITECTURES, SDXL_GRAPH_ARCHITECTURES,
+)
+from .moss_models import (
+ MOSS_CONTROL_NODE,
+ MOSS_IMAGE_ARCHITECTURE,
+ MOSS_IMAGE_TEXT_ENCODER,
+ MOSS_IMAGE_VAE,
+ MOSS_PLUGIN_LOADER,
+ convert_sdxl_graph_to_moss,
+)
_ADDON_PKG = __package__.rsplit('.', 1)[0]
@@ -101,6 +117,60 @@ class _TexturingWorkflowMixin:
"""Texturing workflow methods for WorkflowManager."""
+ def _moss_support(self, server_address):
+ """Return ``(native_loaders, depth_control)`` for a ComfyUI server."""
+ cache = self.__dict__.setdefault("_moss_server_support", {})
+ if server_address not in cache:
+ from ..core.server_api import fetch_node_info
+ clip_loader = fetch_node_info(server_address, 'CLIPLoader') or {}
+ clip_type = (clip_loader.get('input', {}).get('required', {})
+ .get('type', [[]])[0])
+ native = 'moss_image' in (clip_type if isinstance(clip_type, list) else [])
+ if not native and not fetch_node_info(server_address, MOSS_PLUGIN_LOADER):
+ raise RuntimeError(
+ 'ComfyUI has no MOSS-Image support. Update ComfyUI to 0.42 or later, '
+ 'or install the OpenMOSS moss-image custom node.'
+ )
+ control = native and fetch_node_info(server_address, MOSS_CONTROL_NODE) is not None
+ # Probed once per manager, so a ComfyUI update is seen on the next run.
+ cache[server_address] = (native, control)
+ return cache[server_address]
+
+ def _apply_sdxl_graph_architecture(self, prompt, context, depth_info=None):
+ """Run a finished SDXL graph on the selected SDXL-workflow model."""
+ if context.scene.model_architecture != MOSS_IMAGE_ARCHITECTURE:
+ return
+ scene = context.scene
+ server = context.preferences.addons[_ADDON_PKG].preferences.server_address
+ native, control = self._moss_support(server)
+ depth_image = None
+ if getattr(scene, 'moss_depth_control', False) and depth_info:
+ if control:
+ depth_image = depth_info['name']
+ else:
+ print('[StableGen] MOSS-Image depth control needs ComfyUI 0.42.3 or later '
+ 'with core MOSS-Image support; generating without it.')
+ removed = convert_sdxl_graph_to_moss(
+ prompt, scene.model_name, native=native, depth_image=depth_image,
+ depth_strength=getattr(scene, 'moss_depth_strength', 1.0),
+ depth_end=getattr(scene, 'moss_depth_end', 0.5),
+ )
+ print(
+ '[StableGen] MOSS-Image architecture: '
+ f'{"core" if native else "custom-node"} loaders, '
+ f'{MOSS_IMAGE_TEXT_ENCODER} and {MOSS_IMAGE_VAE}'
+ + (', depth control' if depth_image else '')
+ + (f'; ignored SDXL-only {", ".join(sorted(set(removed)))}' if removed else '')
+ + '.'
+ )
+
+ def _convert_native_edit_graph(self, prompt, nodes, context, **options):
+ """Swap the legacy Qwen Edit graph for the selected native edit model."""
+ if context.scene.model_architecture == 'fibo_edit':
+ self._convert_to_fibo_edit(prompt, nodes, context, **options)
+ else:
+ self._convert_to_qwen_image_21(prompt, nodes, context, **options)
+
def _convert_to_qwen_image_21(
self, prompt, nodes, context, *, projected_context_target=False
):
@@ -237,12 +307,182 @@ class _TexturingWorkflowMixin:
retain_reference(reference)
graph[nodes['pos_prompt']]['inputs'][f'images.image_{index}'] = reference
+ schedule = ''
+ if (context.scene.model_architecture == 'qwen_image_21_turbo'
+ and context.scene.steps == QWEN_IMAGE_21_TURBO_STEPS):
+ self._use_manual_sigmas(
+ graph, nodes['sampler'], QWEN_IMAGE_21_TURBO_SIGMAS
+ )
+ schedule = ' on the trained Turbo schedule'
+
prompt.clear()
prompt.update(graph)
print(
'[StableGen] Qwen-Image 2.1 architecture: using '
f'{QWEN_IMAGE_21_TEXT_ENCODER}, {QWEN_IMAGE_21_VAE}, '
- f'{graph[nodes["sampler"]]["inputs"]["steps"]} steps and no legacy LoRA.'
+ f'{context.scene.steps} steps{schedule} and no legacy LoRA.'
+ )
+
+ @staticmethod
+ def _use_manual_sigmas(graph, sampler_id, sigmas):
+ """Replace a KSampler with SamplerCustomAdvanced on fixed sigmas.
+
+ The sampler keeps its node id, so decoders and latent locks that link
+ to it, and seed overrides through ``noise_seed``, continue to work.
+ """
+ inputs = graph[sampler_id]['inputs']
+ base = int(sampler_id) * 10 + 900
+ noise_id, guider_id, select_id, sigmas_id = (
+ str(base + offset) for offset in range(4)
+ )
+ graph[noise_id] = {
+ 'inputs': {'noise_seed': inputs['seed']},
+ 'class_type': 'RandomNoise',
+ '_meta': {'title': 'Random Noise'},
+ }
+ graph[guider_id] = {
+ 'inputs': {
+ 'model': inputs['model'],
+ 'positive': inputs['positive'],
+ 'negative': inputs['negative'],
+ 'cfg': inputs['cfg'],
+ },
+ 'class_type': 'CFGGuider',
+ '_meta': {'title': 'CFG Guider'},
+ }
+ graph[select_id] = {
+ 'inputs': {'sampler_name': inputs['sampler_name']},
+ 'class_type': 'KSamplerSelect',
+ '_meta': {'title': 'Sampler'},
+ }
+ graph[sigmas_id] = {
+ 'inputs': {'sigmas': sigmas},
+ 'class_type': 'ManualSigmas',
+ '_meta': {'title': 'Trained Sigmas'},
+ }
+ graph[sampler_id] = {
+ 'inputs': {
+ 'noise': [noise_id, 0],
+ 'guider': [guider_id, 0],
+ 'sampler': [select_id, 0],
+ 'sigmas': [sigmas_id, 0],
+ 'latent_image': inputs['latent_image'],
+ },
+ 'class_type': 'SamplerCustomAdvanced',
+ '_meta': {'title': 'Sampler (Custom Advanced)'},
+ }
+
+ def _convert_to_fibo_edit(
+ self, prompt, nodes, context, *, projected_context_target=False
+ ):
+ """Replace the legacy Qwen Edit graph with Bria FIBO 2.0 nodes.
+
+ Like the Qwen 2.1 adapter, this keeps StableGen's semantic image
+ routing and swaps only the model layer. FIBO edits its first image,
+ so projected context moves into that slot, and its prompts index
+ images explicitly as ``<image_N>``. The first image also fixes the
+ output size: FIBO would otherwise crop it to its ~1 MP trained size,
+ which would no longer register with the camera.
+ """
+ old_inputs = prompt[nodes['pos_prompt']].get('inputs', {})
+ image_refs = [
+ old_inputs[key]
+ for key in ('image1', 'image2', 'image3')
+ if key in old_inputs
+ ]
+ mapping = {}
+ if projected_context_target and len(image_refs) >= 2:
+ image_refs[0], image_refs[1] = image_refs[1], image_refs[0]
+ mapping = {1: 2, 2: 1}
+ final_prompt = fibo_prompt(old_inputs.get('prompt', ''), mapping)
+
+ encoder = {
+ 'clip': ['3', 0],
+ 'prompt': final_prompt,
+ 'negative_prompt': getattr(context.scene, 'comfyui_negative_prompt', ''),
+ 'vae': ['4', 0],
+ 'width': 0,
+ 'height': 0,
+ 'batch_size': 1,
+ }
+ graph = {
+ nodes['unet_loader']: {
+ 'inputs': {'unet_name': context.scene.model_name, 'weight_dtype': 'default'},
+ 'class_type': 'UNETLoader',
+ '_meta': {'title': 'Load FIBO 2.0 Diffusion Model'},
+ },
+ '3': {
+ 'inputs': {'clip_name': FIBO_TEXT_ENCODER, 'type': 'fibo2', 'device': 'default'},
+ 'class_type': 'CLIPLoader',
+ '_meta': {'title': 'Load Qwen3-VL 4B Text Encoder'},
+ },
+ '4': {
+ 'inputs': {'vae_name': FIBO_VAE},
+ 'class_type': 'VAELoader',
+ '_meta': {'title': 'Load FIBO 2.0 VAE'},
+ },
+ nodes['pos_prompt']: {
+ 'inputs': encoder,
+ 'class_type': 'TextEncodeFibo2',
+ '_meta': {'title': 'FIBO 2.0 Edit Conditioning'},
+ },
+ nodes['sampler']: {
+ 'inputs': {
+ 'model': [nodes['unet_loader'], 0],
+ 'seed': context.scene.seed,
+ 'steps': context.scene.steps,
+ 'cfg': context.scene.cfg,
+ 'sampler_name': context.scene.sampler,
+ 'scheduler': context.scene.scheduler,
+ 'positive': [nodes['pos_prompt'], 0],
+ 'negative': [nodes['pos_prompt'], 1],
+ 'latent_image': [nodes['pos_prompt'], 2],
+ 'denoise': 1.0,
+ },
+ 'class_type': 'KSampler',
+ '_meta': {'title': 'FIBO 2.0 Sampler'},
+ },
+ '2': {
+ 'inputs': {'samples': [nodes['sampler'], 0], 'vae': ['4', 0]},
+ 'class_type': 'VAEDecode',
+ '_meta': {'title': 'VAE Decode'},
+ },
+ nodes['save_image']: {
+ 'inputs': {'images': ['2', 0]},
+ 'class_type': 'SaveImageWebsocket',
+ '_meta': {'title': 'SaveImageWebsocket'},
+ },
+ }
+
+ def retain_reference(reference):
+ node_id = str(reference[0])
+ if node_id in graph or node_id not in prompt:
+ return
+ graph[node_id] = prompt[node_id]
+ for value in prompt[node_id].get('inputs', {}).values():
+ if (isinstance(value, list) and len(value) == 2
+ and isinstance(value[0], (str, int))
+ and isinstance(value[1], int)):
+ retain_reference(value)
+
+ for index, reference in enumerate(image_refs, 1):
+ retain_reference(reference)
+ encoder[f'images.image_{index}'] = reference
+ if image_refs:
+ graph['17'] = {
+ 'inputs': {'image': image_refs[0]},
+ 'class_type': 'GetImageSize',
+ '_meta': {'title': 'Edited Image Size'},
+ }
+ encoder['width'] = ['17', 0]
+ encoder['height'] = ['17', 1]
+
+ prompt.clear()
+ prompt.update(graph)
+ print(
+ '[StableGen] FIBO 2.0 architecture: using '
+ f'{FIBO_TEXT_ENCODER}, {FIBO_VAE}, {len(image_refs)} image(s) '
+ f'and {context.scene.steps} steps.'
)
def _crop_and_vignette(
@@ -624,10 +864,10 @@ class _TexturingWorkflowMixin:
context_mode in {'REPLACE_STYLE', 'ADDITIONAL'} or
(_t2_style and not getattr(context.scene, 'qwen_trellis2_style_initial_only', False))
)
- is_qwen21 = context.scene.model_architecture == 'qwen_image_21'
+ native_graph = context.scene.model_architecture in CANVAS_EDIT_ARCHITECTURES
architecture_default = (
- 'QWEN_21_DEFAULT' if is_qwen21 else 'QWEN_EDIT_LEGACY'
+ 'QWEN_21_DEFAULT' if native_graph else 'QWEN_EDIT_LEGACY'
)
selected_template = template_id or getattr(
context.scene, 'qwen_prompt_template', architecture_default
@@ -675,7 +915,7 @@ class _TexturingWorkflowMixin:
has_magenta_regions=has_context_canvas,
gray_background=(
has_context_canvas
- and not is_qwen21
+ and not native_graph
and getattr(
context.scene, 'qwen_prompt_gray_background', True
)
@@ -759,14 +999,14 @@ class _TexturingWorkflowMixin:
'style_map_loader': "15", # Image 2 (style)
'context_render_loader': "16", # Image 3 (context render)
}
- is_qwen21 = context.scene.model_architecture == 'qwen_image_21'
+ native_graph = context.scene.model_architecture in CANVAS_EDIT_ARCHITECTURES
# --- Build LoRA chain ---
is_nunchaku = (
- not is_qwen21
+ not native_graph
and context.scene.model_name.lower().endswith('.safetensors')
)
- if not is_qwen21:
+ if not native_graph:
initial_model_input = [NODES['unet_loader'], 0]
dummy_clip_input = [NODES['unet_loader'], 0]
lora_class = (
@@ -851,8 +1091,8 @@ class _TexturingWorkflowMixin:
prompt[NODES['pos_prompt']]['inputs']['prompt'] = final_prompt
- if is_qwen21:
- self._convert_to_qwen_image_21(prompt, NODES, context)
+ if native_graph:
+ self._convert_native_edit_graph(prompt, NODES, context)
else:
# --- Reference Latent chain (Qwen unzoom fix) ---
# The overlay is a semantic selection guide, never an appearance latent.
@@ -878,12 +1118,12 @@ class _TexturingWorkflowMixin:
"class_type": "NunchakuQwenImageDiTLoader",
"_meta": {"title": "Nunchaku Qwen-Image DiT Loader"},
}
- elif not is_qwen21:
+ elif not native_graph:
prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name
graph_issues = (validate_workflow_graph(
prompt,
- ((NODES['pos_prompt'],) if is_qwen21
+ ((NODES['pos_prompt'],) if native_graph
else (NODES['pos_prompt'], NODES['neg_prompt'])),
))
if graph_issues:
@@ -933,16 +1173,16 @@ class _TexturingWorkflowMixin:
'style_map_loader': "15", # Image 2 (style)
'context_render_loader': "16", # Image 3 (context render)
}
- is_qwen21 = context.scene.model_architecture == 'qwen_image_21'
+ native_graph = context.scene.model_architecture in CANVAS_EDIT_ARCHITECTURES
# --- Build LoRA chain ---
# The Qwen workflow uses model-only LoRAs. We can reuse the existing
# chain builder by providing a dummy CLIP input that won't be used.
is_nunchaku = (
- not is_qwen21
+ not native_graph
and context.scene.model_name.lower().endswith('.safetensors')
)
- if not is_qwen21:
+ if not native_graph:
initial_model_input = [NODES['unet_loader'], 0]
dummy_clip_input = [NODES['unet_loader'], 0]
lora_class = (
@@ -1139,8 +1379,8 @@ class _TexturingWorkflowMixin:
prompt[NODES['pos_prompt']]['inputs'][style_slot] = [scale_node_key, 0]
prompt[NODES['neg_prompt']]['inputs'][style_slot] = [scale_node_key, 0]
- if is_qwen21:
- self._convert_to_qwen_image_21(
+ if native_graph:
+ self._convert_native_edit_graph(
prompt,
NODES,
context,
@@ -1226,7 +1466,7 @@ class _TexturingWorkflowMixin:
)
# --- Configure Sampler ---
- if not is_qwen21:
+ if not native_graph:
prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed
prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps
prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg
@@ -1248,12 +1488,12 @@ class _TexturingWorkflowMixin:
"title": "Nunchaku Qwen-Image DiT Loader"
}
}
- elif not is_qwen21:
+ elif not native_graph:
prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name
graph_issues = (validate_workflow_graph(
prompt,
- ((NODES['pos_prompt'],) if is_qwen21
+ ((NODES['pos_prompt'],) if native_graph
else (NODES['pos_prompt'], NODES['neg_prompt'])),
))
if graph_issues:
@@ -1555,6 +1795,8 @@ class _TexturingWorkflowMixin:
prompt = self._build_controlnet_chain(prompt, context, controlnet_info, NODES)
# Save prompt for debugging (in revision dir)
+ self._apply_sdxl_graph_architecture(
+ prompt, context, depth_info=(controlnet_info or {}).get('depth'))
self._save_prompt_to_file(prompt, revision_dir, workflow="sdxl_generate")
# Execute generation and get results
@@ -1604,10 +1846,10 @@ class _TexturingWorkflowMixin:
# 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', 'qwen_image_21', 'flux2_klein'):
+ if tex_mode not in DIFFUSION_ARCHITECTURES:
architecture = getattr(scene, 'trellis2_initial_image_arch', 'sdxl')
- if architecture == 'qwen_image_21':
+ if architecture in CANVAS_EDIT_ARCHITECTURES:
prompt, save_node = self._build_qwen_image_21_txt2img(context)
elif architecture == 'qwen_image_edit':
prompt, save_node = self._build_qwen_txt2img(context)
@@ -1715,6 +1957,7 @@ class _TexturingWorkflowMixin:
prompt["2"]["inputs"]["clip"] = final_clip
prompt["3"]["inputs"]["clip"] = final_clip
+ self._apply_sdxl_graph_architecture(prompt, context)
return prompt, "7"
# ── PBR Decomposition (Marigold IID) ───────────────────────────────
@@ -2491,7 +2734,7 @@ class _TexturingWorkflowMixin:
return prompt, "7"
def _build_qwen_image_21_txt2img(self, context):
- """Return a native Qwen-Image 2.1 text-to-image graph."""
+ """Return a native Qwen-Image 2.1, 2.1 Turbo or FIBO text-to-image graph."""
prompt = json.loads(prompt_text_qwen_image_edit)
nodes = {
'sampler': "1",
@@ -2516,7 +2759,7 @@ class _TexturingWorkflowMixin:
):
prompt.pop(loader_id, None)
- self._convert_to_qwen_image_21(prompt, nodes, context)
+ self._convert_native_edit_graph(prompt, nodes, context)
return prompt, nodes['save_image']
def _create_base_prompt(self, context):
@@ -2673,6 +2916,8 @@ class _TexturingWorkflowMixin:
# Get the dynamic collection of ControlNet units
controlnet_units = getattr(context.scene, "controlnet_units", [])
+ if context.scene.model_architecture == MOSS_IMAGE_ARCHITECTURE:
+ controlnet_units = []
current_pos = pos_input
current_neg = neg_input
has_union = False
@@ -2718,7 +2963,7 @@ class _TexturingWorkflowMixin:
"negative": [current_neg, 1] if (idx > 0 or current_neg == "228" or current_neg == "51") else [current_neg, 0],
"control_net": [loader_key, 0],
"image": [load_key, 0],
- "vae": [vae_input, 2] if context.scene.model_architecture == "sdxl" else [vae_input, 0],
+ "vae": [vae_input, 2] if context.scene.model_architecture in SDXL_GRAPH_ARCHITECTURES else [vae_input, 0],
},
"class_type": "ControlNetApplyAdvanced",
"_meta": {
@@ -2816,9 +3061,12 @@ class _TexturingWorkflowMixin:
controlnet_info
)
- # Connect final node outputs to the KSampler
+ # Connect final node outputs to the KSampler. Without any applied unit
+ # (MOSS-Image has no ControlNet) the text encoders connect directly.
prompt[NODES['sampler']]["inputs"]["positive"] = [final_node, 0]
- prompt[NODES['sampler']]["inputs"]["negative"] = [final_node, 1]
+ prompt[NODES['sampler']]["inputs"]["negative"] = (
+ [NODES['neg_prompt'], 0] if final_node == NODES['pos_prompt'] else [final_node, 1]
+ )
return prompt
@@ -2847,6 +3095,7 @@ class _TexturingWorkflowMixin:
sampler['positive'] = [nodes['pos_prompt'], 0]
sampler['negative'] = [nodes['neg_prompt'], 0]
sampler['denoise'] = context.scene.sg_masked_strength
+ self._apply_sdxl_graph_architecture(prompt, context)
self._save_prompt_to_file(prompt, get_generation_dirs(context)['revision'], workflow='masked_sdxl')
server = context.preferences.addons[_ADDON_PKG].preferences.server_address
client_id = str(uuid.uuid4())
@@ -2911,6 +3160,8 @@ class _TexturingWorkflowMixin:
prompt[NODES['sampler']]["inputs"]["negative"] = [NODES['neg_prompt'], 0]
# Save prompt for debugging
+ self._apply_sdxl_graph_architecture(
+ prompt, context, depth_info=(controlnet_info or {}).get('depth'))
self._save_prompt_to_file(prompt, output_dir, workflow="sdxl_refine")
# Execute generation and get results
diff --git a/stablegen/ui/model_units.py b/stablegen/ui/model_units.py
index 5a7b43a..b657782 100644
--- a/stablegen/ui/model_units.py
+++ b/stablegen/ui/model_units.py
@@ -15,7 +15,10 @@ from .presets import update_parameters
from ..utils import sg_modal_active
from ..core import ADDON_PKG
from ..core.server_api import _fetch_api_list, fetch_diffusion_models
-from ..texturing.qwen_models import is_qwen_image_21_model
+from ..texturing.qwen_models import (
+ is_fibo_model, is_moss_image_model,
+ is_qwen_image_21_model, is_qwen_image_21_turbo_model,
+)
from ..core.state import (
_cached_checkpoint_list,
_cached_checkpoint_architecture,
@@ -25,6 +28,23 @@ from ..core.state import (
_run_async,
)
+# Architectures whose model is listed from the diffusion-model folders:
+# (accepts filename, description used in refresh reports).
+_DIFFUSION_MODEL_FILTERS = {
+ 'flux1': (lambda name: True, "UNET"),
+ 'qwen_image_edit': (
+ lambda name: not (is_qwen_image_21_model(name)
+ or is_moss_image_model(name) or is_fibo_model(name)),
+ "Qwen-Image-Edit model"),
+ 'qwen_image_21': (
+ lambda name: (is_qwen_image_21_model(name)
+ and not is_qwen_image_21_turbo_model(name)),
+ "Qwen-Image 2.1 model"),
+ 'qwen_image_21_turbo': (is_qwen_image_21_turbo_model, "Qwen-Image 2.1 Turbo model"),
+ 'moss_image': (is_moss_image_model, "MOSS-Image model"),
+ 'fibo_edit': (is_fibo_model, "FIBO model"),
+}
+
# ── Enum callbacks for model dropdowns ─────────────────────────────────────
@@ -209,19 +229,11 @@ class RefreshCheckpointList(bpy.types.Operator):
if architecture == 'sdxl':
model_list = _fetch_api_list(server_address, "/models/checkpoints")
model_type_desc = "Checkpoint"
- elif architecture in ('flux1', 'qwen_image_edit', 'qwen_image_21'):
+ elif architecture in _DIFFUSION_MODEL_FILTERS:
model_list = fetch_diffusion_models(server_address)
- if model_list is not None and architecture == 'qwen_image_21':
- model_list = [name for name in model_list
- if is_qwen_image_21_model(name)]
- elif model_list is not None and architecture == 'qwen_image_edit':
- model_list = [name for name in model_list
- if not is_qwen_image_21_model(name)]
- model_type_desc = (
- "UNET" if architecture == 'flux1'
- else "Qwen-Image 2.1 model" if architecture == 'qwen_image_21'
- else "Qwen-Image-Edit model"
- )
+ accepts, model_type_desc = _DIFFUSION_MODEL_FILTERS[architecture]
+ if model_list is not None:
+ model_list = [name for name in model_list if accepts(name)]
elif architecture == 'flux2_klein':
model_list = _fetch_api_list(server_address, "/models/diffusion_models")
model_type_desc = "Diffusion Model"
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index e006bbf..80bb32c 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -3,15 +3,20 @@
import os
import bpy # pylint: disable=import-error
import mathutils # pylint: disable=import-error
-from ..generation_status import draw_stage_progress, server_status_active
+from ..core.generation_status import draw_stage_progress, server_status_active
import math
from ..utils import sg_modal_active
from ..core import get_addon_prefs, legacy_panel_enabled
from .presets import PRESETS, GEN_PARAMETERS
-from ..feature_flags import experiments_enabled, active_experiments
-from ..architecture_options import (
+from ..core.feature_flags import experiments_enabled, active_experiments
+from ..core.architectures import (
active_deprecated_architectures, deprecated_architectures_enabled,
+ active_experimental_architectures, experimental_architectures_enabled,
+ CANVAS_EDIT_ARCHITECTURES, DIFFUSION_ARCHITECTURES, EDIT_ARCHITECTURES,
+ MASKED_EDIT_ARCHITECTURES, NATIVE_GRAPH_ARCHITECTURES, QWEN_21_ARCHITECTURES,
+ QWEN_ARCHITECTURES,
)
+from ..texturing.qwen_models import QWEN_IMAGE_21_TURBO_STEPS
from . import queue as _queue_mod
_ADDON_PKG = __package__.rsplit('.', 1)[0]
@@ -51,6 +56,9 @@ _DISPLAY_NAMES = {
'flux1': 'FLUX.1',
'qwen_image_edit': 'Qwen Image Edit',
'qwen_image_21': 'Qwen Image 2.1',
+ 'qwen_image_21_turbo': 'Qwen Image 2.1 Turbo',
+ 'moss_image': 'MOSS Image',
+ 'fibo_edit': 'FIBO 2.0 Edit',
'flux2_klein': 'FLUX.2 Klein',
'trellis2': 'TRELLIS.2',
'standard': 'Standard',
@@ -72,7 +80,7 @@ def _fmt_diff_val(v):
def _is_masked_edit_mode(scene):
- if scene.model_architecture.startswith('qwen'):
+ if scene.model_architecture in QWEN_ARCHITECTURES:
return scene.qwen_generation_method == 'masked_edit'
return scene.generation_method == 'masked_edit'
@@ -193,6 +201,17 @@ class StableGenPanel(bpy.types.Panel):
# Saved FLUX scenes remain intact, but their settings and actions
# are hidden until the user opts in or chooses a supported model.
return
+ if active_experimental_architectures(scene) and not experimental_architectures_enabled(context):
+ box = layout.box()
+ box.label(text="Experimental architecture hidden", icon='INFO')
+ box.label(text="Enable experimental architectures in add-on preferences.")
+ box.prop(scene, "architecture_mode")
+ if scene.architecture_mode == 'trellis2':
+ box.prop(scene, "trellis2_texture_mode")
+ if (scene.trellis2_texture_mode in ('none', 'native')
+ and scene.trellis2_generate_from == 'prompt'):
+ box.prop(scene, "trellis2_initial_image_arch")
+ return
config_error_message = None
if not os.path.exists(addon_prefs.output_dir):
@@ -496,8 +515,8 @@ class StableGenPanel(bpy.types.Panel):
elif masked_preview:
action_row.operator('stablegen.resolve_masked_edit', text='Apply', icon='CHECKMARK').apply = True
action_row.operator('stablegen.resolve_masked_edit', text='Discard', icon='LOOP_BACK').apply = False
- elif scene.model_architecture not in {'sdxl', 'qwen_image_edit', 'qwen_image_21'}:
- action_row.operator('stablegen.masked_edit', text='Masked Edit requires Qwen or SDXL', icon='ERROR')
+ elif scene.model_architecture not in MASKED_EDIT_ARCHITECTURES:
+ action_row.operator('stablegen.masked_edit', text='Masked Edit requires Qwen, FIBO, MOSS or SDXL', icon='ERROR')
action_row.enabled = False
elif not bpy.app.online_access:
action_row.operator('stablegen.masked_edit', text='Enable online access in preferences', icon='ERROR')
@@ -729,7 +748,7 @@ class StableGenPanel(bpy.types.Panel):
is_trellis2 = getattr(scene, 'architecture_mode', 'sdxl') == 'trellis2'
trellis2_tex_mode = getattr(scene, 'trellis2_texture_mode', 'native')
- trellis2_diffusion_texturing = is_trellis2 and trellis2_tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein')
+ trellis2_diffusion_texturing = is_trellis2 and trellis2_tex_mode in DIFFUSION_ARCHITECTURES
main_params_box = layout.box()
main_params_col = main_params_box.column()
@@ -861,7 +880,7 @@ class StableGenPanel(bpy.types.Panel):
if 'generation_method' in _diff_props or 'qwen_generation_method' in _diff_props:
split.alert = True
split.label(text="Generation Mode:")
- if scene.model_architecture.startswith("qwen"):
+ if scene.model_architecture in QWEN_ARCHITECTURES:
split.prop(scene, "qwen_generation_method", text="")
else:
split.prop(scene, "generation_method", text="")
@@ -882,7 +901,7 @@ class StableGenPanel(bpy.types.Panel):
if 'generation_method' in _diff_props or 'qwen_generation_method' in _diff_props:
split.alert = True
split.label(text="Generation Mode:")
- if scene.model_architecture.startswith("qwen"):
+ if scene.model_architecture in QWEN_ARCHITECTURES:
split.prop(scene, "qwen_generation_method", text="")
else:
split.prop(scene, "generation_method", text="")
@@ -1278,7 +1297,22 @@ class StableGenPanel(bpy.types.Panel):
if 'scheduler' in _diff_props:
split.label(text="→ " + _diff_props['scheduler'])
- if scene.model_architecture == 'qwen_image_21':
+ if (scene.model_architecture == 'qwen_image_21_turbo'
+ and scene.steps == QWEN_IMAGE_21_TURBO_STEPS):
+ content_box.label(text="Turbo samples its trained 8-step schedule", icon='INFO')
+
+ if scene.model_architecture == 'moss_image':
+ row = content_box.row()
+ for prop in ('moss_depth_control', 'moss_depth_strength', 'moss_depth_end'):
+ if prop in _diff_props:
+ row.alert = True
+ row.prop(scene, "moss_depth_control", text="Depth Control", toggle=True)
+ if scene.moss_depth_control:
+ row = content_box.row(align=True)
+ row.prop(scene, "moss_depth_strength", text="Strength")
+ row.prop(scene, "moss_depth_end", text="End")
+
+ if scene.model_architecture in QWEN_21_ARCHITECTURES:
row = content_box.row()
if 'qwen_image_21_native_rgba' in _diff_props:
row.alert = True
@@ -1291,13 +1325,13 @@ class StableGenPanel(bpy.types.Panel):
if 'qwen_image_21_native_rgba' in _diff_props:
row.label(text="→ " + _diff_props['qwen_image_21_native_rgba'])
- if scene.model_architecture != 'qwen_image_21':
+ if scene.model_architecture not in NATIVE_GRAPH_ARCHITECTURES:
row = content_box.row()
row.prop(scene, "clip_skip", text="CLIP layer skip")
# --- LoRA Settings ---
if ((_show_diffusion_sections or _show_initial_image_settings)
- and scene.model_architecture != 'qwen_image_21'):
+ and scene.model_architecture not in NATIVE_GRAPH_ARCHITECTURES):
content_box = draw_collapsible_section(advanced_params_box, "show_lora_settings", "LoRA Management", icon="MODIFIER")
else:
content_box = None
@@ -1315,7 +1349,7 @@ class StableGenPanel(bpy.types.Panel):
sub_row = unit_box.row(align=True)
sub_row.prop(lora_unit, "model_strength", text="Model Strength")
- if not scene.model_architecture.startswith("qwen") and scene.model_architecture != 'flux2_klein': # Qwen/Klein use model only loras
+ if not scene.model_architecture in QWEN_ARCHITECTURES and scene.model_architecture != 'flux2_klein': # Qwen/Klein use model only loras
sub_row.prop(lora_unit, "clip_strength", text="CLIP Strength")
# Icon to indicate selection more clearly alongside the alert state
@@ -1400,7 +1434,7 @@ class StableGenPanel(bpy.types.Panel):
sub.label(text="→" + _diff_props['weight_exponent'])
# Row 2 & 3: Reset toggles and values (only for sequential / qwen)
- if scene.generation_method == 'sequential' or scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ if scene.generation_method == 'sequential' or scene.model_architecture in EDIT_ARCHITECTURES:
split = content_box.split(factor=0.5, align=False)
split.prop(scene, "discard_factor_generation_only", text="Resets", toggle=True)
split.prop(scene, "weight_exponent_generation_only", text="Resets", toggle=True)
@@ -1476,7 +1510,7 @@ class StableGenPanel(bpy.types.Panel):
if scene.sg_auto_view_sequence:
experiments.prop(scene, "sg_anchor_camera")
qwen_exp = experiments.column()
- qwen_exp.enabled = scene.model_architecture.startswith('qwen') and scene.qwen_generation_method == 'generate'
+ qwen_exp.enabled = scene.model_architecture in QWEN_ARCHITECTURES and scene.qwen_generation_method == 'generate'
style = qwen_exp.row()
style.enabled = scene.qwen_context_render_mode == 'ADDITIONAL'
style.prop(scene, "qwen_global_style_vlm_only", toggle=True)
@@ -1618,8 +1652,10 @@ class StableGenPanel(bpy.types.Panel):
if scene.model_architecture == 'qwen_image_edit':
row = sub_box_rescale.row()
row.prop(scene, "qwen_rescale_alignment", text="Qwen VL-Aligned Rescale (112px)", toggle=True, icon="SNAP_INCREMENT")
- elif scene.model_architecture == 'qwen_image_21':
+ elif scene.model_architecture in QWEN_21_ARCHITECTURES:
sub_box_rescale.label(text="Qwen 2.1 aligns to 32px", icon="SNAP_INCREMENT")
+ elif scene.model_architecture in ('moss_image', 'fibo_edit'):
+ sub_box_rescale.label(text="Aligns to 16px latent patches", icon="SNAP_INCREMENT")
row = content_box.row()
if 'overwrite_material' in _diff_props:
row.alert = True
@@ -1628,17 +1664,19 @@ class StableGenPanel(bpy.types.Panel):
row.label(text="→ " + _diff_props['overwrite_material'])
# --- Image Guidance (IPAdapter & ControlNet) ---
- if _show_diffusion_sections:
+ # MOSS-Image has neither IPAdapter nor ControlNet models.
+ if _show_diffusion_sections and scene.model_architecture != 'moss_image':
if scene.model_architecture in ['sdxl', 'flux1']:
content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", "Image Guidance (IPAdapter & ControlNet)", icon="MODIFIER")
elif scene.model_architecture == 'flux2_klein':
content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", "FLUX.2 Klein Guidance", icon="MODIFIER")
- else: # Qwen Image
- content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", "Qwen Image Guidance", icon="MODIFIER")
+ else: # Qwen Image and FIBO
+ guidance_title = "FIBO Guidance" if scene.model_architecture == 'fibo_edit' else "Qwen Image Guidance"
+ content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", guidance_title, icon="MODIFIER")
else:
content_box = None
if content_box:
- if scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ if scene.model_architecture in EDIT_ARCHITECTURES:
if scene.model_architecture == 'flux2_klein' or scene.qwen_generation_method == 'generate':
split = content_box.split(factor=0.5)
split.label(text="Guidance Map:")
@@ -1725,7 +1763,7 @@ class StableGenPanel(bpy.types.Panel):
row = content_box.row()
row.prop(scene, "qwen_timestep_zero_ref", text="Timestep-Zero References (color shift fix)", toggle=True, icon="COLORSET_08_VEC")
- if scene.model_architecture in {'qwen_image_edit', 'qwen_image_21'}:
+ if scene.model_architecture in QWEN_ARCHITECTURES:
split = content_box.split(factor=0.5)
split.label(text="Prompt Template:")
split.prop(scene, "qwen_prompt_template", text="")
@@ -1736,9 +1774,8 @@ class StableGenPanel(bpy.types.Panel):
row.prop(scene, "qwen_use_custom_prompts", text="Custom Guidance Prompts", toggle=True, icon="TEXT")
custom_guidance_enabled = scene.qwen_use_custom_prompts
- if (scene.model_architecture in {
- 'qwen_image_edit', 'qwen_image_21'
- } or custom_guidance_enabled):
+ if (scene.model_architecture in QWEN_ARCHITECTURES
+ or custom_guidance_enabled):
custom_prompt_box = content_box.box()
# Initial Image Prompt
@@ -1776,7 +1813,7 @@ class StableGenPanel(bpy.types.Panel):
context_box = content_box.box()
context_box.label(text="Context Render Options")
- if scene.model_architecture != 'qwen_image_21':
+ if scene.model_architecture not in CANVAS_EDIT_ARCHITECTURES:
row = context_box.row()
row.prop(scene, "qwen_prompt_gray_background", text="Prompt: Gray Background", toggle=True)
@@ -1884,7 +1921,7 @@ class StableGenPanel(bpy.types.Panel):
cn_box.operator("stablegen.add_controlnet_unit", text="Add ControlNet Unit", icon="ADD")
cn_box.operator("stablegen.remove_controlnet_unit", text="Remove Last ControlNet Unit", icon="REMOVE")
- if _show_diffusion_sections and scene.model_architecture not in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ if _show_diffusion_sections and scene.model_architecture not in EDIT_ARCHITECTURES:
# --- Inpainting Options (Conditional) ---
if scene.generation_method == 'uv_inpaint' or scene.generation_method == 'sequential':
content_box = draw_collapsible_section(advanced_params_box, "show_masking_inpainting_settings", "Inpainting Options", icon="MOD_MASK")
@@ -1934,7 +1971,7 @@ class StableGenPanel(bpy.types.Panel):
draw_masked_edit_controls(mode_specific_outer_box, context)
# Qwen Local Edit Mode Parameters
- elif scene.model_architecture.startswith('qwen') and scene.qwen_generation_method == 'local_edit':
+ elif scene.model_architecture in QWEN_ARCHITECTURES and scene.qwen_generation_method == 'local_edit':
row = mode_specific_outer_box.row()
row.alignment = 'CENTER'
row.label(text="Qwen Local Edit Parameters", icon='BRUSH_DATA')
@@ -1991,7 +2028,7 @@ class StableGenPanel(bpy.types.Panel):
row.prop(scene, "view_blend_color_match_strength", text="Strength")
# Qwen Refine Mode Parameters
- elif scene.model_architecture.startswith('qwen') and scene.qwen_generation_method == 'refine':
+ elif scene.model_architecture in QWEN_ARCHITECTURES and scene.qwen_generation_method == 'refine':
row = mode_specific_outer_box.row()
row.alignment = 'CENTER'
row.label(text="Qwen Refine Parameters", icon='SHADERFX')
@@ -2061,7 +2098,7 @@ class StableGenPanel(bpy.types.Panel):
sub_ip_box_separate.prop(scene, "sequential_desaturate_factor", text="Reference desaturation")
sub_ip_box_separate.prop(scene, "sequential_contrast_factor", text="Reference contrast reduction")
- if context.scene.model_architecture not in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ if context.scene.model_architecture not in EDIT_ARCHITECTURES:
split = sub_ip_box_separate.split(factor=0.5)
if context.scene.model_architecture == 'sdxl':
split.label(text="Weight Type:")
@@ -2261,7 +2298,7 @@ class StableGenPanel(bpy.types.Panel):
sub_ip_seq_box.prop(scene, "sequential_desaturate_factor", text="Reference desaturation")
sub_ip_seq_box.prop(scene, "sequential_contrast_factor", text="Reference contrast reduction")
- if context.scene.model_architecture not in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ if context.scene.model_architecture not in EDIT_ARCHITECTURES:
split = sub_ip_seq_box.split(factor=0.5)
if context.scene.model_architecture == 'sdxl':
split.label(text="Weight Type:")
@@ -2352,7 +2389,7 @@ class StableGenPanel(bpy.types.Panel):
context_box = preview_box.box()
context_box.label(text="Context Render Options")
- if scene.model_architecture != 'qwen_image_21':
+ if scene.model_architecture not in CANVAS_EDIT_ARCHITECTURES:
context_box.prop(
scene,
"qwen_prompt_gray_background",
@@ -2362,7 +2399,7 @@ class StableGenPanel(bpy.types.Panel):
colors_box = context_box.box()
colors_box.label(text="Context Render Colors")
- if scene.model_architecture != 'qwen_image_21':
+ if scene.model_architecture not in CANVAS_EDIT_ARCHITECTURES:
colors_box.prop(
scene, "qwen_guidance_background_color", text="Image background"
)
diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.py
index b26d8e4..80d42bf 100644
--- a/stablegen/ui/presets.py
+++ b/stablegen/ui/presets.py
@@ -4,10 +4,11 @@ import math
import bpy # pylint: disable=import-error
import mathutils # pylint: disable=import-error
from ..utils import sg_modal_active
-from ..feature_flags import TEXTURING_DEFAULTS, EXPERIMENTAL_FEATURE_DEFAULTS, experiments_enabled
-from ..architecture_options import (
- DEPRECATION_NOTICE, deprecated_architectures_enabled,
- preset_uses_deprecated_architecture,
+from ..core.feature_flags import TEXTURING_DEFAULTS, EXPERIMENTAL_FEATURE_DEFAULTS, experiments_enabled
+from ..core.architectures import (
+ DEPRECATION_NOTICE, deprecated_architectures_enabled, experimental_architectures_enabled,
+ preset_uses_deprecated_architecture, preset_uses_experimental_architecture, DIFFUSION_ARCHITECTURES,
+ QWEN_ARCHITECTURES,
)
PRESETS = {
@@ -250,15 +251,133 @@ PRESETS["REFINE (QWEN 2.1)"] = {
"lora_units": [],
}
+# Qwen-Image 2.1 Turbo keeps every Qwen 2.1 view, context and projection
+# strategy and changes only the sampling: its trained 8-step schedule at CFG 1
+# with Euler. The scheduler is unused at 8 steps; Simple applies otherwise.
+_QWEN_21_TURBO_PURPOSES = {
+ "QWEN 2.1 PRECISE": "multi-view texturing with projected context renders that preserve textured regions and repair uncovered areas",
+ "QWEN 2.1 PRECISE+": "Precise with Confidence-Gated Context, Acquisition Quality Weighting and Depth/Part Projection Guard",
+ "QWEN 2.1 SAFE": "multi-view texturing that uses the initial generated view as the appearance reference for every later camera",
+ "QWEN 2.1 CONTEXT + REFERENCE": "sequential texturing combining the projected context with the first view as a persistent appearance reference",
+ "LOCAL EDIT (QWEN 2.1)": "targeted changes to an existing texture through detail cameras pointed at the area to edit",
+ "REFINE (QWEN 2.1)": "restyling or modifying the existing texture across the scene's camera views",
+}
+for _base_name, _purpose in _QWEN_21_TURBO_PURPOSES.items():
+ PRESETS[_base_name.replace("QWEN 2.1", "QWEN 2.1 TURBO")] = {
+ **PRESETS[_base_name],
+ "description": (
+ f"Qwen-Image 2.1 Turbo {_purpose}. Matches {_base_name.title()} except "
+ "for sampling: the Turbo model's trained 8-step schedule at CFG 1 with "
+ "Euler, several times faster than 20 DPM++ SDE steps. Native RGBA "
+ "output is on and transparent pixels are excluded from projection."
+ ),
+ "architecture_mode": "qwen_image_21_turbo",
+ "model_architecture": "qwen_image_21_turbo",
+ "steps": 8,
+ "cfg": 1.0,
+ "sampler": "euler",
+ "scheduler": "simple",
+ }
+
+# Bria FIBO 2.0 Edit reuses the Qwen 2.1 strategies: like Qwen 2.1 it edits
+# its first image, so projected context becomes that image. FIBO 2.0 Edit
+# Turbo samples 4 Euler steps at CFG 1 and has no transparency output. Its
+# presets set 1 MP, since a scene raised for Qwen 2.1's 2K would otherwise keep
+# its target: at 2.5 MP FIBO redraws the edited subject at its ~1 MP trained
+# scale in the top of the canvas, so the view no longer registers.
+_FIBO_PURPOSES = {
+ "QWEN 2.1 PRECISE": ("FIBO PRECISE", "multi-view texturing with projected context renders that preserve textured regions and repair uncovered areas"),
+ "QWEN 2.1 SAFE": ("FIBO SAFE", "multi-view texturing that uses the initial generated view as the appearance reference for every later camera"),
+ "LOCAL EDIT (QWEN 2.1)": ("LOCAL EDIT (FIBO)", "targeted changes to an existing texture through detail cameras pointed at the area to edit"),
+ "REFINE (QWEN 2.1)": ("REFINE (FIBO)", "restyling or modifying the existing texture across the scene's camera views"),
+}
+for _base_name, (_fibo_name, _purpose) in _FIBO_PURPOSES.items():
+ _values = {key: value for key, value in PRESETS[_base_name].items()
+ if key != "qwen_image_21_native_rgba"}
+ PRESETS[_fibo_name] = {
+ **_values,
+ "description": (
+ f"Experimental Bria FIBO 2.0 Edit {_purpose}. Matches "
+ f"{_base_name.title()}'s camera, context and projection settings and "
+ "samples FIBO 2.0 Edit Turbo with 4 Euler steps at CFG 1 and 1 MP. Image "
+ "references are written as <image_N>. Needs a ComfyUI build with core "
+ "FIBO 2.0 support (master from 2026-10-21), the fibo2 edit model, "
+ "qwen3vl_4b_int8_convrot and flux2-vae."
+ ),
+ "architecture_mode": "fibo_edit",
+ "model_architecture": "fibo_edit",
+ "auto_rescale_target_mp": 1.0,
+ "steps": 4,
+ "cfg": 1.0,
+ "sampler": "euler",
+ "scheduler": "simple",
+ }
+
+# MOSS-Image runs the SDXL workflows (classical inpainting, Differential
+# Diffusion) with the model card's sampler: 50 steps, CFG 3, Euler, SGM
+# Uniform. Geometry comes from its color/depth control adapter instead of
+# ControlNet; IPAdapter and LoRA do not exist for it. Existing ControlNet
+# units are kept untouched for switching back to SDXL.
+_MOSS_SAMPLING = {
+ "moss_depth_control": True,
+ "moss_depth_strength": 1.0,
+ "moss_depth_end": 0.5,
+ "architecture_mode": "moss_image",
+ "model_architecture": "moss_image",
+ "steps": 50,
+ "cfg": 3.0,
+ "sampler": "euler",
+ "scheduler": "sgm_uniform",
+ "refine_steps": 50,
+ "refine_cfg": 3.0,
+ "refine_sampler": "euler",
+ "refine_scheduler": "sgm_uniform",
+ "sequential_ipadapter": False,
+ "sequential_ipadapter_regenerate": False,
+ "lora_units": [],
+}
+
+
+def _moss_preset(base, description, **overrides):
+ values = {key: value for key, value in PRESETS[base].items()
+ if key != "controlnet_units"}
+ return {**values, **_MOSS_SAMPLING, "description": description, **overrides}
+
+
+PRESETS["MOSS SEQUENTIAL"] = _moss_preset(
+ "DEFAULT",
+ "MOSS-Image sequential texturing using the SDXL workflow: each later "
+ "camera inpaints only the surface not yet covered, with Differential "
+ "Diffusion and a blurred, grown visibility mask so new texture continues "
+ "the projected context. Every view follows its depth map through the "
+ "MOSS color/depth control adapter until half of sampling. Uses the model "
+ "card's 50 steps, CFG 3, Euler and SGM Uniform. Depth control needs "
+ "ComfyUI 0.42.3 or later and the adapter in models/loras; without it the "
+ "first view follows only the prompt.",
+)
+PRESETS["LOCAL REFINE (MOSS)"] = _moss_preset(
+ "LOCAL REFINE",
+ "MOSS-Image local refinement using the SDXL local edit mode: point new "
+ "cameras at the area to improve and the current texture is re-rendered "
+ "at the edit strength with depth control, then projected back with "
+ "feathered edges. Uses 50 steps, CFG 3, Euler and SGM Uniform.",
+)
+PRESETS["UV INPAINTING (MOSS)"] = _moss_preset(
+ "UV INPAINTING",
+ "MOSS-Image UV inpainting: fills untextured areas directly in the baked UV "
+ "texture with Differential Diffusion. Bake textures manually first to "
+ "fine-tune the unwrap. Uses 50 steps, CFG 3, Euler and SGM Uniform.",
+)
+
# Stock presets select their architecture's native guidance wording. Including
# the enum makes applying one reset a previously selected comparison template.
for _preset_values in PRESETS.values():
_preset_architecture = _preset_values.get("model_architecture")
if _preset_architecture == "qwen_image_edit":
_preset_values.setdefault("qwen_prompt_template", "QWEN_EDIT_LEGACY")
- elif _preset_architecture == "qwen_image_21":
+ elif _preset_architecture in QWEN_ARCHITECTURES:
_preset_values.setdefault("qwen_prompt_template", "QWEN_21_DEFAULT")
- if _preset_architecture in {"qwen_image_edit", "qwen_image_21"}:
+ if _preset_architecture in QWEN_ARCHITECTURES:
# Prepared-template fields are derived live. Keeping stale copies in a
# stock preset would overwrite them after the template is selected.
for _prompt_field in (
@@ -368,6 +487,9 @@ GEN_PARAMETERS = [
'qwen_prompt_gray_background',
'qwen_rescale_alignment',
'qwen_image_21_native_rgba',
+ 'moss_depth_control',
+ 'moss_depth_strength',
+ 'moss_depth_end',
'qwen_generation_method',
'qwen_refine_use_prev_ref',
'qwen_refine_use_depth',
@@ -469,7 +591,9 @@ GEN_PARAMETERS = [
# ── Preset diff preview helpers ──────────────────────────────────────────
-def _build_preset_items(context, include_deprecated, selected=None):
+def _build_preset_items(context, include_deprecated, selected=None, include_experimental=None):
+ if include_experimental is None:
+ include_experimental = experimental_architectures_enabled(context)
# Group presets by architecture for easier navigation.
_ARCH_GROUP_ORDER = [
('sdxl', 'SDXL'),
@@ -477,6 +601,10 @@ def _build_preset_items(context, include_deprecated, selected=None):
('qwen_image_21', 'Qwen Image 2.1'),
('flux2_klein', 'FLUX.2 Klein (Deprecated)'),
('trellis2', 'TRELLIS.2 Pipeline'),
+ # Later architectures follow so saved preset numbers above stay put.
+ ('qwen_image_21_turbo', 'Qwen Image 2.1 Turbo (Experimental)'),
+ ('moss_image', 'MOSS Image (Experimental)'),
+ ('fibo_edit', 'FIBO 2.0 Edit (Experimental)'),
]
_known_groups = {k for k, _ in _ARCH_GROUP_ORDER}
@@ -488,6 +616,9 @@ def _build_preset_items(context, include_deprecated, selected=None):
deprecated = preset_uses_deprecated_architecture(preset)
if deprecated and not include_deprecated and key != selected:
continue
+ if (not include_experimental and key != selected
+ and preset_uses_experimental_architecture(preset)):
+ continue
if preset.get('architecture_mode') == 'trellis2':
grp = 'trellis2'
else:
@@ -541,7 +672,7 @@ def get_preset_items(self, context):
global _READING_PRESET_SELECTION
# Keep the old, unfiltered menu's numeric values. Hiding Klein presets must
# not silently turn a saved TRELLIS preset (or Custom) into another preset.
- full_items = _build_preset_items(context, include_deprecated=True)
+ full_items = _build_preset_items(context, include_deprecated=True, include_experimental=True)
numbers = {item[0]: index for index, item in enumerate(full_items) if item[0]}
if _READING_PRESET_SELECTION:
items = tuple(item + (numbers[item[0]],) if item[0] else item
@@ -556,6 +687,7 @@ def get_preset_items(self, context):
_READING_PRESET_SELECTION = False
visible_items = _build_preset_items(
context, deprecated_architectures_enabled(context), selected=selected,
+ include_experimental=experimental_architectures_enabled(context),
)
items = tuple(item + (numbers[item[0]],) if item[0] else item
for item in visible_items)
@@ -579,6 +711,12 @@ def update_parameters(self, context):
if (preset_uses_deprecated_architecture(preset)
and not deprecated_architectures_enabled(context)):
continue
+ if (preset_uses_experimental_architecture(preset)
+ and not experimental_architectures_enabled(context)):
+ continue
+ # A texturing preset can share every stored value with a TRELLIS.2 one; never match across the two modes.
+ if (preset.get('architecture_mode') == 'trellis2') != (getattr(scene, 'architecture_mode', '') == 'trellis2'):
+ continue
expected = preset if preset.get('custom', False) else {**TEXTURING_DEFAULTS, **preset}
# First check regular parameters
if all(
@@ -690,7 +828,7 @@ class ResetQwenPrompt(bpy.types.Operator):
if selected == 'CUSTOM':
selected = (
'QWEN_21_DEFAULT'
- if context.scene.model_architecture == 'qwen_image_21'
+ if context.scene.model_architecture != 'qwen_image_edit'
else 'QWEN_EDIT_LEGACY'
)
return get_defaults(
@@ -754,6 +892,10 @@ class ApplyPreset(bpy.types.Operator):
and not deprecated_architectures_enabled(context)):
self.report({'ERROR'}, "Enable deprecated architectures in add-on preferences first; these architectures no longer receive support")
return {'CANCELLED'}
+ if (preset_uses_experimental_architecture(values)
+ and not experimental_architectures_enabled(context)):
+ self.report({'ERROR'}, "Enable experimental architectures in add-on preferences first")
+ return {'CANCELLED'}
if not values.get("custom", False):
for key, value in TEXTURING_DEFAULTS.items():
@@ -841,7 +983,7 @@ class ApplyPreset(bpy.types.Operator):
# include architecture_mode, update the visible dropdown to match.
if "architecture_mode" not in values:
arch = context.scene.model_architecture
- if arch in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ if arch in DIFFUSION_ARCHITECTURES:
context.scene.architecture_mode = arch
if skipped:
diff --git a/stablegen/ui/queue.py b/stablegen/ui/queue.py
index da830ee..f4a10e7 100644
--- a/stablegen/ui/queue.py
+++ b/stablegen/ui/queue.py
@@ -14,6 +14,7 @@ from bpy.app.handlers import persistent
from ..core import ADDON_PKG
from ..utils import sg_modal_active
+from ..core.architectures import DIFFUSION_ARCHITECTURES
# ── Constants ──────────────────────────────────────────────────────────────
@@ -840,7 +841,7 @@ def _queue_tick():
# Trellis2Generate finished — enter settling phase to wait for
# _schedule_texture_generation / _deferred_generate to fire.
- if tex_mode in ('sdxl', 'flux1', 'qwen_image_edit', 'qwen_image_21', 'flux2_klein'):
+ if tex_mode in DIFFUSION_ARCHITECTURES:
_queue_phase = 'settling'
_queue_settle_deadline = _time.monotonic() + 15.0 # generous: server may need VRAM flush
_queue_texturing_seen = False
diff --git a/stablegen/ui/studio.py b/stablegen/ui/studio.py
index 7025ae1..290b7b3 100644
--- a/stablegen/ui/studio.py
+++ b/stablegen/ui/studio.py
@@ -29,12 +29,108 @@ from .studio_widgets import (Painter, FONT_SIZE, CONTROL_HEIGHT, CONTROL_GAP,
from .presets import PRESETS
from ..utils import sg_modal_active
from ..core import ADDON_PKG, legacy_panel_enabled
-from ..generation_status import WAITING_STAGES
+from ..core.generation_status import WAITING_STAGES
+from ..core.architectures import ARCHITECTURE_ITEMS, QWEN_ARCHITECTURES, architecture_status
TAB = 'StableGen'
PAGES = [('GENERATE', 'Texture'), ('CAMERAS', 'Cameras'), ('BLEND', 'Blending')]
MORE = [('TOOLS', 'Tools'), ('QUEUE', 'Scene queue'), ('DEBUG', 'Diagnostics'),
('MESH', 'Mesh & rig'), ('PRINT', '3D printing'), ('EXPERIMENTS', 'Experiments')]
+# Architectures that generate the asset itself rather than texturing an existing mesh.
+ASSET_ARCHITECTURES = {'trellis2'}
+
+
+ARCHITECTURE_PROPERTIES = {'architecture_mode', 'model_architecture', 'trellis2_texture_mode', 'trellis2_initial_image_arch'}
+
+
+def _architecture_tags(prop, identifier):
+ """Tags for an architecture choice, drawn right to left: its role, then its support status."""
+ if prop not in ARCHITECTURE_PROPERTIES:
+ return []
+ tags = ['Asset generation' if identifier in ASSET_ARCHITECTURES else 'Texturing'] if prop == 'architecture_mode' else []
+ status = architecture_status(identifier)
+ return tags + [status] if status else tags
+
+
+# Preset names repeat their model and variant, which the panel shows as tags instead: it lists only the current
+# architecture's presets, so the model name is redundant there.
+PRESET_MODEL_NAMES = {'qwen_image_edit': 'qwen', 'qwen_image_21': 'qwen 2.1', 'qwen_image_21_turbo': 'qwen 2.1 turbo',
+ 'fibo_edit': 'fibo', 'moss_image': 'moss', 'flux2_klein': 'klein'}
+PRESET_VARIANTS = {'nunchaku': 'Nunchaku', 'experimental': 'Experimental'}
+PRESET_WORKFLOWS = ('New texture', 'Refine', 'Local edit', 'UV inpaint', 'Mesh + texture', 'Mesh only')
+
+
+def _preset_workflow(preset):
+ if preset.get('architecture_mode') == 'trellis2':
+ return 'Mesh only' if preset.get('trellis2_texture_mode') == 'none' else 'Mesh + texture'
+ if preset.get('generation_method') == 'uv_inpaint':
+ return 'UV inpaint'
+ if 'local_edit' in (preset.get('generation_method'), preset.get('qwen_generation_method')):
+ return 'Local edit'
+ if preset.get('qwen_generation_method') == 'refine':
+ return 'Refine'
+ return 'New texture'
+
+
+def _preset_model(preset):
+ if preset.get('architecture_mode') == 'trellis2':
+ return preset.get('trellis2_texture_mode', 'none')
+ return preset.get('model_architecture', 'sdxl')
+
+
+def _strip(label, word):
+ lower = label.casefold()
+ if lower.endswith(' (' + word + ')'):
+ return label[:-len(word) - 3], True
+ if lower.startswith(word + ' '):
+ return label[len(word) + 1:], True
+ return label, False
+
+
+def _preset_label(identifier, label):
+ preset = PRESETS.get(identifier)
+ if not preset:
+ return label
+ trellis = preset.get('architecture_mode') == 'trellis2'
+ for word in ('mesh + texture', 'mesh only', *PRESET_VARIANTS) if trellis else PRESET_VARIANTS:
+ label = _strip(label, word)[0]
+ name = PRESET_MODEL_NAMES.get(_preset_model(preset))
+ if name:
+ label = _strip(label, name)[0]
+ if label.startswith('Uv '): # title() case of UV
+ label = 'UV ' + label[3:]
+ # TRELLIS.2 (MESH ONLY) is the stock mesh preset once its tag says what it does.
+ return 'Default' if trellis and label.casefold() == 'trellis.2' else label
+
+
+def _preset_tags(identifier):
+ """Tags for a preset, drawn right to left: its workflow, then its texture model (TRELLIS.2) and variant."""
+ preset = PRESETS.get(identifier)
+ if not preset:
+ return []
+ tags = [_preset_workflow(preset)]
+ if preset.get('architecture_mode') == 'trellis2' and preset.get('trellis2_texture_mode') not in (None, 'none', 'native'):
+ tags.append(_architecture_label(preset['trellis2_texture_mode']))
+ tags += [tag for word, tag in PRESET_VARIANTS.items() if _strip(identifier, word)[1]]
+ return tags
+
+
+def _architecture_label(identifier):
+ return next((item[1] for item in ARCHITECTURE_ITEMS if item[0] == identifier), identifier)
+
+
+def _choice_tags(prop, identifier):
+ return _preset_tags(identifier) if prop == 'stablegen_preset' else _architecture_tags(prop, identifier)
+
+
+def _draw_tags(p, tags, right, y, enabled=True):
+ """Draw *tags* ending at *right*; returns the width they take, gaps included."""
+ used = 0
+ for tag in tags:
+ used += p.tag(tag, right - used, y, enabled=enabled) + 4
+ return used
+
+
PROJECTION_KEYS = {'discard_factor', 'weight_exponent', 'early_priority', 'early_priority_strength',
'bake_visibility_weights', 'sg_texturing_frame', 'sg_allow_backface_projection',
'sg_rework_acquisition_quality', 'sg_rework_projection_guard', 'sg_guard_directional',
@@ -402,6 +498,11 @@ class StudioSession:
(PRESETS[item[0]].get('architecture_mode') or PRESETS[item[0]].get('model_architecture', 'sdxl')) == arch))]
value = binding.value(bpy.context)
items = [(item[0], item[1], item[2] if len(item) > 2 else '') for item in items if item and item[0]]
+ if binding.property == 'stablegen_preset':
+ # Group by workflow (new texture, refine, local edit, ...); Custom stays last.
+ order = {w: n for n, w in enumerate(PRESET_WORKFLOWS)}
+ items = sorted(((i, _preset_label(i, label), d) for i, label, d in items),
+ key=lambda item: order.get(_preset_workflow(PRESETS[item[0]]), 99) if item[0] in PRESETS else 100)
if not items:
self.native(binding=binding)
return
@@ -698,7 +799,7 @@ class StudioSession:
return {'PASS_THROUGH'}
if self.menu:
if event.value == 'PRESS' and event.type == 'ESC':
- self.menu = None
+ self.menu = self.menu.get('parent')
self.area.tag_redraw()
self.update_hover()
return {'RUNNING_MODAL'}
@@ -749,7 +850,7 @@ class StudioSession:
if event.type == 'LEFTMOUSE' and event.value in {'PRESS', 'DOUBLE_CLICK'}:
target = self.hit_target()
if self.menu and (target is None or not isinstance(target.action, tuple) or not target.action[0].startswith('menu-')):
- self.menu = None
+ self.menu = self.menu.get('parent')
self.area.tag_redraw()
return {'RUNNING_MODAL'}
if self.edit and target and target.key == self.edit['key']:
@@ -758,7 +859,9 @@ class StudioSession:
else:
self.commit()
self.activate(target)
- if self.edit and target and target.action[2]:
+ # Only a field's own click places the caret; buttons such as Search also start an edit.
+ if (self.edit and target and isinstance(target.action, tuple) and target.action[0] == 'edit'
+ and target.action[2]):
self.select_caret(x, y)
self.edit['selecting'] = True
self.area.tag_redraw()
@@ -832,9 +935,18 @@ class StudioSession:
return height + label_height + 24
if prop.type == 'ENUM':
label_value = model.enum_label(binding, ctx)
+ if binding.property == 'stablegen_preset':
+ label_value = _preset_label(value, label_value)
painter.outline(x, y, width, CONTROL_HEIGHT, fill='menu',
border='hover_border' if enabled and self.hovered(key) else 'menu_border', corners=corners)
- painter.text(label_value, x + 8, y + 5, FONT_SIZE, 'menu_text' if enabled else 'disabled', width - 33)
+ text_width = width - 33
+ tags = _choice_tags(binding.property, value)
+ # In a narrow field an architecture drops its role tag before its support status; a preset keeps its
+ # workflow tag longest.
+ while tags and painter.measure(label_value) + sum(painter.measure(t, 9) + 14 for t in tags) + 40 > width:
+ tags.pop(-1 if binding.property == 'stablegen_preset' else 0)
+ text_width -= _draw_tags(painter, tags, x + width - 24, y + 4, enabled)
+ painter.text(label_value, x + 8, y + 5, FONT_SIZE, 'menu_text' if enabled else 'disabled', text_width)
painter.icon('down', x + width - 16, y + 6, 10, 'menu_text' if enabled else 'disabled')
painter.target(key, (x, y, width, CONTROL_HEIGHT), ('enum', binding), enabled, hint)
elif prop.type in {'STRING', 'INT', 'FLOAT'} and not getattr(prop, 'is_array', False):
@@ -1286,30 +1398,28 @@ class StudioSession:
p.text(dict(MORE).get(current_page, 'Search'), x + 26, 29, 10, 'muted', width - 80)
scene = bpy.context.scene
y = 42
- native = scene.architecture_mode == 'trellis2' and scene.trellis2_texture_mode in {'native', 'none'}
- if not native:
- p.outline(x, y, width, 46, 'raised')
- tools = [('object.add_cameras', 'Add cameras', 'camera'),
- ('object.collect_camera_prompts', 'Collect camera prompts' if width >= 360 else 'Collect prompts', 'document')]
- for i, (name, text, icon) in enumerate(tools):
- with _viewport(self):
- enabled = model.operator(name).poll() and not self.busy
- key = 'toolbar:' + name
- p.button(key, (x + i * width / 2 + 1, y + 1, width / 2 - 2, CONTROL_HEIGHT), text,
- ('operator', name, {}), icon=icon, enabled=enabled, hover=self.hovered(key),
- hint=help_text.operator_hint(name, bpy.context, enabled, busy=self.busy))
- p.rect(x + width / 2, y + 1, 1, CONTROL_HEIGHT, 'line')
- p.rect(x + 1, y + 24, width - 2, 1, 'divider')
- tools = [('object.clone_camera', 'Clone', 'clone'), ('object.mirror_camera', 'Mirror', 'mirror'),
- ('object.apply_auto_aspect', 'Auto aspect' if width >= 360 else 'Aspect', 'expand'), ('stablegen.camera_display', 'Display', 'labels')]
- for i, (name, text, icon) in enumerate(tools):
- with _viewport(self):
- enabled = model.operator(name).poll() and (not self.busy or name == 'stablegen.camera_display')
- key = 'toolbar:' + name
- p.button(key, (x + i * width / 4 + 1, y + 25, width / 4 - 2, 20), text,
- ('operator', name, {}), icon=icon, enabled=enabled, hover=self.hovered(key),
- hint=help_text.operator_hint(name, bpy.context, enabled, busy=self.busy))
- y += 56
+ p.outline(x, y, width, 46, 'raised')
+ tools = [('object.add_cameras', 'Add cameras', 'camera'),
+ ('object.collect_camera_prompts', 'Collect camera prompts' if width >= 360 else 'Collect prompts', 'document')]
+ for i, (name, text, icon) in enumerate(tools):
+ with _viewport(self):
+ enabled = model.operator(name).poll() and not self.busy
+ key = 'toolbar:' + name
+ p.button(key, (x + i * width / 2 + 1, y + 1, width / 2 - 2, CONTROL_HEIGHT), text,
+ ('operator', name, {}), icon=icon, enabled=enabled, hover=self.hovered(key),
+ hint=help_text.operator_hint(name, bpy.context, enabled, busy=self.busy))
+ p.rect(x + width / 2, y + 1, 1, CONTROL_HEIGHT, 'line')
+ p.rect(x + 1, y + 24, width - 2, 1, 'divider')
+ tools = [('object.clone_camera', 'Clone', 'clone'), ('object.mirror_camera', 'Mirror', 'mirror'),
+ ('object.apply_auto_aspect', 'Auto aspect' if width >= 360 else 'Aspect', 'expand'), ('stablegen.camera_display', 'Display', 'labels')]
+ for i, (name, text, icon) in enumerate(tools):
+ with _viewport(self):
+ enabled = model.operator(name).poll() and (not self.busy or name == 'stablegen.camera_display')
+ key = 'toolbar:' + name
+ p.button(key, (x + i * width / 4 + 1, y + 25, width / 4 - 2, 20), text,
+ ('operator', name, {}), icon=icon, enabled=enabled, hover=self.hovered(key),
+ hint=help_text.operator_hint(name, bpy.context, enabled, busy=self.busy))
+ y += 56
cw = (width - 12) / 2
left = self.draw_binding(p, self.binding('architecture_mode'), 'Architecture', x, y, cw)
actions = [item for item in model.controls(self.document.presets)
@@ -1715,7 +1825,7 @@ class StudioSession:
p.button('refresh-models', (x + width - 25, y - CONTROL_HEIGHT - CONTROL_GAP, 25, CONTROL_HEIGHT), '',
('operator', 'stablegen.refresh_checkpoint_list', {}), icon='reset', enabled=not self.busy,
hint='Refresh the available ComfyUI models after connecting the server or adding model files')
- masked = (scene.qwen_generation_method if scene.model_architecture.startswith('qwen') else scene.generation_method) == 'masked_edit' and scene.architecture_mode != 'trellis2'
+ masked = (scene.qwen_generation_method if scene.model_architecture in QWEN_ARCHITECTURES else scene.generation_method) == 'masked_edit' and scene.architecture_mode != 'trellis2'
prompt = 'sg_masked_prompt' if masked else 'comfyui_prompt'
if hasattr(scene, prompt) and not trellis:
y += self.draw_binding(p, self.binding(prompt), 'Edit instructions' if masked else 'Object prompt' if native else 'Texture prompt', x, y + 4, width, multiline=True, height=112) + 6
@@ -1725,7 +1835,7 @@ class StudioSession:
handled.discard('comfyui_prompt')
mask_commands = {'stablegen.paint_edit_mask', 'stablegen.finish_edit_mask', 'stablegen.clear_edit_mask'}
if not native:
- mode_key = 'qwen_generation_method' if scene.model_architecture.startswith('qwen') else 'generation_method'
+ mode_key = 'qwen_generation_method' if scene.model_architecture in QWEN_ARCHITECTURES else 'generation_method'
cw = (width - 12) / 2
left = self.draw_binding(p, self.binding(mode_key), 'Texture workflow', x, y, cw)
right = self.draw_binding(p, self.binding('texture_objects'), 'Target objects', x + cw + 12, y, cw)
@@ -1858,7 +1968,7 @@ class StudioSession:
p.target('camera-drag:' + camera.name, grip, ('camera-drag', camera.name), not self.busy,
'Drag to change generation order. Dropping enables custom order; Esc cancels.')
p.button('look:' + camera.name, (x + width - 37, y + (10 if selected else 28), 25, CONTROL_HEIGHT), '',
- ('operator', 'stablegen.panel_camera', {'camera_name': camera.name}), icon='eye', enabled=not self.busy,
+ ('operator', 'stablegen.studio_look_camera', {'camera_name': camera.name}), icon='eye', enabled=not self.busy,
hint='Look through ' + camera.name)
image_rect = (x + 12, y + 43, 70, 160) if selected else (x + 30, y + 12, 60, 60)
p.outline(*image_rect, 'menu', 'menu_border', 2)
@@ -1903,13 +2013,22 @@ class StudioSession:
menu = self.menu
items = self.menu_items()
ax, ay, aw, ah = menu['anchor']
- width = min(p.width - 30, max(220, aw))
- rows = min(9, len(items), max(1, int((p.height - 100) / 24)))
- menu['rows'] = rows
- height = 30 + max(1, rows) * 24 + 6
+ width = max(220, aw)
+ if menu.get('binding'):
+ # Room for each label and its tags.
+ width = max([width] + [p.measure(label) + sum(p.measure(t, 9) + 14 for t in _choice_tags(menu['binding'].property, i)) + 40
+ for i, label, _ in items])
+ width = min(p.width - 30, width)
x = min(max(15, ax), p.width - width - 15)
y = ay + ah + 5
- if y + height > p.height - 10:
+ if menu.get('drop_down'):
+ # Always open below the anchor and fill the space to the bottom; the rest scrolls.
+ rows = min(len(items), max(1, int((p.height - 10 - y - 36) / 24)))
+ else:
+ rows = min(9, len(items), max(1, int((p.height - 100) / 24)))
+ menu['rows'] = rows
+ height = 30 + max(1, rows) * 24 + 6
+ if not menu.get('drop_down') and y + height > p.height - 10:
y = max(10, ay - height - 5)
menu['rect'] = (x, y, width, height)
p.outline(x, y, width, height, 'raised', 'line', 6)
@@ -1923,7 +2042,11 @@ class StudioSession:
key = 'choice:' + identifier
if i == menu['index'] or self.hovered(key):
p.rect(*rect, 'selected')
- p.text(label, rect[0] + 8, rect[1] + 5, FONT_SIZE, 'text', width - 26)
+ label_width = width - 26
+ if menu.get('binding'):
+ label_width -= _draw_tags(p, _choice_tags(menu['binding'].property, identifier),
+ rect[0] + rect[2] - 6, rect[1] + 4)
+ p.text(label, rect[0] + 8, rect[1] + 5, FONT_SIZE, 'text', label_width)
p.target(key, rect, ('menu-item', identifier), True, description)
if len(items) > rows:
p.rect(x + width - 5, y + 31 + start / len(items) * (height - 36), 2,
@@ -2046,6 +2169,16 @@ class StudioSession:
self.callout_width = width if self.callout_width is None else min(self.callout_width, width)
self.draw_widen_callout(p, top, width)
if self.menu:
+ parent = self.menu.get('parent')
+ if parent:
+ # A submenu (the LoRA folder filter) opens over its picker, which stays visible but inert.
+ menu, before = self.menu, len(p.targets)
+ self.menu = parent
+ try:
+ self.draw_menu(p)
+ finally:
+ self.menu = menu
+ del p.targets[before:]
self.draw_menu(p)
# Layout changes can put a different control under a stationary mouse.
self.update_hover(p.targets, cursor=False)
@@ -2265,6 +2398,32 @@ class SG_OT_StudioSelectCamera(bpy.types.Operator):
return {'FINISHED'}
+class SG_OT_StudioLookCamera(bpy.types.Operator):
+ bl_idname = 'stablegen.studio_look_camera'
+ bl_label = 'View Camera'
+ bl_description = 'Select this camera and look through it in the viewport'
+ bl_options = {'INTERNAL'}
+ camera_name: bpy.props.StringProperty()
+
+ @classmethod
+ def poll(cls, context):
+ return not sg_modal_active(context)
+
+ def execute(self, context):
+ camera = context.scene.objects.get(self.camera_name)
+ if camera is None or camera.type != 'CAMERA':
+ self.report({'ERROR'}, 'Camera is no longer in this scene')
+ return {'CANCELLED'}
+ from ..cameras.operators import switch_viewport_to_camera
+ switch_viewport_to_camera(context, camera)
+ if camera.name in context.view_layer.objects:
+ for obj in context.selected_objects:
+ obj.select_set(False)
+ camera.select_set(True)
+ context.view_layer.objects.active = camera
+ return {'FINISHED'}
+
+
class SG_OT_StudioPreferences(bpy.types.Operator):
bl_idname = 'stablegen.studio_preferences'
bl_label = 'StableGen Preferences'
@@ -2371,7 +2530,7 @@ def _load_pre(_):
_pending.clear()
-STUDIO_UI_CLASSES = diagnostics.CLASSES + [lora.SG_OT_StudioLoRA, SG_OT_StudioSession, SG_OT_StudioNative, SG_OT_StudioSelectCamera,
+STUDIO_UI_CLASSES = diagnostics.CLASSES + [lora.SG_OT_StudioLoRA, SG_OT_StudioSession, SG_OT_StudioNative, SG_OT_StudioSelectCamera, SG_OT_StudioLookCamera,
SG_OT_StudioReorderCamera, SG_OT_StudioSortCameras,
SG_OT_StudioPreferences, tips.SG_OT_ResetTips, SG_PT_StudioCanvas]
diff --git a/stablegen/ui/studio_help.py b/stablegen/ui/studio_help.py
index d2a080d..a75885a 100644
--- a/stablegen/ui/studio_help.py
+++ b/stablegen/ui/studio_help.py
@@ -2,6 +2,7 @@
import bpy
from . import studio_model as model
+from ..core.architectures import EDIT_ARCHITECTURES
def property_hint(binding, context):
@@ -23,7 +24,7 @@ def property_hint(binding, context):
('This also drives per-camera diffusion textures.' if shared else
'Diffusion textures use the separate prompt on the Texture tab.'))
if key == 'sequential_ipadapter':
- if scene.model_architecture in {'qwen_image_edit', 'qwen_image_21', 'flux2_klein'}:
+ if scene.model_architecture in EDIT_ARCHITECTURES:
return ('Use the first or most recent generated view as an image reference for style continuity. '
'An enabled external style reference can take precedence.')
return ('Use IPAdapter with the first or most recent generated view for style continuity. '
diff --git a/stablegen/ui/studio_lora.py b/stablegen/ui/studio_lora.py
index 18aea7d..d0fae35 100644
--- a/stablegen/ui/studio_lora.py
+++ b/stablegen/ui/studio_lora.py
@@ -140,7 +140,7 @@ def folders(s):
s.menu = {'anchor': parent['folder_rect'], 'items': [('__all__', 'All folders', '')]
+ [(value, 'Root folder' if value == '.' else value, value) for value in values],
- 'query': '', 'binding': None, 'index': 0, 'scroll': 0, 'callback': choose}
+ 'query': '', 'binding': None, 'index': 0, 'scroll': 0, 'callback': choose, 'parent': parent, 'drop_down': True}
def keyboard(s, event):
@@ -289,13 +289,27 @@ def draw_menu(s, p):
menu, items = s.menu, s.menu_items()
ax, ay, aw, ah = menu['anchor']
width = min(p.width - 30, max(280, aw))
- rows = min(8, len(items), max(1, int((p.height - 150) / 45)))
- menu['rows'] = rows
- height = 109 + max(1, rows) * 45 + 29
+ chrome = 109 + 29
+ if not menu.get('placed'):
+ # The picker always opens downward. When the anchor sits too low for a few rows, scroll the page once so
+ # the anchor moves up, and keep the anchor attached to it.
+ menu['placed'] = True
+ want = ay + ah + 5 + chrome + min(len(items), 6) * 45 - (p.height - 10)
+ shift = max(0, min(want, s.max_scroll - s.scroll.get(s.page, 0)))
+ if shift:
+ s.scroll[s.page] = s.scroll.get(s.page, 0) + shift
+ ay -= shift
+ menu['anchor'] = (ax, ay, aw, ah)
+ s.area.tag_redraw()
x = min(max(15, ax), p.width - width - 15)
y = ay + ah + 5
- if y + height > p.height - 10:
- y = max(10, ay - height - 5)
+ rows = min(len(items), max(1, int((p.height - 10 - y - chrome) / 45)))
+ if rows < min(len(items), 2):
+ # Last resort at the very end of the page: open upward.
+ rows = min(len(items), max(1, int((ay - 15 - chrome) / 45)))
+ y = max(10, ay - chrome - rows * 45 - 5)
+ menu['rows'] = rows
+ height = chrome + max(1, rows) * 45
menu['rect'] = (x, y, width, height)
p.rect(x - 1, y + 2, width + 2, height + 2, 'panel_shadow', 4)
p.outline(x, y, width, height, 'tooltip', 'section_border', 4)
diff --git a/stablegen/ui/studio_model.py b/stablegen/ui/studio_model.py
index 85856a8..7dd1920 100644
--- a/stablegen/ui/studio_model.py
+++ b/stablegen/ui/studio_model.py
@@ -8,7 +8,7 @@ import bpy
from .presentation import Layout, Control, capture_panel
from .presets import get_preset_items
from .model_units import update_model_list, get_lora_models, get_controlnet_models
-from ..architecture_options import (architecture_items, model_architecture_items,
+from ..core.architectures import (architecture_items, model_architecture_items,
trellis_texture_items, trellis_initial_image_items)
diff --git a/stablegen/ui/studio_widgets.py b/stablegen/ui/studio_widgets.py
index 0f8e3ff..60fb1b5 100644
--- a/stablegen/ui/studio_widgets.py
+++ b/stablegen/ui/studio_widgets.py
@@ -437,6 +437,13 @@ class Painter:
text = text[:-1]
return text + '…' if text else ''
+ def tag(self, text, right, y, *, enabled=True):
+ """A small rounded label ending at *right*; returns its width."""
+ width = self.measure(text, 9) + 10
+ self.outline(right - width, y, width, 15, 'hover_soft', 'line', 3)
+ self.text(text, right - width + 5, y + 2, 9, 'secondary' if enabled else 'disabled')
+ return width
+
def text(self, text, x, y, size=FONT_SIZE, tint='text', width=None):
text = str(text)
if width is not None:
diff --git a/stablegen/comfy_workflow_export.py b/stablegen/util/comfy_workflow_export.py
similarity index 76%
rename from stablegen/comfy_workflow_export.py
rename to stablegen/util/comfy_workflow_export.py
index ed0b771..92a725e 100644
--- a/stablegen/comfy_workflow_export.py
+++ b/stablegen/util/comfy_workflow_export.py
@@ -1,4 +1,4 @@
-"""Create editable ComfyUI workflow files from StableGen Qwen 2.1 prompts."""
+"""Create editable ComfyUI workflow files from StableGen Qwen 2.1 and FIBO prompts."""
from __future__ import annotations
@@ -16,7 +16,20 @@ _OUTPUTS = {
('negative', 'CONDITIONING'),
('latent', 'LATENT'),
],
+ 'TextEncodeFibo2': [
+ ('positive', 'CONDITIONING'),
+ ('negative', 'CONDITIONING'),
+ ('latent', 'LATENT'),
+ ],
+ 'GetImageSize': [('width', 'INT'), ('height', 'INT'), ('batch_size', 'INT')],
'KSampler': [('LATENT', 'LATENT')],
+ 'RandomNoise': [('NOISE', 'NOISE')],
+ 'CFGGuider': [('GUIDER', 'GUIDER')],
+ 'KSamplerSelect': [('SAMPLER', 'SAMPLER')],
+ 'ManualSigmas': [('SIGMAS', 'SIGMAS')],
+ 'SamplerCustomAdvanced': [
+ ('output', 'LATENT'), ('denoised_output', 'LATENT'),
+ ],
'VAEDecode': [('IMAGE', 'IMAGE')],
'SaveImage': [('images', 'IMAGE')],
'SaveImageWebsocket': [],
@@ -30,6 +43,13 @@ _WIDGETS = {
'VAELoader': ['vae_name'],
'QwenImage21Cache': ['device', 'dtype'],
'TextEncodeQwenImage21': ['prompt', 'negative_prompt', 'resolution'],
+ 'TextEncodeFibo2': [
+ 'prompt', 'negative_prompt', 'width', 'height', 'batch_size'
+ ],
+ 'RandomNoise': ['noise_seed'],
+ 'CFGGuider': ['cfg'],
+ 'KSamplerSelect': ['sampler_name'],
+ 'ManualSigmas': ['sigmas'],
'KSampler': [
'seed', 'steps', 'cfg', 'sampler_name', 'scheduler', 'denoise'
],
@@ -47,6 +67,26 @@ _LINK_INPUT_TYPES = {
'vae': 'VAE',
**{f'images.image_{index}': 'IMAGE' for index in range(1, 17)},
},
+ 'TextEncodeFibo2': {
+ 'clip': 'CLIP',
+ 'vae': 'VAE',
+ 'width': 'INT',
+ 'height': 'INT',
+ **{f'images.image_{index}': 'IMAGE' for index in range(1, 17)},
+ },
+ 'GetImageSize': {'image': 'IMAGE'},
+ 'CFGGuider': {
+ 'model': 'MODEL',
+ 'positive': 'CONDITIONING',
+ 'negative': 'CONDITIONING',
+ },
+ 'SamplerCustomAdvanced': {
+ 'noise': 'NOISE',
+ 'guider': 'GUIDER',
+ 'sampler': 'SAMPLER',
+ 'sigmas': 'SIGMAS',
+ 'latent_image': 'LATENT',
+ },
'KSampler': {
'model': 'MODEL',
'positive': 'CONDITIONING',
@@ -65,6 +105,19 @@ _INPUT_ORDER = {
'prompt', 'negative_prompt', 'resolution',
*[f'images.image_{index}' for index in range(2, 17)],
],
+ 'TextEncodeFibo2': [
+ 'clip', 'prompt', 'negative_prompt', 'vae',
+ *[f'images.image_{index}' for index in range(1, 17)],
+ 'width', 'height', 'batch_size',
+ ],
+ 'GetImageSize': ['image'],
+ 'RandomNoise': ['noise_seed'],
+ 'CFGGuider': ['model', 'positive', 'negative', 'cfg'],
+ 'KSamplerSelect': ['sampler_name'],
+ 'ManualSigmas': ['sigmas'],
+ 'SamplerCustomAdvanced': [
+ 'noise', 'guider', 'sampler', 'sigmas', 'latent_image'
+ ],
'KSampler': [
'model', 'seed', 'steps', 'cfg', 'sampler_name', 'scheduler',
'positive', 'negative', 'latent_image', 'denoise',
@@ -82,6 +135,11 @@ _WIDGET_TYPES = {
'cfg': 'FLOAT',
'denoise': 'FLOAT',
'resolution': 'INT',
+ 'noise_seed': 'INT',
+ 'width': 'INT',
+ 'height': 'INT',
+ 'batch_size': 'INT',
+ 'sigmas': 'STRING',
'megapixels': 'FLOAT',
'resolution_steps': 'INT',
'prompt': 'STRING',
@@ -97,7 +155,14 @@ _POSITIONS = {
'ImageScaleToTotalPixels': (330, 650),
'QwenImage21Cache': (360, 0),
'TextEncodeQwenImage21': (360, 220),
+ 'TextEncodeFibo2': (360, 220),
+ 'GetImageSize': (360, 860),
'KSampler': (920, 0),
+ 'RandomNoise': (920, 0),
+ 'CFGGuider': (920, 140),
+ 'KSamplerSelect': (920, 300),
+ 'ManualSigmas': (920, 400),
+ 'SamplerCustomAdvanced': (1220, 0),
'VAEDecode': (1260, 0),
'SaveImage': (1540, 0),
}
@@ -122,11 +187,14 @@ def _integer_node_id(node_id):
def _widget_value(class_type, name, api_inputs):
if class_type == 'SaveImage' and name == 'filename_prefix':
return api_inputs.get(name, 'StableGen_test')
- return api_inputs.get(name)
+ value = api_inputs.get(name)
+ # A widget driven by a link (FIBO's size from GetImageSize) keeps a
+ # placeholder value; the link supplies the real one.
+ return 0 if _is_link(value) else value
def _node_size(class_type):
- if class_type == 'TextEncodeQwenImage21':
+ if class_type in ('TextEncodeQwenImage21', 'TextEncodeFibo2'):
return [500, 610]
if class_type == 'LoadImage':
return [300, 300]
@@ -136,7 +204,7 @@ def _node_size(class_type):
def qwen_image_21_ui_workflow(prompt):
- """Return a frontend workflow for a Qwen 2.1 API prompt, or ``None``.
+ """Return a frontend workflow for a Qwen 2.1 or FIBO API prompt, or ``None``.
ComfyUI API prompts normally import through ``loadApiJson``. Frontend
1.53.x currently throws while reconstructing Qwen 2.1's COMFY_AUTOGROW_V3
@@ -144,7 +212,7 @@ def qwen_image_21_ui_workflow(prompt):
remains editable and runnable in the browser.
"""
if not any(
- node.get('class_type') == 'TextEncodeQwenImage21'
+ node.get('class_type') in ('TextEncodeQwenImage21', 'TextEncodeFibo2')
for node in prompt.values()
if isinstance(node, dict)
):
@@ -186,7 +254,14 @@ def qwen_image_21_ui_workflow(prompt):
link_types = _LINK_INPUT_TYPES.get(class_type, {})
ui_inputs = []
for name in input_order:
- if name in link_types:
+ if name in link_types and name in widgets:
+ ui_inputs.append({
+ 'name': name,
+ 'type': link_types[name],
+ 'widget': {'name': name},
+ 'link': None,
+ })
+ elif name in link_types:
ui_inputs.append({
'name': name,
'type': link_types[name],
@@ -213,7 +288,7 @@ def qwen_image_21_ui_workflow(prompt):
widget_values = [
_widget_value(class_type, name, api_inputs) for name in widgets
]
- if class_type == 'KSampler':
+ if class_type in ('KSampler', 'RandomNoise'):
widget_values.insert(1, 'fixed')
if class_type == 'LoadImage':
widget_values.append('image')
diff --git a/stablegen/util/mirror_color.py b/stablegen/util/mirror_color.py
index 7e48d89..4a5c0b7 100644
--- a/stablegen/util/mirror_color.py
+++ b/stablegen/util/mirror_color.py
@@ -8,6 +8,7 @@ from mathutils import Vector
from ..utils import get_file_path, get_last_material_index, sg_modal_active
from ..texturing.projection import project_image
from .color_match import color_match_single
+from ..core.architectures import QWEN_ARCHITECTURES
def _build_mirrored_camera_matrix(
cam: bpy.types.Object,
@@ -510,7 +511,7 @@ class MirrorReproject(bpy.types.Operator):
return {'CANCELLED'}
# Branch: local_edit vs everything else
- if scene.generation_method == 'local_edit' or (scene.model_architecture.startswith('qwen') and scene.qwen_generation_method == 'local_edit'):
+ if scene.generation_method == 'local_edit' or (scene.model_architecture in QWEN_ARCHITECTURES and scene.qwen_generation_method == 'local_edit'):
return self._do_refine_mirror(context, to_texture)
else:
return self._do_standard_mirror(context, to_texture)
diff --git a/stablegen/prompt_archive.py b/stablegen/util/prompt_archive.py
similarity index 100%
rename from stablegen/prompt_archive.py
rename to stablegen/util/prompt_archive.py
diff --git a/stablegen/utils.py b/stablegen/utils.py
index 7dedb9e..9769907 100644
--- a/stablegen/utils.py
+++ b/stablegen/utils.py
@@ -500,6 +500,14 @@ def get_compositor_node_tree(scene):
return None
+def new_compositor_math(nodes, operation):
+ """Add a Math node to a compositor tree. Blender 4.x has its own CompositorNodeMath (4.2-4.4 accept
+ no other); Blender 5 removed it in favour of the shared ShaderNodeMath."""
+ node = nodes.new('CompositorNodeMath' if hasattr(bpy.types, 'CompositorNodeMath') else 'ShaderNodeMath')
+ node.operation = operation
+ return node
+
+
def configure_output_node_paths(node, directory, filename):
"""Configure output node paths using Blender 5.0+ image-mode semantics with 4.x fallback."""
diff --git a/stablegen/workflows.py b/stablegen/workflows.py
index dc21a9e..b370e35 100644
--- a/stablegen/workflows.py
+++ b/stablegen/workflows.py
@@ -11,8 +11,8 @@ import email.utils
from datetime import datetime, timezone, timedelta
from .timeout_config import get_timeout
-from .prompt_archive import archive_prompt
-from .generation_status import set_server_stage, node_stage
+from .util.prompt_archive import archive_prompt
+from .core.generation_status import set_server_stage, node_stage
from io import BytesIO
import numpy as np
@@ -484,7 +484,7 @@ class _WorkflowBase:
elif message['type'] == 'executing':
data = message['data']
- if data['prompt_id'] == prompt_id:
+ if data.get('prompt_id') == prompt_id:
if data['node'] is None:
break # Execution is complete
else: