Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
add the new stablegen panel with custom controls and workflow cards
sakalondf7338322fb56
diff --git a/stablegen/__init__.py b/stablegen/__init__.pyindex e70751e..f5a91d3 100644--- a/stablegen/__init__.py+++ b/stablegen/__init__.py@@ -13,6 +13,10 @@ from .ui.presets import (ResetQwenPrompt, ResetTexturingExperiments, SwitchToMeshGeneration,)from .ui.panel import StableGenPanel, StableGenPrintPanel+from .ui.panel_variants import (+ VARIANT_UI_CLASSES, register_variant_properties, unregister_variant_properties,+)+from .ui.studio import STUDIO_UI_CLASSES, register_studio_ui, unregister_studio_uifrom .ui.queue import (SG_UL_SceneQueueList, SceneQueueAdd, SceneQueueRemove, SceneQueueClear,SceneQueueMoveUp, SceneQueueMoveDown, SceneQueueOpenResult,@@ -197,6 +201,8 @@ classes = [classes.extend(_debug_classes)classes.extend(REGRESSION_CLASSES)classes.extend(masked_edit.MASKED_EDIT_CLASSES)+classes.extend(VARIANT_UI_CLASSES)+classes.extend(STUDIO_UI_CLASSES)def register():@@ -214,9 +220,13 @@ def register():_sg_queue_load_handler=_sg_queue_load_handler,_sg_queue_load=_sg_queue_load,)+ register_variant_properties()+ register_studio_ui()def unregister():+ unregister_studio_ui()+ unregister_variant_properties()masked_edit.unregister_properties()from .mesh_gen.batch import unregister_batchfrom .dae_import.batch_texture import unregister_batch_texturediff --git a/stablegen/architecture_options.py b/stablegen/architecture_options.pynew file mode 100644index 0000000..d5118d9--- /dev/null+++ b/stablegen/architecture_options.py@@ -0,0 +1,95 @@+"""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/core/preferences.py b/stablegen/core/preferences.pyindex 1d68864..198f2ea 100644--- a/stablegen/core/preferences.py+++ b/stablegen/core/preferences.py@@ -10,6 +10,7 @@ Contains:import bpy # pylint: disable=import-error+from ..architecture_options import redraw_architecture_menusfrom ..ui.presets import update_parametersfrom ..utils import sg_modal_activefrom . import ADDON_PKG@@ -58,6 +59,13 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):"""Preferences for the StableGen addon."""bl_idname = ADDON_PKG+ enable_deprecated_architectures: bpy.props.BoolProperty(+ name="Enable Deprecated Architectures",+ description="Show FLUX.1 and FLUX.2 Klein architectures and their settings; these architectures no longer receive further support",+ default=False,+ 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",@@ -194,6 +202,9 @@ 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_deprecated_architectures")+ if self.enable_deprecated_architectures:+ layout.label(text="FLUX.1 and FLUX.2 Klein no longer receive support.", icon='INFO')layout.prop(self, "enable_scene_queue")layout.separator()@@ -246,9 +257,13 @@ class CheckServerStatus(bpy.types.Operator):bl_idname = "stablegen.check_server_status"bl_label = "Check Server Status"bl_description = "Ping the ComfyUI server to check connectivity"+ _checking = False@classmethoddef poll(cls, context):+ if cls._checking:+ cls.poll_message_set("Checking server connection")+ return Falseprefs = context.preferences.addons.get(ADDON_PKG)if not prefs or not prefs.preferences.server_address:cls.poll_message_set("Server address not configured (check addon preferences)")@@ -280,6 +295,8 @@ class CheckServerStatus(bpy.types.Operator):return resultdef _on_done(result):+ # Also release the button after an error or a superseded request.+ type(self)._checking = Falseif result is None:return_prefs = bpy.context.preferences.addons[ADDON_PKG].preferences@@ -305,7 +322,12 @@ class CheckServerStatus(bpy.types.Operator):else:print(f"[StableGen] ComfyUI server unreachable or timed out at {server_addr}.")- _run_async(_bg_work, _on_done, track_generation=True)+ type(self)._checking = True+ try:+ _run_async(_bg_work, _on_done, track_generation=True)+ except Exception:+ type(self)._checking = False+ raiseself.report({'INFO'}, f"Checking server at {server_addr}...")return {'FINISHED'}diff --git a/stablegen/core/properties.py b/stablegen/core/properties.pyindex 04e6d71..421de18 100644--- a/stablegen/core/properties.py+++ b/stablegen/core/properties.py@@ -23,6 +23,10 @@ from .callbacks import ()from . import ADDON_PKGfrom ..feature_flags import TEXTURING_DEFAULTS+from ..architecture_options import (+ architecture_items, model_architecture_items,+ trellis_texture_items, trellis_initial_image_items,+)from ..texturing.qwen_models import QWEN_PROMPT_TEMPLATE_ITEMS@@ -300,7 +304,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,)bpy.types.Scene.use_separate_texture_prompt = bpy.props.BoolProperty(name="Use Separate Texture Prompt",- description="Enable a dedicated prompt field for the texturing pass instead of reusing the main prompt",+ description="Use a dedicated TRELLIS.2 texturing prompt instead of reusing the mesh image prompt",default=False,update=update_parameters)@@ -436,6 +440,8 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,name="Target Megapixels",description=("Target total megapixels when auto-rescaling the render resolution.\n\n"+ "Qwen Image 2.1 automatically aligns the resulting width and height "+ "to multiples of 32 pixels.\n\n""Default: 1.0 MP (~1024\u00d71024). This is the native resolution for SDXL ""and the recommended default for Qwen Image Edit.\n\n""For SDXL / Flux models 1.0 MP is a safe default that matches "@@ -989,7 +995,7 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,# ── Presets ────────────────────────────────────────────────────────bpy.types.Scene.stablegen_preset = bpy.props.EnumProperty(name="Preset", description="Select a preset for easy mode",- items=get_preset_items, default=0+ items=get_preset_items, default=1 # DEFAULT; index 0 is the section header.)bpy.types.Scene.active_preset = bpy.props.StringProperty(name="Active Preset", default="DEFAULT"@@ -999,28 +1005,15 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,bpy.types.Scene.model_architecture = bpy.props.EnumProperty(name="Model Architecture",description="Select the model architecture to use for generation",- items=[- ('sdxl', 'SDXL', ''),- ('flux1', 'FLUX.1', ''),- ('qwen_image_edit', 'Qwen Image Edit', 'Qwen-Image-Edit checkpoints'),- ('qwen_image_21', 'Qwen Image 2.1', 'Qwen-Image 2.1 checkpoints'),- ('flux2_klein', 'FLUX.2 Klein', '')- ],- default='sdxl',+ items=model_architecture_items,+ default=0,update=update_combined)bpy.types.Scene.architecture_mode = bpy.props.EnumProperty(name="Architecture",description="Select the overall generation architecture",- items=[- ('sdxl', 'SDXL', 'Stable Diffusion XL'),- ('flux1', 'FLUX.1', 'FLUX.1 architecture'),- ('qwen_image_edit', 'Qwen Image Edit', 'Qwen-Image-Edit checkpoints'),- ('qwen_image_21', 'Qwen Image 2.1', 'Qwen-Image 2.1 checkpoints'),- ('flux2_klein', 'FLUX.2 Klein', 'FLUX.2 Klein multi-reference edit model (Apache 2.0)'),- ('trellis2', 'TRELLIS.2', 'Image to 3D mesh generation with TRELLIS.2'),- ],- default='sdxl',+ items=architecture_items,+ default=0,update=update_architecture_mode)@@ -1035,28 +1028,14 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,)bpy.types.Scene.trellis2_texture_mode = bpy.props.EnumProperty(name="Texture Mode", description="How to generate textures for the 3D mesh",- items=[- ('none', 'None', 'Shape only, no texture generation'),- ('native', 'Native (TRELLIS.2)', 'Use TRELLIS.2 built-in texture generation'),- ('sdxl', 'SDXL', 'Use SDXL for camera-based texture projection'),- ('flux1', 'FLUX.1', 'Use FLUX.1 for camera-based texture projection'),- ('qwen_image_edit', 'Qwen Image Edit', 'Use Qwen-Image-Edit for camera-based texture projection'),- ('qwen_image_21', 'Qwen Image 2.1', 'Use Qwen-Image 2.1 for camera-based texture projection'),- ('flux2_klein', 'FLUX.2 Klein', 'Use FLUX.2 Klein for camera-based texture projection'),- ],- default='native', update=update_trellis2_texture_mode+ items=trellis_texture_items,+ default=1, update=update_trellis2_texture_mode)bpy.types.Scene.trellis2_initial_image_arch = bpy.props.EnumProperty(name="Initial Image Architecture",description="Diffusion architecture used to generate the initial image when Generate From is set to Prompt and Texture Mode is Native or None",- items=[- ('sdxl', 'SDXL', 'Stable Diffusion XL'),- ('flux1', 'FLUX.1', 'FLUX.1 architecture'),- ('qwen_image_edit', 'Qwen Image Edit', 'Qwen-Image-Edit'),- ('qwen_image_21', 'Qwen Image 2.1', 'Qwen-Image 2.1'),- ('flux2_klein', 'FLUX.2 Klein', 'FLUX.2 Klein multi-reference edit'),- ],- default='sdxl', update=update_trellis2_initial_image_arch+ items=trellis_initial_image_items,+ default=0, update=update_trellis2_initial_image_arch)bpy.types.Scene.trellis2_camera_count = bpy.props.IntProperty(name="Camera Count", description="Number of cameras to place around the generated mesh for texture projection",diff --git a/stablegen/texturing/regression.py b/stablegen/texturing/regression.pyindex ac5ea30..76ddd2a 100644--- a/stablegen/texturing/regression.py+++ b/stablegen/texturing/regression.py@@ -485,12 +485,13 @@ class SG_OT_TexturingRegression(bpy.types.Operator):self.scene.model_name = modelif not self.scene.model_name or self.scene.model_name.startswith(('NO_', 'NONE_')):raise RuntimeError('No usable model selected')+ from .workflows import _texturing_promptself.entry['passes'].append({'preset': self.preset, 'model': self.scene.model_name,'method': self.scene.generation_method,'qwen_method': self.scene.qwen_generation_method,'cameras': [obj.name for obj in cameras],'camera_scope': self.scene['_sg_regression_camera_scope'],- 'prompt': self.scene.texture_prompt if self.scene.use_separate_texture_prompt else self.scene.comfyui_prompt})+ 'prompt': _texturing_prompt(self.scene)})self.scene.sg_last_gen_error = Falseself.phase = 'generation'self.write_report('running')diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.pyindex d11662b..6aebe74 100644--- a/stablegen/texturing/workflows.py+++ b/stablegen/texturing/workflows.py@@ -57,12 +57,13 @@ def _texturing_prompt(scene):"""Return the texturing portion of the prompt.Priority order:- 1. Dedicated ``texture_prompt`` field (if the separate-prompt toggle is on- and the field is non-empty).+ 1. Dedicated TRELLIS.2 ``texture_prompt`` field (if the separate-prompt+ toggle is on and the field is non-empty).2. Legacy ``||`` separator in the main prompt (text after ``||``).3. The full main prompt as-is."""- if getattr(scene, 'use_separate_texture_prompt', False):+ if (getattr(scene, 'architecture_mode', None) == 'trellis2'+ and getattr(scene, 'use_separate_texture_prompt', False)):tex = getattr(scene, 'texture_prompt', '').strip()if tex:return tex@@ -75,12 +76,13 @@ def _texturing_prompt(scene):def _generation_prompt(scene):"""Return the generation / mesh-creation portion of the prompt.- When the separate-texture-prompt toggle is on the entire main prompt is- treated as the generation prompt (no ``||`` splitting). Otherwise the- legacy ``||`` separator is respected.+ In TRELLIS.2, when the separate-texture-prompt toggle is on, the entire+ main prompt is used for mesh image generation (no ``||`` splitting).+ Otherwise the legacy ``||`` separator is respected."""raw = scene.comfyui_prompt- if getattr(scene, 'use_separate_texture_prompt', False):+ if (getattr(scene, 'architecture_mode', None) == 'trellis2'+ and getattr(scene, 'use_separate_texture_prompt', False)):return raw.strip()if '||' in raw:return raw.split('||', 1)[0].strip()diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.pyindex 16ba3a9..2b5dffc 100644--- a/stablegen/ui/panel.py+++ b/stablegen/ui/panel.py@@ -8,6 +8,9 @@ from ..utils import sg_modal_activefrom ..core import get_addon_prefsfrom .presets import PRESETS, GEN_PARAMETERSfrom ..feature_flags import experiments_enabled, active_experiments+from ..architecture_options import (+ active_deprecated_architectures, deprecated_architectures_enabled,+)from . import queue as _queue_mod_ADDON_PKG = __package__.rsplit('.', 1)[0]@@ -172,6 +175,21 @@ class StableGenPanel(bpy.types.Panel):addon_prefs = context.preferences.addons[_ADDON_PKG].preferences+ deprecated = active_deprecated_architectures(scene)+ if deprecated:+ box = layout.box()+ box.label(text="Deprecated architecture: no further support", icon='INFO')+ if not deprecated_architectures_enabled(context):+ box.label(text="Enable deprecated 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")+ # Saved FLUX scenes remain intact, but their settings and actions+ # are hidden until the user opts in or chooses a supported model.+ returnconfig_error_message = Noneif not os.path.exists(addon_prefs.output_dir):@@ -720,12 +738,12 @@ class StableGenPanel(bpy.types.Panel):split.label(text="Prompt:")prompt_row = split.row(align=True)prompt_row.prop(scene, "comfyui_prompt", text="")- # Hide texture prompt toggle when texture mode is none/native (no separate texture pipeline)- if not (is_trellis2 and trellis2_tex_mode in ('none', 'native')):+ # Only TRELLIS.2 has distinct mesh-image and texturing prompts.+ if trellis2_diffusion_texturing:prompt_row.prop(scene, "use_separate_texture_prompt", text="",icon='BRUSH_DATA',icon_only=True)- if scene.use_separate_texture_prompt and not (is_trellis2 and trellis2_tex_mode in ('none', 'native')):+ if trellis2_diffusion_texturing and scene.use_separate_texture_prompt:split = params_container.split(factor=0.25)split.label(text="Texture Prompt:")split.prop(scene, "texture_prompt", text="")diff --git a/stablegen/ui/panel_variants.py b/stablegen/ui/panel_variants.pynew file mode 100644index 0000000..e3f02de--- /dev/null+++ b/stablegen/ui/panel_variants.py@@ -0,0 +1,465 @@+"""Three live UI alternatives alongside the unchanged legacy sidebar."""+import bpy++from ..utils import sg_modal_active+from .presentation import capture_panel++PAGES = (+ ('GENERATE', 'Generate', 'Generation, models and guidance', 'RENDER_STILL', 0),+ ('CAMERAS', 'Cameras', 'Viewpoints, framing and order', 'CAMERA_DATA', 1),+ ('BLEND', 'Blending', 'Projection, visibility and DPPG', 'MOD_MASK', 2),+ ('OUTPUT', 'Output', 'Materials, PBR and export', 'MATERIAL', 3),+ ('MESH', 'Mesh & Rig', 'TRELLIS.2 geometry and rigging', 'MESH_DATA', 4),+ ('TOOLS', 'Tools & Batch', 'Utilities and queued scenes', 'TOOL_SETTINGS', 5),+ ('DEBUG', 'Diagnostics', 'Debug tools and experimental settings', 'GHOST_ENABLED', 6),+ ('PRINT', 'Printing', 'Palette and print exports', 'OUTLINER_OB_MESH', 7),+)+PAGE_LABELS = {item[0]: (item[1], item[3]) for item in PAGES}+STAGES = (+ ('SETUP', 'Set up', 'Model, prompt and generation settings', 'SETTINGS', 0),+ ('VIEWS', 'Arrange views', 'Camera setup and view descriptions', 'CAMERA_DATA', 1),+ ('RUN', 'Generate', 'Generation mode and execution', 'PLAY', 2),+ ('PROJECT', 'Blend & inspect', 'Projection and diagnostics', 'MOD_MASK', 3),+ ('DELIVER', 'Bake & export', 'Materials and deliverables', 'EXPORT', 4),+ ('UTILITY', 'Utilities', 'Batch workflows and remaining tools', 'TOOL_SETTINGS', 5),+)+STATE_NAMES = {'STUDIO': 'sg_ui_studio', 'WORKBENCH': 'sg_ui_workbench', 'FOCUS': 'sg_ui_focus'}+DEFAULT_OPEN = 'main|show_core_settings|show_mode_specific_settings|show_scene_understanding_settings|show_output_material_settings|camera_tools|export'+++def _redraw(self, context):+ for window in context.window_manager.windows:+ for area in window.screen.areas:+ if area.type == 'VIEW_3D':+ area.tag_redraw()+++class SGPanelVariantState(bpy.types.PropertyGroup):+ page: bpy.props.EnumProperty(items=PAGES, default='GENERATE', update=_redraw)+ stage: bpy.props.EnumProperty(items=STAGES, default='SETUP', update=_redraw)+ query: bpy.props.StringProperty(name='Find a setting', description='Search available section titles, controls and tooltips', update=_redraw)+ open_sections: bpy.props.StringProperty(default=DEFAULT_OPEN)+ pinned_sections: bpy.props.StringProperty(default='')+ overview: bpy.props.BoolProperty(default=True)+ show_pins: bpy.props.BoolProperty(name='Pinned Settings', default=True, update=_redraw)+ camera_index: bpy.props.IntProperty(default=0)+++class SG_OT_PanelNavigate(bpy.types.Operator):+ bl_idname = 'stablegen.panel_navigate'+ bl_label = 'Open Settings'+ bl_description = 'Open this part of the StableGen panel'+ bl_options = {'INTERNAL'}+ variant: bpy.props.EnumProperty(items=[(key, key.title(), '') for key in STATE_NAMES])+ destination: bpy.props.StringProperty()+ section: bpy.props.StringProperty()+ mode: bpy.props.EnumProperty(items=[('PAGE', 'Page', ''), ('STAGE', 'Stage', ''), ('OVERVIEW', 'Overview', '')])++ def execute(self, context):+ state = getattr(context.window_manager, STATE_NAMES[self.variant])+ if self.mode == 'STAGE':+ state.stage = self.destination+ elif self.mode == 'OVERVIEW':+ state.overview = True+ state.query = ''+ else:+ state.page = self.destination+ state.overview = False+ state.query = ''+ if self.section:+ keys = set(filter(None, state.open_sections.split('|')))+ keys.add(self.section)+ state.open_sections = '|'.join(sorted(keys))+ elif self.mode == 'PAGE' and self.destination == 'DEBUG':+ keys = set(filter(None, state.open_sections.split('|')))+ keys.add('debug')+ state.open_sections = '|'.join(sorted(keys))+ _redraw(self, context)+ return {'FINISHED'}+++class SG_OT_PanelSection(bpy.types.Operator):+ bl_idname = 'stablegen.panel_section'+ bl_label = 'Expand Section'+ bl_description = 'Expand or collapse this section, or pin it to the Workbench overview'+ bl_options = {'INTERNAL'}+ variant: bpy.props.EnumProperty(items=[(key, key.title(), '') for key in STATE_NAMES])+ section: bpy.props.StringProperty()+ pin: bpy.props.BoolProperty(default=False)++ def execute(self, context):+ state = getattr(context.window_manager, STATE_NAMES[self.variant])+ field = 'pinned_sections' if self.pin else 'open_sections'+ keys = set(filter(None, getattr(state, field).split('|')))+ if self.section in keys:+ keys.remove(self.section)+ else:+ keys.add(self.section)+ setattr(state, field, '|'.join(sorted(keys)))+ _redraw(self, context)+ return {'FINISHED'}+++class SG_OT_PanelCamera(bpy.types.Operator):+ bl_idname = 'stablegen.panel_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_UL_PanelCameras(bpy.types.UIList):+ """A compact view selector with editable per-view descriptions."""+ bl_idname = 'SG_UL_PanelCameras'++ def draw_item(self, context, layout, data, item, icon, active_data, active_property, index):+ camera = item+ cameras = [obj for obj in context.scene.objects if obj.type == 'CAMERA']+ prompt = context.scene.camera_prompts.get(camera.name)+ row = layout.row(align=True)+ row.label(text=f'{cameras.index(camera) + 1:02}', icon='CAMERA_DATA')+ row.label(text=item.name)+ button = row.operator('stablegen.panel_camera', text='', icon='HIDE_OFF')+ button.camera_name = item.name+ if context.region.width >= 430 and prompt:+ row.prop(prompt, 'prompt', text='')++ def filter_items(self, context, data, property):+ return [self.bitflag_filter_item if obj.type == 'CAMERA' else 0+ for obj in getattr(data, property)], []+++def _state(context, variant):+ return getattr(context.window_manager, STATE_NAMES[variant])+++def _nav_button(layout, variant, destination, text, icon, *, active=False, mode='PAGE', section=''):+ op = layout.operator('stablegen.panel_navigate', text=text, icon=icon, depress=active)+ op.variant, op.destination, op.mode, op.section = variant, destination, mode, section+++def _section(layout, section, state, variant, *, force_open=False, pinnable=False, title=None):+ expanded = force_open or section.key in state.open_sections.split('|')+ box = layout.box()+ header = box.row(align=True)+ if force_open:+ header.label(text='', icon='VIEWZOOM')+ else:+ button = header.operator('stablegen.panel_section', text='',+ icon='TRIA_DOWN' if expanded else 'TRIA_RIGHT', emboss=False)+ button.variant, button.section = variant, section.key+ header.label(text=title or section.title, icon=section.icon)+ if pinnable:+ pin = header.operator('stablegen.panel_section', text='',+ icon='SOLO_ON' if section.key in state.pinned_sections.split('|') else 'SOLO_OFF',+ emboss=False)+ pin.variant, pin.section, pin.pin = variant, section.key, True+ if expanded:+ section.content.render(box.column(), contents=True,+ omit_properties={'architecture_mode'} if section.key == 'main' else (),+ narrow=bpy.context.region.width < 420 if bpy.context.region else False)+++def _available_pages(document):+ keys = {section.page for section in document.sections}+ return [item for item in PAGES if item[0] in keys]+++def _effective_page(document, requested):+ pages = [item[0] for item in _available_pages(document)]+ return requested if requested in pages else ('GENERATE' if 'GENERATE' in pages else next(iter(pages), None))+++def _header(layout, context, variant, subtitle, document):+ scene = context.scene+ row = layout.row()+ row.scale_y = 1.15+ row.label(text=variant.title(), icon={'STUDIO': 'WORKSPACE', 'WORKBENCH': 'NODETREE', 'FOCUS': 'SEQ_SEQUENCER'}[variant])+ right = row.row()+ right.alignment = 'RIGHT'+ right.label(text=subtitle)+ row = layout.row(align=True)+ architecture = row.row()+ architecture.alert = document.architecture_alert+ architecture.prop(scene, 'architecture_mode', text='')+ cameras = sum(obj.type == 'CAMERA' for obj in scene.objects)+ row.label(text=f'{cameras} views', icon='CAMERA_DATA')+ for target in document.architecture_targets:+ layout.label(text=target)+++def _shared(layout, context, document, *, idle_generation=True):+ if document.presets:+ document.presets.render(layout, contents=True)+ for notice in document.notices:+ notice.render(layout)+ for action in document.actions:+ # Baking remains available on Output; active baking progress stays+ # shared across pages, like generation and cancellation.+ if action.has_operator('object.bake_textures'):+ continue+ active = any(c.method == 'progress' or (c.method == 'operator' and+ (c.kwargs.get('icon') in {'CANCEL', 'TIME'} or c.args[0] == 'stablegen.resolve_masked_edit'))+ for c in action.controls())+ if not idle_generation and not active and action.has_operator(+ 'object.test_stable', 'object.stablegen_regenerate', 'object.trellis2_generate',+ 'object.trellis2_batch_generate', 'stablegen.masked_edit'):+ continue+ action.render(layout)+++def _output_actions(layout, document):+ for action in document.actions:+ if action.has_operator('object.bake_textures'):+ action.render(layout)+++def _deliver(layout, document, state, variant, sections):+ # Configure material output before baking, then choose export formats.+ ordered = list(sections)+ for section in ordered:+ if section.key == 'show_output_material_settings':+ _section(layout, section, state, variant, pinnable=variant == 'WORKBENCH')+ _output_actions(layout, document)+ for section in ordered:+ if section.key != 'show_output_material_settings':+ _section(layout, section, state, variant, pinnable=variant == 'WORKBENCH')+++def _camera_browser(layout, context, state):+ if any(obj.type == 'CAMERA' for obj in context.scene.objects):+ box = layout.box()+ row = box.row()+ row.label(text='View Navigator', icon='CAMERA_DATA')+ box.template_list('SG_UL_PanelCameras', '', context.scene, 'objects', state, 'camera_index', rows=4, maxrows=6)+++class SG_MT_WorkbenchPages(bpy.types.Menu):+ bl_idname = 'SG_MT_WorkbenchPages'+ bl_label = 'Workbench Pages'++ def draw(self, context):+ for key, label, description, icon, number in _available_pages(capture_panel(context)):+ _nav_button(self.layout, 'WORKBENCH', key, label, icon)+++class _VariantPanel:+ bl_space_type = 'VIEW_3D'+ bl_region_type = 'UI'+ bl_options = set()++ @classmethod+ def poll(cls, context):+ return context.mode in {'OBJECT', 'PAINT_TEXTURE'}+++class SG_PT_Studio(_VariantPanel, bpy.types.Panel):+ bl_idname = 'SG_PT_Studio'+ bl_label = 'StableGen Studio'+ bl_category = 'SG Studio'++ def draw(self, context):+ layout = self.layout+ state = _state(context, 'STUDIO')+ document = capture_panel(context)+ _header(layout, context, 'STUDIO', 'Task workspace', document)+ _shared(layout, context, document)+ available = _available_pages(document)+ page = _effective_page(document, state.page)+ nav = layout.grid_flow(row_major=True, columns=3 if context.region.width >= 360 else 2,+ even_columns=True, even_rows=True, align=True)+ for key, label, description, icon, number in available:+ _nav_button(nav, 'STUDIO', key, label, icon, active=page == key)+ layout.separator(factor=0.6)+ if page == 'CAMERAS':+ _camera_browser(layout, context, state)+ if page == 'OUTPUT':+ _deliver(layout, document, state, 'STUDIO', (s for s in document.sections if s.page == page))+ return+ for section in document.sections:+ if section.page == page:+ _section(layout, section, state, 'STUDIO')+++def _card_summary(section, scene):+ summaries = {+ 'main': 'Prompt, model & generation mode',+ 'camera_tools': 'Create, clone & frame views',+ 'export': 'Materials & game engine formats',+ 'show_texturing_experiments': 'Optional research controls',+ 'print': 'Palette, slices & print exports',+ 'show_trellis2_texture_settings': 'Native texture generation',+ 'show_trellis2_camera_settings': 'Place views for texturing',+ 'show_masking_inpainting_settings': 'Masks & texture repair',+ 'show_core_settings': f'{scene.steps} steps · CFG {scene.cfg:g}',+ 'show_lora_settings': f'{len(scene.lora_units)} LoRA units',+ 'show_image_guidance_settings': 'References & context render',+ 'show_mode_specific_settings': 'Controls for the current mode',+ 'show_scene_understanding_settings': f'Angle {scene.discard_factor:g}° · exponent {scene.weight_exponent:g}',+ 'show_camera_options': 'Prompts & generation order',+ 'show_output_material_settings': 'PBR, display & resolution',+ 'show_trellis2_mesh_settings': 'Geometry & post-processing',+ 'show_trellis2_autorig_settings': 'Rigging, poses & animation',+ 'queue': 'Queued scenes & recording',+ 'tools': 'Import, prepare & process',+ 'debug': 'Materials, measurements & tests',+ }+ return summaries.get(section.key, 'Open settings')+++class SG_PT_Workbench(_VariantPanel, bpy.types.Panel):+ bl_idname = 'SG_PT_Workbench'+ bl_label = 'StableGen Workbench'+ bl_category = 'SG Workbench'++ def draw(self, context):+ layout = self.layout+ state = _state(context, 'WORKBENCH')+ document = capture_panel(context)+ _header(layout, context, 'WORKBENCH', 'Feature browser', document)+ _shared(layout, context, document)+ page = _effective_page(document, state.page)+ row = layout.row(align=True)+ _nav_button(row, 'WORKBENCH', '', 'Overview', 'HOME', active=state.overview, mode='OVERVIEW')+ label, icon = ('Pages', 'SHORTDISPLAY') if state.overview else PAGE_LABELS.get(page, ('Pages', 'SHORTDISPLAY'))+ row.menu('SG_MT_WorkbenchPages', text=label, icon=icon)+ layout.prop(state, 'query', text='', icon='VIEWZOOM')+ query = state.query.strip().casefold()+ if query:+ matches = [section for section in document.sections if query in section.search_text()]+ layout.label(text=f'{len(matches)} matching {"section" if len(matches) == 1 else "sections"}', icon='FILTER')+ for section in matches:+ _section(layout, section, state, 'WORKBENCH', force_open=True, pinnable=True)+ if not matches:+ layout.label(text='No matching settings.', icon='INFO')+ layout.label(text='Check the architecture or mode.')+ return+ if not state.overview:+ if page == 'CAMERAS':+ _camera_browser(layout, context, state)+ if page == 'OUTPUT':+ _deliver(layout, document, state, 'WORKBENCH', (s for s in document.sections if s.page == page))+ return+ for section in document.sections:+ if section.page == page:+ _section(layout, section, state, 'WORKBENCH', pinnable=True)+ return+ pinned = [section for section in document.sections if section.key in state.pinned_sections.split('|')]+ if pinned:+ layout.prop(state, 'show_pins', text=f'Pinned Settings ({len(pinned)})',+ icon='TRIA_DOWN' if state.show_pins else 'TRIA_RIGHT', emboss=False)+ if state.show_pins:+ for section in pinned:+ _section(layout, section, state, 'WORKBENCH', pinnable=True)+ layout.label(text='Browse Features', icon='SHORTDISPLAY')+ for page, label, description, icon, number in _available_pages(document):+ layout.label(text=label, icon=icon)+ grid = layout.grid_flow(row_major=True, columns=2 if context.region.width >= 410 else 1,+ even_columns=True, even_rows=False, align=False)+ for section in document.sections:+ if section.page != page:+ continue+ box = grid.box()+ row = box.row(align=True)+ _nav_button(row, 'WORKBENCH', page, section.title, section.icon, section=section.key)+ box.label(text=_card_summary(section, context.scene))+++def _focus_sections(document, stage):+ pages = {+ 'SETUP': {'GENERATE', 'MESH'}, 'VIEWS': {'CAMERAS'},+ 'RUN': {'GENERATE'}, 'PROJECT': {'BLEND', 'DEBUG'},+ 'DELIVER': {'OUTPUT', 'PRINT'}, 'UTILITY': {'TOOLS', 'DEBUG'},+ }[stage]+ for section in document.sections:+ if section.page not in pages:+ continue+ if stage == 'SETUP' and section.key in {'show_mode_specific_settings', 'show_masking_inpainting_settings'}:+ continue+ if stage == 'RUN' and section.key not in {'show_mode_specific_settings', 'show_masking_inpainting_settings', 'show_image_guidance_settings', 'main'}:+ continue+ if stage == 'PROJECT' and section.key == 'show_texturing_experiments':+ continue+ yield section+++class SG_PT_Focus(_VariantPanel, bpy.types.Panel):+ bl_idname = 'SG_PT_Focus'+ bl_label = 'StableGen Focus'+ bl_category = 'SG Focus'++ def draw(self, context):+ layout = self.layout+ state = _state(context, 'FOCUS')+ document = capture_panel(context)+ _header(layout, context, 'FOCUS', 'Guided workflow', document)+ _shared(layout, context, document, idle_generation=state.stage == 'RUN')+ rail = layout.grid_flow(row_major=True, columns=2, even_columns=True, even_rows=True, align=True)+ for key, label, description, icon, number in STAGES:+ _nav_button(rail, 'FOCUS', key, f'{number + 1} {label}', icon,+ active=state.stage == key, mode='STAGE')+ layout.separator(factor=0.6)+ instructions = {+ 'SETUP': 'Choose models and generation settings.',+ 'VIEWS': 'Arrange cameras and view prompts.',+ 'RUN': 'Review the prompt, then generate.',+ 'PROJECT': 'Inspect coverage and blending.',+ 'DELIVER': 'Set materials, bake, then export.',+ 'UTILITY': 'Tools, scene queue and experiments.',+ }+ layout.label(text=instructions[state.stage], icon='INFO')+ if state.stage == 'VIEWS':+ _camera_browser(layout, context, state)+ sections = list(_focus_sections(document, state.stage))+ if state.stage == 'DELIVER':+ _deliver(layout, document, state, 'FOCUS', sections)+ else:+ for section in sections:+ title = None+ if section.key == 'main':+ title = 'Model & Generation Setup' if state.stage == 'SETUP' else 'Review Prompt & Model'+ _section(layout, section, state, 'FOCUS', title=title)+ if not sections:+ layout.label(text='No additional settings for this stage in the current mode.', icon='INFO')+ navigation = layout.row(align=True)+ keys = [item[0] for item in STAGES]+ index = keys.index(state.stage)+ if index:+ _nav_button(navigation, 'FOCUS', keys[index - 1], 'Previous', 'BACK', mode='STAGE')+ if index < len(keys) - 1:+ _nav_button(navigation, 'FOCUS', keys[index + 1], 'Next', 'FORWARD', mode='STAGE')+++VARIANT_UI_CLASSES = [SGPanelVariantState, SG_OT_PanelNavigate, SG_OT_PanelSection,+ SG_OT_PanelCamera, SG_UL_PanelCameras,+ SG_MT_WorkbenchPages,+ SG_PT_Studio, SG_PT_Workbench, SG_PT_Focus]+++def register_variant_properties():+ for name in STATE_NAMES.values():+ setattr(bpy.types.WindowManager, name, bpy.props.PointerProperty(type=SGPanelVariantState, options={'SKIP_SAVE'}))+++def unregister_variant_properties():+ for name in STATE_NAMES.values():+ if hasattr(bpy.types.WindowManager, name):+ delattr(bpy.types.WindowManager, name)diff --git a/stablegen/ui/presentation.py b/stablegen/ui/presentation.pynew file mode 100644index 0000000..c0620d6--- /dev/null+++ b/stablegen/ui/presentation.py@@ -0,0 +1,316 @@+"""Capture the legacy UI and replay its live controls in alternate layouts.++This is a presentation adapter: it retains RNA bindings, operator properties,+conditional visibility, enable states, and progress without copying workflow logic.+"""+from dataclasses import dataclass, field+from types import SimpleNamespace++from .panel import StableGenPanel, StableGenPrintPanel+++CONTAINERS = {'row', 'column', 'box', 'split', 'grid_flow', 'column_flow'}+LAYOUT_DEFAULTS = {+ 'enabled': True, 'active': True, 'alert': False, 'alignment': 'EXPAND',+ 'scale_x': 1.0, 'scale_y': 1.0, 'use_property_split': False,+ 'use_property_decorate': True, 'operator_context': 'INVOKE_REGION_WIN',+}+SECTION_INFO = {+ 'show_core_settings': ('Sampling & Resolution', 'GENERATE', 'SETTINGS'),+ 'show_lora_settings': ('LoRA Management', 'GENERATE', 'MODIFIER'),+ 'show_camera_options': ('Camera Settings', 'CAMERAS', 'CAMERA_DATA'),+ 'show_scene_understanding_settings': ('Viewpoint Blending', 'BLEND', 'ZOOM_IN'),+ 'show_output_material_settings': ('Output & Materials', 'OUTPUT', 'MATERIAL'),+ 'show_image_guidance_settings': ('Image Guidance', 'GENERATE', 'MODIFIER'),+ 'show_masking_inpainting_settings': ('Inpainting Options', 'GENERATE', 'MOD_MASK'),+ 'show_mode_specific_settings': ('Generation Mode Specifics', 'GENERATE', 'OPTIONS'),+ 'show_texturing_experiments': ('Experimental Texturing', 'DEBUG', 'EXPERIMENTAL'),+ 'show_trellis2_mesh_settings': ('Mesh & Post-Processing', 'MESH', 'MESH_DATA'),+ 'show_trellis2_autorig_settings': ('Rigging & Animation', 'MESH', 'ARMATURE_DATA'),+ 'show_trellis2_texture_settings': ('Native Textures', 'MESH', 'TEXTURE'),+ 'show_trellis2_camera_settings': ('Camera Placement', 'CAMERAS', 'CAMERA_DATA'),+}+STRUCTURAL_PROPERTIES = {+ *SECTION_INFO, 'show_generation_params', 'show_advanced_params', 'sg_show_queue',+}+++class ExpandedData:+ """Override only presentation expansion flags; forward all real scene data."""+ def __init__(self, data):+ object.__setattr__(self, '_data', data)++ def __getattr__(self, name):+ if name == 'windows':+ return [ExpandedWindow(window) for window in self._data.windows]+ if name == 'qwen_refine_mode' and not hasattr(self._data, name):+ # The legacy renderer still reads this retired presentation alias;+ # sequential/separate is now stored in generation_method.+ return self._data.generation_method+ value = getattr(self._data, name)+ if name in STRUCTURAL_PROPERTIES:+ return True+ return value++ def __setattr__(self, name, value):+ setattr(self._data, name, value)+++class ExpandedWindow:+ """Built-in and retiring modal handlers can appear as None in Blender RNA."""+ def __init__(self, window):+ self._window = window++ def __getattr__(self, name):+ if name == 'modal_operators':+ return [op for op in self._window.modal_operators if op is not None]+ return getattr(self._window, name)+++class ExpandedContext:+ def __init__(self, context):+ self._context = context+ self.scene = ExpandedData(context.scene)+ self.window_manager = ExpandedData(context.window_manager)++ def __getattr__(self, name):+ return getattr(self._context, name)+++def _unwrap(value):+ return value._data if isinstance(value, ExpandedData) else value+++@dataclass+class Control:+ method: str+ args: tuple+ kwargs: dict+ properties: dict = field(default_factory=dict)++ def render(self, layout, *, narrow=False):+ if (narrow and self.method == 'prop' and self.args[1]+ in {'sg_projection_guard_scale', 'sg_guard_feather_method'}):+ column = layout.column()+ column.label(text=self.kwargs.get('text', self.args[1]))+ kwargs = dict(self.kwargs, text='')+ column.prop(*self.args, **kwargs)+ return+ result = getattr(layout, self.method)(*self.args, **self.kwargs)+ for name, value in self.properties.items():+ setattr(result, name, value)+++class OperatorProperties:+ def __init__(self, control):+ object.__setattr__(self, '_control', control)++ def __setattr__(self, name, value):+ self._control.properties[name] = value+++class Layout:+ def __init__(self, method='root', args=(), kwargs=None):+ object.__setattr__(self, 'method', method)+ object.__setattr__(self, 'args', args)+ object.__setattr__(self, 'kwargs', kwargs or {})+ object.__setattr__(self, 'attributes', {})+ object.__setattr__(self, 'children', [])++ def __setattr__(self, name, value):+ self.attributes[name] = value++ def __getattr__(self, name):+ if name in LAYOUT_DEFAULTS:+ return self.attributes.get(name, LAYOUT_DEFAULTS[name])++ def record(*args, **kwargs):+ args = tuple(_unwrap(value) for value in args)+ kwargs = {key: _unwrap(value) for key, value in kwargs.items()}+ if name in CONTAINERS:+ child = Layout(name, args, kwargs)+ self.children.append(child)+ return child+ child = Control(name, args, kwargs)+ self.children.append(child)+ return OperatorProperties(child) if name == 'operator' else None+ return record++ def controls(self):+ for child in self.children:+ if isinstance(child, Layout):+ yield from child.controls()+ else:+ yield child++ def has_property(self, name):+ return any(control.method == 'prop' and len(control.args) > 1+ and control.args[1] == name for control in self.controls())++ def has_operator(self, *names):+ return any(control.method == 'operator' and control.args[0] in names+ for control in self.controls())++ def render(self, parent, *, contents=False, omit_properties=(), narrow=False):+ method, kwargs = self.method, self.kwargs+ if (narrow and method == 'row' and len(self.children) >= 3+ and all(isinstance(c, Control) and c.method == 'operator' for c in self.children)):+ method, kwargs = 'grid_flow', dict(row_major=True, columns=2,+ even_columns=True, even_rows=True, align=False)+ if narrow and method == 'split' and kwargs.get('factor') == 0.5:+ # The legacy two-column sliders remain side by side at wide sizes.+ # Reflow them at compact sidebar sizes instead of truncating names.+ if sum(c.method in ('prop', 'operator') for c in self.controls()) >= 2:+ method, kwargs = 'column', {'align': False}+ layout = parent if contents or self.method == 'root' else getattr(parent, method)(+ *self.args, **kwargs)+ for name, value in self.attributes.items():+ setattr(layout, name, value)+ for child in self.children:+ if isinstance(child, Layout):+ if any(isinstance(control, Control) and control.method == 'prop'+ and control.args[1] in omit_properties for control in child.children):+ continue+ child.render(layout, omit_properties=omit_properties, narrow=narrow)+ continue+ if (isinstance(child, Control) and child.method == 'prop'+ and len(child.args) > 1 and child.args[1] in STRUCTURAL_PROPERTIES):+ continue+ child.render(layout, narrow=narrow)+++@dataclass+class Section:+ key: str+ title: str+ page: str+ icon: str+ content: Layout++ def search_text(self):+ parts = [self.title]+ for control in self.content.controls():+ parts.append(str(control.kwargs.get('text', '')))+ if control.method == 'prop' and len(control.args) > 1:+ data, name = control.args[:2]+ parts.append(name.replace('_', ' '))+ prop = data.bl_rna.properties.get(name)+ if prop:+ parts.extend((prop.name, prop.description))+ return ' '.join(parts).casefold()+++@dataclass+class Document:+ sections: list = field(default_factory=list)+ actions: list = field(default_factory=list)+ notices: list = field(default_factory=list)+ presets: Layout | None = None+ architecture_alert: bool = False+ architecture_targets: list = field(default_factory=list)+++def _section_parts(node):+ """Find a legacy section header and its content, preserving its real title."""+ for child in node.children:+ if isinstance(child, Control) and child.method == 'prop' and len(child.args) > 1:+ key = child.args[1]+ if key in SECTION_INFO:+ content = next((sibling for sibling in node.children+ if isinstance(sibling, Layout) and sibling.method == 'box'), None)+ if content:+ title, page, icon = SECTION_INFO[key]+ return Section(key, child.kwargs.get('text') or title, page, icon, content)+ elif isinstance(child, Layout):+ result = _section_parts(child)+ if result:+ return result+ return None+++def _advanced_sections(node):+ # The advanced column contains one box per section. Descending into an+ # already matched section would duplicate its conditional feature subboxes.+ for child in node.children:+ if not isinstance(child, Layout):+ continue+ section = _section_parts(child)+ if section and not child.has_property('show_advanced_params'):+ yield section+ else:+ yield from _advanced_sections(child)+++def _main_content(node):+ for child in node.children:+ if not isinstance(child, Layout):+ continue+ if child.method == 'box' and not child.has_property('show_generation_params'):+ return child+ result = _main_content(child)+ if result:+ return result+ return node+++def capture_panel(context):+ root = Layout()+ StableGenPanel.draw(SimpleNamespace(layout=root), ExpandedContext(context))+ document = Document()+ camera_tools = Layout()+ action_ops = ('object.test_stable', 'object.stablegen_regenerate',+ 'object.stablegen_autorig_selected_mesh',+ 'object.trellis2_generate', 'object.trellis2_batch_generate',+ 'object.trellis2_batch_cancel', 'stablegen.masked_edit',+ 'stablegen.stop_masked_edit', 'stablegen.resolve_masked_edit',+ 'object.bake_textures')+ for child in root.children:+ if not isinstance(child, Layout):+ continue+ if child.has_property('stablegen_preset'):+ document.presets = child+ elif child.has_property('show_generation_params'):+ document.sections.append(Section('main', 'Main Parameters', 'GENERATE', 'OPTIONS',+ _main_content(child)))+ elif child.has_property('show_advanced_params'):+ document.sections.extend(_advanced_sections(child))+ elif child.has_property('sg_show_queue'):+ document.sections.append(Section('queue', 'Scene Queue', 'TOOLS', 'SEQ_SEQUENCER', child))+ elif child.has_operator('stablegen.debug_solid_colors'):+ document.sections.append(Section('debug', 'Debug / Diagnostics', 'DEBUG', 'GHOST_ENABLED', child))+ elif child.has_operator('object.switch_material'):+ document.sections.append(Section('tools', 'Tools', 'TOOLS', 'TOOL_SETTINGS', child))+ elif child.has_operator(*action_ops) or any(c.method == 'progress' for c in child.controls()):+ document.actions.append(child)+ elif child.has_operator('object.add_cameras', 'object.clone_camera', 'object.collect_camera_prompts',+ 'object.mirror_camera', 'object.apply_auto_aspect', 'object.toggle_camera_labels') and not child.has_operator('stablegen.switch_to_mesh_generation'):+ camera_tools.children.append(child)+ elif child.has_operator('object.export_game_engine'):+ document.sections.append(Section('export', 'Game Engine Export', 'OUTPUT', 'EXPORT', child))+ else:+ # Inline prerequisites and deprecated-architecture notices retain+ # their original controls. They remain visible across all pages.+ controls = list(child.controls())+ if any(c.method == 'label' and c.kwargs.get('text') == 'Widen panel for side-by-side layout' for c in controls):+ continue+ if any(c.method == 'label' and c.kwargs.get('icon') in ('ERROR', 'INFO') for c in controls):+ document.notices.append(child)+ elif controls:+ # Informational status (model refresh, masked edit readiness)+ # should not disappear when moving the legacy action area.+ document.actions.append(child)+ if camera_tools.children:+ document.sections.insert(0, Section('camera_tools', 'Camera Tools', 'CAMERAS', 'CAMERA_DATA', camera_tools))+ for section in document.sections:+ if section.key == 'main':+ for row in section.content.children:+ if isinstance(row, Layout) and row.has_property('architecture_mode'):+ document.architecture_alert = row.attributes.get('alert', False)+ document.architecture_targets = [c.kwargs['text'] for c in row.controls()+ if c.method == 'label' and c.kwargs.get('text', '').startswith('→')]+ prefs = context.preferences.addons.get(__package__.rsplit('.', 1)[0])+ if prefs and prefs.preferences.enable_print_tab:+ print_root = Layout()+ StableGenPrintPanel.draw(SimpleNamespace(layout=print_root), ExpandedContext(context))+ document.sections.append(Section('print', '3D Printing', 'PRINT', 'OUTLINER_OB_MESH', print_root))+ return documentdiff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.pyindex ec50a84..b26d8e4 100644--- a/stablegen/ui/presets.py+++ b/stablegen/ui/presets.py@@ -5,6 +5,10 @@ import bpy # pylint: disable=import-errorimport mathutils # pylint: disable=import-errorfrom ..utils import sg_modal_activefrom ..feature_flags import TEXTURING_DEFAULTS, EXPERIMENTAL_FEATURE_DEFAULTS, experiments_enabled+from ..architecture_options import (+ DEPRECATION_NOTICE, deprecated_architectures_enabled,+ preset_uses_deprecated_architecture,+)PRESETS = {"DEFAULT": {"description": "Default settings for general purpose generation", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 90.0, "weight_exponent": 3.0, "weight_exponent_generation_only": False, "weight_exponent_after_generation": 15.0, "view_blend_use_color_match": False, "view_blend_color_match_method": "hm-mvgd-hm", "view_blend_color_match_strength": 1.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 0.8, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.15, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "pbr_decomposition": False, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},@@ -98,6 +102,34 @@ PRESETS["QWEN 2.1 PRECISE"] = {"lora_units": [],}+PRESETS["QWEN 2.1 PRECISE+"] = {+ **PRESETS["QWEN 2.1 PRECISE"],+ "description": (+ "Qwen-Image 2.1 Precise with Confidence-Gated Context (CGC), Acquisition "+ "Quality Weighting (AQW) and Depth/Part Projection Guard (DPPG). CGC "+ "retains reliable projected texture as context and marks low-confidence "+ "regions for repair. AQW favors views with better projected detail when "+ "blending textures. DPPG limits foreground silhouettes leaking onto "+ "surfaces behind them at depth, object and material boundaries. "+ "Uses a 0.50 context trust threshold, a 3 px silhouette margin and "+ "backface projection. Retains Qwen 2.1 Precise's projected-context "+ "strategy, 20 steps, CFG 1.0, DPM++ SDE, SGM Uniform, blending exponent "+ "7 and native RGBA output, with no Lightning LoRA. Transparent pixels "+ "are excluded from projection. Research options are off. Best suited "+ "to overlapping camera views; fine patterns and material continuity "+ "can still vary, and standard Precise can work better on some assets."+ ),+ "architecture_mode": "qwen_image_21",+ "generation_mode": "standard",+ "qwen_use_confidence_context": True,+ "sg_rework_acquisition_quality": True,+ "sg_rework_projection_guard": True,+ "qwen_trust_threshold": 0.5,+ "sg_silhouette_margin": 3,+ "sg_allow_backface_projection": True,+ **EXPERIMENTAL_FEATURE_DEFAULTS,+}+PRESETS["QWEN 2.1 SAFE"] = {**PRESETS["QWEN SAFE"],"weight_exponent": 7.0,@@ -166,6 +198,58 @@ PRESETS["QWEN 2.1 CONTEXT + REFERENCE"] = {**TEXTURING_DEFAULTS,}+PRESETS["LOCAL EDIT (QWEN 2.1)"] = {+ **PRESETS["LOCAL EDIT (QWEN)"],+ "description": (+ "Use Qwen-Image 2.1 to make targeted changes to an existing texture. "+ "Point detail cameras at the area to edit and describe the desired "+ "change, such as a new color, lettering, style or surface detail. "+ "Preserves the original Local Edit camera coverage and edge-feathering "+ "settings so the edited projections blend into the existing material. "+ "Uses 20 steps, CFG 1.0, DPM++ SDE, SGM Uniform, blending exponent 7 "+ "and native RGBA output, with no Lightning LoRA. Transparent generated "+ "pixels do not contribute to projection. This edits camera-selected "+ "areas; use Masked Edit generation mode for painted-mask selection."+ ),+ "architecture_mode": "qwen_image_21",+ "model_architecture": "qwen_image_21",+ "generation_mode": "standard",+ "weight_exponent": 7.0,+ "steps": 20,+ "cfg": 1.0,+ "sampler": "dpmpp_sde",+ "scheduler": "sgm_uniform",+ "qwen_image_21_native_rgba": True,+ "qwen_guidance_background_color": mathutils.Color((0.5, 0.5, 0.5)),+ "lora_units": [],+}++PRESETS["REFINE (QWEN 2.1)"] = {+ **PRESETS["REFINE (QWEN)"],+ "description": (+ "Use Qwen-Image 2.1 to restyle or modify the existing texture across "+ "the scene's camera views. Each view uses the current textured render "+ "as its editing input, making this suitable for overall color, art "+ "style or surface-appearance changes. Preserves the original Qwen "+ "Refine workflow settings. Uses 20 steps, CFG 1.0, DPM++ SDE, SGM "+ "Uniform, blending exponent 7 and native RGBA output, with no Lightning "+ "LoRA. Transparent generated pixels are excluded from projection. "+ "Use Local Edit for camera-targeted changes or Masked Edit generation "+ "mode to select an area by painting."+ ),+ "architecture_mode": "qwen_image_21",+ "model_architecture": "qwen_image_21",+ "generation_mode": "standard",+ "weight_exponent": 7.0,+ "steps": 20,+ "cfg": 1.0,+ "sampler": "dpmpp_sde",+ "scheduler": "sgm_uniform",+ "qwen_image_21_native_rgba": True,+ "qwen_guidance_background_color": mathutils.Color((0.5, 0.5, 0.5)),+ "lora_units": [],+}+# 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():@@ -385,13 +469,13 @@ GEN_PARAMETERS = [# ── Preset diff preview helpers ──────────────────────────────────────────-def get_preset_items(self, context):+def _build_preset_items(context, include_deprecated, selected=None):# Group presets by architecture for easier navigation._ARCH_GROUP_ORDER = [- ('sdxl', 'SDXL / FLUX.1'),+ ('sdxl', 'SDXL'),('qwen_image_edit', 'Qwen Image Edit'),('qwen_image_21', 'Qwen Image 2.1'),- ('flux2_klein', 'FLUX.2 Klein'),+ ('flux2_klein', 'FLUX.2 Klein (Deprecated)'),('trellis2', 'TRELLIS.2 Pipeline'),]_known_groups = {k for k, _ in _ARCH_GROUP_ORDER}@@ -401,14 +485,27 @@ def get_preset_items(self, context):for key, preset in PRESETS.items():if '(EXPERIMENTAL)' in key and not experiments_enabled(context):continue+ deprecated = preset_uses_deprecated_architecture(preset)+ if deprecated and not include_deprecated and key != selected:+ continueif preset.get('architecture_mode') == 'trellis2':grp = 'trellis2'else:grp = preset.get('model_architecture', 'sdxl')groups.setdefault(grp, []).append(- (key, key.title(), preset.get('description', f'Preset {key}'))+ (key, key.title() + (' (Deprecated)' if deprecated else ''),+ preset.get('description', f'Preset {key}')+ + (f'. {DEPRECATION_NOTICE}' if deprecated else '')))+ qwen_edit_items = groups.get('qwen_image_edit', [])+ qwen_edit_ids = [item[0] for item in qwen_edit_items]+ if 'QWEN PRECISE' in qwen_edit_ids and 'QWEN PRECISE+' in qwen_edit_ids:+ precise_plus = qwen_edit_items.pop(qwen_edit_ids.index('QWEN PRECISE+'))+ precise_index = next(i for i, item in enumerate(qwen_edit_items)+ if item[0] == 'QWEN PRECISE')+ qwen_edit_items.insert(precise_index + 1, precise_plus)+items = []first_group = Truefor grp_key, _label in _ARCH_GROUP_ORDER:@@ -426,13 +523,45 @@ def get_preset_items(self, context):for grp_key, grp_items in groups.items():if grp_key not in _known_groups:items.append(('', '', ''))- items.append(('', grp_key.replace('_', ' ').title(), ''))+ label = ('FLUX.1 (Deprecated)' if grp_key == 'flux1'+ else grp_key.replace('_', ' ').title())+ items.append(('', label, ''))items.extend(grp_items)items.append(('', '', '')) # separator before Customitems.append(('CUSTOM', 'Custom', 'Custom configuration'))return items++_PRESET_ENUM_CACHE = {}+_READING_PRESET_SELECTION = False+++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)+ 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+ for item in full_items)+ return _PRESET_ENUM_CACHE.setdefault(items, items)+ # Reading through RNA is portable across Blender's old and new property+ # storage. The nested items callback above temporarily supplies the full menu.+ _READING_PRESET_SELECTION = True+ try:+ selected = getattr(self, 'stablegen_preset', None)+ finally:+ _READING_PRESET_SELECTION = False+ visible_items = _build_preset_items(+ context, deprecated_architectures_enabled(context), selected=selected,+ )+ items = tuple(item + (numbers[item[0]],) if item[0] else item+ for item in visible_items)+ # Blender's dynamic enums borrow their strings; keep every returned variant.+ return _PRESET_ENUM_CACHE.setdefault(items, items)+def normalize_value(key, value):if key == "trellis2_remesh" and isinstance(value, bool):return "qdc" if value else "none"@@ -447,6 +576,9 @@ def update_parameters(self, context):for name, preset in PRESETS.items():if '(EXPERIMENTAL)' in name and not experiments_enabled(context):continue+ if (preset_uses_deprecated_architecture(preset)+ and not deprecated_architectures_enabled(context)):+ continueexpected = preset if preset.get('custom', False) else {**TEXTURING_DEFAULTS, **preset}# First check regular parametersif all(@@ -618,6 +750,10 @@ class ApplyPreset(bpy.types.Operator):return {'CANCELLED'}if preset in PRESETS:values = PRESETS[preset]+ if (preset_uses_deprecated_architecture(values)+ 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 not values.get("custom", False):for key, value in TEXTURING_DEFAULTS.items():diff --git a/stablegen/ui/studio.py b/stablegen/ui/studio.pynew file mode 100644index 0000000..ce5ce27--- /dev/null+++ b/stablegen/ui/studio.py@@ -0,0 +1,2069 @@+"""Custom Studio sidebar, alongside the existing native StableGen panels.++GPU drawing lives only in this tab's UI region. A lightweight input operator+passes viewport and native-tab events through. Every workflow command invokes+its existing Blender operator; every setting writes its original RNA property.+"""+import json+import logging+from pathlib import Path+import re+import time++import bpy+import blf+from bpy.app.handlers import persistent++from . import studio_model as model+from . import studio_diagnostics as diagnostics+from . import studio_hierarchy as hierarchy_model+from . import studio_cards as cards+from .presentation import Layout, Control, Section, STRUCTURAL_PROPERTIES+from .studio_text import TextBuffer, wrap+from .studio_widgets import (Painter, FONT_SIZE, CONTROL_HEIGHT, CONTROL_GAP,+ TEXT_LINE_HEIGHT, TEXT_PADDING, font_size)+from .presets import PRESETS+from ..utils import sg_modal_active+from ..core import ADDON_PKG++TAB = 'SG Studio UI'+PAGES = [('GENERATE', 'Texture'), ('CAMERAS', 'Cameras'), ('BLEND', 'Blending')]+MORE = [('TOOLS', 'Tools'), ('QUEUE', 'Scene queue'), ('DEBUG', 'Diagnostics'),+ ('MESH', 'Mesh & rig'), ('PRINT', '3D printing'), ('EXPERIMENTS', 'Experiments')]+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',+ 'sg_silhouette_margin', 'sg_guard_foreground_margin', 'sg_silhouette_depth',+ 'sg_guard_coverage_rescue', 'sg_silhouette_feather', 'sg_projection_guard_scale',+ 'sg_guard_feather_method'}+SECTIONS = {'show_core_settings': 'Sampling & resolution', 'show_lora_settings': 'LoRA',+ 'show_image_guidance_settings': 'Image guidance', 'show_mode_specific_settings': 'Mode settings',+ 'show_scene_understanding_settings': 'Viewpoint blending',+ 'show_output_material_settings': 'Output & materials', 'debug': 'Diagnostics'}+_sessions = {}+_cursor_owners = {}+_window_mouse = {}+_pending = set()+_handler = None+_registered = False+_font_id = None+_font_path = ''+_log = logging.getLogger(__name__)+++def _context(session):+ return bpy.context.temp_override(window=session.window, area=session.area, region=session.region)+++def _viewport(session):+ region = next(r for r in session.area.regions if r.type == 'WINDOW')+ return bpy.context.temp_override(window=session.window, area=session.area, region=region)+++def _undo(message):+ try:+ bpy.ops.ed.undo_push(message=message)+ except RuntimeError:+ # File loading and a closing area can invalidate an otherwise valid edit.+ _log.debug('Undo push unavailable', exc_info=True)+++def _binding_key(binding):+ return f'{binding.root}:{binding.name}:{binding.path}:{binding.property}'+++class StudioSession:+ def __init__(self, context):+ self.window, self.area, self.region = context.window, context.area, context.region+ self.key = (self.window.as_pointer(), self.area.as_pointer())+ self.page = 'MESH' if context.scene.architecture_mode == 'trellis2' else 'GENERATE'+ self.architecture = context.scene.architecture_mode+ self.open = {'show_scene_understanding_settings', 'show_core_settings'}+ self.scroll = {}+ self.text_scroll = {}+ self.text_fields = {}+ self.prompt_editor = None+ self.targets = []+ self.pointer = (-1, -1)+ self.mouse = (-1, -1)+ self.pointer_valid = False+ self.hover_key, self.hover_since = '', time.monotonic()+ self.hover_signature = None+ self.hover_origin = self.pointer+ self.tooltip_key = ''+ self.tooltip_rect = None+ self.cursor = ''+ self.last_refresh = 0+ self.edit = None+ self.drag = None+ self.menu = None+ self.query = ''+ self.popup = False+ self.alive = True+ self.error = ''+ self.notice = ''+ self.notice_until = 0+ self.dirty_projection = False+ self.last_projection = None+ self.scene_pointer = context.scene.as_pointer()+ self.document = None+ self.hierarchies = {}+ self.busy = False+ self.ctrl = False+ self.camera_images = {}+ self.card_bounds = {}++ def valid(self):+ try:+ return (self.alive and self.window in bpy.context.window_manager.windows[:]+ and self.area in self.window.screen.areas[:] and self.area.type == 'VIEW_3D'+ and self.region in self.area.regions[:])+ except ReferenceError:+ return False++ def active(self):+ return self.valid() and self.area.spaces.active.show_region_ui and self.region.active_panel_category == TAB++ def native_resize_active(self):+ """Blender owns hover and the cursor while moving a region or area edge."""+ return any(op is not None and op.bl_idname in {'SCREEN_OT_region_scale', 'SCREEN_OT_area_move'}+ for op in getattr(self.window, 'modal_operators', ()))++ def release_cursor(self):+ """Restore the native cursor only if this sidebar owns the window override."""+ if _cursor_owners.get(self.key[0]) is self:+ try:+ self.window.cursor_modal_restore()+ except (ReferenceError, RuntimeError):+ pass+ _cursor_owners.pop(self.key[0], None)+ self.cursor = ''++ def set_cursor(self, cursor):+ owner = _cursor_owners.get(self.key[0])+ if owner is not None and owner is not self:+ owner.release_cursor()+ if cursor == 'DEFAULT':+ self.release_cursor()+ # The canvas consumes native hover events, so Blender cannot clear+ # its resize cursor when the pointer enters our controls or gaps.+ self.window.cursor_set('DEFAULT')+ return+ if self.cursor != cursor:+ # Modal restore must not revive a resize cursor saved on entry.+ self.window.cursor_set('DEFAULT')+ self.window.cursor_modal_set(cursor)+ self.cursor = cursor+ _cursor_owners[self.key[0]] = self++ def clear_hover(self, *, leave=False):+ changed = bool(self.hover_key or self.tooltip_key)+ self.hover_key, self.hover_signature = '', None+ self.hover_since = time.monotonic()+ self.hover_origin = self.pointer+ self.tooltip_key, self.tooltip_rect = '', None+ if leave:+ self.pointer_valid = False+ self.release_cursor()+ if changed and self.valid():+ self.area.tag_redraw()++ def pointer_inside(self):+ if not self.pointer_valid:+ return False+ # A modal handler in another Studio area may consume the move first.+ self.mouse = _window_mouse.get(self.key[0], self.mouse)+ scale = max(.8, bpy.context.preferences.system.ui_scale)+ self.pointer = ((self.mouse[0] - self.region.x) / scale,+ (self.region.y + self.region.height - self.mouse[1]) / scale)+ x, y = self.pointer+ # Leave native category tabs and the sidebar resize border to Blender.+ return 8 < x < self.region.width / scale - 28 and 0 <= y < self.region.height / scale++ def hit_target(self, targets=None):+ return next((t for t in reversed(self.targets if targets is None else targets)+ if t.contains(*self.pointer) and (not self.menu or t.key.startswith('choice:'))), None)++ def update_hover(self, targets=None, *, moved=False, cursor=True):+ if not self.active() or self.popup or self.native_resize_active():+ self.clear_hover(leave=True)+ return None+ inside = self.pointer_inside()+ if self.drag or self.edit and self.edit['selecting']:+ self.clear_hover()+ if cursor:+ self.set_cursor('MOVE_X' if self.drag else 'TEXT')+ return None+ if not inside:+ self.clear_hover()+ if cursor:+ self.release_cursor()+ return None+ target = self.hit_target(targets)+ signature = (target.key, target.rect, target.clip, target.hint, target.enabled) if target else None+ distance = ((self.pointer[0] - self.hover_origin[0]) ** 2+ + (self.pointer[1] - self.hover_origin[1]) ** 2)+ if signature != self.hover_signature or moved and distance > 9:+ self.clear_hover()+ self.hover_key = target.key if target else ''+ self.hover_signature = signature+ if target:+ self.area.tag_redraw()+ if cursor:+ self.set_cursor('MOVE_X' if self.drag else target.cursor if target else 'DEFAULT')+ return target++ def tooltip_target(self, targets=None):+ if (not bpy.context.preferences.view.show_tooltips or self.drag or self.popup+ or self.notice and time.monotonic() < self.notice_until):+ return None+ target = self.hit_target(targets) if self.pointer_inside() else None+ if (target and target.key == self.hover_key and target.hint+ and not (self.edit and self.edit['key'] == target.key)+ and time.monotonic() - self.hover_since >= .65):+ return target+ return None++ def tick(self, now):+ if not self.active() or self.popup:+ self.clear_hover(leave=True)+ return+ if now - self.last_refresh >= .25:+ self.refresh()+ self.update_hover()+ tooltip = self.tooltip_target()+ if (tooltip.key if tooltip else '') != self.tooltip_key:+ self.area.tag_redraw()++ def refresh(self):+ self.last_refresh = time.monotonic()+ with _context(self):+ ctx = bpy.context+ if ctx.scene.architecture_mode != self.architecture:+ previous_architecture = self.architecture+ self.architecture = ctx.scene.architecture_mode+ if self.architecture == 'trellis2' or previous_architecture == 'trellis2':+ self.page = 'MESH' if self.architecture == 'trellis2' else 'GENERATE'+ if ctx.scene.as_pointer() != self.scene_pointer:+ self.edit = self.drag = self.menu = None+ self.scene_pointer = ctx.scene.as_pointer()+ self.last_projection = None+ self.dirty_projection = False+ self.clear_hover(leave=True)+ self.document = model.document(ctx)+ self.hierarchies.clear()+ if self.page == 'CAMERAS':+ self.camera_images = model.projected_images(ctx)+ self.busy = sg_modal_active(ctx) or any(c.control.method == 'progress'+ for n in self.document.actions for c in model.controls(n))+ values = tuple(getattr(ctx.scene, key, None) for key in sorted(PROJECTION_KEYS))+ if self.last_projection is not None and values != self.last_projection and not self.busy:+ self.dirty_projection = bool(ctx.scene.output_timestamp)+ self.last_projection = values+ if self.busy and self.edit:+ self.edit = None+ self.area.tag_redraw()++ def tell(self, message):+ self.notice, self.notice_until = message, time.monotonic() + 5+ self.area.tag_redraw()++ def call(self, name, properties=None, *, mode='INVOKE_DEFAULT'):+ display = next((key for key, operator in diagnostics.OPERATORS.items()+ if name == 'stablegen.' + operator), None)+ if display:+ return self.call('stablegen.studio_diagnostic', {'value': json.dumps(display)}, mode='EXEC_DEFAULT')+ self.commit()+ self.clear_hover(leave=True)+ try:+ with _viewport(self):+ op = model.operator(name)+ if not op.poll():+ self.tell('This command is unavailable for the current scene or operation.')+ return+ if diagnostics.active(bpy.context.scene) and name not in {+ 'stablegen.studio_diagnostic', 'stablegen.debug_open_projection_line',+ 'stablegen.studio_preferences', 'stablegen.export_retarget_debug_bundle'}:+ diagnostics.restore(bpy.context.scene)+ result = op(mode, **(properties or {}))+ if name == 'stablegen.studio_diagnostic' and 'FINISHED' in result:+ _undo('Change diagnostic display')+ if name in {'object.stablegen_reproject', 'object.test_stable', 'object.stablegen_regenerate'} and 'CANCELLED' not in result:+ self.dirty_projection = False+ self.refresh()+ return result+ except (RuntimeError, TypeError, ValueError) as exc:+ self.tell(str(exc).split('\n')[0])+ _log.warning('Studio command %s: %s', name, exc)++ def native(self, section='', binding=None, index=-1):+ self.commit()+ self.menu = None+ self.clear_hover(leave=True)+ with _context(self):+ bpy.ops.stablegen.studio_native('INVOKE_DEFAULT', section=section,+ binding=json.dumps(binding.__dict__) if binding else '',+ control_index=index)++ def commit(self, cancel=False):+ edit, self.edit = self.edit, None+ if not edit or cancel:+ return+ if edit['key'] == 'search':+ self.query = edit['buffer'].text+ return+ try:+ with _context(self):+ binding, text = edit['binding'], edit['buffer'].text+ prop = binding.rna(bpy.context)+ value = float(text) if prop.type == 'FLOAT' else int(text) if prop.type == 'INT' else text+ if binding.value(bpy.context) != value:+ self.write_binding(binding, value)+ self.refresh()+ except (ValueError, TypeError, ReferenceError, RuntimeError) as exc:+ self.tell('Could not apply this value: ' + str(exc).split('\n')[0])++ def set_value(self, binding, value, undo=True):+ with _context(self):+ if self.busy:+ return+ self.write_binding(binding, value, undo)+ self.refresh()++ def write_binding(self, binding, value, undo=True):+ if binding.path == 'sg_studio_diagnostics':+ with _viewport(self):+ bpy.ops.stablegen.studio_diagnostic('EXEC_DEFAULT', setting=binding.property,+ value=json.dumps(value))+ _undo('Change diagnostic display')+ else:+ binding.set(bpy.context, value)+ if undo:+ _undo('Change ' + binding.rna(bpy.context).name)++ def begin_edit(self, target, select=False):+ self.commit()+ binding = target.action[1]+ with _context(self):+ value = self.query if binding is None else binding.value(bpy.context)+ buffer = TextBuffer(str(value))+ if select:+ buffer.anchor = 0+ self.edit = {'key': target.key, 'binding': binding, 'buffer': buffer,+ 'rect': target.rect, 'lines': self.text_fields.get(target.key, ([],0))[0],+ 'scroll': self.text_scroll.get(target.key, 0), 'follow_caret': False,+ 'multiline': bool(target.action[2]), 'selecting': False}+ self.menu = None+ self.area.tag_redraw()++ def enum_menu(self, target):+ self.commit()+ binding = target.action[1]+ with _context(self):+ items = list(model.enum_items(binding, bpy.context))+ if binding.property == 'stablegen_preset':+ arch = bpy.context.scene.architecture_mode+ items = [item for item in items if item and item[0] and+ (item[0] == 'CUSTOM' or (item[0] in PRESETS and+ (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 not items:+ self.native(binding=binding)+ return+ self.menu = {'anchor': target.rect, 'items': items, 'query': '', 'binding': binding,+ 'index': next((i for i, item in enumerate(items) if item[0] == value), 0), 'scroll': 0}++ def navigate(self, page):+ self.commit()+ self.page, self.menu = page, None+ self.clear_hover()+ if page == 'SEARCH':+ buffer = TextBuffer(self.query)+ buffer.anchor = 0+ self.edit = {'key': 'search', 'binding': None, 'buffer': buffer,+ 'rect': (0,0,0,0), 'lines': [], 'scroll': 0,+ 'multiline': False, 'selecting': False}+ self.area.tag_redraw()++ def expand_prompt(self, binding, label):+ previous = self.page+ self.navigate('EDITOR')+ self.prompt_editor = (binding, label, previous)+ self.scroll['EDITOR'] = 0++ def activate(self, target):+ self.clear_hover()+ if not target or not target.enabled:+ return+ action = target.action+ if callable(action):+ self.commit()+ action()+ elif action[0] == 'operator':+ self.call(action[1], action[2])+ elif action[0] == 'toggle':+ self.commit()+ with _context(self):+ value = not action[1].value(bpy.context)+ self.set_value(action[1], value)+ elif action[0] == 'edit':+ self.begin_edit(target, select=not action[2])+ elif action[0] == 'enum':+ self.enum_menu(target)+ elif action[0] == 'section':+ self.commit()+ if action[1] in self.open:+ self.open.remove(action[1])+ else:+ self.open.add(action[1])+ elif action[0] == 'native':+ self.native(action[1], index=action[2])+ elif action[0] == 'slider':+ self.commit()+ with _context(self):+ before = action[1].value(bpy.context)+ self.drag = {'binding': action[1], 'min': action[2], 'max': action[3],+ 'rect': target.rect, 'before': before}+ self.slide(self.pointer[0])+ elif action[0] == 'menu-item':+ menu = self.menu+ self.menu = None+ if menu.get('binding'):+ self.set_value(menu['binding'], action[1])+ if menu['binding'].property == 'stablegen_preset' and action[1] != 'CUSTOM':+ self.call('stablegen.apply_preset', mode='EXEC_DEFAULT')+ elif menu.get('callback'):+ menu['callback'](action[1])+ else:+ self.navigate(action[1])+ self.area.tag_redraw()++ def slide(self, x):+ drag = self.drag+ if not drag or self.busy:+ return+ left, _, width, _ = drag['rect']+ value = drag['min'] + max(0, min(1, (x - left) / width)) * (drag['max'] - drag['min'])+ self.set_value(drag['binding'], value, undo=False)++ def select_caret(self, x, y, extend=False):+ edit = self.edit+ if not edit or not edit['lines']:+ return+ rx, ry, width, height = edit['rect']+ row = int((y - ry - TEXT_PADDING) / TEXT_LINE_HEIGHT) if edit['multiline'] else 0+ index = max(0, min(len(edit['lines']) - 1, row + edit['scroll']))+ start, end, line = edit['lines'][index]+ # BLF uses the same loaded font and pixel scale as the displayed editor.+ blf.size(_font_id, font_size() * self.scale)+ distances = [blf.dimensions(_font_id, line[:i])[0] / self.scale for i in range(len(line) + 1)]+ caret = min(range(len(distances)), key=lambda i: abs(distances[i] - (x - rx - TEXT_PADDING))) + start+ edit['buffer'].move(caret, select=extend)+ edit['follow_caret'] = True++ def text_event(self, event):+ edit, key = self.edit, event.type+ if not edit or event.value != 'PRESS':+ return False+ buffer = edit['buffer']+ ctrl = event.ctrl or event.oskey+ if key == 'ESC':+ self.commit(cancel=True)+ elif key in {'RET', 'NUMPAD_ENTER'}:+ if edit['multiline'] and not ctrl:+ buffer.replace('\n')+ else:+ self.commit()+ elif ctrl and key == 'A':+ buffer.anchor, buffer.caret = 0, len(buffer.text)+ elif ctrl and key in {'C', 'X'}:+ start, end = buffer.selection+ if start != end:+ self.window_manager.clipboard = buffer.text[start:end]+ if key == 'X':+ buffer.replace('')+ elif ctrl and key == 'V':+ text = self.window_manager.clipboard+ buffer.replace(text if edit['multiline'] else text.replace('\n', ' ').replace('\r', ''))+ elif ctrl and key in {'Z', 'Y'}:+ buffer.undo(redo=key == 'Y' or event.shift)+ elif key in {'LEFT_ARROW', 'RIGHT_ARROW'}:+ direction = -1 if key == 'LEFT_ARROW' else 1+ start, end = buffer.selection+ destination = (start if direction < 0 else end) if start != end and not event.shift else buffer.word(direction) if ctrl else buffer.caret + direction+ buffer.move(destination, event.shift)+ elif key in {'HOME', 'END'}:+ if ctrl:+ destination = 0 if key == 'HOME' else len(buffer.text)+ else:+ destination = buffer.text.rfind('\n', 0, buffer.caret) + 1 if key == 'HOME' else buffer.text.find('\n', buffer.caret)+ if destination < 0:+ destination = len(buffer.text)+ buffer.move(destination, event.shift)+ elif key in {'UP_ARROW', 'DOWN_ARROW'} and edit['lines']:+ lines = edit['lines']+ row = next((i for i, (a, b, _) in enumerate(lines) if a <= buffer.caret <= b), len(lines) - 1)+ column = buffer.caret - lines[row][0]+ target = max(0, min(len(lines) - 1, row + (-1 if key == 'UP_ARROW' else 1)))+ buffer.move(min(lines[target][1], lines[target][0] + column), event.shift)+ elif key in {'BACK_SPACE', 'DEL'}:+ buffer.delete(backward=key == 'BACK_SPACE', word=ctrl)+ elif key == 'TAB':+ candidates = [t for t in self.targets if t.enabled and isinstance(t.action, tuple) and t.action[0] in {'edit', 'enum', 'toggle'}]+ index = next((i for i, target in enumerate(candidates) if target.key == edit['key']), -1)+ self.commit()+ if candidates:+ self.activate(candidates[(index + (-1 if event.shift else 1)) % len(candidates)])+ elif getattr(event, 'unicode', '') and not ctrl and not event.alt:+ buffer.replace(event.unicode)+ else:+ return False+ if self.edit:+ self.edit['follow_caret'] = True+ self.clear_hover()+ self.area.tag_redraw()+ return True++ @property+ def window_manager(self):+ return bpy.context.window_manager++ def event(self, event):+ self.ctrl = event.ctrl or event.oskey+ self.scale = max(.8, bpy.context.preferences.system.ui_scale)+ mouse_event = event.type in {'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE', 'LEFTMOUSE', 'RIGHTMOUSE',+ 'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'TRACKPADPAN'}+ if event.type == 'WINDOW_DEACTIVATE':+ _window_mouse.pop(self.key[0], None)+ self.clear_hover(leave=True)+ return {'PASS_THROUGH'}+ if mouse_event:+ self.mouse = (event.mouse_x, event.mouse_y)+ _window_mouse[self.key[0]] = self.mouse+ self.pointer_valid = True+ inside = self.pointer_inside()+ x, y = self.pointer+ if not self.active() or self.popup:+ self.clear_hover(leave=True)+ if not self.active():+ self.commit()+ self.menu = None+ return {'PASS_THROUGH'}+ if event.value == 'PRESS' and event.type == 'ESC' and self.drag:+ drag, self.drag = self.drag, None+ self.set_value(drag['binding'], drag['before'], undo=False)+ self.update_hover()+ return {'RUNNING_MODAL'}+ if self.edit and event.value == 'PRESS' and (event.ctrl or event.oskey) and event.type == 'S':+ self.commit()+ self.clear_hover(leave=True)+ return {'PASS_THROUGH'}+ if event.type in {'MOUSEMOVE', 'INBETWEEN_MOUSEMOVE'}:+ if self.drag:+ self.slide(x)+ self.clear_hover()+ self.set_cursor('MOVE_X')+ return {'RUNNING_MODAL'}+ if self.edit and self.edit['selecting']:+ self.select_caret(x, y, extend=True)+ self.set_cursor('TEXT')+ self.area.tag_redraw()+ return {'RUNNING_MODAL'}+ target = self.update_hover(moved=True)+ if target and self.menu:+ self.menu['index'] = next((i for i, item in enumerate(self.menu_items())+ if item[0] == target.action[1]), self.menu['index'])+ # The GPU canvas covers native controls; do not let those steal hover.+ return {'RUNNING_MODAL'} if inside else {'PASS_THROUGH'}+ if mouse_event and event.value in {'PRESS', 'DOUBLE_CLICK'}:+ self.clear_hover()+ if event.type == 'LEFTMOUSE' and event.value == 'RELEASE':+ if self.drag:+ drag, self.drag = self.drag, None+ with _context(self):+ if drag['binding'].value(bpy.context) != drag['before']:+ _undo('Adjust ' + drag['binding'].rna(bpy.context).name)+ self.update_hover()+ return {'RUNNING_MODAL'}+ if self.edit:+ self.edit['selecting'] = False+ self.update_hover()+ return {'RUNNING_MODAL'} if inside else {'PASS_THROUGH'}+ if self.edit and self.text_event(event):+ return {'RUNNING_MODAL'}+ if not inside:+ self.clear_hover()+ self.release_cursor()+ if event.type == 'LEFTMOUSE' and event.value == 'PRESS':+ self.commit()+ self.menu = None+ return {'PASS_THROUGH'}+ if self.menu:+ if event.value == 'PRESS' and event.type == 'ESC':+ self.menu = None+ self.area.tag_redraw()+ self.update_hover()+ return {'RUNNING_MODAL'}+ if event.value == 'PRESS' and event.type in {'UP_ARROW', 'DOWN_ARROW', 'RET', 'NUMPAD_ENTER', 'BACK_SPACE'} or (event.value == 'PRESS' and getattr(event, 'unicode', '')):+ self.clear_hover(leave=True)+ items = self.menu_items()+ if event.type in {'UP_ARROW', 'DOWN_ARROW'}:+ self.menu['index'] = max(0, min(len(items) - 1, self.menu['index'] + (-1 if event.type == 'UP_ARROW' else 1)))+ self.menu['scroll'] = max(0, self.menu['index'] - 5)+ elif event.type in {'RET', 'NUMPAD_ENTER'} and items:+ item = items[min(self.menu['index'], len(items) - 1)]+ from .studio_widgets import Target+ self.activate(Target('menu', (0, 0, 0, 0), ('menu-item', item[0])))+ elif event.type == 'BACK_SPACE':+ self.menu['query'] = self.menu['query'][:-1]+ self.menu['index'] = self.menu['scroll'] = 0+ elif getattr(event, 'unicode', ''):+ self.menu['query'] += event.unicode+ self.menu['index'] = self.menu['scroll'] = 0+ self.area.tag_redraw()+ return {'RUNNING_MODAL'}+ if event.type in {'WHEELUPMOUSE', 'WHEELDOWNMOUSE', 'TRACKPADPAN'}:+ self.clear_hover()+ change = -45 if event.type == 'WHEELUPMOUSE' else 45+ if event.type == 'TRACKPADPAN':+ change = (event.mouse_prev_y - event.mouse_y) / self.scale+ if self.menu:+ maximum = max(0, len(self.menu_items()) - self.menu.get('rows', 6))+ self.menu['scroll'] = max(0, min(maximum, self.menu['scroll'] + (-1 if change < 0 else 1)))+ else:+ target = next((t for t in reversed(self.targets) if t.contains(x, y) and t.key in self.text_fields), None)+ # A prompt owns scrolling only while it is the active editor.+ if target and self.edit and self.edit['key'] == target.key:+ lines, count = self.text_fields[target.key]+ before = self.edit['scroll']+ offset = max(0, min(len(lines) - count, before + (-2 if change < 0 else 2)))+ self.text_scroll[target.key] = offset+ self.edit.update(scroll=offset, follow_caret=False)+ else:+ self.scroll[self.page] = max(0, min(self.max_scroll, self.scroll.get(self.page, 0) + change))+ self.area.tag_redraw()+ return {'RUNNING_MODAL'}+ 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 target.action[0] != 'menu-item'):+ self.menu = None+ self.area.tag_redraw()+ return {'RUNNING_MODAL'}+ if self.edit and target and target.key == self.edit['key']:+ self.select_caret(x, y, extend=event.shift)+ self.edit['selecting'] = True+ else:+ self.commit()+ self.activate(target)+ if self.edit and target and target.action[2]:+ self.select_caret(x, y)+ self.edit['selecting'] = True+ self.area.tag_redraw()+ self.update_hover()+ return {'RUNNING_MODAL'}+ if event.value == 'PRESS' and event.type == 'ESC' and self.edit:+ self.commit(cancel=True)+ return {'RUNNING_MODAL'}+ if event.value == 'PRESS' and (event.ctrl or event.oskey) and event.type == 'K':+ self.navigate('SEARCH')+ return {'RUNNING_MODAL'}+ if (event.value == 'PRESS' and not mouse_event and event.type not in+ {'LEFT_SHIFT', 'RIGHT_SHIFT', 'LEFT_CTRL', 'RIGHT_CTRL', 'LEFT_ALT', 'RIGHT_ALT', 'OSKEY'}):+ # Native shortcuts can open dialogs that have their own cursor handling.+ self.clear_hover(leave=True)+ return {'PASS_THROUGH'}++ def hovered(self, key):+ return key == self.hover_key++ def draw_binding(self, painter, binding, label, x, y, width, *, enabled=True, multiline=False, height=112, corners='ALL'):+ ctx = bpy.context+ prop, value = binding.rna(ctx), binding.value(ctx)+ key = _binding_key(binding)+ enabled = enabled and not self.busy and not prop.is_readonly+ if prop.type == 'BOOLEAN':+ lines = wrap(label, width - 40, painter.measure)+ height = max(CONTROL_HEIGHT, len(lines) * 16 + 6)+ painter.switch(key, (x, y, width, height), label, value, ('toggle', binding),+ enabled=enabled, hint=prop.description, hover=self.hovered(key))+ return height + CONTROL_GAP+ inline = (prop.type in {'INT', 'FLOAT'} and not prop.is_array and width >= 210+ and not multiline and painter.measure(label) <= width - 100)+ label_height = 0+ if inline:+ painter.text(label, x, y + 5, FONT_SIZE, 'text' if enabled else 'disabled', width - 100)+ else:+ label_width = max(30, width - 56 if multiline else width - 12)+ labels = wrap(label, label_width, painter.measure)+ for i, (_, _, line) in enumerate(labels):+ painter.text(line, x, y + i * 14, FONT_SIZE, 'text' if enabled else 'disabled')+ label_height = len(labels) * 14 + 3+ if multiline and self.page != 'EDITOR':+ painter.button(key + ':expand', (x + width - 22, y - 4, 22, CONTROL_HEIGHT), '',+ lambda: self.expand_prompt(binding, label), icon='expand', enabled=enabled,+ hover=self.hovered(key + ':expand'), hint='Expand this prompt editor')+ y += label_height+ editing = self.edit if self.edit and self.edit['key'] == key else None+ if multiline:+ display = editing['buffer'].text if editing else value+ lines, scroll = painter.text_field(key, (x, y, width, height), display,+ ('edit', binding, True), enabled=enabled,+ hint=prop.description, editing=editing['buffer'] if editing else None,+ scroll=editing['scroll'] if editing else self.text_scroll.get(key, 0), multiline=True,+ follow_caret=editing.get('follow_caret', True) if editing else False)+ self.text_scroll[key] = scroll+ self.text_fields[key] = (lines, max(1, int((height - TEXT_PADDING * 2) / TEXT_LINE_HEIGHT)))+ if editing:+ editing.update(rect=(x, y, width, height), lines=lines, scroll=scroll, follow_caret=False)+ painter.text(f'{len(str(display).split())} words', x + width - 55, y + height + 5, 10, 'muted')+ painter.text('Ctrl Enter to finish' if editing else 'Click to edit · Enter adds a line', x, y + height + 5, 10, 'muted', width - 68)+ return height + label_height + 24+ if prop.type == 'ENUM':+ label_value = model.enum_label(binding, ctx)+ 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)+ 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, prop.description)+ elif prop.type in {'STRING', 'INT', 'FLOAT'} and not getattr(prop, 'is_array', False):+ display = editing['buffer'].text if editing else f'{value:.{prop.precision}f}'.rstrip('0').rstrip('.') if isinstance(value, float) and prop.precision > 0 else str(value)+ filepath = prop.type == 'STRING' and prop.subtype in {'FILE_PATH', 'DIR_PATH'}+ field_width = 90 if inline else width - 27 if filepath else width+ field_x = x + width - field_width if inline else x+ lines, scroll = painter.text_field(key, (field_x, y, field_width, CONTROL_HEIGHT), display,+ ('edit', binding, False), enabled=enabled, hint=prop.description,+ editing=editing['buffer'] if editing else None,+ kind='number' if prop.type in {'INT','FLOAT'} else 'field')+ if editing:+ editing.update(rect=(field_x, y, field_width, CONTROL_HEIGHT), lines=lines, scroll=scroll)+ if filepath:+ painter.button(key + ':browse', (x + width - 24, y, 24, CONTROL_HEIGHT), '',+ lambda: self.native(binding=binding), icon='folder', enabled=enabled,+ hover=self.hovered(key + ':browse'), hint='Browse with Blender\'s file picker')+ else:+ color = getattr(prop, 'subtype', '') in {'COLOR', 'COLOR_GAMMA'} and prop.is_array+ painter.button(key, (x, y, width - 34 if color else width, CONTROL_HEIGHT), 'Open color picker' if color else 'Edit ' + label, lambda: self.native(binding=binding),+ icon='settings', style='outlined', enabled=enabled, hint=prop.description)+ if color:+ rgb = [max(0, min(1, c)) for c in value[:3]]+ if prop.subtype == 'COLOR':+ rgb = [12.92*c if c <= .0031308 else 1.055*c**(1/2.4)-.055 for c in rgb]+ painter.rect(x + width - 27, y + 2, 24, CONTROL_HEIGHT - 4, (*rgb, 1), 3)+ painter.target(key + ':color', (x + width - 30, y, 30, CONTROL_HEIGHT),+ lambda: self.native(binding=binding), enabled, prop.description)+ return label_height + CONTROL_HEIGHT + CONTROL_GAP++ def binding(self, name):+ return model.Binding.from_data(bpy.context.scene, name)++ def draw_slider(self, p, name, label, x, y, width, minimum, maximum, unit='', *, enabled=True):+ binding = self.binding(name)+ value = binding.value(bpy.context)+ key = _binding_key(binding)+ enabled = enabled and not self.busy and not binding.rna(bpy.context).is_readonly+ narrow = width < 160+ p.text(label, x, y, FONT_SIZE, 'text' if enabled else 'disabled', width if narrow else width - 75)+ edit_width = 60+ ex, ey = x + width - edit_width, y + 16 if narrow else y - 4+ editing = self.edit if self.edit and self.edit['key'] == key else None+ precision = binding.rna(bpy.context).precision+ number = f'{value:.{precision}f}'+ display = editing['buffer'].text if editing else (number.rstrip('0').rstrip('.') if precision else number) + unit+ lines, scroll = p.text_field(key, (ex, ey, edit_width, CONTROL_HEIGHT), display, ('edit', binding, False),+ enabled=enabled, hint=binding.rna(bpy.context).description,+ editing=editing['buffer'] if editing else None, kind='number')+ if editing:+ editing.update(rect=(ex, ey, edit_width, CONTROL_HEIGHT), lines=lines, scroll=scroll)+ track_y = y + (46 if narrow else 27)+ p.rect(x, track_y, width, 3, 'line', 1)+ fill = max(0, min(1, (value - minimum) / (maximum - minimum)))+ p.rect(x, track_y, width * fill, 3, 'blue', 1)+ radius = 5 if enabled and (self.hovered(key + ':slider') or self.drag and self.drag['binding'] == binding) else 4+ p.rect(x + width * fill - radius, track_y + 1 - radius, radius * 2, radius * 2,+ 'accent' if enabled else 'disabled', radius)+ p.target(key + ':slider', (x, track_y - 7, width, 17), ('slider', binding, minimum, maximum),+ enabled, binding.rna(bpy.context).description)+ return 65 if narrow else 46++ def section_summary(self, key):+ scene = bpy.context.scene+ if key == 'show_core_settings':+ return f'{scene.steps} steps · CFG {scene.cfg:g} · {scene.sampler.replace("_", " ")}'+ if key == 'show_lora_settings':+ return f'{len(scene.lora_units)} adapters'+ if key == 'show_mode_specific_settings':+ return 'Controls for the current generation mode'+ if key == 'show_image_guidance_settings':+ return 'References, context and prompt templates'+ return ''++ def draw_section(self, p, section, x, y, width, force=False, omit=()):+ key = section.key+ expanded = force or key in self.open+ summary = self.section_summary(key)+ h = 40 if summary and not expanded else 29+ if self.hovered('section:' + key):+ p.rect(x, y, width, h - 3, 'hover_soft', 2)+ p.icon('down' if expanded else 'right', x + 2, y + 9, 10, 'text')+ p.text(SECTIONS.get(key, section.title), x + 19, y + 6, FONT_SIZE, 'text', width - 27)+ if summary and not expanded:+ p.text(summary, x + 19, y + 23, 10, 'secondary', width - 27)+ p.target('section:' + key, (x, y, width, h), ('section', key), True, section.title)+ y += h+ if expanded:+ omit = set(omit)+ if key == 'show_output_material_settings' and any(s.key == 'show_core_settings' for s in self.document.sections):+ omit.update(cards.RESOLUTION_KEYS)+ if key == 'show_core_settings':+ omit.add('qwen_image_21_native_rgba')+ y = cards.sections(self, p, section, x, y, width, omit)+ if key == 'show_core_settings':+ output = next((s for s in self.document.sections if s.key == 'show_output_material_settings'), None)+ if output:+ ids = {id(c) for c in output.content.controls() if cards.property_name(c) in cards.RESOLUTION_KEYS}+ node = cards.select(output.content, ids)+ if node:+ y = cards.draw(self, p, cards.partition(node, cards.SCHEMAS['resolution']),+ output.key, x, y, width)+ rgba = cards.select(section.content, {id(c) for c in section.content.controls()+ if cards.property_name(c) == 'qwen_image_21_native_rgba'})+ if rgba:+ y = cards.draw(self, p, cards.partition(rgba, cards.SCHEMAS[key]), section.key, x, y, width)+ return y + 6++ def draw_dependent(self, p, x, y, width, draw, anchors=None):+ """Indent a dependency scope and extend its rail through all descendants."""+ start = y+ before = len(p.targets)+ end = draw(x + 18, y + 2, width - 18)+ if end > start + 2:+ targets = p.targets[before:]+ # Include nested children and the entire final control, even when+ # its dropdown or text field is below a separate caption.+ last = max((t.rect[1] + t.rect[3] for t in targets),+ default=end - CONTROL_GAP)+ p.dependency_rail(x + 6, start - 6, last)+ return end + 6+ return start++ def draw_control(self, p, live, x, y, width, section, index, label=None, hierarchy=None, anchors=None, card_body=False):+ before = len(p.targets)+ if card_body and live.control.method == 'prop':+ name = live.control.args[1]+ label = cards.LABELS.get(name) or getattr(hierarchy, 'card_labels', {}).get(id(live.control)) or label+ if card_body and live.control.method == 'prop' and live.control.args[1] in {'discard_factor', 'weight_exponent'}:+ name = live.control.args[1]+ end = y + self.draw_slider(p, name, label or ('Discard angle' if name == 'discard_factor' else 'Exponent'),+ x, y, width, 0 if name == 'discard_factor' else .1,+ 180 if name == 'discard_factor' else 15, '°' if name == 'discard_factor' else '',+ enabled=live.enabled)+ else:+ end = self.draw_plain_control(p, live, x, y, width, section, index, label)+ if anchors is not None and end > y:+ targets = p.targets[before:]+ anchors.append(targets[0].rect[1] + targets[0].rect[3] / 2 if targets else (y + end - CONTROL_GAP) / 2)+ child = hierarchy.children.get(id(live.control)) if hierarchy else None+ if child:+ child_anchors = []+ end = self.draw_dependent(p, x, end, width, lambda cx, cy, cw:+ self.draw_node(p, child, cx, cy, cw, section, hierarchy=hierarchy, anchors=child_anchors,+ card_body=card_body), child_anchors)+ return end++ def draw_plain_control(self, p, live, x, y, width, section, index, label=None):+ control = live.control+ enabled = live.enabled+ if control.method == 'prop':+ data, name = control.args[:2]+ if name in STRUCTURAL_PROPERTIES:+ return y+ label = label or control.kwargs.get('text') or data.bl_rna.properties[name].name+ try:+ binding = model.Binding.from_data(data, name)+ multiline = binding.rna(bpy.context).type == 'STRING' and 'prompt' in name and 'use_' not in name+ return y + self.draw_binding(p, binding, label, x, y, width, enabled=enabled, multiline=multiline,+ height=48 if name == 'comfyui_negative_prompt' else 90 if multiline else 112)+ except (TypeError, ReferenceError, ValueError):+ pass+ elif control.method == 'label':+ text = control.kwargs.get('text', '')+ if text:+ # Instructions and warnings wrap rather than disappearing at narrow widths.+ lines = wrap(text, width, lambda s: p.measure(s, 11))+ for _, _, line in lines:+ p.text(line, x, y + 3, 11, 'warning' if live.alert else 'muted')+ y += 16+ return y + 3+ return y+ elif control.method == 'separator':+ return y + 6+ elif control.method == 'operator':+ name = control.args[0]+ op = model.operator(name)+ label = label or control.kwargs.get('text') or op.get_rna_type().name+ if not control.kwargs.get('text') and name == 'wm.context_set_int':+ index_value = control.properties.get('value', 0)+ path = control.properties.get('data_path', '')+ label = f'Filament {index_value + 1}' if path == 'scene.stablegen_print_palette_index' else 'Select adapter' if path == 'scene.lora_units_index' else label+ if name == 'stablegen.move_camera_order':+ label = 'Move earlier' if control.properties.get('direction') == 'UP' else 'Move later'+ with _viewport(self):+ available = enabled and op.poll()+ icon = {'object.bake_textures': 'grid', 'object.switch_material': 'layers',+ 'object.export_game_engine': 'download', 'stablegen.prepare_mask_paint': 'settings'}.get(name, 'arrow')+ p.button(f'op:{section}:{index}:{name}', (x, y, width, CONTROL_HEIGHT), label,+ ('operator', name, control.properties), icon=icon, style='quiet',+ enabled=available, hover=self.hovered(f'op:{section}:{index}:{name}'),+ hint=op.get_rna_type().description)+ return y + CONTROL_HEIGHT + CONTROL_GAP+ elif control.method == 'progress':+ factor = max(0, min(1, control.kwargs.get('factor', 0)))+ text = re.sub(r'\s*\(\s*\d+(?:\.\d+)?%\)\s*$', '', control.kwargs.get('text', ''))+ p.text(text, x, y, 11, 'secondary', width - 38)+ p.text(f'{factor:.0%}', x + width - 34, y, 11, 'secondary')+ p.rect(x, y + 17, width, 3, 'line', 1)+ p.rect(x, y + 17, width * factor, 3, 'blue', 1)+ return y + 28+ elif control.method == 'template_list' and len(control.args) >= 6:+ owner, name, index_owner, index_name = control.args[2:6]+ items = getattr(owner, name)+ selected = getattr(index_owner, index_name)+ p.text(f'{len(items)} item' + ('' if len(items) == 1 else 's'), x, y, 11, 'muted')+ y += 18+ if 0 <= selected < len(items):+ item = items[selected]+ title = getattr(item, 'label', '') or getattr(item, 'scene_name', '') or getattr(item, 'name', '')+ p.text(f'{selected + 1}. {title}', x, y, FONT_SIZE, 'text', width)+ y += 19+ status = getattr(item, 'status', '')+ if status:+ p.text(status.replace('_', ' ').capitalize(), x, y, 10, 'muted', width)+ y += 17+ label = label or control.kwargs.get('text') or {'template_list': 'Edit list', 'template_curve_mapping': 'Edit curve',+ 'operator_menu_enum': 'Choose action'}.get(control.method, 'Open editor')+ p.button(f'native:{section}:{index}', (x, y, width, CONTROL_HEIGHT), label,+ ('native', section, index), icon='settings', style='outlined', enabled=enabled and not self.busy)+ return y + CONTROL_HEIGHT + CONTROL_GAP++ def draw_node(self, p, node, x, y, width, section, enabled=True, alert=False, omit=None, hierarchy=None, anchors=None, card_body=False):+ omit = omit or set()+ if hierarchy is None:+ key = (id(node), frozenset(omit))+ if key not in self.hierarchies:+ self.hierarchies[key] = hierarchy_model.build(node, omit)+ hierarchy = self.hierarchies[key]+ node = hierarchy.root+ enabled = enabled and node.attributes.get('enabled', True) and node.attributes.get('active', True)+ alert = alert or node.attributes.get('alert', False)+ children = []+ def omitted(c):+ return (c.method == 'prop' and c.args[1] in omit or c.method == 'operator' and 'op:' + c.args[0] in omit+ or id(c) in hierarchy.redundant_labels+ or section == 'main' and c.method == 'operator' and c.args[0] == 'stablegen.refresh_checkpoint_list'+ or section in {'tools', 'debug'} and c.method == 'label'+ and c.kwargs.get('text', '') in {'Tools', 'Debug / Diagnostics'})+ for child in node.children:+ if isinstance(child, Control) and omitted(child):+ continue+ if isinstance(child, Layout):+ child_controls = list(child.controls())+ if any(omitted(c) for c in child_controls) and all(omitted(c) or c.method in {'label', 'separator'} for c in child_controls):+ continue+ children.append(child)+ flat = list(node.controls())+ if node.method in {'row', 'split'}:+ labels = [c for c in flat if c.method == 'label' and c.kwargs.get('text') and not omitted(c)]+ fields = [c for c in flat if c.method in {'prop', 'operator'} and not omitted(c)]+ if (len(labels) == 1 and len(fields) == 1+ and not labels[0].kwargs['text'].startswith('→')+ and not (fields[0].method == 'operator'+ and labels[0].kwargs.get('icon') in {'ERROR', 'INFO', 'WARNING'})):+ c = fields[0]+ caption = labels[0].kwargs['text'].rstrip(':')+ if c.method == 'prop' and c.args[0].bl_rna.properties[c.args[1]].type == 'BOOLEAN':+ caption = c.kwargs.get('text') or c.args[0].bl_rna.properties[c.args[1]].name+ return self.draw_control(p, model.LiveControl(c, enabled, alert), x, y, width,+ section, self.control_index(section, c), caption, hierarchy, anchors, card_body)+ if not labels and len(children) in {2, 3} and all(isinstance(c, Control) and c.method in {'prop', 'operator'} for c in children):+ prompts = [c for c in children if c.method == 'prop' and 'prompt' in c.args[1]+ and c.args[0].bl_rna.properties[c.args[1]].type == 'STRING']+ if len(prompts) == 1 and len(children) == 2:+ other = next(c for c in children if c is not prompts[0])+ if other.method == 'operator' and not other.kwargs.get('text'):+ key = f'op:{section}:{self.control_index(section, other)}:{other.args[0]}'+ op = model.operator(other.args[0])+ with _viewport(self):+ available = enabled and not self.busy and op.poll()+ p.button(key, (x + width - 46, y - 4, 22, CONTROL_HEIGHT), '',+ ('operator',other.args[0],other.properties), icon='reset', enabled=available,+ hover=self.hovered(key), hint=op.get_rna_type().description)+ return self.draw_control(p, model.LiveControl(prompts[0],enabled,alert),x,y,width,section,+ self.control_index(section,prompts[0]), hierarchy=hierarchy, anchors=anchors, card_body=card_body)+ columns = len(children)+ # Small utilities and numeric fields share a row; long switches keep their full label.+ long_bool = any(c.method == 'prop' and c.args[0].bl_rna.properties[c.args[1]].type == 'BOOLEAN'+ and len(c.kwargs.get('text') or c.args[0].bl_rna.properties[c.args[1]].name) > 24 for c in children)+ long_field = bool(prompts)+ long_command = any(c.method == 'operator' and p.measure(c.kwargs.get('text') or model.operator(c.args[0]).get_rna_type().name)+ > (width - 10*(columns-1))/columns - 32 for c in children)+ if width / columns >= 130 and not long_bool and not long_field and not long_command:+ cw = (width - 10 * (columns - 1)) / columns+ return max(self.draw_control(p, model.LiveControl(c, enabled, alert), x + i * (cw + 10), y, cw,+ section, self.control_index(section, c), hierarchy=hierarchy, anchors=anchors, card_body=card_body) for i, c in enumerate(children))+ for index, child in enumerate(children):+ if isinstance(child, Control) and child.method == 'label' and index + 1 < len(children) and isinstance(children[index+1],Layout):+ fields = [c for c in children[index+1].controls() if c.method == 'prop']+ caption = child.kwargs.get('text','').rstrip(':').casefold()+ if len(fields) == 1 and fields[0].args[0].bl_rna.properties[fields[0].args[1]].name.casefold() == caption:+ continue+ if isinstance(child, Layout):+ inset = 8 if child.method == 'box' and node.method != 'root' and not card_body else 0+ start = y+ if inset:+ p.begin_group()+ y = self.draw_node(p, child, x + inset, y + (6 if inset else 0),+ width - inset * 2, section, enabled, alert, omit, hierarchy, anchors, card_body)+ if inset:+ if y > start + 6:+ y += 5+ p.end_group((x, start, width, y - start), 'subbox')+ y += 6+ else:+ p.end_group((x, start, width, 0), 'subbox')+ y = start+ else:+ y = self.draw_control(p, model.LiveControl(child, enabled, alert), x, y, width, section,+ self.control_index(section, child), hierarchy=hierarchy, anchors=anchors, card_body=card_body)+ return y++ def control_index(self, section, control):+ node = next((s.content for s in self.document.sections if s.key == section), None)+ if node is None:+ return -1+ return next((i for i, c in enumerate(node.controls()) if c is control), -1)++ def section_page(self, section):+ if bpy.context.scene.architecture_mode == 'trellis2':+ if section.key == 'show_trellis2_texture_settings':+ return 'GENERATE'+ if (section.key in {'show_core_settings', 'show_lora_settings'} and+ bpy.context.scene.trellis2_texture_mode in {'native', 'none'}):+ return 'MESH'+ return ('QUEUE' if section.key == 'queue' else+ 'EXPERIMENTS' if section.key == 'show_texturing_experiments' else+ 'GENERATE' if section.page == 'OUTPUT' else section.page)++ def pages(self):+ if bpy.context.scene.architecture_mode == 'trellis2':+ return [('MESH', 'Mesh'), *PAGES]+ return PAGES + [('TOOLS', 'Tools')]++ def more_menu(self, rect):+ available = {self.section_page(s) for s in self.document.sections}+ primary = dict(self.pages())+ self.menu = {'anchor': rect, 'items': [(key, name, '') for key, name in MORE if key in available and key not in primary],+ 'query': '', 'binding': None, 'index': 0, 'scroll': 0}++ def draw_header(self, p, x, width):+ p.icon('layers', x, 12, 18, 'accent')+ p.text('StableGen', x + 26, 12, 13, 'text')+ p.button('search-button', (x + width - 50, 9, 22, CONTROL_HEIGHT), '', lambda: self.navigate('SEARCH'),+ icon='search', hover=self.hovered('search-button'), hint='Find a setting · Ctrl K')+ p.button('preferences', (x + width - 23, 9, 23, CONTROL_HEIGHT), '', lambda: self.call('stablegen.studio_preferences'),+ icon='settings', enabled=not self.busy, hover=self.hovered('preferences'), hint='StableGen add-on preferences')+ current_page = self.prompt_editor[2] if self.page == 'EDITOR' and self.prompt_editor else self.page+ if current_page not in dict(self.pages()):+ 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=model.operator(name).get_rna_type().description)+ 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'), ('object.toggle_camera_labels', 'Labels', 'labels')]+ 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 / 4 + 1, y + 25, width / 4 - 2, 20), text,+ ('operator', name, {}), icon=icon, enabled=enabled, hover=self.hovered(key),+ hint=model.operator(name).get_rna_type().description)+ 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)+ if item.control.method == 'operator'] if self.document.presets else []+ compact_actions = len(actions) > 1 or cw < 130+ buttons = []+ for item in actions:+ name = item.control.args[0]+ label, icon = {'stablegen.save_preset': ('Save', 'plus'),+ 'stablegen.apply_preset': ('Apply', 'right'),+ 'stablegen.delete_preset': ('', 'x')}.get(name, ('', 'settings'))+ buttons.append((item, '' if compact_actions else label, icon,+ 60 if label and not compact_actions else 26))+ button_space = sum(button[3] for button in buttons)+ preset_x = x + cw + 12+ right = self.draw_binding(p, self.binding('stablegen_preset'), 'Preset', preset_x, y, cw - button_space,+ corners='LEFT' if buttons else 'ALL')+ button_x = preset_x + cw - button_space+ for i, (item, label, icon, button_width) in enumerate(buttons):+ c = item.control+ with _viewport(self):+ op = model.operator(c.args[0])+ enabled = item.enabled and not self.busy and op.poll()+ hint = op.get_rna_type().description+ p.button('preset:' + c.args[0], (button_x, y + right - CONTROL_HEIGHT - CONTROL_GAP,+ button_width, CONTROL_HEIGHT), label,+ ('operator', c.args[0], c.properties), icon=icon, style='outlined', enabled=enabled, hint=hint,+ corners='RIGHT' if i == len(buttons) - 1 else 'NONE')+ button_x += button_width+ y += max(left, right)+ pages = self.pages() + [('MORE', 'More')]+ p.outline(x, y, width, 28, 'card', 'section_border', 4)+ compact = width < 360+ widths = [(width - 30) / 4] * 4 + [30] if compact else [width * n for n in (.22, .24, .25, .19, .1)]+ px = x+ for (page, label), w in zip(pages, widths):+ active = current_page == page or page == 'MORE' and current_page not in dict(self.pages())+ key = 'tab:' + page+ rect = (px, y, w, 27)+ action = (lambda r=rect: self.more_menu(r)) if page == 'MORE' else lambda page=page: self.navigate(page)+ caption = '' if page == 'MORE' else (+ {'CAMERAS': 'Views', 'BLEND': 'Blend'}.get(page, label) if compact else label)+ if active or self.hovered(key):+ # Use the shared frame for both the tint and border so selection+ # reaches its existing edges and rounded outer corners.+ previous_clip = p.clip_rect+ left = round(px * p.scale) / p.scale+ right = round((px + w) * p.scale) / p.scale+ try:+ p.clip((left, y - 1, right - left, 30))+ p.outline(x, y, width, 28, 'tab_selected' if active else 'card',+ 'accent' if active else 'hover_border', 4)+ finally:+ p.clip(previous_clip)+ p.button(key, rect, caption, action, icon='more' if page == 'MORE' else None,+ style='tab', active=active, hover=self.hovered(key), hint=label)+ px += w+ return y + 29++ def clear_camera_selection(self):+ with _viewport(self):+ for obj in bpy.context.selected_objects:+ if obj.type == 'CAMERA':+ obj.select_set(False)+ if bpy.context.view_layer.objects.active and bpy.context.view_layer.objects.active.type == 'CAMERA':+ bpy.context.view_layer.objects.active = next((o for o in bpy.context.selected_objects if o.type == 'MESH'), None)+ self.refresh()++ def draw_footer(self, p, x, width):+ progress = [item for n in self.document.actions for item in model.controls(n) if item.control.method == 'progress']+ decision = [item for n in self.document.actions for item in model.controls(n)+ if item.control.method == 'operator' and item.control.args[0] == 'stablegen.resolve_masked_edit']+ utilities = self.page in {'TOOLS', 'DEBUG'} and not decision+ preview = diagnostics.active(bpy.context.scene)+ # Keep the last action row twelve pixels clear of the panel's bottom edge.+ bottom_padding = 12+ if progress:+ height = max(92, 10 + len(progress) * 28 + 24 + bottom_padding)+ elif utilities:+ height = 10 + (28 if preview else 0) + CONTROL_HEIGHT + bottom_padding+ else:+ height = 10 + 20 + 35 + CONTROL_HEIGHT + bottom_padding+ y = p.height - height+ p.rect(0, y, p.width, height, 'card')+ p.rect(0, y, p.width, 1, 'section_border')+ top = y+ y += 10+ if not self.document.actions and not utilities:+ p.text('Choose a supported architecture to continue.', x, y, 11, 'muted', width)+ return top+ if progress:+ for item in progress:+ y = self.draw_control(p, item, x, y, width, 'actions', 0)+ cancel = next((item for n in self.document.actions for item in model.controls(n)+ if item.control.method == 'operator' and+ (item.control.kwargs.get('icon') == 'CANCEL' or 'Cancel' in item.control.kwargs.get('text', '') or item.control.args[0] == 'stablegen.stop_masked_edit')), None)+ if cancel:+ c = cancel.control+ p.button('cancel', (x, y, width, 24), c.kwargs.get('text', 'Stop'), ('operator', c.args[0], c.properties),+ icon='stop', style='outlined', enabled=cancel.enabled)+ return top+ if utilities:+ if preview:+ with _viewport(self):+ available = model.operator('stablegen.studio_diagnostic').poll()+ p.button('return-textures', (x, y, width, CONTROL_HEIGHT), 'Return to textures',+ lambda: self.call('stablegen.studio_diagnostic', {'value': '"TEXTURES"'}, mode='EXEC_DEFAULT'),+ icon='reset', style='outlined', enabled=available,+ hint='Restore the original mesh, materials and render settings' if available else 'Switch to Object Mode to restore textures')+ y += 28+ self.draw_footer_commands(p, x, y, width)+ return top+ scene = bpy.context.scene+ from ..core.preferences import CheckServerStatus+ prefs = bpy.context.preferences.addons[ADDON_PKG].preferences+ checking_server = CheckServerStatus._checking+ refresh_server = checking_server or bool(prefs.server_address and not prefs.server_online)+ selected = [o for o in bpy.context.selected_objects if o.type == 'CAMERA']+ count = sum(o.type == 'CAMERA' for o in scene.objects)+ native = scene.architecture_mode == 'trellis2'+ primary = model.action(self.document, 'object.test_stable', 'object.stablegen_regenerate',+ 'object.trellis2_generate', 'object.trellis2_batch_generate', 'stablegen.masked_edit')+ disabled_reason = ''+ if primary:+ text = primary.control.kwargs.get('text', '')+ if any(word in text.lower() for word in ('cannot', 'enable online', 'select an image')):+ disabled_reason = text.replace('Cannot generate: ', '').replace('Cannot edit: ', '')+ scope = 'TRELLIS.2 · Shape and texture' if native else f'{len(selected)} selected views' if selected else f'{count} views · ' + ('Selected objects' if scene.texture_objects == 'selected' else 'All visible objects')+ p.text('Checking server…' if checking_server else disabled_reason or ('Reproject changes before baking' if self.dirty_projection else scope), x, y, 10,+ 'warning' if disabled_reason or self.dirty_projection else 'muted', width - 64)+ if selected and not native:+ p.button('all-views', (x + width - 65, y - 3, 65, 18), 'All views', self.clear_camera_selection,+ enabled=not self.busy, hint='Clear only the selected cameras; retain selected meshes')+ else:+ p.text(f'Seed {scene.trellis2_seed if native else scene.seed}', x + width - 64, y, 10, 'muted', 64)+ y += 20+ if decision:+ for i, item in enumerate(decision):+ c = item.control+ p.button('decision:' + str(i), (x + i * (width + 10) / 2, y, (width - 10) / 2, 28),+ c.kwargs.get('text', ''), ('operator', c.args[0], c.properties), style='primary' if i == 0 else 'outlined')+ elif primary:+ c = primary.control+ label = 'Generate asset' if native else 'Regenerate selected views' if c.args[0] == 'object.stablegen_regenerate' else 'Edit painted selection' if c.args[0] == 'stablegen.masked_edit' else 'Generate textures'+ with _viewport(self):+ available = primary.enabled and not disabled_reason and model.operator(c.args[0]).poll()+ refresh_width = 34 if refresh_server else 0+ p.button('generate', (x, y, width - refresh_width, 28), label, ('operator', c.args[0], c.properties),+ icon='play', style='primary', enabled=available and not self.busy and not checking_server,+ corners='LEFT' if refresh_server else 'ALL',+ hint=disabled_reason or model.operator(c.args[0]).get_rna_type().description)+ if refresh_server:+ with _viewport(self):+ refresh_available = model.operator('stablegen.check_server_status').poll() and not self.busy+ p.button('refresh-server', (x + width - refresh_width, y, refresh_width, 28), '',+ ('operator', 'stablegen.check_server_status', {}), icon='reset', style='outlined',+ enabled=refresh_available, corners='RIGHT', hover=self.hovered('refresh-server'),+ hint='Checking server connection…' if checking_server else+ 'Refresh server connection and available models · ' + prefs.server_address)+ y += 35+ self.draw_footer_commands(p, x, y, width)+ return top++ def draw_footer_commands(self, p, x, y, width):+ commands = [('object.stablegen_reproject', 'Reproject', 'layers'),+ ('object.bake_textures', 'Bake', 'grid'), ('object.export_game_engine', 'Export', 'download')]+ cw = (width - 16) / 3+ for i, (name, label, icon) in enumerate(commands):+ with _viewport(self):+ enabled = model.operator(name).poll() and not self.busy+ if name == 'object.bake_textures' and self.dirty_projection:+ enabled = False+ key = 'footer:' + name+ p.button(key, (x + i * (cw + 8), y, cw, CONTROL_HEIGHT), label, ('operator', name, {}), icon=icon,+ style='outlined', enabled=enabled, active=name == 'object.stablegen_reproject' and self.dirty_projection,+ hover=self.hovered(key), hint='Reproject changed settings before baking' if name == 'object.bake_textures' and self.dirty_projection else model.operator(name).get_rna_type().description)++ def live_operator(self, name):+ return next((item for section in self.document.sections for item in model.controls(section.content)+ if item.control.method == 'operator' and item.control.args[0] == name), None)++ def draw_actions(self, p, title, commands, x, y, width, *, collapsible=False):+ """Task cards preserve each original operator's poll and arguments."""+ key = 'utilities:' + title+ if collapsible:+ if self.hovered('section:' + key):+ p.rect(x, y, width, 26, 'hover_soft', 2)+ p.icon('down' if key in self.open else 'right', x + 8, y + 8, 10, 'text')+ p.text(title, x + 25, y + 7, FONT_SIZE, 'text', width - 33)+ p.target('section:' + key, (x, y, width, 26), ('section', key), True, title)+ y += 30+ if key not in self.open:+ return y+ else:+ p.text(title, x, y + 3, FONT_SIZE, 'secondary', width)+ y += 23+ rows = []+ for name, label, icon in commands:+ item = self.live_operator(name)+ if item is None:+ continue+ with _viewport(self):+ op = model.operator(name)+ enabled = item.enabled and op.poll()+ hint = op.get_rna_type().description+ cancellation = name in {'stablegen.batch_texture_dae_cancel', 'stablegen.stop_texturing_regression',+ 'stablegen.debug_force_generation_idle', 'stablegen.interactive_discard_cancel',+ 'stablegen.interactive_discard_apply'}+ enabled = enabled and (not self.busy or cancellation)+ rows.append((name, label, icon, item.control.properties, enabled, hint))+ if not rows:+ return y+ return cards.actions(self, p, rows, x, y, width)++ def draw_tools(self, p, x, y, width):+ scene = bpy.context.scene+ y = self.draw_actions(p, 'Scene setup', [+ ('object.add_hdri', 'Add HDRI lighting', 'light'),+ ('object.apply_all_mesh_modifiers', 'Apply all modifiers', 'modifier'),+ ('object.curves_to_mesh', 'Convert curves to mesh', 'curve')], x, y, width)+ y = self.draw_actions(p, 'Texture utilities', [+ ('object.switch_material', 'Switch material', 'material'),+ ('object.stablegen_mirror_reproject', 'Mirror last projection', 'mirror'),+ ('object.stablegen_local_postprocess', 'Local post-processing', 'settings')], x, y, width)+ y = self.draw_actions(p, 'Presentation', [+ ('object.export_orbit_gif', 'Export orbit GIF / MP4', 'camera')], x, y, width)+ y = self.draw_actions(p, 'Import & batch', [+ ('stablegen.import_dae', 'Import DAE', 'download'),+ ('stablegen.batch_import_dae', 'Batch import DAE', 'folder'),+ ('stablegen.batch_texture_dae', 'Batch texture DAE / GLB', 'layers')], x, y, width)+ wm = bpy.context.window_manager+ if getattr(wm, 'sg_batch_tex_running', False):+ total = max(1, wm.sg_batch_tex_total)+ p.text(f'{wm.sg_batch_tex_index} / {total} models · {wm.sg_batch_tex_phase.replace("_", " ")}',+ x, y, FONT_SIZE, 'text', width)+ p.rect(x, y + 20, width, 3, 'line', 1)+ p.rect(x, y + 20, width * min(1, wm.sg_batch_tex_index / total), 3, 'blue', 1)+ y += 31+ y = self.draw_actions(p, 'Running batch', [+ ('stablegen.batch_texture_dae_cancel', 'Stop batch', 'stop')], x, y, width)+ if scene.architecture_mode != 'trellis2':+ y = self.draw_actions(p, 'Mesh & rig', [+ ('object.stablegen_make_solid', 'Make solid', 'material'),+ ('object.stablegen_autorig_selected_mesh', 'Auto-rig selected character', 'rig')], x, y, width)+ return y++ def diagnostic_camera_menu(self, rect):+ state = bpy.context.scene.sg_studio_diagnostics+ items = [(obj.name, obj.name, 'Inspect this camera') for obj in bpy.context.scene.objects if obj.type == 'CAMERA']+ items.sort()+ self.menu = {'anchor': rect, 'items': items, 'query': '', 'binding': None,+ 'callback': lambda name: self.call('stablegen.studio_diagnostic',+ {'setting': 'camera', 'value': json.dumps(name)}, mode='EXEC_DEFAULT'),+ 'index': next((i for i, item in enumerate(items) if state.camera and item[0] == state.camera.name), 0), 'scroll': 0}++ def draw_diagnostics(self, p, x, y, width):+ scene, state = bpy.context.scene, bpy.context.scene.sg_studio_diagnostics+ if not any(s.key == 'debug' for s in self.document.sections):+ p.text('Enable Debug in add-on preferences to use diagnostics.', x, y, FONT_SIZE, 'secondary', width)+ return y + 28+ start = y+ p.begin_group()+ y = cards.heading(p, 'Viewport inspection', x + 12, y + 11, width - 24, 'eye')+ p.rect(x + 12, y - 3, width - 24, 1, 'divider')+ with _viewport(self):+ available = model.operator('stablegen.studio_diagnostic').poll()+ y += self.draw_binding(p, model.Binding.from_data(state, 'mode'), 'Display', x + 8, y + 8, width - 16, enabled=available) + 8+ description = next(item[2] for item in diagnostics.MODES if item[0] == state.mode)+ for _, _, line in wrap(description, width - 16, p.measure):+ p.text(line, x + 8, y, 10, 'secondary')+ y += 15+ y += 6+ if diagnostics.active(scene):+ count = sum(record.object is not None for record in state.meshes)+ p.text(f'Previewing {count} mesh' + ('es' if count != 1 else '') + ' · Originals preserved',+ x + 8, y, 10, 'accent', width - 16)+ y += 22+ options = {'GRID': ['grid_size'], 'COVERAGE': ['coverage'], 'CONFIDENCE': ['confidence'],+ 'DPPG': ['scope', 'stage']}.get(state.mode, [])+ for key in options:+ binding = model.Binding.from_data(state, key)+ y += self.draw_binding(p, binding, binding.rna(bpy.context).name, x + 8, y, width - 16, enabled=available)+ if state.mode in {'WEIGHT', 'FEATHER', 'VISIBILITY', 'CONFIDENCE'} or state.mode == 'DPPG' and state.scope == 'ACTIVE':+ p.text('Camera', x + 8, y, FONT_SIZE, 'text')+ y += 17+ rect = (x + 8, y, width - 16, CONTROL_HEIGHT)+ p.outline(*rect, 'menu', 'hover_border' if self.hovered('diagnostic-camera') else 'menu_border')+ p.text(state.camera.name if state.camera else 'Choose camera', rect[0] + 8, y + 5, FONT_SIZE, 'menu_text', width - 49)+ p.icon('down', x + width - 24, y + 6, 10, 'menu_text')+ p.target('diagnostic-camera', rect, lambda rect=rect: self.diagnostic_camera_menu(rect), available and not self.busy,+ 'Choose the camera whose signal is displayed')+ y += CONTROL_HEIGHT + 8+ y += 2+ p.end_group((x, start, width, y - start), 'subbox', 'section_border', 3)+ y += 12+ y = self.draw_actions(p, 'Projection analysis', [+ ('stablegen.debug_projection_line', 'Measure a surface line', 'graph'),+ ('stablegen.debug_open_projection_line', 'Open last line report', 'document'),+ ('stablegen.interactive_discard_check', 'Interactive discard check', 'eye')], x, y, width)+ from ..debug_tools import SG_OT_InteractiveDiscardCheck, SG_OT_DebugProjectionLine+ if SG_OT_DebugProjectionLine.status:+ for _, _, line in wrap(SG_OT_DebugProjectionLine.status, width, p.measure):+ p.text(line, x, y, 10, 'secondary')+ y += 15+ y += 6+ if SG_OT_InteractiveDiscardCheck._active is not None:+ tools = next((s for s in self.document.sections if s.key == 'tools'), None)+ if tools:+ block = next((child for child in tools.content.children if isinstance(child, Layout) and+ any(item.control.method == 'operator' and item.control.args[0] == 'stablegen.interactive_discard_apply'+ for item in model.controls(child))), None)+ if block:+ y = self.draw_node(p, block, x, y, width, 'tools')+ from ..texturing.regression import SG_OT_TexturingRegression+ if SG_OT_TexturingRegression._active is not None:+ p.text('Workflow tests', x, y, FONT_SIZE, 'secondary')+ y += 23+ for _, _, line in wrap(SG_OT_TexturingRegression.status, width, p.measure):+ p.text(line, x, y, FONT_SIZE, 'text')+ y += 16+ y = self.draw_actions(p, 'Running test', [+ ('stablegen.stop_texturing_regression', 'Stop workflow test', 'stop')], x, y + 6, width)+ else:+ y = self.draw_actions(p, 'Workflow tests', [+ ('stablegen.texturing_regression', 'Run texturing regression', 'play'),+ ('stablegen.export_retarget_debug_bundle', 'Export retarget test bundle', 'download')], x, y, width)+ y = self.draw_actions(p, 'Rig diagnostics', [+ ('stablegen.debug_skinning_weights', 'Inspect skin weights', 'rig'),+ ('stablegen.debug_clear_skinning_weights', 'Restore skin colors', 'reset'),+ ('stablegen.debug_convert_fortune_rig', 'Convert rig to Fortune', 'rig'),+ ('stablegen.debug_make_solid', 'Inspect Make Solid', 'material')], x, y, width, collapsible=True)+ return self.draw_actions(p, 'Recovery', [+ ('stablegen.debug_restore_material', 'Clear mesh materials', 'x'),+ ('stablegen.debug_force_generation_idle', 'Reset stalled generation', 'stop')], x, y, width, collapsible=True)++ def draw_generate(self, p, x, y, width):+ scene = bpy.context.scene+ main = next((s for s in self.document.sections if s.key == 'main'), None)+ if main is None:+ return y+ start = y+ p.begin_group()+ y = cards.heading(p, 'Texture input', x + 12, y + 11, width - 24, 'layers')+ p.rect(x + 12, y - 3, width - 24, 1, 'divider')+ outer_x, outer_width = x, width+ x, width, y = x + 12, width - 24, y + 6+ native = scene.architecture_mode == 'trellis2' and scene.trellis2_texture_mode in {'native', 'none'}+ trellis = scene.architecture_mode == 'trellis2'+ if trellis:+ y += self.draw_binding(p, self.binding('trellis2_texture_mode'), 'Texture mode', x, y, width)+ y += self.draw_binding(p, self.binding('use_separate_texture_prompt'), 'Use separate texture prompt', x, y + 3, width,+ enabled=not native) + 3+ if scene.use_separate_texture_prompt:+ y = self.draw_dependent(p, x, y, width, lambda cx, cy, cw:+ cy + self.draw_binding(p, self.binding('texture_prompt'), 'Texture prompt', cx, cy, cw,+ multiline=True, height=112, enabled=not native)) + 6+ if not native:+ if not scene.use_separate_texture_prompt:+ for _, _, line in wrap('Texturing uses the prompt on the Mesh tab.', width, p.measure):+ p.text(line, x, y, 10, 'secondary')+ y += 15+ y += 10+ else:+ p.text('Native textures follow the input image.' if scene.trellis2_texture_mode == 'native' else 'Texture generation is disabled.',+ x, y, 10, 'secondary', width)+ y += 25+ checkpoint = model.first_property(self.document, 'model_name')+ if checkpoint and not (trellis and native):+ y += self.draw_binding(p, self.binding('model_name'), 'Checkpoint', x, y, width - 31)+ 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 real ComfyUI model list')+ masked = (scene.qwen_generation_method if scene.model_architecture.startswith('qwen') 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+ handled = {'architecture_mode', 'stablegen_preset', 'model_name', 'comfyui_prompt', 'sg_masked_prompt',+ 'generation_method', 'qwen_generation_method', 'texture_objects'}+ if masked:+ 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'+ cw = (width - 12) / 2+ left = self.draw_binding(p, self.binding(mode_key), 'Generation mode', x, y, cw)+ right = self.draw_binding(p, self.binding('texture_objects'), 'Target objects', x + cw + 12, y, cw)+ y += max(left, right)+ if masked:+ mode_section = next((s for s in self.document.sections if s.key == 'show_mode_specific_settings'), None)+ commands = [item for item in model.controls(mode_section.content)+ if item.control.method == 'operator' and item.control.args[0] in mask_commands] if mode_section else []+ for i, item in enumerate(commands):+ c = item.control+ with _viewport(self):+ available = item.enabled and not self.busy and model.operator(c.args[0]).poll()+ columns = 2 if width >= 320 else 1+ command_width = (width - 12 * (columns - 1)) / columns+ p.button('mask:' + c.args[0], (x + i % columns * (command_width + 12),+ y + i // columns * (CONTROL_HEIGHT + CONTROL_GAP), command_width, CONTROL_HEIGHT),+ c.kwargs.get('text') or model.operator(c.args[0]).get_rna_type().name,+ ('operator', c.args[0], c.properties), style='outlined', enabled=available,+ icon='settings' if i == 0 else 'x', hint=model.operator(c.args[0]).get_rna_type().description)+ if commands:+ y += ((len(commands) + columns - 1) // columns) * (CONTROL_HEIGHT + CONTROL_GAP)+ y += 8+ p.end_group((outer_x, start, outer_width, y - start), 'subbox', 'section_border', 3)+ x, width, y = outer_x, outer_width, y + 12+ if main and scene.architecture_mode != 'trellis2':+ extras = Layout()+ extras.children.extend(item.control for item in model.controls(main.content)+ if item.control.method == 'prop' and item.control.args[1] not in handled+ and item.control.args[1] not in STRUCTURAL_PROPERTIES)+ if extras.children:+ y = self.draw_section(p, Section('main_extra', 'Additional prompts', 'GENERATE', '', extras), x, y, width)+ for section in self.document.sections:+ if self.section_page(section) == 'GENERATE' and section.key not in {'main', 'export'}:+ omit = {prompt} | {'op:' + name for name in mask_commands} if masked and section.key == 'show_mode_specific_settings' else {prompt}+ y = self.draw_section(p, section, x, y, width, force=masked and section.key == 'show_mode_specific_settings', omit=omit)+ return y++ def draw_mesh(self, p, x, y, width):+ scene = bpy.context.scene+ main = next((s for s in self.document.sections if s.key == 'main'), None)+ if main:+ start = y+ p.begin_group()+ y = cards.heading(p, 'Mesh input', x + 12, y + 11, width - 24, 'layers')+ p.rect(x + 12, y - 3, width - 24, 1, 'divider')+ outer_x, outer_width = x, width+ x, width, y = x + 12, width - 24, y + 6+ y += self.draw_binding(p, self.binding('trellis2_generate_from'), 'Generate mesh from', x, y, width)+ if scene.trellis2_generate_from == 'prompt':+ shared = scene.trellis2_texture_mode != 'none' and (+ not scene.use_separate_texture_prompt or scene.trellis2_texture_mode == 'native')+ y += self.draw_binding(p, self.binding('comfyui_prompt'), 'Mesh image & texture prompt' if shared else 'Mesh image prompt', x, y + 4, width,+ multiline=True, height=112) + 6+ hint = ('Generates the input image for the mesh.' if scene.trellis2_texture_mode == 'none' else+ 'Generates the mesh’s input image. Texturing uses its separate prompt.'+ if scene.use_separate_texture_prompt and scene.trellis2_texture_mode != 'native' else+ 'Generates the input image for the mesh and also guides texturing.')+ for _, _, line in wrap(hint, width, p.measure):+ p.text(line, x, y, 10, 'secondary')+ y += 15+ y += 10+ y += self.draw_binding(p, self.binding('trellis2_preview_gallery_enabled'), 'Preview gallery', x, y, width)+ binding = self.binding('trellis2_preview_gallery_count')+ y = self.draw_dependent(p, x, y, width, lambda cx, cy, cw:+ cy + self.draw_binding(p, binding, 'Image count', cx, cy, cw,+ enabled=scene.trellis2_preview_gallery_enabled)) + 5+ else:+ shared = scene.trellis2_texture_mode not in {'native', 'none'} and not scene.use_separate_texture_prompt+ y += self.draw_binding(p, self.binding('comfyui_prompt'), 'Shared texture prompt' if shared else 'Mesh image prompt', x, y + 4, width,+ multiline=True, height=112, enabled=shared) + 6+ p.text('Mesh generation uses the selected input image.', x, y, 10, 'secondary', width)+ y += 25+ omit = {'architecture_mode', 'stablegen_preset', 'comfyui_prompt', 'texture_prompt',+ 'use_separate_texture_prompt', 'trellis2_texture_mode', 'trellis2_generate_from',+ 'trellis2_preview_gallery_enabled', 'trellis2_preview_gallery_count',+ 'generation_method', 'qwen_generation_method', 'texture_objects'}+ if scene.trellis2_texture_mode not in {'native', 'none'}:+ omit.add('model_name')+ omit.add('op:stablegen.refresh_checkpoint_list')+ y = self.draw_node(p, main.content, x, y, width, 'main', omit=omit)+ y += 8+ p.end_group((outer_x, start, outer_width, y - start), 'subbox', 'section_border', 3)+ x, width, y = outer_x, outer_width, y + 12+ for section in self.document.sections:+ if self.section_page(section) == 'MESH':+ y = self.draw_section(p, section, x, y, width)+ return self.draw_actions(p, 'Mesh & rig utilities', [+ ('object.stablegen_make_solid', 'Make solid', 'material'),+ ('object.stablegen_autorig_selected_mesh', 'Auto-rig selected character', 'rig')], x, y, width)++ def draw_cameras(self, p, x, y, width):+ scene = bpy.context.scene+ from ..texturing.view_plan import order_cameras+ cameras = order_cameras((o for o in scene.objects if o.type == 'CAMERA'),+ [item.name for item in scene.sg_camera_order] if scene.sg_use_custom_camera_order else ())+ p.text('Scene cameras', x, y, 13)+ p.text(f'{len(cameras)} views', x + width - 58, y + 2, 10, 'muted')+ y += 29+ def setup(cx, cy, cw):+ cy += self.draw_binding(p, self.binding('use_camera_prompts'), 'Use camera descriptions', cx, cy, cw)+ return cy + self.draw_binding(p, self.binding('sg_use_custom_camera_order'), 'Custom generation order', cx, cy, cw)+ y = cards.group(p, 'View setup', x, y, width, setup, 'camera')+ camera_options = next((s for s in self.document.sections if s.key == 'show_camera_options'), None)+ if camera_options and scene.sg_use_custom_camera_order:+ y = cards.sections(self, p, camera_options, x, y, width,+ omit={'use_camera_prompts', 'sg_use_custom_camera_order'})+ if not cameras:+ p.text('Add cameras using the toolbar above.', x, y, FONT_SIZE, 'muted', width)+ y += 27+ for i, camera in enumerate(cameras):+ start = y+ p.begin_group()+ selected = camera.select_get()+ hovered = self.hovered('camera:' + camera.name) and not self.busy+ tx = x + 12 if selected else x + 85+ p.text(f'{i + 1:02} · {camera.name}', tx, y + 16, FONT_SIZE, 'text', x + width - tx - 44)+ image = self.camera_images.get(camera.name)+ prompt = scene.camera_prompts.get(camera.name)+ if not selected:+ title = prompt.prompt if prompt and prompt.prompt else 'Generated' if image else 'No generated image'+ p.text(title, tx, y + 36, 10, 'secondary', width - 124)+ p.target('camera:' + camera.name, (x + 1, y + 1, width - 43, 38 if selected else 82),+ lambda name=camera.name: self.call('stablegen.studio_select_camera', {'camera_name': name, 'extend': self.ctrl}),+ not self.busy, camera.name + ' · Ctrl click to add to selection')+ 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,+ hint='Look through ' + camera.name)+ image_rect = (x + 12, y + 43, 70, 160) if selected else (x + 12, y + 12, 60, 60)+ p.outline(*image_rect, 'menu', 'menu_border', 2)+ if image:+ p.image(image, image_rect)+ else:+ ix, iy, iw, ih = image_rect+ p.icon('camera', ix + (iw - 25) / 2, iy + (ih - 25) / 2, 25)+ if selected:+ y += 43+ y += self.draw_binding(p, model.Binding.from_data(camera, 'name'), 'Camera name', x + 98, y, width - 110)+ if prompt and scene.use_camera_prompts:+ y += self.draw_binding(p, model.Binding.from_data(prompt, 'prompt'), 'View description', x + 98, y, width - 110,+ multiline=True, height=93)+ y = max(y, image_rect[1] + image_rect[3]) + 12+ else:+ y += 84+ p.end_group((x, start, width, y - start), 'subbox', 'accent' if selected else 'hover_border' if hovered else 'section_border', 3)+ y += 8+ for section in self.document.sections:+ if section.page == 'CAMERAS' and section.key not in {'camera_tools', 'show_camera_options'}:+ y = self.draw_section(p, section, x, y + 8, width, omit={'use_camera_prompts','sg_use_custom_camera_order'})+ return y++ def menu_items(self):+ query = self.menu['query'].casefold()+ return [item for item in self.menu['items'] if query in item[1].casefold()]++ def draw_menu(self, p):+ 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+ 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)+ menu['rect'] = (x, y, width, height)+ p.outline(x, y, width, height, 'raised', 'line', 6)+ p.text(menu['query'] or 'Type to filter…', x + 10, y + 8, FONT_SIZE, 'text' if menu['query'] else 'muted', width - 20)+ p.rect(x + 8, y + 25, width - 16, 1, 'line')+ if not items:+ p.text('No matching choices', x + 10, y + 35, FONT_SIZE, 'muted')+ start = min(menu['scroll'], max(0, len(items) - rows))+ for i, (identifier, label, description) in enumerate(items[start:start + rows], start):+ rect = (x + 5, y + 30 + (i - start) * 24, width - 10, CONTROL_HEIGHT)+ 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)+ 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,+ max(12, rows / len(items) * (height - 36)), 'muted', 1)++ def draw_search(self, p, x, y, width):+ editing = self.edit if self.edit and self.edit['key'] == 'search' else None+ value = editing['buffer'].text if editing else self.query+ lines, scroll = p.text_field('search', (x, y, width, CONTROL_HEIGHT), value, ('edit', None, False),+ editing=editing['buffer'] if editing else None, hint='Search visible settings and tooltips')+ if editing:+ editing.update(rect=(x, y, width, CONTROL_HEIGHT), lines=lines, scroll=scroll)+ y += 36+ query = value.strip().casefold()+ if not query:+ p.text('Find a setting, workflow or tool.', x, y, FONT_SIZE, 'muted')+ return y + 30+ found = False+ for section in self.document.sections:+ for i, item in enumerate(model.controls(section.content)):+ control = item.control+ if control.method not in {'prop', 'operator'}:+ continue+ text = control.kwargs.get('text', '')+ if control.method == 'prop':+ prop = control.args[0].bl_rna.properties.get(control.args[1])+ if prop:+ text += ' ' + prop.name + ' ' + prop.description + ' ' + control.args[1]+ elif control.method == 'operator':+ rna = model.operator(control.args[0]).get_rna_type()+ text += ' ' + rna.name + ' ' + rna.description+ if query not in text.casefold():+ continue+ found = True+ p.text(section.title, x, y, 10, 'muted')+ y = self.draw_control(p, item, x, y + 17, width, section.key, i) + 6+ if not found:+ p.text('No matching controls in this architecture or mode.', x, y, 11, 'muted', width)+ y += 30+ return y++ def draw_prompt_editor(self, p, x, y, width, bottom):+ if not self.prompt_editor:+ return y+ binding, label, previous = self.prompt_editor+ p.button('close-editor', (x, y, width, CONTROL_HEIGHT), 'Back to ' + dict(self.pages() + MORE).get(previous, 'settings'),+ lambda: self.navigate(previous), icon='arrow', active=True)+ y += 34+ return y + self.draw_binding(p, binding, label, x, y, width, multiline=True,+ height=max(100, bottom - y - 60))++ def draw(self):+ global _font_id+ if _font_id is None:+ _font_id = blf.load(_font_path) if _font_path else 0+ if _font_id < 0:+ _font_id = 0+ self.scale = max(.8, bpy.context.preferences.system.ui_scale)+ p = Painter(self.region, self.scale, _font_id)+ p.hover_key = self.hover_key+ try:+ self.text_fields = {}+ self.card_bounds = {}+ p.panel()+ x, width = 12, p.width - 24+ top = self.draw_header(p, x, width)+ bottom = self.draw_footer(p, x, width)+ clip = (1, top + 1, p.width - 2, max(0, bottom - top - 2))+ p.clip(clip)+ offset = self.scroll.get(self.page, 0)+ y = top + 12 - offset+ for node in self.document.notices:+ y = self.draw_node(p, node, x, y, width, 'notices')+ if self.page == 'GENERATE':+ y = self.draw_generate(p, x, y, width)+ elif self.page == 'CAMERAS':+ y = self.draw_cameras(p, x, y, width)+ elif self.page == 'TOOLS':+ y = self.draw_tools(p, x, y, width)+ elif self.page == 'DEBUG':+ y = self.draw_diagnostics(p, x, y, width)+ elif self.page == 'MESH' and bpy.context.scene.architecture_mode == 'trellis2':+ y = self.draw_mesh(p, x, y, width)+ elif self.page == 'SEARCH':+ y = self.draw_search(p, x, y, width)+ elif self.page == 'EDITOR':+ y = self.draw_prompt_editor(p, x, y, width, bottom)+ else:+ sections = [section for section in self.document.sections if self.section_page(section) == self.page]+ for section in sections:+ y = self.draw_section(p, section, x, y, width)+ if self.page == 'MESH':+ y = self.draw_actions(p, 'Mesh & rig utilities', [+ ('object.stablegen_make_solid', 'Make solid', 'material'),+ ('object.stablegen_autorig_selected_mesh', 'Auto-rig selected character', 'rig')], x, y, width)+ self.max_scroll = max(0, y + offset + 20 - bottom)+ if offset > self.max_scroll:+ self.scroll[self.page] = self.max_scroll+ self.area.tag_redraw()+ if self.max_scroll:+ available = bottom - top+ thumb = max(24, available * available / (available + self.max_scroll))+ p.rect(p.width - 5, top + offset / self.max_scroll * max(0, available - thumb), 2, thumb, 'muted', 1)+ p.clip(None)+ if self.menu:+ self.draw_menu(p)+ # Layout changes can put a different control under a stationary mouse.+ self.update_hover(p.targets, cursor=False)+ self.tooltip_key, self.tooltip_rect = '', None+ if self.notice and time.monotonic() < self.notice_until:+ lines = wrap(self.notice, width - 24, lambda s: p.measure(s, 11))[:4]+ h = len(lines) * 18 + 18+ p.outline(x, bottom - h - 8, width, h, 'raised', 'line', 5)+ for i, (_, _, line) in enumerate(lines):+ p.text(line, x + 12, bottom - h + i * 18, 11, 'warning')+ else:+ target = self.tooltip_target(p.targets)+ if target:+ tw = min(width, max(180, min(420, p.measure(target.hint, 11) + 24)))+ lines = wrap(target.hint, tw - 24, lambda s: p.measure(s, 11))+ maximum = max(1, int((p.height - 46) / 18))+ if len(lines) > maximum:+ lines = lines[:maximum]+ start, end, text = lines[-1]+ lines[-1] = (start, end, p.fit(text, tw - 38, 11) + '…')+ h = len(lines) * 18 + 18+ ax, ay, aw, ah = target.rect+ if target.clip:+ ay, ah = max(ay, target.clip[1]), min(ay + ah, target.clip[1] + target.clip[3]) - max(ay, target.clip[1])+ if self.menu:+ ax, ay, aw, ah = self.menu['rect']+ tx = max(14, min(ax, p.width - tw - 12))+ ty = ay + ah + 8+ if ty + h > p.height - 10:+ ty = max(10, ay - h - 8)+ p.rect(tx - 1, ty + 2, tw + 2, h + 2, 'panel_shadow', 5)+ p.outline(tx, ty, tw, h, 'tooltip', 'tooltip_line', 4)+ for i, (_, _, line) in enumerate(lines):+ p.text(line, tx + 12, ty + 8 + i * 18, 11, 'tooltip_text')+ self.tooltip_key, self.tooltip_rect = target.key, (tx, ty, tw, h)+ self.targets = p.targets+ finally:+ p.finish()+++class SG_OT_StudioSession(bpy.types.Operator):+ bl_idname = 'stablegen.studio_session'+ bl_label = 'StableGen Studio Input'+ bl_options = {'INTERNAL'}++ def invoke(self, context, event):+ if context.area is None or context.area.type != 'VIEW_3D' or context.region.type != 'UI':+ return {'CANCELLED'}+ key = (context.window.as_pointer(), context.area.as_pointer())+ if key in _sessions and _sessions[key].alive:+ return {'CANCELLED'}+ self.session = StudioSession(context)+ _sessions[key] = self.session+ try:+ self.session.refresh()+ except Exception as exc:+ _sessions.pop(key, None)+ self.report({'ERROR'}, 'Could not open Studio: ' + str(exc))+ _log.exception('Studio startup error')+ return {'CANCELLED'}+ context.window_manager.modal_handler_add(self)+ if not bpy.app.timers.is_registered(_tick):+ bpy.app.timers.register(_tick, first_interval=.05, persistent=True)+ return {'RUNNING_MODAL'}++ def modal(self, context, event):+ session = self.session+ if not _registered or not session.valid():+ session.clear_hover(leave=True)+ if _sessions.get(session.key) is session:+ del _sessions[session.key]+ return {'FINISHED'}+ try:+ return session.event(event)+ except (ReferenceError, RuntimeError, ValueError, TypeError) as exc:+ session.edit = session.drag = session.menu = None+ session.clear_hover(leave=True)+ session.tell(str(exc).split('\n')[0])+ _log.exception('Studio input error')+ return {'PASS_THROUGH'}++ def cancel(self, context):+ if hasattr(self, 'session'):+ self.session.alive = False+ self.session.clear_hover(leave=True)+++class SG_OT_StudioNative(bpy.types.Operator):+ """Retain Blender's native controls for specialized editors and lists."""+ bl_idname = 'stablegen.studio_native'+ bl_label = 'StableGen Settings'+ bl_options = {'INTERNAL'}+ section: bpy.props.StringProperty()+ binding: bpy.props.StringProperty()+ control_index: bpy.props.IntProperty(default=-1)++ def invoke(self, context, event):+ self.session_key = (context.window.as_pointer(), context.area.as_pointer())+ session = _sessions.get(self.session_key)+ if session:+ session.clear_hover(leave=True)+ session.popup = True+ return context.window_manager.invoke_props_dialog(self, width=max(380, min(620, context.region.width)))++ def draw(self, context):+ layout = self.layout+ layout.use_property_decorate = False+ if self.binding:+ binding = model.Binding(**json.loads(self.binding))+ data = binding.data(context)+ layout.prop(data, binding.property)+ return+ document = model.document(context)+ section = next((s for s in document.sections if s.key == self.section), None)+ if section:+ layout.label(text=section.title)+ if self.control_index >= 0:+ items = list(section.content.controls())+ if self.control_index < len(items):+ items[self.control_index].render(layout)+ else:+ section.content.render(layout, contents=True, narrow=context.region.width < 420)++ def finish(self):+ session = _sessions.get(getattr(self, 'session_key', None))+ if session:+ session.popup = False+ session.refresh()++ def execute(self, context):+ self.finish()+ return {'FINISHED'}++ def cancel(self, context):+ self.finish()+++class SG_OT_StudioSelectCamera(bpy.types.Operator):+ bl_idname = 'stablegen.studio_select_camera'+ bl_label = 'Select Camera'+ bl_description = 'Select this view; Ctrl click adds or removes it from the selection'+ bl_options = {'UNDO', 'INTERNAL'}+ camera_name: bpy.props.StringProperty()+ extend: bpy.props.BoolProperty(default=False)++ @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' or camera.name not in context.view_layer.objects:+ return {'CANCELLED'}+ if not self.extend:+ for obj in context.selected_objects:+ if obj.type == 'CAMERA':+ obj.select_set(False)+ camera.select_set(not camera.select_get() if self.extend else True)+ if camera.select_get():+ context.view_layer.objects.active = camera+ return {'FINISHED'}+++class SG_OT_StudioPreferences(bpy.types.Operator):+ bl_idname = 'stablegen.studio_preferences'+ bl_label = 'StableGen Preferences'+ bl_options = {'INTERNAL'}++ def execute(self, context):+ bpy.ops.preferences.addon_show('INVOKE_DEFAULT', module=ADDON_PKG)+ return {'FINISHED'}+++def _ensure_session(context):+ if bpy.app.background or not _registered:+ return+ window, area = context.window, context.area+ key = (window.as_pointer(), area.as_pointer())+ if key in _sessions or key in _pending:+ return+ _pending.add(key)++ def start():+ _pending.discard(key)+ if not _registered:+ return None+ try:+ if window not in bpy.context.window_manager.windows[:] or area not in window.screen.areas[:]:+ return None+ region = next((r for r in area.regions if r.type == 'UI'), None)+ if region and region.active_panel_category == TAB:+ with bpy.context.temp_override(window=window, area=area, region=region):+ bpy.ops.stablegen.studio_session('INVOKE_DEFAULT')+ except ReferenceError:+ pass+ return None+ bpy.app.timers.register(start, first_interval=.05)+++class SG_PT_StudioCanvas(bpy.types.Panel):+ bl_idname = 'SG_PT_StudioCanvas'+ bl_label = 'StableGen Studio UI'+ bl_space_type = 'VIEW_3D'+ bl_region_type = 'UI'+ bl_category = TAB+ bl_options = {'HIDE_HEADER'}++ @classmethod+ def poll(cls, context):+ return context.mode in {'OBJECT', 'PAINT_TEXTURE'}++ def draw(self, context):+ _ensure_session(context)+ # Provide a native entry point even if custom drawing failed to start.+ self.layout.operator('stablegen.studio_session', text='Open StableGen Studio', icon='WORKSPACE')+ # Native sidebar resize zones follow the panel's layout footprint.+ # Reserve the canvas height so its lower border remains draggable too.+ spacer = self.layout.row()+ spacer.scale_y = max(1, (context.region.height / context.preferences.system.ui_scale - 80) / 20)+ spacer.label(text='')+++def _draw():+ context = bpy.context+ if context.area is None or context.region.type != 'UI' or context.region.active_panel_category != TAB:+ return+ session = _sessions.get((context.window.as_pointer(), context.area.as_pointer()))+ if session and session.active() and session.document:+ try:+ session.draw()+ session.error = ''+ except Exception as exc:+ if str(exc) != session.error:+ _log.exception('Studio drawing error')+ session.error = str(exc)+++def _tick():+ if not _registered:+ return None+ for key, session in list(_sessions.items()):+ if not session.valid():+ session.clear_hover(leave=True)+ session.alive = False+ _sessions.pop(key, None)+ else:+ try:+ session.tick(time.monotonic())+ except (ReferenceError, RuntimeError):+ _log.debug('Studio refresh temporarily unavailable', exc_info=True)+ return .05+++@persistent+def _load_pre(_):+ for session in _sessions.values():+ session.clear_hover(leave=True)+ session.alive = False+ _sessions.clear()+ _window_mouse.clear()+ _pending.clear()+++STUDIO_UI_CLASSES = diagnostics.CLASSES + [SG_OT_StudioSession, SG_OT_StudioNative, SG_OT_StudioSelectCamera,+ SG_OT_StudioPreferences, SG_PT_StudioCanvas]+++def register_studio_ui():+ global _registered, _handler, _font_id, _font_path+ _registered = True+ diagnostics.register()+ _font_id = None+ if not bpy.app.background:+ # Load after Blender initializes its UI fonts, at the first actual draw.+ fonts = bpy.utils.system_resource('DATAFILES', path='fonts')+ for path in (Path(fonts) / 'Inter.woff2' if fonts else Path('__missing_font__'),+ Path('C:/Windows/Fonts/segoeui.ttf'),+ Path('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'),+ Path('/System/Library/Fonts/Supplemental/Arial.ttf')):+ if path.is_file():+ _font_path = str(path)+ break+ _handler = bpy.types.SpaceView3D.draw_handler_add(_draw, (), 'UI', 'POST_PIXEL')+ bpy.app.timers.register(_tick, first_interval=.05, persistent=True)+ if _load_pre not in bpy.app.handlers.load_pre:+ bpy.app.handlers.load_pre.append(_load_pre)+++def unregister_studio_ui():+ global _registered, _handler+ _registered = False+ diagnostics.unregister()+ _load_pre(None)+ if _handler:+ bpy.types.SpaceView3D.draw_handler_remove(_handler, 'UI')+ _handler = None+ if bpy.app.timers.is_registered(_tick):+ bpy.app.timers.unregister(_tick)+ if _load_pre in bpy.app.handlers.load_pre:+ bpy.app.handlers.load_pre.remove(_load_pre)diff --git a/stablegen/ui/studio_cards.py b/stablegen/ui/studio_cards.pynew file mode 100644index 0000000..34ed217--- /dev/null+++ b/stablegen/ui/studio_cards.py@@ -0,0 +1,568 @@+"""Card presentation for Studio, using the captured native controls.++The native panel decides which controls exist and whether they are enabled.+This module partitions that capture without replacing RNA bindings, command+arguments or native-editor indices. Unclassified controls get a fallback card,+so adding a setting to the source panel cannot silently hide it in Studio.+"""+from dataclasses import dataclass++import bpy++from . import studio_model as model, studio_hierarchy as hierarchy+from .presentation import Control, Layout, STRUCTURAL_PROPERTIES+from .studio_text import wrap+from .studio_widgets import FONT_SIZE, CONTROL_HEIGHT, CONTROL_GAP++GAP = 8+PAD = 12+RESOLUTION_KEYS = {'auto_rescale', 'auto_rescale_target_mp', 'qwen_rescale_alignment'}+++@dataclass(frozen=True)+class Spec:+ key: str+ title: str+ icon: str = 'settings'+ keys: tuple = ()+ feature: str = ''+ rows: tuple = ()+ description: str = ''+ beside: str = ''+ dividers: tuple = ()+ parent: str = ''+++def feature(key, title, icon, **kwargs):+ """A feature owns the controls that are already conditional in the capture."""+ return Spec(key, title, icon, (key,), feature=key, **kwargs)+++SCHEMAS = {+ 'show_core_settings': (+ Spec('sampling', 'Sampling', 'curve', ('steps', 'cfg', 'sampler', 'scheduler',+ 'comfyui_negative_prompt', 'clip_skip'), rows=(('steps', 'cfg'), ('sampler', 'scheduler'))),+ Spec('seed', 'Seed & repeatability', 'reset', ('seed', 'control_after_generate')),+ feature('qwen_image_21_native_rgba', 'Native RGBA output', 'layers',+ description='Preserve transparency in generated images.'),+ ),+ 'resolution': (feature('auto_rescale', 'Auto rescale', 'expand'),),+ 'show_scene_understanding_settings': (+ Spec('angle', 'Angle rejection', 'shield', ('discard_factor', 'discard_factor_generation_only'), beside='angle'),+ Spec('exponent', 'View preference', 'curve', ('weight_exponent', 'weight_exponent_generation_only'), beside='angle'),+ feature('early_priority', 'Prioritize initial views', 'arrow'),+ Spec('visibility', 'Visibility & source quality', 'eye', ('sg_allow_backface_projection',+ 'sg_rework_acquisition_quality', 'bake_visibility_weights', 'sg_texturing_frame'),+ rows=(('sg_allow_backface_projection',), ('sg_rework_acquisition_quality',),+ ('bake_visibility_weights',), ('sg_texturing_frame',))),+ feature('sg_rework_projection_guard', 'Depth / part projection guard', 'shield',+ rows=(('sg_silhouette_margin',), ('sg_guard_directional',),+ ('sg_silhouette_depth', 'sg_guard_coverage_rescue'),+ ('sg_silhouette_feather',), ('sg_projection_guard_scale',), ('sg_guard_feather_method',)),+ dividers=(('sg_silhouette_feather', 'Boundary transition'),)),+ ),+ 'show_image_guidance_settings': (+ Spec('structure', 'Structure & reference colors', 'layers', ('qwen_guidance_map_type',+ 'qwen_timestep_zero_ref', 'qwen_refine_use_prev_ref', 'qwen_refine_use_depth')),+ Spec('style', 'Style reference', 'eye', ('qwen_use_external_style_image',+ 'qwen_use_trellis2_style', 'sequential_ipadapter')),+ Spec('context', 'Sequential context', 'shield', ('qwen_context_render_mode', 'qwen_voronoi_mode')),+ Spec('wording', 'Guidance wording', 'labels', ('qwen_prompt_template', 'qwen_use_custom_prompts',+ 'op:stablegen.reset_qwen_prompt')),+ feature('use_ipadapter', 'External image reference', 'eye'),+ feature('use_flux_lora', 'FLUX depth LoRA', 'layers'),+ ),+ 'show_mode_specific_settings': (+ Spec('edit', 'Edit strength', 'curve', ('denoise',)),+ Spec('visibility', 'Visibility map', 'eye', ('sequential_smooth', 'weight_exponent_mask'),+ rows=(('sequential_factor_smooth', 'sequential_factor_smooth_2'),)),+ feature('sequential_ipadapter', 'Previous view reference', 'eye'),+ feature('refine_angle_ramp_active', 'Angle-based blending', 'curve'),+ feature('visibility_vignette', 'Vignette blending', 'layers'),+ feature('refine_edge_feather_projection', 'Projection edge feather', 'curve'),+ feature('view_blend_use_color_match', 'Match viewport colors', 'material'),+ feature('refine_images', 'Refine generated views', 'curve'),+ Spec('uv', 'UV inpainting', 'layers', ('allow_modify_existing_textures', 'ask_object_prompts')),+ ),+ 'show_masking_inpainting_settings': (+ feature('differential_diffusion', 'Differential diffusion', 'curve'),+ Spec('mask', 'Mask preparation', 'shield', ('mask_blocky', 'blur_mask', 'grow_mask_by')),+ ),+ 'show_output_material_settings': (+ # PBR map ownership is explicit: material assignment stays editable even+ # when the albedo map is off, as it does in the native panel.+ Spec('pbr', 'PBR decomposition', 'material', ('pbr_decomposition', 'op:stablegen.check_server_status'), feature='pbr_decomposition',+ description='Extract material maps from generated views.'),+ Spec('albedo', 'Albedo', 'material', ('pbr_map_albedo', 'pbr_albedo_source', 'pbr_delight_strength',+ 'pbr_albedo_auto_saturation', 'pbr_albedo_saturation_mode', 'pbr_replace_color_with_albedo'),+ feature='pbr_map_albedo', description='Base color', parent='pbr',+ rows=(('pbr_albedo_source',), ('pbr_albedo_auto_saturation',), ('pbr_replace_color_with_albedo',))),+ Spec('roughness', 'Roughness', 'curve', ('pbr_map_roughness',), feature='pbr_map_roughness',+ description='Reflection softness', beside='material', parent='pbr'),+ Spec('metallic', 'Metallic', 'material', ('pbr_map_metallic',), feature='pbr_map_metallic',+ description='Metal or dielectric', beside='material', parent='pbr'),+ Spec('normal', 'Normal', 'layers', ('pbr_map_normal', 'pbr_normal_strength'), feature='pbr_map_normal',+ description='Surface detail', beside='detail', parent='pbr'),+ Spec('height', 'Height', 'modifier', ('pbr_map_height', 'pbr_height_scale'), feature='pbr_map_height',+ description='Displacement', beside='detail', parent='pbr'),+ Spec('ao', 'Ambient occlusion', 'eye', ('pbr_map_ao', 'pbr_ao_samples', 'pbr_ao_distance'),+ feature='pbr_map_ao', description='Baked from mesh geometry in Blender.', parent='pbr',+ rows=(('pbr_ao_samples', 'pbr_ao_distance'),)),+ Spec('emission', 'Emission', 'light', ('pbr_map_emission', 'pbr_emission_method',+ 'pbr_emission_threshold', 'pbr_emission_strength', 'pbr_emission_saturation_min',+ 'pbr_emission_value_min', 'pbr_emission_bloom'), feature='pbr_map_emission',+ description='Self-illumination', parent='pbr',+ rows=(('pbr_emission_saturation_min', 'pbr_emission_value_min'),)),+ Spec('processing', 'Shared processing', 'settings', ('pbr_use_native_resolution',+ 'pbr_processing_resolution', 'pbr_tiling', 'pbr_tile_grid', 'pbr_tile_superres',+ 'pbr_tile_albedo', 'pbr_tile_material', 'pbr_tile_normal', 'pbr_tile_height',+ 'pbr_tile_emission', 'pbr_denoise_steps', 'pbr_ensemble_size'), parent='pbr',+ rows=(('pbr_use_native_resolution',), ('pbr_tiling',), ('pbr_denoise_steps', 'pbr_ensemble_size'))),+ Spec('material', 'Material & lighting', 'material', ('fallback_color', 'overwrite_material', 'pbr_auto_lighting')),+ ),+ 'show_trellis2_mesh_settings': (+ Spec('mesh_seed', 'Mesh repeatability', 'reset', ('trellis2_seed',)),+ Spec('shape', 'Shape generation', 'layers', ('trellis2_ss_guidance', 'trellis2_ss_steps',+ 'trellis2_shape_guidance', 'trellis2_shape_steps', 'trellis2_max_tokens')),+ feature('trellis2_post_processing_enabled', 'Mesh post-processing', 'modifier'),+ Spec('model', 'Mesh model', 'settings', ('trellis2_resolution', 'trellis2_precision', 'trellis2_attn_backend')),+ Spec('conditioning', 'Image conditioning', 'eye', ('trellis2_background_color', 'trellis2_bg_removal', 'trellis2_shade_mode')),+ ),+ 'show_trellis2_autorig_settings': (+ Spec('autorig', 'Auto-rig', 'rig', ('trellis2_autorig_enabled', 'trellis2_autorig_use_transfer',+ 'trellis2_autorig_use_postprocess', 'trellis2_autorig_use_skeleton',+ 'trellis2_autorig_cleanup_cross_limb_weights', 'trellis2_autorig_garment_mode',+ 'op:stablegen.check_server_status'), feature='trellis2_autorig_enabled'),+ Spec('mapping', 'Rig mapping & display', 'rig', ('trellis2_autorig_bone_heuristic',+ 'trellis2_autorig_bone_display_type', 'op:stablegen.characterize_rig',+ 'op:stablegen.edit_rig_mapping', 'op:stablegen.toggle_rig_mapping_overlay',+ 'op:stablegen.toggle_collision_proxy_overlay', 'op:stablegen.apply_autorig_bone_display')),+ Spec('pose', 'Reference poses & animation', 'play', ('op:stablegen.apply_rig_pose_preset',+ 'op:stablegen.match_source_reference_pose', 'op:stablegen.set_retarget_reference_pose',+ 'op:stablegen.apply_animation_to_rig', 'op:stablegen.toggle_retarget_source_preview')),+ Spec('decode', 'Rig sampling', 'curve', ('trellis2_autorig_top_k', 'trellis2_autorig_top_p',+ 'trellis2_autorig_temperature', 'trellis2_autorig_repetition_penalty', 'trellis2_autorig_num_beams')),+ Spec('checkpoint', 'Rig model', 'settings', ('trellis2_autorig_model_ckpt', 'trellis2_autorig_hf_path')),+ ),+ 'show_trellis2_texture_settings': (+ Spec('texture', 'Native texture generation', 'layers', ('trellis2_tex_guidance',+ 'trellis2_tex_steps', 'trellis2_texture_size', 'trellis2_auto_lighting')),+ ),+ 'show_trellis2_camera_settings': (+ Spec('placement', 'View placement', 'camera', ('trellis2_import_scale', 'trellis2_placement_mode',+ 'trellis2_camera_count', 'trellis2_coverage_target', 'trellis2_max_auto_cameras', 'trellis2_fan_angle')),+ Spec('coverage', 'Coverage & framing', 'eye', ('trellis2_auto_aspect', 'trellis2_occlusion_mode',+ 'trellis2_exclude_bottom', 'trellis2_clamp_elevation')),+ Spec('behavior', 'Camera lifecycle', 'camera', ('trellis2_auto_prompts',+ 'trellis2_consider_existing', 'trellis2_delete_cameras')),+ ),+ 'show_camera_options': (+ Spec('order', 'Generation order', 'camera', ('sg_use_custom_camera_order',+ 'op:stablegen.apply_camera_order_preset', 'op:stablegen.sync_camera_order',+ 'op:stablegen.move_camera_order', 'native:template_list')),+ ),+ 'show_texturing_experiments': (+ Spec('resolution', 'Resolution & display', 'expand', ('sg_rework_aligned_resolution',+ 'sg_rework_full_resolution_scale', 'sg_rework_final_display')),+ feature('sg_auto_view_sequence', 'Automatic view sequence', 'camera'),+ Spec('context', 'Experimental Qwen context', 'shield', ('qwen_global_style_vlm_only',+ 'qwen_context_vlm_only', 'qwen_latent_locked_context', 'qwen_regularize_context_mask',+ 'qwen_use_projection_write_masks', 'qwen_reject_residual_fallback')),+ ),+ 'queue': (+ Spec('scenes', 'Queued scenes', 'layers', ('op:stablegen.queue_move_up',+ 'op:stablegen.queue_move_down', 'op:stablegen.queue_remove', 'op:stablegen.queue_add',+ 'op:stablegen.queue_open_result', 'op:stablegen.queue_invalidate',+ 'op:stablegen.queue_clear', 'op:stablegen.queue_process', 'native:template_list')),+ feature('sg_queue_gif_export', 'Orbit export', 'camera'),+ ),+ 'print': (+ Spec('palette', 'Filament palette', 'material', ('stablegen_print_preset', 'name', 'color',+ 'op:wm.context_set_int', 'op:stablegen.add_palette_color', 'op:stablegen.remove_palette_color')),+ feature('stablegen_print_dithered', 'Full-spectrum dithering', 'grid'),+ Spec('cleanup', 'Color cleanup', 'curve', ('stablegen_print_smoothing', 'stablegen_print_chroma_threshold')),+ feature('stablegen_print_make_solid', 'Solid print preparation', 'modifier'),+ feature('stablegen_print_show_advanced', 'Advanced solver', 'settings'),+ Spec('export', 'Print preview & export', 'download', ('op:object.stablegen_preview_quantization',+ 'op:object.stablegen_preview_sliced', 'op:object.stablegen_clear_quantization_preview',+ 'op:object.export_stl', 'op:object.export_3mf', 'op:object.export_textured_print_obj')),+ ),+}++# Captions can be shortened in Studio without changing their tooltips or values.+LABELS = {+ 'cfg': 'Guidance · CFG', 'control_after_generate': 'After generation',+ 'qwen_guidance_map_type': 'Guidance image', 'qwen_timestep_zero_ref': 'Timestep-zero references',+ 'qwen_custom_prompt_initial': 'Initial view', 'qwen_custom_prompt_seq_none': 'Subsequent views',+ 'qwen_custom_prompt_seq_replace': 'Subsequent views', 'qwen_custom_prompt_seq_additional': 'Subsequent views',+ 'discard_factor_generation_only': 'Reset after generation',+ 'weight_exponent_generation_only': 'Reset after generation',+ 'weight_exponent_after_generation': 'Exponent after',+ 'auto_rescale_target_mp': 'Target megapixels', 'sg_texturing_frame': 'Texturing frame',+ 'bake_visibility_weights': 'Bake transform-stable visibility',+ 'sg_allow_backface_projection': 'Allow backface projection',+ 'sg_rework_acquisition_quality': 'Acquisition quality weighting',+ 'sg_guard_coverage_rescue': 'Coverage rescue', 'sg_guard_directional': 'Depth-aware margins',+ 'sg_silhouette_depth': 'Depth threshold', 'sg_projection_guard_scale': 'Guard resolution',+ 'sg_guard_feather_method': 'Feather method', 'sg_silhouette_feather': 'Silhouette feather (px)',+ 'discard_factor_after_generation': 'Angle after',+ 'trellis2_resolution': 'Resolution', 'trellis2_background_color': 'Background',+ 'trellis2_bg_removal': 'Background removal',+ 'pbr_albedo_source': 'Extraction model', 'pbr_delight_strength': 'Highlight removal',+ 'pbr_albedo_auto_saturation': 'Correct saturation', 'pbr_albedo_saturation_mode': 'Correction across views',+ 'pbr_replace_color_with_albedo': 'Use as material base color',+ 'pbr_use_native_resolution': 'Use source image resolution', 'pbr_tiling': 'Tiling',+ 'pbr_tile_superres': 'Keep upscaled maps', 'pbr_height_scale': 'Displacement scale',+ 'pbr_emission_method': 'Detection method', 'pbr_emission_threshold': 'Detection threshold',+ 'pbr_emission_saturation_min': 'Minimum saturation', 'pbr_emission_value_min': 'Minimum brightness',+ 'pbr_ao_samples': 'Bake samples', 'pbr_ao_distance': 'Ray distance',+ 'pbr_normal_strength': 'Normal strength', 'pbr_auto_lighting': 'Add studio lighting after projection',+}+DECORATIVE = {+ 'Maps to Extract:', 'PBR Decomposition', 'Post-Processing:', 'Shape Generation:',+ 'Model:', 'Conditioning:', 'Misc:', 'LoRA Units', 'ControlNet Units',+ 'Qwen Local Edit Parameters', 'Qwen Refine Parameters', 'Grid Mode Parameters',+ 'Separate Mode Parameters', 'Refine Mode Parameters', 'Local Edit Parameters',+ 'Sequential Mode Parameters', 'UV Inpainting Parameters', 'Masked Edit Parameters',+ 'Multi-Color 3D Print Palette',+}+++def property_name(control):+ return control.args[1] if control.method == 'prop' and len(control.args) > 1 else ''+++def token(control):+ if control.method in {'operator', 'operator_menu_enum'}:+ return 'op:' + control.args[0]+ return property_name(control) or 'native:' + control.method+++def family(keys):+ result = set(keys)+ pending = list(keys)+ while pending:+ for child in hierarchy.FAMILIES.get(pending.pop(), ()):+ if child not in result:+ result.add(child)+ pending.append(child)+ return result+++def select(node, ids):+ """Keep original controls and all inherited layout states, including alerts."""+ if isinstance(node, Control):+ return node if id(node) in ids else None+ result = Layout(node.method, node.args, dict(node.kwargs))+ result.attributes.update(node.attributes)+ result.children.extend(c for child in node.children if (c := select(child, ids)) is not None)+ return result if result.children else None+++@dataclass+class Card:+ spec: Spec+ content: Layout+++def partition(source, specs, omit=(), title='Additional settings', *, _tokens=None):+ """Assign each source control to exactly one card; never alter the capture."""+ controls = list(source.controls())+ excluded = {id(c) for c in controls if property_name(c) in omit or token(c) in omit+ or property_name(c) in STRUCTURAL_PROPERTIES}+ explicit = {key: spec.key for spec in specs for key in spec.keys}+ expanded = {key: spec.key for spec in reversed(specs) for key in family(spec.keys)}+ expanded.update(explicit)+ def key(c):+ override = (_tokens or {}).get(id(c))+ return override if override in expanded else token(c)+ assignments = {id(c): expanded[key(c)] for c in controls if key(c) in expanded and id(c) not in excluded}+ fallback = '__other__'++ def assign(node, inherited=None):+ groups = [{assignments[id(c)] for c in child.controls() if id(c) in assignments}+ if isinstance(child, Layout) else {assignments[id(child)]} if id(child) in assignments else set()+ for child in node.children]+ known = set.union(set(), *groups)+ owner = next(iter(known)) if len(known) == 1 else inherited+ for i, child in enumerate(node.children):+ if isinstance(child, Layout):+ assign(child, owner)+ continue+ if id(child) in assignments or id(child) in excluded:+ continue+ # Labels, refresh/reset commands and native editors accompany their+ # closest field. A heterogeneous row keeps its source annotations.+ nearby = next((g for g in groups[i + 1:] if g), None) if child.method in {'label', 'separator'} else None+ if not nearby:+ nearby = next((g for g in reversed(groups[:i]) if g), None)+ group = owner or (next(iter(nearby)) if nearby and len(nearby) == 1 else fallback)+ assignments[id(child)] = group++ assign(source)+ result = []+ for spec in (*specs, Spec(fallback, title)):+ ids = {id(c) for c in controls if assignments.get(id(c), fallback) == spec.key and id(c) not in excluded}+ node = select(source, ids)+ if node and any(c.method not in {'label', 'separator'} for c in node.controls()):+ result.append(Card(spec, node))+ elif node and any(c.method == 'label' and c.kwargs.get('icon') in {'ERROR', 'INFO', 'WARNING'} for c in node.controls()):+ result.append(Card(spec, node))+ return result+++def note(p, text, x, y, width, tint='secondary'):+ for _, _, line in wrap(text, width, lambda value: p.measure(value, 10)):+ p.text(line, x, y, 10, tint)+ y += 14+ return y + 4+++def heading(p, text, x, y, width, icon='settings'):+ p.icon(icon, x, y + 1, 12, 'secondary')+ p.text(text, x + 19, y, FONT_SIZE, 'text', width - 19)+ return y + 23+++def captions(source):+ """Keep native captions when rearranging their fields, without orphan labels."""+ labels, ids = {}, set()+ def visit(node):+ for child in node.children:+ if isinstance(child, Layout):+ visit(child)+ fields = [c for c in node.controls() if c.method == 'prop']+ texts = [c for c in node.children if isinstance(c, Control) and c.method == 'label'+ and c.kwargs.get('text') and not c.kwargs['text'].startswith('→')]+ if node.method in {'row', 'split'} and len(fields) == len(texts) == 1:+ labels.setdefault(id(fields[0]), texts[0].kwargs['text'].rstrip(':'))+ ids.add(id(texts[0]))+ for i, child in enumerate(node.children[:-1]):+ following = node.children[i + 1]+ if (isinstance(child, Control) and child.method == 'label' and isinstance(following, Layout)+ and child.kwargs.get('text', '').endswith(':')):+ fields = [c for c in following.controls() if c.method == 'prop']+ if len(fields) == 1:+ labels.setdefault(id(fields[0]), child.kwargs['text'].rstrip(':'))+ ids.add(id(child))+ visit(source)+ return labels, ids+++def group(p, title, x, y, width, draw, icon='settings'):+ start = y+ p.begin_group()+ y = heading(p, title, x + PAD, y + 11, width - PAD * 2, icon)+ p.rect(x + PAD, y - 3, width - PAD * 2, 1, 'divider')+ y = draw(x + PAD, y + 6, width - PAD * 2) + 8+ p.end_group((x, start, width, y - start), 'subbox', 'section_border', 3)+ return y + GAP+++def _body(s, p, node, tree, section, spec, x, y, width):+ """Reorder selected root rows; conditional descendants retain their rails."""+ used = set()+ root_controls = list(node.controls())+ for row in spec.rows:+ parts = []+ for name in row:+ # A descendant belongs to its existing owner, not to a second row.+ ids = {id(c) for c in root_controls if property_name(c) == name}+ if ids:+ part = select(node, ids)+ parts.append(part)+ used.update(ids)+ if not parts:+ continue+ if row[0] in dict(spec.dividers):+ p.rect(x, y + 2, width, 1, 'divider')+ p.text(dict(spec.dividers)[row[0]], x, y + 13, FONT_SIZE, 'secondary', width)+ y += 34+ columns = len(parts) if width >= 320 else 1+ cw = (width - 14 * (columns - 1)) / columns+ for first in range(0, len(parts), columns):+ y = max(s.draw_node(p, part, x + i * (cw + 14), y, cw, section,+ hierarchy=tree, card_body=True)+ for i, part in enumerate(parts[first:first + columns]))+ remaining = select(node, {id(c) for c in root_controls if id(c) not in used})+ if remaining:+ y = s.draw_node(p, remaining, x, y, width, section, hierarchy=tree, card_body=True)+ return y+++def content(s, p, card, section, x, y, width):+ spec = card.spec+ tree = hierarchy.build(card.content)+ tree.card_labels, caption_ids = captions(card.content)+ tree.redundant_labels.update(caption_ids)+ tree.redundant_labels.update(id(c) for c in card.content.controls()+ if c.method == 'label' and c.kwargs.get('text') in DECORATIVE)+ root = tree.root+ toggle = next((live for live in model.controls(root) if property_name(live.control) == spec.feature), None) if spec.feature else None+ cx, cw = x + PAD, width - PAD * 2+ if toggle:+ p.icon(spec.icon, cx, y + 13, 13, 'secondary')+ y = s.draw_plain_control(p, toggle, cx + 21, y + 8, cw - 21, section,+ s.control_index(section, toggle.control), spec.title)+ ids = {id(c) for c in root.controls() if c is not toggle.control}+ root = select(root, ids) or Layout()+ children = tree.children.get(id(toggle.control))+ if children:+ root.children.append(children)+ else:+ y = heading(p, spec.title, cx, y + 11, cw, spec.icon)+ if spec.description:+ y = note(p, spec.description, cx, y, cw)+ visible = [c for c in root.controls() if c.method not in {'label', 'separator'}]+ if visible or any(c.method == 'label' and c.kwargs.get('icon') in {'ERROR', 'INFO', 'WARNING'} for c in root.controls()):+ p.rect(cx, y - (3 if not toggle else 0), cw, 1, 'divider')+ y = _body(s, p, root, tree, section, spec, cx, y + 7, cw)+ return y + 8+++def draw_family(s, p, parent, children, section, x, y, width):+ """Keep the parent header and its child cards inside one measured boundary."""+ start = y+ p.begin_group()+ y = content(s, p, parent, section, x, y, width)+ s.card_bounds[section + ':' + parent.spec.key + ':header'] = (x, start, width, y - start)+ p.rect(x + PAD, y - 1, width - PAD * 2, 1, 'divider')+ y = draw(s, p, children, section, x + 10, y + 9, width - 20) + 4+ rect = (x, start, width, y - start)+ s.card_bounds[section + ':' + parent.spec.key] = rect+ p.end_group(rect, 'group_body', 'group_border', 3)+ return y + 14+++def draw(s, p, cards, section, x, y, width):+ # Relationships affect presentation only. Visibility, bindings and state+ # still come from the original native panel capture.+ keys = {card.spec.key for card in cards}+ children, roots = {}, []+ for card in cards:+ if card.spec.parent and card.spec.parent in keys:+ children.setdefault(card.spec.parent, []).append(card)+ else:+ roots.append(card)+ index = 0+ while index < len(roots):+ card = roots[index]+ if card.spec.key in children:+ y = draw_family(s, p, card, children[card.spec.key], section, x, y, width)+ index += 1+ continue+ row = [card]+ if (width >= 440 and card.spec.beside and index + 1 < len(roots)+ and roots[index + 1].spec.beside == card.spec.beside+ and roots[index + 1].spec.key not in children):+ row.append(roots[index + 1])+ cw = (width - GAP * (len(row) - 1)) / len(row)+ p.begin_group()+ end = max(content(s, p, c, section, x + i * (cw + GAP), y, cw) for i, c in enumerate(row))+ rects = [(x + i * (cw + GAP), y, cw, end - y) for i in range(len(row))]+ for c, rect in zip(row, rects):+ s.card_bounds[section + ':' + c.spec.key] = rect+ p.end_group_row(rects, 'subbox', 'section_border', 3)+ y = end + GAP+ index += len(row)+ return y+++def sections(s, p, section, x, y, width, omit=()):+ specs = SCHEMAS.get(section.key, ())+ # Collection cards follow the actual RNA items, including their selection+ # and removal operators. No cached pointer is held after undo or refresh.+ if section.key in {'show_lora_settings', 'show_image_guidance_settings'}:+ collection = 'lora_units' if section.key == 'show_lora_settings' else 'controlnet_units'+ prefix = 'LoRA' if collection == 'lora_units' else 'ControlNet'+ groups = []+ for i, unit in enumerate(getattr(bpy.context.scene, collection)):+ keys = tuple('data:' + str(unit.as_pointer()) + ':' + prop.identifier for prop in unit.bl_rna.properties)+ title = f'{prefix} {i + 1}'+ if collection == 'controlnet_units':+ title += ' · ' + unit.unit_type.replace('_', ' ').title()+ groups.append(Spec(f'unit:{i}', title, 'layers', keys))+ if groups:+ # Resolve names locally to avoid confusing multiple model_name RNA+ # fields with the scene's checkpoint.+ source = section.content+ explicit = {id(c): 'data:' + str(c.args[0].as_pointer()) + ':' + c.args[1]+ for c in source.controls() if c.method == 'prop'}+ specs = (*specs, *groups)+ cards = partition_data(source, specs, explicit, omit,+ 'Adapter management' if prefix == 'LoRA' else 'ControlNet management')+ else:+ cards = partition(section.content, specs, omit,+ 'Adapter management' if prefix == 'LoRA' else 'ControlNet management')+ else:+ cards = partition(section.content, specs, omit, section.title.replace(' Settings', ''))+ return draw(s, p, cards, section.key, x, y, width)+++def partition_data(source, specs, data_tokens, omit, title):+ """Use per-item tokens while keeping original Controls in the final cards."""+ # Token overrides are scoped to one partition operation, never stored on RNA+ # or on the source controls.+ return partition(source, specs, omit, title, _tokens=data_tokens)+++ACTION_DESCRIPTIONS = {+ 'object.switch_material': 'Change the material shown on the model.',+ 'object.stablegen_mirror_reproject': 'Mirror the last texture projection.',+ 'object.stablegen_local_postprocess': 'Adjust existing generated textures.',+ 'object.add_hdri': 'Add environment lighting to the scene.',+ 'object.apply_all_mesh_modifiers': 'Apply modifiers on the scene meshes.',+ 'object.curves_to_mesh': 'Convert curves into mesh geometry.',+ 'stablegen.import_dae': 'Load a single model.',+ 'stablegen.batch_import_dae': 'Import multiple DAE files.',+ 'stablegen.batch_texture_dae': 'Process a folder of DAE / GLB models.',+ 'stablegen.batch_texture_dae_cancel': 'Stop processing after the current model.',+ 'object.export_orbit_gif': 'Render an orbit as a GIF or video.',+ 'object.stablegen_make_solid': 'Prepare a closed, printable mesh.',+ 'object.stablegen_autorig_selected_mesh': 'Generate a rig for the selected character.',+ 'stablegen.debug_projection_line': 'Compare view contributions along a surface line.',+ 'stablegen.debug_open_projection_line': 'Open the latest diagnostic graphs.',+ 'stablegen.interactive_discard_check': 'Adjust a camera’s context with a live preview.',+ 'stablegen.texturing_regression': 'Run the existing workflow checks.',+ 'stablegen.stop_texturing_regression': 'Stop the running workflow check.',+ 'stablegen.export_retarget_debug_bundle': 'Save a reproducible rig diagnostic package.',+ 'stablegen.debug_skinning_weights': 'Inspect how bones influence the mesh.',+ 'stablegen.debug_clear_skinning_weights': 'Restore the original vertex colors.',+ 'stablegen.debug_convert_fortune_rig': 'Convert the selected rig to Fortune.',+ 'stablegen.debug_make_solid': 'Inspect solid-mesh preparation.',+ 'stablegen.debug_restore_material': 'Remove the selected meshes’ materials.',+ 'stablegen.debug_force_generation_idle': 'Clear a stalled generation state.',+}+++def actions(s, p, rows, x, y, width):+ columns = 2 if width >= 440 else 1+ cw = (width - GAP * (columns - 1)) / columns+ for first in range(0, len(rows), columns):+ p.begin_group()+ end = y+ rects = []+ for i, (name, label, icon, properties, enabled, hint) in enumerate(rows[first:first + columns]):+ cx = x + i * (cw + GAP)+ p.icon(icon, cx + 12, y + 13, 15, 'secondary' if enabled else 'disabled')+ lines = wrap(label, cw - 68, p.measure)+ cy = y + 12+ for _, _, line in lines:+ p.text(line, cx + 36, cy, FONT_SIZE, 'text' if enabled else 'disabled')+ cy += 15+ cy = note(p, ACTION_DESCRIPTIONS.get(name, hint), cx + 12, cy + 7, cw - 24)+ p.icon('right', cx + cw - 21, y + 16, 10, 'secondary' if enabled else 'disabled')+ end = max(end, cy + 8)+ rects.append((cx, y, cw, 0))+ rects = [(cx, y, cw, end - y) for cx, _, cw, _ in rects]+ for i, (name, _, _, properties, enabled, hint) in enumerate(rows[first:first + columns]):+ key = 'utility:' + name+ p.target(key, rects[i], ('operator', name, properties), enabled, hint)+ # A hovered card changes only its existing boundary and background.+ # Draw each measured backdrop behind its content in one deferred layer.+ styles = [('hover_soft', 'hover_border') if enabled and s.hovered('utility:' + name)+ else ('subbox', 'section_border')+ for name, _, _, _, enabled, _ in rows[first:first + columns]]+ p.end_group_row(rects, 'subbox', 'section_border', 3, styles=styles)+ y = end + GAP+ return y + 4diff --git a/stablegen/ui/studio_diagnostics.py b/stablegen/ui/studio_diagnostics.pynew file mode 100644index 0000000..1beb532--- /dev/null+++ b/stablegen/ui/studio_diagnostics.py@@ -0,0 +1,329 @@+"""Reversible diagnostic displays used by Studio, backed by saved Blender IDs.++Existing diagnostics may replace UVs, materials and render settings. Run them+on private mesh/material copies, retaining the originals across undo and saves.+"""+import json+import uuid++import bpy++from ..utils import sg_modal_active++MODES = [+ ('TEXTURES', 'Projected textures', 'Return to the original mesh and materials'),+ ('SOLID', 'View colors', 'One solid color per camera, through the real projection pipeline'),+ ('GRID', 'Projection grid', 'Check projected image alignment and distortion'),+ ('COVERAGE', 'Coverage', 'Inspect how well the cameras cover the surface'),+ ('VISIBILITY', 'Visibility', 'Inspect which surfaces the cameras can see'),+ ('WEIGHT', 'Camera weight', 'Inspect the selected camera’s contribution'),+ ('FEATHER', 'Camera feather', 'Inspect the selected camera’s image-edge fade'),+ ('CONFIDENCE', 'Confidence', 'Inspect the actual projection confidence graph'),+ ('SEAMS', 'UV seams', 'Inspect the mesh UV layout'),+ ('DPPG', 'DPPG masks', 'Inspect guard rejection and feathering in the actual projection graph'),+]+OPERATORS = {+ 'SOLID': 'debug_solid_colors', 'GRID': 'debug_grid_pattern',+ 'COVERAGE': 'debug_coverage_heatmap', 'VISIBILITY': 'debug_visibility_material',+ 'WEIGHT': 'debug_per_camera_weight', 'FEATHER': 'debug_feather_preview',+ 'CONFIDENCE': 'debug_confidence_diagnostic', 'SEAMS': 'debug_uv_seam_viz',+ 'DPPG': 'debug_dppg_material',+}+OPTIONS = {'mode', 'camera', 'grid_size', 'coverage', 'confidence', 'scope', 'stage'}+_OWNED = '_sg_studio_preview'+++class SGStudioPreviewSlot(bpy.types.PropertyGroup):+ material: bpy.props.PointerProperty(type=bpy.types.Material)+ object_material: bpy.props.PointerProperty(type=bpy.types.Material)+ link: bpy.props.StringProperty()+++class SGStudioPreviewMesh(bpy.types.PropertyGroup):+ object: bpy.props.PointerProperty(type=bpy.types.Object)+ mesh: bpy.props.PointerProperty(type=bpy.types.Mesh)+ slots: bpy.props.CollectionProperty(type=SGStudioPreviewSlot)+ active_index: bpy.props.IntProperty()+++class SGStudioPreviewCamera(bpy.types.PropertyGroup):+ object: bpy.props.PointerProperty(type=bpy.types.Object)+ had_color: bpy.props.BoolProperty()+ color: bpy.props.StringProperty()+++class SGStudioDiagnostics(bpy.types.PropertyGroup):+ mode: bpy.props.EnumProperty(name='Viewport display', items=MODES, default='TEXTURES')+ camera: bpy.props.PointerProperty(name='Camera', type=bpy.types.Object,+ poll=lambda _self, obj: obj.type == 'CAMERA')+ grid_size: bpy.props.IntProperty(name='Grid cell size', default=64, min=8, max=512,+ description='Checkerboard cell size in pixels')+ coverage: bpy.props.EnumProperty(name='Coverage measure', default='AVERAGE', items=[+ ('AVERAGE', 'Average', 'Mean coverage across all cameras'),+ ('MAX', 'Best camera', 'Strongest available camera weight')])+ confidence: bpy.props.EnumProperty(name='Confidence signal', default='QUALITY', items=[+ ('QUALITY', 'Best source quality', 'Quality of accepted sources'),+ ('ACQUISITION', 'Camera quality', 'Raw acquisition quality of the selected camera'),+ ('TRUSTED', 'Trusted context', 'Areas accepted as trustworthy context'),+ ('REPAIR', 'Repair mask', 'Areas which must be regenerated'),+ ('WRITE', 'Write mask', 'Generated-pixel write mask'),+ ('GUARD', 'Depth / part guard', 'Rear-surface rejection for the selected camera')])+ scope: bpy.props.EnumProperty(name='Cameras', default='ALL', items=[+ ('ALL', 'All cameras', 'Strongest effect from any valid camera'),+ ('ACTIVE', 'Selected camera', 'Inspect the camera chosen below')])+ stage: bpy.props.EnumProperty(name='Mask stage', default='CURRENT', items=[+ ('CURRENT', 'Effective masks', 'After coverage rescue and occlusion limits'),+ ('BEFORE_RESCUE', 'Before coverage rescue', 'Original guard and feather fields')])+ # Persistent RNA references keep the baseline alive, including after undo or+ # saving while a diagnostic display is active. No name-based restoration.+ meshes: bpy.props.CollectionProperty(type=SGStudioPreviewMesh)+ cameras: bpy.props.CollectionProperty(type=SGStudioPreviewCamera)+ token: bpy.props.StringProperty()+ render_state: bpy.props.StringProperty()+ original_camera: bpy.props.PointerProperty(type=bpy.types.Object)+++def active(scene):+ state = scene.sg_studio_diagnostics+ return bool(state.token and state.meshes)+++def _targets(context):+ from ..debug_tools import _get_target_meshes+ return [obj for obj in _get_target_meshes(context)+ if obj.library is None and obj.data.library is None]+++def _snapshot(context, state):+ targets = _targets(context)+ if not targets:+ raise ValueError('Select an editable mesh to inspect.')+ state.token = uuid.uuid4().hex+ for obj in targets:+ record = state.meshes.add()+ record.object, record.mesh = obj, obj.data+ record.active_index = obj.active_material_index+ for slot in obj.material_slots:+ item = record.slots.add()+ item.material, item.link = slot.material, slot.link+ # Blender retains an object override even while the slot uses DATA.+ # Preserve it too; otherwise a discarded preview can retain images+ # or silently become visible when the user changes the slot linkage.+ slot.link = 'OBJECT'+ item.object_material = slot.material+ slot.link = item.link+ for camera in context.scene.objects:+ if camera.type == 'CAMERA':+ record = state.cameras.add()+ record.object = camera+ record.had_color = '_sg_debug_projection_color' in camera+ if record.had_color:+ record.color = json.dumps(tuple(camera['_sg_debug_projection_color']))+ scene = context.scene+ state.original_camera = scene.camera+ values = {'engine': scene.render.engine}+ for key in ('device', 'shading_system', 'use_osl'):+ if hasattr(scene.cycles, key):+ values[key] = getattr(scene.cycles, key)+ state.render_state = json.dumps(values)+++def _cleanup():+ # Remove only data created by this preview and no longer in use. A user who+ # deliberately reuses a preview material elsewhere retains that material.+ for collection in (bpy.data.meshes, bpy.data.materials, bpy.data.images):+ for data in list(collection):+ if data.get(_OWNED) and data.users == 0:+ collection.remove(data)+ while True:+ unused = [group for group in bpy.data.node_groups if group.get(_OWNED) and group.users == 0]+ if not unused:+ break+ for group in unused:+ bpy.data.node_groups.remove(group)+++def restore(scene, *, finish=True):+ state = scene.sg_studio_diagnostics+ if not state.token:+ state.mode = 'TEXTURES'+ return+ for record in state.meshes:+ obj = record.object+ if obj is None or record.mesh is None or obj.type != 'MESH':+ continue+ obj.data = record.mesh+ for slot, saved in zip(obj.material_slots, record.slots):+ slot.link = 'OBJECT'+ slot.material = saved.object_material+ slot.link = saved.link+ obj.active_material_index = record.active_index+ for record in state.cameras:+ if record.object is not None:+ if record.had_color:+ record.object['_sg_debug_projection_color'] = tuple(json.loads(record.color))+ elif '_sg_debug_projection_color' in record.object:+ del record.object['_sg_debug_projection_color']+ values = json.loads(state.render_state or '{}')+ if 'engine' in values:+ scene.render.engine = values.pop('engine')+ for key, value in values.items():+ setattr(scene.cycles, key, value)+ scene.camera = state.original_camera+ if finish:+ state.meshes.clear()+ state.cameras.clear()+ state.token, state.render_state = '', ''+ state.original_camera = None+ state.mode = 'TEXTURES'+ _cleanup()+++def _private_meshes(state):+ materials, groups = {}, {}++ def private_group(source):+ if source not in groups:+ group = source.copy()+ group.use_fake_user = False+ groups[source] = group+ group[_OWNED] = state.token+ for node in group.nodes:+ if node.type == 'GROUP' and node.node_tree:+ node.node_tree = private_group(node.node_tree)+ return groups[source]++ def private_material(source):+ if source is None:+ return None+ if source not in materials:+ mat = source.copy()+ mat.use_fake_user = False+ materials[source] = mat+ mat[_OWNED] = state.token+ if mat.use_nodes:+ for node in mat.node_tree.nodes:+ if node.type == 'GROUP' and node.node_tree:+ node.node_tree = private_group(node.node_tree)+ return materials[source]++ targets = []+ for record in state.meshes:+ obj = record.object+ if obj is None or obj.type != 'MESH' or record.mesh is None:+ continue+ obj.data = record.mesh.copy()+ obj.data.use_fake_user = False+ obj.data[_OWNED] = state.token+ for index, source in enumerate(record.mesh.materials):+ obj.data.materials[index] = private_material(source)+ for slot, saved in zip(obj.material_slots, record.slots):+ slot.link = 'OBJECT'+ slot.material = private_material(saved.object_material)+ slot.link = saved.link+ targets.append(obj)+ if not targets:+ raise ValueError('The inspected meshes no longer exist.')+ return targets+++def apply(context):+ state, scene = context.scene.sg_studio_diagnostics, context.scene+ if state.mode == 'TEXTURES':+ restore(scene)+ return+ mode = state.mode+ if state.token:+ restore(scene, finish=False)+ else:+ _snapshot(context, state)+ collections = (bpy.data.meshes, bpy.data.materials, bpy.data.node_groups, bpy.data.images)+ before = [set(collection) for collection in collections]+ original_selection = set(context.selected_objects)+ original_active = context.view_layer.objects.active+ try:+ meshes = _private_meshes(state)+ camera = state.camera+ if camera is None or camera.name not in scene.objects:+ camera = next((obj for obj in context.selected_objects if obj.type == 'CAMERA'), scene.camera)+ if camera is None or camera.name not in scene.objects:+ camera = next((obj for obj in scene.objects if obj.type == 'CAMERA'), None)+ if camera is None:+ raise ValueError('Add cameras before inspecting projection.')+ state.camera = camera+ selected = meshes + [camera]+ kwargs = {'grid_size': state.grid_size} if mode == 'GRID' else (+ {'mode': state.coverage} if mode == 'COVERAGE' else+ {'mode': state.confidence} if mode == 'CONFIDENCE' else+ {'scope': state.scope, 'stage': state.stage} if mode == 'DPPG' else {})+ with context.temp_override(selected_objects=selected, selected_editable_objects=selected,+ active_object=camera, object=camera):+ op = getattr(bpy.ops.stablegen, OPERATORS[mode])+ if not op.poll():+ raise ValueError('This diagnostic requires meshes, cameras and Debug enabled in preferences.')+ result = op('EXEC_DEFAULT', **kwargs)+ if 'FINISHED' not in result:+ raise ValueError('This signal is unavailable. Reproject textures with the relevant feature enabled.')+ except Exception:+ # Include new IDs even when an existing diagnostic fails halfway through.+ for collection, previous in zip(collections, before):+ for data in set(collection) - previous:+ data[_OWNED] = state.token+ restore(scene)+ raise+ finally:+ for obj in context.view_layer.objects:+ obj.select_set(obj in original_selection)+ if original_active and original_active.name in context.view_layer.objects:+ context.view_layer.objects.active = original_active+ for collection, previous in zip(collections, before):+ for data in set(collection) - previous:+ data[_OWNED] = state.token+++class SG_OT_StudioDiagnostic(bpy.types.Operator):+ bl_idname = 'stablegen.studio_diagnostic'+ bl_label = 'Change Diagnostic Display'+ bl_description = 'Inspect projection using temporary data; restore the original textures at any time'+ bl_options = {'REGISTER', 'UNDO'}++ setting: bpy.props.StringProperty(default='mode', options={'HIDDEN'})+ value: bpy.props.StringProperty(default='"TEXTURES"', options={'HIDDEN'})++ @classmethod+ def poll(cls, context):+ return context.mode == 'OBJECT' and not sg_modal_active(context)++ def execute(self, context):+ if self.setting not in OPTIONS:+ return {'CANCELLED'}+ state = context.scene.sg_studio_diagnostics+ try:+ value = json.loads(self.value)+ if self.setting == 'camera':+ value = bpy.data.objects.get(value) if value else None+ setattr(state, self.setting, value)+ apply(context)+ except Exception as exc:+ restore(context.scene)+ self.report({'WARNING'}, str(exc).split('\n')[0])+ return {'FINISHED'} # rollback itself must be undoable+ for screen in bpy.data.screens:+ for area in screen.areas:+ if area.type == 'VIEW_3D':+ area.tag_redraw()+ return {'FINISHED'}+++CLASSES = [SGStudioPreviewSlot, SGStudioPreviewMesh, SGStudioPreviewCamera,+ SGStudioDiagnostics, SG_OT_StudioDiagnostic]+++def register():+ bpy.types.Scene.sg_studio_diagnostics = bpy.props.PointerProperty(type=SGStudioDiagnostics)+++def unregister():+ for scene in bpy.data.scenes:+ restore(scene)+ del bpy.types.Scene.sg_studio_diagnosticsdiff --git a/stablegen/ui/studio_hierarchy.py b/stablegen/ui/studio_hierarchy.pynew file mode 100644index 0000000..2c794fb--- /dev/null+++ b/stablegen/ui/studio_hierarchy.py@@ -0,0 +1,222 @@+"""Presentation ownership for conditional controls in the Studio sidebar.++The captured legacy layout remains intact for native popups and command indices.+This adapter moves only visible controls into their owner's presentation scope;+it retains every original Control and every inherited layout enable/alert state.+"""+from dataclasses import dataclass++from .presentation import Control, Layout+++# A child may have different owners in different workflows. The closest preceding+# owner on the same RNA data wins, so repeated style controls keep their own scope.+FAMILIES = {+ 'discard_factor_generation_only': ('discard_factor_after_generation',),+ 'weight_exponent_generation_only': ('weight_exponent_after_generation',),+ 'early_priority': ('early_priority_strength',),+ 'sg_rework_projection_guard': ('sg_guard_directional', 'sg_silhouette_margin',+ 'sg_silhouette_depth', 'sg_guard_coverage_rescue', 'sg_silhouette_feather',+ 'sg_projection_guard_scale', 'sg_guard_feather_method'),+ 'sg_guard_directional': ('sg_guard_foreground_margin',),+ 'sequential_smooth': ('sequential_factor', 'sequential_factor_smooth', 'sequential_factor_smooth_2'),+ 'sequential_ipadapter': ('sequential_ipadapter_mode', 'ipadapter_weight_type',+ 'ipadapter_strength', 'ipadapter_start', 'ipadapter_end', 'sequential_ipadapter_regenerate'),+ 'sequential_ipadapter_regenerate': ('sequential_ipadapter_regenerate_wo_controlnet',),+ 'use_ipadapter': ('ipadapter_image', 'ipadapter_strength', 'ipadapter_start',+ 'ipadapter_end', 'ipadapter_weight_type'),+ 'sequential_ipadapter_mode': ('sequential_desaturate_factor', 'sequential_contrast_factor'),+ 'qwen_use_external_style_image': ('qwen_external_style_image', 'qwen_external_style_initial_only'),+ 'qwen_external_style_initial_only': ('sequential_ipadapter_mode',),+ 'qwen_use_trellis2_style': ('qwen_trellis2_style_initial_only',),+ 'qwen_trellis2_style_initial_only': ('sequential_ipadapter_mode',),+ 'qwen_use_custom_prompts': ('qwen_custom_prompt_initial', 'qwen_custom_prompt_seq_none',+ 'qwen_custom_prompt_seq_replace', 'qwen_custom_prompt_seq_additional'),+ 'qwen_prompt_template': ('qwen_custom_prompt_initial', 'qwen_custom_prompt_seq_none',+ 'qwen_custom_prompt_seq_replace', 'qwen_custom_prompt_seq_additional'),+ 'qwen_context_render_mode': ('qwen_prompt_gray_background', 'qwen_guidance_background_color',+ 'qwen_guidance_fallback_color', 'qwen_use_confidence_context'),+ 'qwen_use_confidence_context': ('qwen_trust_threshold', 'qwen_context_fallback_dilation',+ 'qwen_context_cleanup'),+ 'qwen_context_cleanup': ('qwen_context_cleanup_hue_tolerance', 'qwen_context_cleanup_value_adjust'),+ 'qwen_regularize_context_mask': ('qwen_mask_min_island_area', 'qwen_mask_min_hole_area',+ 'qwen_mask_min_strip_width', 'qwen_mask_uncertainty_dilation', 'qwen_mask_keep_largest_components'),+ 'qwen_reject_residual_fallback': ('qwen_residual_fallback_tolerance',),+ 'qwen_latent_locked_context': ('qwen_latent_lock_neutral_fill',),+ 'sg_auto_view_sequence': ('sg_anchor_camera',),+ 'auto_rescale': ('auto_rescale_target_mp', 'qwen_rescale_alignment'),+ 'use_separate_texture_prompt': ('texture_prompt',),+ 'use_flux_lora': ('canny_threshold_low', 'canny_threshold_high'),+ 'differential_diffusion': ('differential_noise',),+ 'differential_noise': ('mask_blocky', 'blur_mask', 'grow_mask_by'),+ 'blur_mask': ('blur_mask_radius', 'blur_mask_sigma'),+ 'refine_angle_ramp_active': ('refine_angle_ramp_pos_0', 'refine_angle_ramp_pos_1'),+ 'visibility_vignette': ('refine_feather_ramp_pos_0', 'refine_feather_ramp_pos_1',+ 'visibility_vignette_width', 'visibility_vignette_softness', 'visibility_vignette_blur'),+ 'refine_edge_feather_projection': ('refine_edge_feather_width', 'refine_edge_feather_softness'),+ 'view_blend_use_color_match': ('view_blend_color_match_method', 'view_blend_color_match_strength'),+ 'refine_images': ('refine_sampler', 'refine_scheduler', 'denoise', 'refine_cfg',+ 'refine_steps', 'refine_prompt', 'refine_upscale_method'),+ 'pbr_decomposition': ('pbr_map_albedo', 'pbr_map_roughness', 'pbr_map_metallic',+ 'pbr_map_normal', 'pbr_map_height', 'pbr_map_ao', 'pbr_map_emission',+ 'pbr_use_native_resolution', 'pbr_tiling', 'pbr_denoise_steps',+ 'pbr_ensemble_size', 'pbr_replace_color_with_albedo', 'pbr_auto_lighting'),+ 'pbr_map_normal': ('pbr_normal_strength',),+ 'pbr_map_height': ('pbr_height_scale',),+ 'pbr_map_ao': ('pbr_ao_samples', 'pbr_ao_distance'),+ 'pbr_map_emission': ('pbr_emission_method', 'pbr_emission_threshold', 'pbr_emission_strength'),+ 'pbr_emission_method': ('pbr_emission_saturation_min', 'pbr_emission_value_min', 'pbr_emission_bloom'),+ 'pbr_map_albedo': ('pbr_albedo_source', 'pbr_albedo_auto_saturation'),+ 'pbr_albedo_source': ('pbr_delight_strength',),+ 'pbr_albedo_auto_saturation': ('pbr_albedo_saturation_mode',),+ 'pbr_tiling': ('pbr_tile_grid', 'pbr_tile_superres', 'pbr_tile_albedo',+ 'pbr_tile_material', 'pbr_tile_normal', 'pbr_tile_height', 'pbr_tile_emission'),+ 'pbr_use_native_resolution': ('pbr_processing_resolution',),+ 'trellis2_post_processing_enabled': ('trellis2_decimate_method', 'trellis2_decimation',+ 'trellis2_remesh_method', 'trellis2_solidify'),+ 'trellis2_exclude_bottom': ('trellis2_exclude_bottom_angle',),+ 'trellis2_clamp_elevation': ('trellis2_min_elevation', 'trellis2_max_elevation'),+ 'trellis2_preview_gallery_enabled': ('trellis2_preview_gallery_count',),+ 'sg_queue_gif_export': ('sg_queue_gif_duration', 'sg_queue_gif_fps',+ 'sg_queue_gif_resolution', 'sg_queue_gif_samples', 'sg_queue_gif_engine',+ 'sg_queue_gif_interpolation', 'sg_queue_gif_use_hdri', 'sg_queue_gif_denoiser',+ 'sg_queue_gif_use_gpu', 'sg_queue_gif_also_no_pbr'),+ 'sg_queue_gif_use_hdri': ('sg_queue_gif_hdri_path', 'sg_queue_gif_hdri_strength',+ 'sg_queue_gif_hdri_rotation', 'sg_queue_gif_env_mode'),+ 'stablegen_print_dithered': ('stablegen_print_dither_method', 'stablegen_print_model_height',+ 'stablegen_print_layer_height'),+ 'stablegen_print_make_solid': ('stablegen_print_raycast_count', 'stablegen_print_keep_largest_island',+ 'stablegen_print_single_filament_internal'),+ 'stablegen_print_single_filament_internal': ('stablegen_print_internal_visibility_threshold',),+ 'stablegen_print_show_advanced': ('stablegen_print_solver_formula', 'stablegen_print_solver_init',+ 'stablegen_print_solver_steps', 'stablegen_print_saturation_penalty'),+ 'stablegen_print_solver_formula': ('stablegen_print_scattering_weight',),+}+PARENTS = {}+for parent, children in FAMILIES.items():+ for child in children:+ PARENTS.setdefault(child, []).append(parent)++# Technical notes that are already available in the corresponding field tooltip.+TOOLTIP_LABELS = {'auto_rescale': {'Qwen 2.1 aligns to 32px'}}+++def _property(control):+ if control.method != 'prop' or len(control.args) < 2:+ return None+ data, name = control.args[:2]+ return data.as_pointer(), name+++@dataclass+class Hierarchy:+ source: Layout+ root: Layout+ children: dict+ redundant_labels: set+++def build(source, omit=()):+ """Extract owner scopes without changing the source layout or control order."""+ controls = list(source.controls())+ positions = {id(c): i for i, c in enumerate(controls)}+ properties, by_property = {}, {}+ for c in controls:+ key = _property(c)+ if key:+ properties[id(c)] = key+ if key[1] not in omit:+ by_property.setdefault(key, []).append(id(c))+ owners = {}+ for child, (data, name) in properties.items():+ candidates = [parent for parent_name in PARENTS.get(name, ())+ for parent in by_property.get((data, parent_name), ())+ if positions[parent] < positions[child]]+ if candidates:+ owners[child] = max(candidates, key=positions.get)++ def ancestors(cid):+ seen = set()+ while cid in owners:+ cid = owners[cid]+ if cid in seen:+ raise ValueError('Cyclic Studio control ownership')+ seen.add(cid)+ return seen++ boxes = {}+ def claim_boxes(node):+ for c in node.children:+ if isinstance(c, Layout):+ claim_boxes(c)+ if node is source or node.method != 'box':+ return+ members = {id(c) for c in node.controls()}+ chains = [ancestors(cid) - members for cid in members if cid in owners]+ if not chains:+ return+ common = set.intersection(*chains)+ if common:+ parent = max(common, key=lambda cid: len(ancestors(cid)))+ boxes[id(node)] = parent+ for cid in members:+ if cid not in owners:+ owners[cid] = parent+ claim_boxes(source)++ def title(text):+ words = text.casefold().rstrip(':').split()+ while words and words[-1] in {'options', 'settings', 'parameters'}:+ words.pop()+ return ' '.join(words)++ redundant_labels = set()+ by_id = {id(c): c for c in controls}+ for c in controls:+ parent = by_id.get(owners.get(id(c)))+ if c.method != 'label' or parent is None or parent.method != 'prop':+ continue+ data, name = parent.args[:2]+ caption = title(c.kwargs.get('text', ''))+ if (caption and caption in {title(parent.kwargs.get('text', '')),+ title(data.bl_rna.properties[name].name)} or+ c.kwargs.get('text') in TOOLTIP_LABELS.get(name, ())):+ # The controlling field and its rail already name this scope. Keep+ # the native label in the source for native popups and diagnostics.+ redundant_labels.add(id(c))++ def omitted(control):+ key = _property(control)+ return (key is not None and key[1] in omit or+ control.method == 'operator' and 'op:' + control.args[0] in omit)++ def extract(node, owner):+ if isinstance(node, Control):+ if omitted(node):+ return None+ return node if owners.get(id(node)) == owner else None+ if omit and node is not source:+ native_controls = list(node.controls())+ # Custom Studio controls replace some native labeled rows. Keep the+ # renderer's original omission rule before extracting their fields,+ # so their now-empty labels cannot leak back into the presentation.+ if (any(omitted(c) for c in native_controls) and+ all(omitted(c) or c.method in {'label', 'separator'} for c in native_controls)):+ return None+ result = Layout('column' if id(node) in boxes else node.method, node.args, dict(node.kwargs))+ result.attributes.update(node.attributes)+ result.children.extend(part for c in node.children if (part := extract(c, owner)) is not None)+ if not result.children:+ return None+ # Keep the background margin beside the outer guard, before the nested+ # depth-aware controls, rather than splitting the two margins apart.+ if owner is not None and properties.get(owner, (None, ''))[1] == 'sg_rework_projection_guard' and id(node) in boxes:+ result.children.sort(key=lambda part: 0 if (+ isinstance(part, Control) and properties.get(id(part), (None, ''))[1] == 'sg_silhouette_margin'+ or isinstance(part, Layout) and part.has_property('sg_silhouette_margin')) else 1)+ return result++ root = extract(source, None) or Layout()+ children = {owner: extract(source, owner) for owner in set(owners.values())}+ return Hierarchy(source, root, {key: value for key, value in children.items() if value is not None},+ redundant_labels)diff --git a/stablegen/ui/studio_model.py b/stablegen/ui/studio_model.pynew file mode 100644index 0000000..dd2b0af--- /dev/null+++ b/stablegen/ui/studio_model.py@@ -0,0 +1,182 @@+"""Live RNA bindings for the custom Studio sidebar; no generation logic."""+from dataclasses import dataclass+import json+from pathlib import Path++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,+ trellis_texture_items, trellis_initial_image_items)+++@dataclass+class LiveControl:+ control: Control+ enabled: bool = True+ alert: bool = False+++def controls(node, enabled=True, alert=False):+ """Keep inherited enable/alert states when moving native controls."""+ enabled = enabled and node.attributes.get('enabled', True) and node.attributes.get('active', True)+ alert = alert or node.attributes.get('alert', False)+ for child in node.children:+ if isinstance(child, Layout):+ yield from controls(child, enabled, alert)+ else:+ yield LiveControl(child, enabled, alert)+++def operator(name):+ namespace, identifier = name.split('.', 1)+ return getattr(getattr(bpy.ops, namespace), identifier)+++@dataclass(frozen=True)+class Binding:+ """Resolve RNA again after undo instead of holding invalid datablocks."""+ root: str+ name: str+ path: str+ property: str++ @classmethod+ def from_data(cls, data, property):+ owner = data.id_data+ if isinstance(owner, bpy.types.Scene):+ root, name = 'scene', owner.name+ elif isinstance(owner, bpy.types.WindowManager):+ root, name = 'wm', ''+ elif isinstance(owner, bpy.types.Object):+ root, name = 'object', owner.name+ elif isinstance(owner, bpy.types.Material):+ root, name = 'material', owner.name+ else:+ raise TypeError('This RNA control needs its native editor')+ path = '' if data.as_pointer() == owner.as_pointer() else data.path_from_id()+ return cls(root, name, path, property)++ def data(self, context):+ if self.root == 'scene':+ owner = context.scene if context.scene.name == self.name else bpy.data.scenes.get(self.name)+ elif self.root == 'wm':+ owner = context.window_manager+ elif self.root == 'object':+ owner = bpy.data.objects.get(self.name)+ else:+ owner = bpy.data.materials.get(self.name)+ if owner is None:+ raise ReferenceError('The edited datablock no longer exists')+ return owner.path_resolve(self.path) if self.path else owner++ def value(self, context):+ return getattr(self.data(context), self.property)++ def rna(self, context):+ return self.data(context).bl_rna.properties[self.property]++ def set(self, context, value):+ data = self.data(context)+ prop = data.bl_rna.properties[self.property]+ if prop.type in {'INT', 'FLOAT'} and not prop.is_array:+ value = max(prop.hard_min, min(prop.hard_max, value))+ value = int(round(value)) if prop.type == 'INT' else float(value)+ setattr(data, self.property, value)+++def enum_items(binding, context):+ data, key = binding.data(context), binding.property+ callbacks = {'architecture_mode': architecture_items,+ 'model_architecture': model_architecture_items,+ 'trellis2_texture_mode': trellis_texture_items,+ 'trellis2_initial_image_arch': trellis_initial_image_items,+ 'stablegen_preset': get_preset_items,+ 'sequential_ipadapter_mode': None}+ if key == 'sequential_ipadapter_mode':+ from ..core.properties import _get_ipadapter_mode_items+ return _get_ipadapter_mode_items(data, context)+ if key in callbacks:+ return callbacks[key](data, context)+ if key == 'model_name':+ if isinstance(data, bpy.types.Scene):+ return update_model_list(data, context)+ if data.bl_rna.identifier == 'LoRAUnit':+ return get_lora_models(data, context)+ if data.bl_rna.identifier == 'ControlNetUnit':+ return get_controlnet_models(context, data.unit_type)+ return [(item.identifier, item.name, item.description)+ for item in binding.rna(context).enum_items]+++def enum_label(binding, context):+ value = binding.value(context)+ return next((item[1] for item in enum_items(binding, context)+ if item and item[0] == value), str(value))+++def document(context):+ return capture_panel(context)+++def first_property(document, name):+ for section in document.sections:+ for item in controls(section.content):+ c = item.control+ if c.method == 'prop' and c.args[1] == name:+ return item+ return None+++def action(document, *names):+ for node in document.actions:+ for item in controls(node):+ if item.control.method == 'operator' and item.control.args[0] in names:+ return item+ return None+++def projected_images(context):+ """Read actual projection textures, honoring the saved view plan if present.++ No render, file recovery, image loading or material change is performed here.+ """+ from ..texturing.view_plan import generation_cameras, order_cameras, order_cameras_from_manifest+ scene = context.scene+ objects = context.selected_objects if scene.texture_objects == 'selected' else context.view_layer.objects+ textures = {}+ latest = -1+ for obj in objects:+ if obj.type != 'MESH' or obj.hide_get():+ continue+ for slot in obj.material_slots:+ if not slot.material or not slot.material.use_nodes:+ continue+ for node in slot.material.node_tree.nodes:+ if node.type != 'TEX_IMAGE' or node.image is None:+ continue+ parts = node.label.split('-')+ if len(parts) != 2 or not all(part.isdigit() for part in parts):+ continue+ index, material = map(int, parts)+ if material > latest:+ latest, textures = material, {}+ if material == latest:+ textures.setdefault(index, node.image)+ if not textures:+ return {}+ custom = [item.name for item in scene.sg_camera_order] if scene.sg_use_custom_camera_order else ()+ cameras = order_cameras(generation_cameras(scene), custom)+ for image in textures.values():+ folder = Path(bpy.path.abspath(image.filepath, library=image.library)).parent+ if folder.name.lower() != 'generated':+ continue+ try:+ manifest = json.loads((folder.parent / 'view_plan.json').read_text(encoding='utf8'))+ cameras = order_cameras_from_manifest(cameras, manifest)+ break+ except (OSError, ValueError, TypeError):+ continue+ return {camera.name: textures[i] for i, camera in enumerate(cameras) if i in textures}diff --git a/stablegen/ui/studio_text.py b/stablegen/ui/studio_text.pynew file mode 100644index 0000000..dc94fe2--- /dev/null+++ b/stablegen/ui/studio_text.py@@ -0,0 +1,88 @@+"""Small Unicode text buffer with selection and local undo for Studio fields.++Changes are committed to RNA on leaving a field. While typing, Ctrl-Z applies+only to this buffer and never undoes the scene beneath an active UI session.+"""+from dataclasses import dataclass, field+++@dataclass+class TextBuffer:+ text: str+ caret: int = 0+ anchor: int = 0+ history: list = field(default_factory=list)+ future: list = field(default_factory=list)++ def __post_init__(self):+ self.caret = self.anchor = len(self.text)++ @property+ def selection(self):+ return min(self.caret, self.anchor), max(self.caret, self.anchor)++ def snapshot(self):+ return self.text, self.caret, self.anchor++ def replace(self, value):+ self.history.append(self.snapshot())+ self.history = self.history[-150:]+ self.future.clear()+ start, end = self.selection+ self.text = self.text[:start] + value + self.text[end:]+ self.caret = self.anchor = start + len(value)++ def move(self, destination, select=False):+ self.caret = max(0, min(len(self.text), destination))+ if not select:+ self.anchor = self.caret++ def word(self, direction):+ index = self.caret+ if direction < 0:+ while index and self.text[index - 1].isspace():+ index -= 1+ while index and not self.text[index - 1].isspace():+ index -= 1+ else:+ while index < len(self.text) and not self.text[index].isspace():+ index += 1+ while index < len(self.text) and self.text[index].isspace():+ index += 1+ return index++ def delete(self, backward=False, word=False):+ if self.caret == self.anchor:+ self.anchor = self.word(-1 if backward else 1) if word else max(0, min(len(self.text), self.caret + (-1 if backward else 1)))+ if self.caret != self.anchor:+ self.replace('')++ def undo(self, redo=False):+ source, target = (self.future, self.history) if redo else (self.history, self.future)+ if source:+ target.append(self.snapshot())+ self.text, self.caret, self.anchor = source.pop()+++def wrap(text, width, measure):+ """Return (start, end, displayed text) without changing the source string."""+ result = []+ start = 0+ for paragraph in text.split('\n'):+ if not paragraph:+ result.append((start, start, ''))+ offset = 0+ while offset < len(paragraph):+ end, last_space = offset, None+ while end < len(paragraph):+ if measure(paragraph[offset:end + 1]) > width and end > offset:+ break+ if paragraph[end].isspace():+ last_space = end + 1+ end += 1+ if end < len(paragraph) and last_space is not None and last_space > offset:+ end = last_space+ result.append((start + offset, start + end, paragraph[offset:end]))+ offset = end+ start += len(paragraph) + 1+ return resultdiff --git a/stablegen/ui/studio_widgets.py b/stablegen/ui/studio_widgets.pynew file mode 100644index 0000000..a7bc10d--- /dev/null+++ b/stablegen/ui/studio_widgets.py@@ -0,0 +1,457 @@+"""GPU widgets for Studio's sidebar. Bounds also define their hit targets."""+from dataclasses import dataclass+import math++import bpy+import blf+import gpu+from gpu_extras.batch import batch_for_shader++from .studio_text import wrap++FONT_SIZE = 11+CONTROL_HEIGHT = 22+CONTROL_GAP = 5+TEXT_LINE_HEIGHT = 17+TEXT_PADDING = 8+++def font_size(size=FONT_SIZE):+ """Use Blender's widget font size; coordinates already follow its UI scale."""+ styles = bpy.context.preferences.ui_styles+ return size * styles[0].widget.points / FONT_SIZE if styles else size+++def color(value):+ return tuple(int(value[i:i + 2], 16) / 255 for i in (0, 2, 4)) + (1,)+++COLORS = {key: color(value) for key, value in {+ 'panel': '3d3d3d', 'field': '1d1d1d', 'field_text': 'e6e6e6',+ 'number': '545454', 'number_text': 'e6e6e6', 'menu': '282828', 'menu_text': 'e6e6e6',+ 'raised': '545454', 'line': '494949', 'divider': '464646', 'text': 'e6e6e6',+ 'secondary': 'c4c4c4', 'muted': '999999', 'accent': '8fa6ca',+ 'blue': '4772b3', 'on_accent': 'ffffff', 'hover': '545454', 'disabled': '787878',+ 'warning': 'c0a673', 'selected': '404c5e', 'card': '353535',+ 'text_selected': '4a4a4a', 'number_selected': '6e6e6e',+ 'cursor': '71a8ff', 'switch_off': '545454', 'switch_knob': 'ffffff',+ 'outer_edge': '494949',+ 'hover_border': '858585', 'hover_soft': '454545', 'blue_hover': '5980bd',+ 'switch_off_hover': '666666', 'tooltip': '191919',+ 'tooltip_text': 'e6e6e6', 'tooltip_line': '555555',+}.items()}+++def _rgba(value):+ value = tuple(value)+ return value if len(value) == 4 else value + (1,)+++def _mix(a, b, factor):+ return tuple(a[i] * (1 - factor) + b[i] * factor for i in range(3)) + (1,)+++def _over(foreground, background):+ foreground = _rgba(foreground)+ return _mix(background, foreground, foreground[3])+++def theme_colors(context):+ """Read the active native palette each draw, including unsaved theme edits."""+ theme = context.preferences.themes[0]+ ui = theme.user_interface+ space = theme.view_3d.space+ # Panel colors moved from editor spaces to User Interface in Blender 5.0.+ panels = getattr(space, 'panelcolors', None)+ back = getattr(ui, 'panel_back', getattr(panels, 'back', COLORS['panel']))+ panel = _over(back, COLORS['panel'])+ text = _rgba(getattr(ui, 'panel_text', space.text))+ border = _over(getattr(ui, 'panel_outline', (1, 1, 1, .067)), panel)+ tool, field, number, menu = ui.wcol_tool, ui.wcol_text, ui.wcol_num, ui.wcol_menu+ blue = _over(tool.inner_sel, panel)+ field_back = _over(field.inner, panel)+ card = _over(getattr(ui, 'panel_sub_back', (0, 0, 0, .12)), panel)+ subbox = _mix(card, field_back, .2)+ section_border = _mix(border, text, .075)+ return {+ 'panel': panel, 'field': field_back, 'field_text': _rgba(field.text),+ 'number': _over(number.inner, panel), 'number_text': _rgba(number.text),+ 'menu': _over(menu.inner, panel), 'menu_text': _rgba(menu.text),+ 'field_border': _over(field.outline, panel), 'number_border': _over(number.outline, panel),+ 'menu_border': _over(menu.outline, panel), 'tool_border': _over(tool.outline, panel),+ 'raised': _over(tool.inner, panel), 'line': border, 'divider': _mix(panel, border, .7),+ 'outer_edge': border, 'panel_shadow': _rgba(ui.widget_emboss),+ 'text': text, 'secondary': _mix(text, panel, .2),+ 'muted': _mix(text, panel, .3), 'disabled': _mix(text, panel, .65),+ 'blue': blue, 'on_accent': _rgba(tool.text_sel),+ # Colored text needs contrast on both Blender's dark and light themes.+ 'accent': _mix(blue, text, .45), 'cursor': _rgba(ui.widget_text_cursor),+ 'hover': _mix(_over(tool.inner, panel), text, .08),+ 'hover_soft': _mix(panel, text, .055), 'hover_border': _mix(border, text, .3),+ 'blue_hover': _mix(blue, _rgba(tool.text_sel), .12),+ 'selected': _mix(panel, blue, .28),+ 'tab_selected': _mix(card, blue, .14),+ 'card': card, 'section_header': _mix(panel, text, .085), 'section_body': card,+ 'section_border': section_border, 'subbox': subbox,+ 'group_body': _mix(panel, subbox, .3), 'group_border': _mix(section_border, text, .16),+ 'dependency_rail': _mix(panel, text, .23),+ 'text_selected': _over(field.item, field_back),+ 'number_selected': _mix(_over(number.inner, panel), _rgba(number.text), .18),+ 'warning': _mix(_rgba(getattr(ui.wcol_state, 'warning', COLORS['warning'])), text, .35),+ 'switch_off': _over(ui.wcol_toggle.inner, panel), 'switch_knob': _rgba(ui.wcol_option.item),+ 'switch_off_hover': _mix(_over(ui.wcol_toggle.inner, panel), text, .14),+ 'tooltip': _over(ui.wcol_tooltip.inner, panel),+ 'tooltip_text': _rgba(ui.wcol_tooltip.text),+ 'tooltip_line': _over(ui.wcol_tooltip.outline, _over(ui.wcol_tooltip.inner, panel)),+ }+++@dataclass+class Target:+ key: str+ rect: tuple+ action: object+ enabled: bool = True+ hint: str = ''+ clip: tuple | None = None++ @property+ def cursor(self):+ if not self.enabled:+ return 'DEFAULT'+ kind = self.action[0] if isinstance(self.action, tuple) else ''+ return 'TEXT' if kind == 'edit' else 'MOVE_X' if kind == 'slider' else 'DEFAULT'++ def contains(self, x, y):+ rx, ry, width, height = self.rect+ inside = rx <= x <= rx + width and ry <= y <= ry + height+ if inside and self.clip:+ cx, cy, cw, ch = self.clip+ inside = cx <= x <= cx + cw and cy <= y <= cy + ch+ return inside+++class Painter:+ def __init__(self, region, scale=1, font=0):+ self.region, self.scale, self.font = region, scale, font+ self.colors = theme_colors(bpy.context)+ self.width = region.width / scale - 28+ self.height = region.height / scale+ self.shader = gpu.shader.from_builtin('UNIFORM_COLOR')+ self.targets = []+ self.hover_key = ''+ self.layers = []+ self.clip_rect = None+ self.canvas_clip = None+ self.previous_blend = gpu.state.blend_get()+ self.previous_scissor = gpu.state.scissor_get()+ self.viewport = gpu.state.viewport_get()+ gpu.state.blend_set('ALPHA')+ gpu.state.scissor_test_set(False)++ def finish(self):+ self.canvas_clip = None+ self.clip(None)+ gpu.state.scissor_set(*self.previous_scissor)+ gpu.state.blend_set(self.previous_blend)++ def clip(self, rect):+ if self.canvas_clip:+ if rect is None:+ rect = self.canvas_clip+ else:+ x, y = max(rect[0], self.canvas_clip[0]), max(rect[1], self.canvas_clip[1])+ right = min(rect[0] + rect[2], self.canvas_clip[0] + self.canvas_clip[2])+ bottom = min(rect[1] + rect[3], self.canvas_clip[1] + self.canvas_clip[3])+ rect = (x, y, max(0, right - x), max(0, bottom - y))+ self.clip_rect = rect+ gpu.state.scissor_test_set(rect is not None)+ if rect:+ x, y, w, h = rect+ gpu.state.scissor_set(int(self.viewport[0] + x * self.scale),+ int(self.viewport[1] + (self.height - y - h) * self.scale),+ max(0, int(w * self.scale)), max(0, int(h * self.scale)))++ def panel(self):+ """Cover the native backing and bring the frame to the sidebar's left edge."""+ # Cover the native backing panel first, including the rounded corners and+ # gutter; its offset outline must not show through beside our own frame.+ self.rect(0, 0, self.width + 1, self.height, 'panel')+ x, y, width, height = 0, 2, self.width, self.height - 4+ ui = bpy.context.preferences.themes[0].user_interface+ radius = max(0, min(8, ui.panel_roundness * 10))+ self.rect(x, y + 1, width, height + 1, 'panel_shadow', radius + 1)+ self.outline(x, y, width, height, 'panel', 'outer_edge', radius)+ # Header/footer painting must not overwrite the frame or its curved corners.+ inset = max(1, radius)+ self.canvas_clip = (x + 1, y + inset, width - 2, height - inset * 2)+ self.clip(None)++ def begin_group(self):+ """Collect drawing once, so the measured group's backdrop can go behind it."""+ self.layers.append([])++ def end_group(self, rect, fill='section_body', border='section_border', radius=4):+ self.end_group_row([rect], fill, border, radius)++ def end_group_row(self, rects, fill='section_body', border='section_border', radius=4, *, styles=None):+ """Give adjacent cards a shared measured height without drawing twice."""+ commands = self.layers.pop()+ previous_clip = self.clip_rect+ for i, rect in enumerate(rects):+ card_fill, card_border = styles[i] if styles else (fill, border)+ self.outline(*rect, card_fill, card_border, radius)+ if self.layers:+ self.layers[-1].extend(commands)+ else:+ try:+ for method, args, clip in commands:+ if clip != self.clip_rect:+ self.clip(clip)+ method(*args)+ finally:+ if previous_clip != self.clip_rect:+ self.clip(previous_clip)++ def emit(self, method, *args):+ if self.layers:+ self.layers[-1].append((method, args, self.clip_rect))+ else:+ method(*args)++ def polygon(self, points, tint):+ self.emit(self.draw_polygon, tuple(points), tint)++ def draw_polygon(self, points, tint):+ if len(points) < 3:+ return+ vertices = [(x * self.scale, (self.height - y) * self.scale) for x, y in points]+ self.shader.bind()+ self.shader.uniform_float('color', self.colors.get(tint, tint))+ batch_for_shader(self.shader, 'TRIS', {'pos': vertices},+ indices=[(0, i, i + 1) for i in range(1, len(vertices) - 1)]).draw(self.shader)++ def rect(self, x, y, width, height, tint, radius=0, *, corners='ALL'):+ if width <= 0 or height <= 0:+ return+ radius = min(radius, width / 2, height / 2)+ if radius:+ points = []+ right = radius if corners in {'ALL', 'RIGHT'} else 0+ left = radius if corners in {'ALL', 'LEFT'} else 0+ for cx, cy, angle, r in ((x + width - right, y + right, -90, right),+ (x + width - right, y + height - right, 0, right),+ (x + left, y + height - left, 90, left),+ (x + left, y + left, 180, left)):+ if not r:+ points.append((cx, cy))+ continue+ for j in range(5):+ a = math.radians(angle + j * 22.5)+ points.append((cx + math.cos(a) * r, cy + math.sin(a) * r))+ else:+ points = [(x, y), (x + width, y), (x + width, y + height), (x, y + height)]+ self.polygon(points, tint)++ def outline(self, x, y, width, height, fill='field', border='line', radius=4, *, corners='ALL'):+ self.rect(x, y, width, height, border, radius, corners=corners)+ self.rect(x + 1, y + 1, width - 2, height - 2, fill, max(0, radius - 1), corners=corners)++ def line(self, points, tint='muted', thickness=1):+ for (x1, y1), (x2, y2) in zip(points, points[1:]):+ length = math.hypot(x2 - x1, y2 - y1)+ if length:+ dx, dy = -(y2 - y1) / length * thickness / 2, (x2 - x1) / length * thickness / 2+ self.polygon([(x1 + dx, y1 + dy), (x2 + dx, y2 + dy),+ (x2 - dx, y2 - dy), (x1 - dx, y1 - dy)], tint)++ def dependency_rail(self, x, top, last):+ """One straight rail through the dependency scope, without branches."""+ self.line([(x, top), (x, last)], 'dependency_rail', 1 / self.scale)++ def measure(self, text, size=FONT_SIZE):+ blf.size(self.font, font_size(size) * self.scale)+ return blf.dimensions(self.font, text)[0] / self.scale++ def fit(self, text, width, size=FONT_SIZE):+ if self.measure(text, size) <= width:+ return text+ while text and self.measure(text + '…', size) > width:+ text = text[:-1]+ return text + '…' if text else ''++ def text(self, text, x, y, size=FONT_SIZE, tint='text', width=None):+ text = str(text)+ if width is not None:+ text = self.fit(text, width, size)+ self.emit(self.draw_text, text, x, y, size, tint)++ def draw_text(self, text, x, y, size, tint):+ size = font_size(size)+ blf.size(self.font, size * self.scale)+ blf.color(self.font, *self.colors.get(tint, tint))+ blf.position(self.font, x * self.scale, (self.height - y - size) * self.scale, 0)+ blf.draw(self.font, text)++ def image(self, image, rect):+ self.emit(self.draw_image, image, rect)++ def draw_image(self, image, rect):+ x, y, width, height = rect+ iw, ih = image.size+ if iw <= 0 or ih <= 0:+ return+ ratio = min(width / iw, height / ih)+ w, h = iw * ratio, ih * ratio+ x, y = x + (width - w) / 2, y + (height - h) / 2+ shader = gpu.shader.from_builtin('IMAGE')+ texture = gpu.texture.from_image(image)+ shader.bind()+ shader.uniform_sampler('image', texture)+ positions = [(px * self.scale, (self.height - py) * self.scale)+ for px, py in ((x, y+h), (x+w, y+h), (x+w, y), (x, y))]+ batch_for_shader(shader, 'TRI_FAN', {'pos': positions,+ 'texCoord': [(0,0), (1,0), (1,1), (0,1)]}).draw(shader)++ def icon(self, name, x, y, size=15, tint='secondary'):+ if name == 'more':+ diameter = max(2, round(size * self.scale / 4))+ gap = max(1, round(size * self.scale / 8))+ left = round((x + size / 2) * self.scale - (3 * diameter + 2 * gap) / 2)+ top = round((y + size / 2) * self.scale - diameter / 2)+ for i in range(3):+ self.rect((left + i * (diameter + gap)) / self.scale, top / self.scale,+ diameter / self.scale, diameter / self.scale, tint, diameter / (2 * self.scale))+ return+ paths = {+ 'camera': [[(2, 5), (6, 5), (8, 2), (13, 2), (15, 5), (19, 5), (19, 17), (2, 17), (2, 5)]],+ 'document': [[(13, 2), (4, 2), (4, 19), (17, 19), (17, 6), (13, 2), (13, 6), (17, 6)], [(7, 10), (14, 10)], [(7, 14), (12, 14)]],+ 'clone': [[(8, 7), (19, 7), (19, 18), (8, 18), (8, 7)], [(14, 4), (3, 4), (3, 14), (5, 14)]],+ 'mirror': [[(10, 2), (10, 19)], [(2, 6), (6, 6), (6, 15), (2, 15), (2, 6)], [(14, 6), (18, 6), (18, 15), (14, 15), (14, 6)]],+ 'expand': [[(12, 2), (19, 2), (19, 9)], [(19, 2), (12, 9)], [(8, 19), (2, 19), (2, 12)], [(2, 19), (9, 12)]],+ 'labels': [[(3, 3), (18, 3)], [(10, 3), (10, 18)], [(6, 18), (14, 18)]],+ 'down': [[(5, 8), (10, 13), (15, 8)]],+ 'right': [[(7, 5), (12, 10), (7, 15)]],+ 'reset': [[(4, 4), (4, 10), (10, 10)], [(4, 10), (7, 4), (14, 4), (18, 8), (18, 14), (14, 18), (7, 18), (4, 15)]],+ 'search': [[(14, 14), (19, 19)]],+ 'settings': [[(2, 5), (19, 5)], [(2, 10), (19, 10)], [(2, 15), (19, 15)], [(7, 3), (7, 7)], [(14, 8), (14, 12)], [(9, 13), (9, 17)]],+ 'play': [[(6, 3), (18, 10), (6, 18), (6, 3)]],+ 'stop': [[(5, 5), (16, 5), (16, 16), (5, 16), (5, 5)]],+ 'layers': [[(10, 2), (19, 7), (10, 12), (1, 7), (10, 2)], [(1, 11), (10, 16), (19, 11)], [(1, 15), (10, 20), (19, 15)]],+ 'grid': [[(3, 3), (18, 3), (18, 18), (3, 18), (3, 3)], [(3, 8), (18, 8)], [(3, 13), (18, 13)], [(8, 3), (8, 18)], [(13, 3), (13, 18)]],+ 'download': [[(10, 2), (10, 13)], [(5, 8), (10, 13), (15, 8)], [(2, 14), (2, 19), (18, 19), (18, 14)]],+ 'eye': [[(1, 10), (6, 5), (14, 5), (19, 10), (14, 15), (6, 15), (1, 10)]],+ 'x': [[(5, 5), (16, 16)], [(5, 16), (16, 5)]],+ 'plus': [[(10, 3), (10, 18)], [(3, 10), (18, 10)]],+ 'arrow': [[(3, 10), (18, 10)], [(12, 4), (18, 10), (12, 16)]],+ 'folder': [[(2, 6), (2, 18), (19, 18), (19, 6), (10, 6), (8, 3), (2, 3), (2, 6)]],+ 'light': [[(7, 15), (7, 18), (14, 18), (14, 15), (17, 11), (17, 6), (13, 2), (8, 2), (4, 6), (4, 11), (7, 15)], [(7, 15), (14, 15)]],+ 'modifier': [[(3, 3), (8, 3), (8, 8), (13, 8), (13, 13), (18, 13), (18, 18), (3, 18), (3, 3)]],+ 'curve': [[(2, 17), (5, 17), (8, 14), (10, 6), (13, 3), (19, 3)], [(2, 15), (2, 19)], [(19, 1), (19, 5)]],+ 'material': [[(10, 2), (18, 6), (18, 15), (10, 19), (2, 15), (2, 6), (10, 2)], [(2, 6), (10, 10), (18, 6)], [(10, 10), (10, 19)]],+ 'rig': [[(10, 2), (10, 9), (4, 6)], [(10, 9), (17, 5)], [(10, 9), (6, 19)], [(10, 9), (16, 18)]],+ 'graph': [[(2, 2), (2, 18), (19, 18)], [(4, 14), (8, 8), (12, 11), (18, 3)]],+ 'shield': [[(10, 2), (18, 5), (17, 13), (10, 19), (3, 13), (2, 5), (10, 2)]],+ }+ if name in {'camera', 'eye', 'search'}:+ cx, cy, radius = {'camera': (10.5, 11, 4), 'eye': (10, 10, 2.5), 'search': (9, 9, 6)}[name]+ self.line([(x + (cx + math.cos(i * math.pi / 12) * radius) * size / 21,+ y + (cy + math.sin(i * math.pi / 12) * radius) * size / 21)+ for i in range(25)], tint, 1)+ for path in paths.get(name, paths['settings']):+ self.line([(x + px * size / 21, y + py * size / 21) for px, py in path], tint, 1)++ def target(self, key, rect, action, enabled=True, hint=''):+ target = Target(key, rect, action, enabled, hint, self.clip_rect)+ self.targets.append(target)+ return target++ def button(self, key, rect, text, action, *, icon=None, style='quiet', enabled=True, hover=False, active=False, hint='', text_size=FONT_SIZE, corners='ALL'):+ hover = enabled and (hover or key == self.hover_key)+ x, y, w, h = rect+ tint = 'disabled' if not enabled else 'on_accent' if style == 'primary' else 'accent' if active else 'text'+ if style == 'primary':+ self.rect(x, y, w, h, 'blue_hover' if hover else 'blue' if enabled else 'raised', 4, corners=corners)+ elif style == 'outlined':+ self.outline(x, y, w, h, 'hover' if hover else 'raised', 'hover_border' if hover else 'tool_border', corners=corners)+ elif hover and enabled and style != 'tab':+ self.rect(x + 2, y + 2, w - 4, h - 4, 'hover')+ icon_size = 16 if icon == 'more' else 13+ icon_advance = icon_size + 4+ tw = self.measure(text, text_size) if text else 0+ available = w - (icon_advance + 9 if icon and text else 18)+ tw = min(tw, max(0, available))+ start = x + (w - tw - (icon_advance if icon and text else icon_size if icon else 0)) / 2+ if icon:+ self.icon(icon, start, y + (h - icon_size) / 2, icon_size, tint=tint)+ if text:+ self.text(text, start + (icon_advance if icon else 0), y + (h - font_size(text_size)) / 2 - 1, text_size, tint, max(0, available))+ self.target(key, rect, action, enabled, hint)++ def action_row(self, key, rect, label, action, *, icon='settings', enabled=True, hint=''):+ """A left-aligned command in a utility list, with one full-row hit area."""+ x, y, width, height = rect+ hover = enabled and key == self.hover_key+ if hover:+ self.rect(x, y, width, height, 'hover_soft')+ tint = 'text' if enabled else 'disabled'+ self.icon(icon, x + 8, y + (height - 14) / 2, 14, 'secondary' if enabled else 'disabled')+ self.text(label, x + 30, y + (height - font_size()) / 2 - 1, FONT_SIZE, tint, width - 52)+ self.icon('right', x + width - 18, y + (height - 10) / 2, 10,+ 'accent' if hover else 'muted' if enabled else 'disabled')+ self.target(key, rect, action, enabled, hint)++ def switch(self, key, rect, label, checked, action, *, enabled=True, hint='', hover=False):+ hover = enabled and (hover or key == self.hover_key)+ x, y, w, h = rect+ tint = 'text' if enabled else 'disabled'+ if hover:+ self.rect(x, y, w, h, 'hover_soft')+ lines = wrap(label, w - 40, self.measure)+ for i, (_, _, line) in enumerate(lines):+ self.text(line, x, y + (h - len(lines) * 16) / 2 + i * 16, FONT_SIZE, tint)+ sx, sy = x + w - 28, y + (h - 14) / 2+ self.rect(sx, sy, 28, 14, ('blue_hover' if hover else 'blue') if checked and enabled+ else 'switch_off_hover' if hover else 'switch_off', 7)+ self.rect(sx + (16 if checked else 2), sy + 2, 10, 10, 'switch_knob' if enabled else 'muted', 5)+ self.target(key, rect, action, enabled, hint)++ def text_field(self, key, rect, value, action, *, enabled=True, hint='', editing=None, scroll=0, multiline=False, follow_caret=True, kind='field'):+ x, y, w, h = rect+ self.outline(x, y, w, h, fill=kind, border='cursor' if editing else 'hover_border'+ if enabled and key == self.hover_key else kind + '_border')+ self.target(key, rect, action, enabled, hint)+ if not multiline and editing is None:+ self.text(value, x + TEXT_PADDING, y + (h - font_size()) / 2 - 1, FONT_SIZE,+ kind + '_text' if enabled else 'disabled', w - TEXT_PADDING * 2)+ return [], 0+ lines = wrap(value, w - TEXT_PADDING * 2, self.measure)+ line_height = TEXT_LINE_HEIGHT+ padding_y = TEXT_PADDING if multiline else (h - font_size()) / 2 - 1+ count = max(1, int((h - TEXT_PADDING * 2) / line_height)) if multiline else 1+ if editing:+ caret_row = next((i for i, (start, end, _) in enumerate(lines)+ if start <= editing.caret <= end and (editing.caret != end or i == len(lines) - 1 or lines[i + 1][0] != end)), len(lines) - 1)+ if follow_caret and caret_row < scroll:+ scroll = caret_row+ elif follow_caret and caret_row >= scroll + count:+ scroll = caret_row - count + 1+ scroll = max(0, min(max(0, len(lines) - count), scroll))+ for index, (start, end, line) in enumerate(lines[scroll:scroll + count], scroll):+ ly = y + padding_y + (index - scroll) * line_height+ if editing:+ sel_start, sel_end = editing.selection+ a, b = max(start, sel_start), min(end, sel_end)+ if b > a:+ lx = x + TEXT_PADDING + self.measure(value[start:a])+ self.rect(lx, ly - 1, self.measure(value[a:b]), line_height,+ 'number_selected' if kind == 'number' else 'text_selected')+ self.text(line.rstrip('\r'), x + TEXT_PADDING, ly, FONT_SIZE, kind + '_text' if enabled else 'disabled')+ if editing and index == caret_row:+ cx = x + TEXT_PADDING + self.measure(value[start:editing.caret])+ self.rect(cx, ly, 1, font_size() + 3, 'cursor')+ if len(lines) > count:+ track = h - 12+ self.rect(x + w - 5, y + 6 + scroll / len(lines) * track, 2,+ max(10, count / len(lines) * track), 'muted', 1)+ return lines, scrolldiff --git a/stablegen/utils.py b/stablegen/utils.pyindex 69ce5a0..7dedb9e 100644--- a/stablegen/utils.py+++ b/stablegen/utils.py@@ -30,7 +30,7 @@ def sg_modal_active(context):return Falsefor window in context.window_manager.windows:for op in window.modal_operators:- if op.bl_idname in _SG_BLOCKED_MODALS:+ if getattr(op, 'bl_idname', None) in _SG_BLOCKED_MODALS:return Truereturn False