Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
graduate texturing controls and remove per-texel ownership
sakalond774b8f8afc2a
diff --git a/stablegen/core/preferences.py b/stablegen/core/preferences.pyindex 92306a1..3fc1cbe 100644--- a/stablegen/core/preferences.py+++ b/stablegen/core/preferences.py@@ -58,6 +58,12 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):"""Preferences for the StableGen addon."""bl_idname = ADDON_PKG+ 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",+ default=False,+ ) # type: ignore+server_address: bpy.props.StringProperty(name="Server Address",description="Address of the ComfyUI server",@@ -178,6 +184,7 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):layout.prop(self, "save_blend_file")layout.prop(self, "enable_print_tab")+ layout.prop(self, "enable_texturing_experiments")layout.prop(self, "enable_scene_queue")layout.separator()diff --git a/stablegen/core/properties.py b/stablegen/core/properties.pyindex 6b819c7..6ce7270 100644--- a/stablegen/core/properties.py+++ b/stablegen/core/properties.py@@ -19,7 +19,7 @@ from .callbacks import (update_print_dithered,)from . import ADDON_PKG-from ..feature_flags import TEXTURING_REWORK_DEFAULTS+from ..feature_flags import TEXTURING_DEFAULTS# ── Helper(s) used by properties ───────────────────────────────────────────@@ -787,97 +787,55 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,bpy.types.Scene.sg_allow_backface_projection = bpy.props.BoolProperty(name="Allow Backface Projection",description="Use legacy two-sided projection weights. Leave disabled for characters and closed meshes so a camera cannot write through back-facing surfaces",- default=TEXTURING_REWORK_DEFAULTS["sg_allow_backface_projection"], update=update_parameters,+ default=TEXTURING_DEFAULTS["sg_allow_backface_projection"], update=update_parameters,)- # Texturing pipeline rework feature gates. These deliberately default to- # False so a newly opened scene follows the rigging-branch projection and- # sequential-context behavior. Each gate controls one independently- # testable behavior instead of enabling the rework as an inseparable set.- bpy.types.Scene.sg_rework_camera_plan = bpy.props.BoolProperty(- name="Canonical Camera Plan",- description="Snapshot camera order, transforms, intrinsics, prompts, and per-camera resolutions for the whole run",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_camera_plan"], update=update_parameters,- )+ # Scene values remain serializable. Research switches are gated at runtime+ # by the addon preference; CGC/AQW/DPPG are ordinary controls.bpy.types.Scene.sg_rework_aligned_resolution = bpy.props.BoolProperty(name="Improved Aligned Resolution",description="Use the new joint aspect/megapixel/alignment resolution search instead of legacy proportional rounding",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_aligned_resolution"], update=update_parameters,+ default=TEXTURING_DEFAULTS["sg_rework_aligned_resolution"], update=update_parameters,)bpy.types.Scene.sg_rework_full_resolution_scale = bpy.props.BoolProperty(name="Force 100% Guide Resolution",description="Temporarily force Blender resolution percentage to 100 so guides and Qwen inputs match the configured pixel dimensions",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_full_resolution_scale"], update=update_parameters,- )- bpy.types.Scene.sg_rework_safe_render_state = bpy.props.BoolProperty(- name="Transactional Render State",- description="Snapshot and restore render, compositor, material-slot, and scene state around pipeline renders",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_safe_render_state"], update=update_parameters,- )- bpy.types.Scene.sg_rework_reset_controls = bpy.props.BoolProperty(- name="Corrected Angle/Exponent Reset",- description="Reset normalized projection weights and baked visibility consistently on completion, cancellation, and errors",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_reset_controls"], update=update_parameters,- )- bpy.types.Scene.sg_rework_sdxl_registration = bpy.props.BoolProperty(- name="Corrected SDXL Mask Registration",- description="Use the corrected uncropped SDXL sequential mask and projection-alpha registration path",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_sdxl_registration"], update=update_parameters,+ default=TEXTURING_DEFAULTS["sg_rework_full_resolution_scale"], update=update_parameters,)bpy.types.Scene.sg_rework_acquisition_quality = bpy.props.BoolProperty(name="Acquisition Quality Weighting",description="Weight views using projected density and source-camera acquisition quality in addition to legacy visibility/frontality",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_acquisition_quality"], update=update_parameters,- )- bpy.types.Scene.sg_rework_initial_view_priority = bpy.props.BoolProperty(- name="Confidence-Aware Initial View Priority",- description="Use early-view priority only as trusted-owner replacement resistance instead of the legacy recursive blend bias",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_initial_view_priority"], update=update_parameters,+ default=TEXTURING_DEFAULTS["sg_rework_acquisition_quality"], update=update_parameters,)bpy.types.Scene.sg_rework_projection_guard = bpy.props.BoolProperty(name="Depth/Part Projection Guard",description="Reject projection near depth, object-ID, and material-ID discontinuities to reduce foreground silhouettes on rear surfaces",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_projection_guard"], update=update_parameters,- )- bpy.types.Scene.sg_rework_projection_rebuild = bpy.props.BoolProperty(- name="Rebuild Sequential Projection Graph",- description="Rebuild the complete projection material after each generated view instead of using the legacy patch-in-place update",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_projection_rebuild"], update=update_parameters,- )- bpy.types.Scene.sg_rework_projection_geometry = bpy.props.BoolProperty(- name="Projection Geometry Corrections",- description="Use signed facing, parented camera transforms, camera shift, orthographic support, evaluated meshes, and scale-aware ray tolerances",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_projection_geometry"], update=update_parameters,- )- bpy.types.Scene.sg_rework_consistent_frame = bpy.props.BoolProperty(- name="Consistent Texturing Frame",- description="Evaluate guides, visibility, projection, and baking at the explicit Texturing Frame",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_consistent_frame"], update=update_parameters,- )- bpy.types.Scene.sg_rework_workflow_validation = bpy.props.BoolProperty(- name="Workflow Graph Validation",- description="Validate generated Qwen/SDXL workflow graphs and semantic image slots before submission",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_workflow_validation"], update=update_parameters,- )- bpy.types.Scene.sg_rework_qwen_workflow = bpy.props.BoolProperty(- name="Corrected Qwen Workflow Routing",- description="Use corrected Qwen style-slot routing, TRELLIS initial-only fallback, and refine sampler/model configuration",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_qwen_workflow"], update=update_parameters,+ default=TEXTURING_DEFAULTS["sg_rework_projection_guard"], update=update_parameters,)bpy.types.Scene.qwen_global_style_vlm_only = bpy.props.BoolProperty(name="Global Style Reference: VLM Only",description="In Qwen Additional Context mode, keep Image 3 available for visual-language style analysis but exclude it from full-resolution ReferenceLatent conditioning so it competes less with the spatial RGB context",- default=TEXTURING_REWORK_DEFAULTS["qwen_global_style_vlm_only"], update=update_parameters,+ default=TEXTURING_DEFAULTS["qwen_global_style_vlm_only"], update=update_parameters,+ )+ bpy.types.Scene.qwen_context_vlm_only = bpy.props.BoolProperty(+ name="Projected Context: VLM Only",+ description="Experimental: keep the magenta context image available for visual-language analysis but omit its spatial reference latent on later Qwen context views. May reduce copied missing-texture patches while weakening detail and color continuity",+ default=TEXTURING_DEFAULTS["qwen_context_vlm_only"], update=update_parameters,)bpy.types.Scene.qwen_latent_locked_context = bpy.props.BoolProperty(name="Latent-Locked Context Inpainting",description="For later sequential Qwen views, initialize the sampler from the RGB context render and use the exported visibility repair mask as a latent noise mask. White/repair pixels denoise; black/trusted pixels are restored after every sampling step",- default=TEXTURING_REWORK_DEFAULTS["qwen_latent_locked_context"], update=update_parameters,+ default=TEXTURING_DEFAULTS["qwen_latent_locked_context"], update=update_parameters,+ )+ bpy.types.Scene.qwen_latent_lock_neutral_fill = bpy.props.BoolProperty(+ name="Neutral Fill for Latent Lock",+ description="Replace repair pixels with neutral gray before encoding the protected context latent to reduce magenta contamination at its boundary. Keeps the existing repair mask unchanged; requires Latent-Locked Context Inpainting",+ default=TEXTURING_DEFAULTS["qwen_latent_lock_neutral_fill"], update=update_parameters,)bpy.types.Scene.sg_rework_final_display = bpy.props.BoolProperty(name="Continuous Final Display Rebuild",description="After sequential generation, rebuild the final material without generation-only binary Qwen write masks so it matches Reproject",- default=TEXTURING_REWORK_DEFAULTS["sg_rework_final_display"], update=update_parameters,+ default=TEXTURING_DEFAULTS["sg_rework_final_display"], update=update_parameters,)bpy.types.Scene.sg_silhouette_depth = bpy.props.FloatProperty(name="Silhouette Depth",@@ -1230,12 +1188,12 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,bpy.types.Scene.qwen_use_confidence_context = bpy.props.BoolProperty(name="Confidence-Gated Context",description="Build an ownership-independent best-source quality field and replace low-quality context with an explicit binary repair mask. Continuous RGB projection blending is preserved",- default=TEXTURING_REWORK_DEFAULTS["qwen_use_confidence_context"], update=update_parameters,+ default=TEXTURING_DEFAULTS["qwen_use_confidence_context"], update=update_parameters,)bpy.types.Scene.qwen_regularize_context_mask = bpy.props.BoolProperty(name="Regularize Context Boundary",description="Apply island, hole, strip, dilation, and part-aware cleanup to the explicit binary Qwen repair mask",- default=TEXTURING_REWORK_DEFAULTS["qwen_regularize_context_mask"], update=update_parameters,+ default=TEXTURING_DEFAULTS["qwen_regularize_context_mask"], update=update_parameters,)bpy.types.Scene.qwen_trust_threshold = bpy.props.FloatProperty(name="Trusted Source Threshold",@@ -1270,12 +1228,12 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,bpy.types.Scene.qwen_use_projection_write_masks = bpy.props.BoolProperty(name="Protect Trusted Texture",description="Restrict each later Qwen camera's projection contribution to its binary editable/write mask",- default=TEXTURING_REWORK_DEFAULTS["qwen_use_projection_write_masks"], update=update_parameters+ default=TEXTURING_DEFAULTS["qwen_use_projection_write_masks"], update=update_parameters)bpy.types.Scene.qwen_reject_residual_fallback = bpy.props.BoolProperty(name="Reject Residual Magenta",description="Remove residual fallback-color pixels from a Qwen camera's explicit projection write mask",- default=TEXTURING_REWORK_DEFAULTS["qwen_reject_residual_fallback"], update=update_parameters,+ default=TEXTURING_DEFAULTS["qwen_reject_residual_fallback"], update=update_parameters,)bpy.types.Scene.qwen_residual_fallback_tolerance = bpy.props.IntProperty(name="Residual Fallback Tolerance",@@ -1314,6 +1272,9 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,)# ── UI section toggles ─────────────────────────────────────────────+ bpy.types.Scene.show_texturing_experiments = bpy.props.BoolProperty(+ name="Experimental Texturing", default=True,+ )bpy.types.Scene.show_core_settings = bpy.props.BoolProperty(name="Core Generation Settings",description="Parameters used for the image generation process. Also includes LoRAs for faster generation.",@@ -1373,41 +1334,6 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,description="Anchor already-reliable early-view detail by raising its replacement margin. Poorly observed side texels remain untrusted and replaceable",default=False, update=update_parameters)- bpy.types.Scene.sg_texel_ownership = bpy.props.BoolProperty(- name="Per-Texel View Ownership",- description="Select one camera per surface point and keep its detail until a later camera has meaningfully higher confidence. This creates harder camera boundaries than weighted blending",- default=False, update=update_parameters- )- bpy.types.Scene.sg_texel_replacement_margin = bpy.props.FloatProperty(- name="Ownership Replacement Margin",- description="Extra confidence a later camera needs before replacing the current per-texel owner",- default=0.05, min=0.0, max=1.0, update=update_parameters- )- bpy.types.Scene.sg_allow_trusted_replacement = bpy.props.BoolProperty(- name="Allow Trusted Quality Upgrades",- description="Permit a later camera to replace trusted detail only when its source quality exceeds the owner by the replacement margin",- default=False, update=update_parameters,- )- bpy.types.Scene.sg_ownership_blend_mode = bpy.props.EnumProperty(- name="Ownership Detail Fusion",- description="Choose how camera detail is fused after confidence resolution",- items=[- ('OWNER', "Single Detail Owner", "Keep high-frequency detail from one owner; blend only low-frequency seam colour"),- ('HARD', "Hard Owner", "Keep one owner with no seam colour matching"),- ('LEGACY', "Legacy Weighted Blend", "Use the previous weighted camera averaging behavior"),- ],- default='OWNER', update=update_parameters,- )- bpy.types.Scene.sg_ownership_seam_width = bpy.props.FloatProperty(- name="Ownership Seam Width",- description="Quality-distance band where only low-frequency colour is blended between detail owners",- default=0.08, min=0.0, max=0.5, update=update_parameters,- )- bpy.types.Scene.sg_ownership_lowpass_sigma = bpy.props.FloatProperty(- name="Ownership Low-Pass Radius",- description="Image-space Gaussian radius used for seam colour matching; high-frequency detail remains owned by one camera",- default=8.0, min=0.1, max=64.0, update=update_parameters,- )bpy.types.Scene.sg_auto_view_sequence = bpy.props.BoolProperty(name="Overlap-Aware View Sequence",description="Order non-custom camera plans through nearby bridge views to reduce angular jumps and context discontinuities",@@ -1423,11 +1349,6 @@ def register_properties(update_model_list, ControlNetUnit, LoRAUnit,description="Explicit frame used consistently for evaluated character geometry, visibility, projection, and baking",default=1, update=update_parameters,)- bpy.types.Scene.sg_freeze_ownership_after_generation = bpy.props.BoolProperty(- name="Freeze Ownership to UV Texture",- description="Bake resolved camera ownership to UV textures after generation so pose, camera, and scene visibility changes cannot alter the final texture",- default=False, update=update_parameters,- )bpy.types.Scene.sg_material_discard_factor = bpy.props.FloatProperty(name="Material Discard Angle", default=90.0, options={'HIDDEN'})@@ -2056,82 +1977,175 @@ def unregister_properties(load_handler, _sg_queue_load_handler):_simple_scene_props = ['use_flux_lora',- 'comfyui_prompt', 'use_separate_texture_prompt', 'texture_prompt',- 'comfyui_negative_prompt', 'model_name', 'sg_model_name_backup',- 'seed', 'control_after_generate', 'steps', 'cfg',- 'sampler', 'scheduler', 'show_advanced_params', 'show_generation_params',- 'auto_rescale', 'qwen_rescale_alignment', 'auto_rescale_target_mp',- 'generation_method', 'use_ipadapter',- 'refine_images', 'refine_steps', 'refine_sampler', 'refine_scheduler',- 'denoise', 'refine_cfg', 'refine_prompt', 'refine_upscale_method',- 'generation_status', 'sg_last_gen_error', 'generation_progress',- 'overwrite_material', 'bake_visibility_weights',- 'discard_factor', 'discard_factor_generation_only', 'discard_factor_after_generation',- 'weight_exponent', 'weight_exponent_generation_only', 'weight_exponent_after_generation',- 'view_blend_use_color_match', 'view_blend_color_match_method', 'view_blend_color_match_strength',- 'allow_modify_existing_textures', 'ask_object_prompts', 'fallback_color',- 'controlnet_units', 'controlnet_units_index', 'lora_units', 'lora_units_index',- 'weight_exponent_mask', 'sequential_smooth',- 'canny_threshold_low', 'canny_threshold_high',- 'sequential_factor_smooth', 'sequential_factor_smooth_2', 'sequential_factor',- 'grow_mask_by', 'mask_blocky',- 'visibility_vignette', 'visibility_vignette_width', 'visibility_vignette_softness',+ 'comfyui_prompt',+ 'use_separate_texture_prompt',+ 'texture_prompt',+ 'comfyui_negative_prompt',+ 'model_name',+ 'sg_model_name_backup',+ 'sg_qwen_21_architecture_migrated',+ 'sg_qwen_prompt_template_migrated',+ 'seed',+ 'control_after_generate',+ 'steps',+ 'cfg',+ 'sampler',+ 'scheduler',+ 'show_advanced_params',+ 'show_generation_params',+ 'auto_rescale',+ 'qwen_rescale_alignment',+ 'qwen_image_21_native_rgba',+ 'auto_rescale_target_mp',+ 'generation_method',+ 'use_ipadapter',+ 'refine_images',+ 'refine_steps',+ 'refine_sampler',+ 'refine_scheduler',+ 'denoise',+ 'refine_cfg',+ 'refine_prompt',+ 'refine_upscale_method',+ 'generation_status',+ 'sg_last_gen_error',+ 'sg_last_gen_error_message',+ 'generation_progress',+ 'overwrite_material',+ 'bake_visibility_weights',+ 'discard_factor',+ 'discard_factor_generation_only',+ 'discard_factor_after_generation',+ 'weight_exponent',+ 'weight_exponent_generation_only',+ 'weight_exponent_after_generation',+ 'view_blend_use_color_match',+ 'view_blend_color_match_method',+ 'view_blend_color_match_strength',+ 'allow_modify_existing_textures',+ 'ask_object_prompts',+ 'fallback_color',+ 'controlnet_units',+ 'controlnet_units_index',+ 'lora_units',+ 'lora_units_index',+ 'weight_exponent_mask',+ 'sequential_smooth',+ 'canny_threshold_low',+ 'canny_threshold_high',+ 'sequential_factor_smooth',+ 'sequential_factor_smooth_2',+ 'sequential_factor',+ 'grow_mask_by',+ 'mask_blocky',+ 'visibility_vignette',+ 'visibility_vignette_width',+ 'visibility_vignette_softness','visibility_vignette_blur',- 'sg_silhouette_margin', 'sg_silhouette_depth', 'sg_silhouette_rays',+ 'sg_silhouette_margin',+ 'sg_silhouette_feather',+ 'sg_projection_guard_scale',+ 'sg_guard_feather_method',+ 'sg_guard_directional',+ 'sg_guard_foreground_margin',+ 'sg_guard_coverage_rescue',+ 'sg_silhouette_depth',+ 'sg_silhouette_rays','sg_allow_backface_projection',- 'sg_rework_camera_plan', 'sg_rework_aligned_resolution',+ 'sg_rework_aligned_resolution','sg_rework_full_resolution_scale',- 'sg_rework_safe_render_state', 'sg_rework_reset_controls',- 'sg_rework_sdxl_registration', 'sg_rework_acquisition_quality',- 'sg_rework_initial_view_priority',- 'sg_rework_projection_guard', 'sg_rework_projection_rebuild',- 'sg_rework_projection_geometry',- 'sg_rework_consistent_frame', 'sg_rework_workflow_validation',- 'sg_rework_qwen_workflow', 'qwen_global_style_vlm_only',+ 'sg_rework_acquisition_quality',+ 'sg_rework_projection_guard',+ 'qwen_global_style_vlm_only',+ 'qwen_context_vlm_only','qwen_latent_locked_context',+ 'qwen_latent_lock_neutral_fill','sg_rework_final_display',- 'sg_texel_ownership', 'sg_texel_replacement_margin',- 'sg_allow_trusted_replacement', 'sg_ownership_blend_mode',- 'sg_ownership_seam_width', 'sg_ownership_lowpass_sigma',- 'sg_auto_view_sequence', 'sg_anchor_camera', 'sg_texturing_frame',- 'sg_freeze_ownership_after_generation', 'sg_material_discard_factor',+ 'sg_auto_view_sequence',+ 'sg_anchor_camera',+ 'sg_texturing_frame',+ 'sg_material_discard_factor','sg_material_weight_exponent',- 'refine_angle_ramp_active', 'refine_angle_ramp_pos_0', 'refine_angle_ramp_pos_1',- 'refine_feather_ramp_pos_0', 'refine_feather_ramp_pos_1',- 'refine_edge_feather_projection', 'refine_edge_feather_width', 'refine_edge_feather_softness',- 'differential_diffusion', 'differential_noise',- 'blur_mask', 'blur_mask_radius', 'blur_mask_sigma',+ 'refine_angle_ramp_active',+ 'refine_angle_ramp_pos_0',+ 'refine_angle_ramp_pos_1',+ 'refine_feather_ramp_pos_0',+ 'refine_feather_ramp_pos_1',+ 'refine_edge_feather_projection',+ 'refine_edge_feather_width',+ 'refine_edge_feather_softness',+ 'differential_diffusion',+ 'differential_noise',+ 'blur_mask',+ 'blur_mask_radius',+ 'blur_mask_sigma','sequential_custom_camera_order',- 'ipadapter_strength', 'ipadapter_start', 'ipadapter_end',- 'ipadapter_image', 'ipadapter_weight_type',- 'sequential_ipadapter', 'sequential_ipadapter_mode',- 'sequential_desaturate_factor', 'sequential_contrast_factor',- 'sequential_ipadapter_regenerate', 'sequential_ipadapter_regenerate_wo_controlnet',- 'clip_skip', 'stablegen_preset', 'active_preset',- 'model_architecture', 'architecture_mode',- 'output_timestamp', 'camera_prompts', 'use_camera_prompts',- 'sg_camera_order', 'sg_camera_order_index', 'sg_use_custom_camera_order',- 'show_core_settings', 'show_lora_settings', 'show_camera_options',- 'show_scene_understanding_settings', 'show_output_material_settings',- 'show_image_guidance_settings', 'show_masking_inpainting_settings',+ 'ipadapter_strength',+ 'ipadapter_start',+ 'ipadapter_end',+ 'ipadapter_image',+ 'ipadapter_weight_type',+ 'sequential_ipadapter',+ 'sequential_ipadapter_mode',+ 'sequential_desaturate_factor',+ 'sequential_contrast_factor',+ 'sequential_ipadapter_regenerate',+ 'sequential_ipadapter_regenerate_wo_controlnet',+ 'clip_skip',+ 'stablegen_preset',+ 'active_preset',+ 'model_architecture',+ 'architecture_mode',+ 'output_timestamp',+ 'camera_prompts',+ 'use_camera_prompts',+ 'sg_camera_order',+ 'sg_camera_order_index',+ 'sg_use_custom_camera_order',+ 'show_core_settings',+ 'show_texturing_experiments',+ 'show_lora_settings',+ 'show_camera_options',+ 'show_scene_understanding_settings',+ 'show_output_material_settings',+ 'show_image_guidance_settings',+ 'show_masking_inpainting_settings','show_mode_specific_settings',- 'generation_mode', 'early_priority_strength', 'early_priority', 'texture_objects',- 'qwen_generation_method', 'qwen_refine_use_prev_ref', 'qwen_refine_use_depth',+ 'generation_mode',+ 'early_priority_strength',+ 'early_priority',+ 'texture_objects',+ 'qwen_generation_method',+ 'qwen_refine_use_prev_ref',+ 'qwen_refine_use_depth','qwen_timestep_zero_ref',- 'qwen_guidance_map_type', 'qwen_voronoi_mode', 'qwen_context_render_mode',- 'qwen_use_external_style_image', 'qwen_external_style_image',+ 'qwen_guidance_map_type',+ 'qwen_voronoi_mode',+ 'qwen_context_render_mode',+ 'qwen_use_external_style_image',+ 'qwen_external_style_image','qwen_external_style_initial_only',- 'qwen_use_custom_prompts', 'qwen_custom_prompt_initial',- 'qwen_custom_prompt_seq_none', 'qwen_custom_prompt_seq_replace',+ 'qwen_use_custom_prompts',+ 'qwen_prompt_template',+ 'qwen_custom_prompt_initial',+ 'qwen_custom_prompt_seq_none',+ 'qwen_custom_prompt_seq_replace','qwen_custom_prompt_seq_additional',- 'qwen_guidance_fallback_color', 'qwen_guidance_background_color',- 'qwen_context_cleanup', 'qwen_context_cleanup_hue_tolerance',- 'qwen_context_cleanup_value_adjust', 'qwen_context_fallback_dilation',- 'qwen_use_confidence_context', 'qwen_regularize_context_mask',- 'qwen_use_projection_write_masks', 'qwen_residual_fallback_tolerance',+ 'qwen_guidance_fallback_color',+ 'qwen_guidance_background_color',+ 'qwen_context_cleanup',+ 'qwen_context_cleanup_hue_tolerance',+ 'qwen_context_cleanup_value_adjust',+ 'qwen_context_fallback_dilation',+ 'qwen_use_confidence_context',+ 'qwen_regularize_context_mask',+ 'qwen_use_projection_write_masks',+ 'qwen_residual_fallback_tolerance','qwen_reject_residual_fallback',- 'qwen_trust_threshold', 'qwen_mask_min_island_area',- 'qwen_mask_min_hole_area', 'qwen_mask_min_strip_width',+ 'qwen_trust_threshold',+ '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_prompt_gray_background',diff --git a/stablegen/debug_tools.py b/stablegen/debug_tools.pyindex 9cb21b5..fcc928f 100644--- a/stablegen/debug_tools.py+++ b/stablegen/debug_tools.py@@ -1492,30 +1492,28 @@ class SG_OT_DebugRestoreMaterial(bpy.types.Operator):# ═════════════════════════════════════════════════════════════════════════-# 10. Live Ownership / Confidence Diagnostics+# 10. Live Confidence Diagnostics# ═════════════════════════════════════════════════════════════════════════-class SG_OT_DebugOwnershipDiagnostic(bpy.types.Operator):- """Visualize values from the actual projection ownership graph.+class SG_OT_DebugConfidenceDiagnostic(bpy.types.Operator):+ """Visualize values from the actual projection confidence graph.The material is copied before its output is replaced, so the diagnosticcannot alter the production graph. Undo restores the original slots."""- bl_idname = "stablegen.debug_ownership_diagnostic"- bl_label = "Ownership Diagnostic"+ bl_idname = "stablegen.debug_confidence_diagnostic"+ bl_label = "Confidence Diagnostic"bl_options = {'REGISTER', 'UNDO'}mode: bpy.props.EnumProperty(name="Diagnostic",items=[- ('OWNER', "Owner Camera", "Hue identifies the selected source camera"),- ('QUALITY', "Owner Quality", "Resolved acquisition quality of the owner"),+ ('QUALITY', "Best Source Quality", "Resolved acquisition quality of accepted sources"),('ACQUISITION', "Camera Quality", "Raw acquisition quality for the active camera"),- ('TRUSTED', "Trusted Context", "White where owner quality reaches the trust threshold"),+ ('TRUSTED', "Trusted Context", "White where source quality reaches the trust threshold"),('REPAIR', "Repair Mask", "White where the current view must regenerate context"),('WRITE', "Write Mask", "Authoritative generated-pixel write mask for the active camera"),('GUARD', "Depth/Part Guard", "Rear-surface rejection mask for the active camera"),- ('FALLBACK', "Fallback Only", "White where no trusted owner exists"),],default='QUALITY',) # type: ignore@@ -1558,17 +1556,15 @@ class SG_OT_DebugOwnershipDiagnostic(bpy.types.Operator):nodes = mat.node_tree.nodeslinks = mat.node_tree.links- owner_quality = self._find_node(nodes, exact="SGOwnerQuality")- if self.mode == 'OWNER':- source = self._find_node(nodes, exact="SGOwnerCamera")- elif self.mode == 'QUALITY':- source = owner_quality+ source_quality = self._find_node(nodes, exact="SGBestSourceQuality")+ if self.mode == 'QUALITY':+ source = source_qualityelif self.mode == 'ACQUISITION':source = self._find_node(nodes, prefix=f"AcquisitionQuality-{camera_index}-")elif self.mode in {'TRUSTED', 'REPAIR'}:- source = owner_quality+ source = source_qualityelif self.mode == 'WRITE':source = self._find_node(nodes, prefix=f"SequentialWriteWeight-{camera_index}-"@@ -1578,7 +1574,7 @@ class SG_OT_DebugOwnershipDiagnostic(bpy.types.Operator):nodes, prefix=f"ProjectionGuardWeight-{camera_index}-")else:- source = self._find_node(nodes, exact="OwnerUncovered")+ source = Noneif source is None or not source.outputs:bpy.data.materials.remove(mat)@@ -1604,19 +1600,8 @@ class SG_OT_DebugOwnershipDiagnostic(bpy.types.Operator):ramp = nodes.new("ShaderNodeValToRGB")ramp.label = f"SGDebug-{self.mode}"- if self.mode == 'OWNER':- normalize = nodes.new("ShaderNodeMath")- normalize.operation = 'DIVIDE'- normalize.inputs[1].default_value = max(len(cameras) - 1, 1)- links.new(value_socket, normalize.inputs[0])- value_socket = normalize.outputs[0]- ramp.color_ramp.elements[0].color = (1.0, 0.0, 0.0, 1.0)- ramp.color_ramp.elements[1].color = (0.0, 0.2, 1.0, 1.0)- middle = ramp.color_ramp.elements.new(0.5)- middle.color = (0.0, 1.0, 0.1, 1.0)- else:- ramp.color_ramp.elements[0].color = (0.0, 0.0, 0.0, 1.0)- ramp.color_ramp.elements[1].color = (1.0, 1.0, 1.0, 1.0)+ ramp.color_ramp.elements[0].color = (0.0, 0.0, 0.0, 1.0)+ ramp.color_ramp.elements[1].color = (1.0, 1.0, 1.0, 1.0)links.new(value_socket, ramp.inputs['Fac'])emission = nodes.new("ShaderNodeEmission")@@ -1906,6 +1891,6 @@ debug_classes = [SG_OT_DebugSkinningWeights,SG_OT_DebugClearSkinningWeights,SG_OT_DebugRestoreMaterial,- SG_OT_DebugOwnershipDiagnostic,+ SG_OT_DebugConfidenceDiagnostic,SG_OT_DebugMakeSolid,]diff --git a/stablegen/feature_flags.py b/stablegen/feature_flags.pyindex 7853c4c..6ebb31a 100644--- a/stablegen/feature_flags.py+++ b/stablegen/feature_flags.py@@ -1,40 +1,44 @@-"""StableGen texturing experiment switches and legacy-compatible defaults."""+"""Regular texturing defaults and preference-gated research options."""-# This mapping is deliberately Blender-independent so tests and preset code can-# verify the baseline without importing the add-on registration graph.-TEXTURING_REWORK_DEFAULTS = {- "sg_rework_camera_plan": False,- "sg_rework_aligned_resolution": False,- "sg_rework_full_resolution_scale": False,- "sg_rework_safe_render_state": False,- "sg_rework_reset_controls": False,- "sg_rework_sdxl_registration": False,+GRADUATED_FEATURE_DEFAULTS = {+ "qwen_use_confidence_context": False,"sg_rework_acquisition_quality": False,- "sg_rework_initial_view_priority": False,"sg_rework_projection_guard": False,- "sg_rework_projection_rebuild": False,- "sg_rework_projection_geometry": False,- "sg_rework_consistent_frame": False,- "sg_rework_workflow_validation": False,- "sg_rework_qwen_workflow": False,- "qwen_global_style_vlm_only": False,- "qwen_latent_locked_context": False,- "sg_rework_final_display": False,- "qwen_use_confidence_context": False,- "qwen_regularize_context_mask": False,- "qwen_use_projection_write_masks": False,- "qwen_reject_residual_fallback": False,- "sg_texel_ownership": False,- "sg_auto_view_sequence": False,- "sg_freeze_ownership_after_generation": False,- # Legacy projection used abs(dot), i.e. two-sided/backface contribution."sg_allow_backface_projection": True,}+EXPERIMENTAL_FEATURE_DEFAULTS = dict.fromkeys((+ "sg_rework_aligned_resolution", "sg_rework_full_resolution_scale",+ "sg_rework_final_display", "qwen_global_style_vlm_only",+ "qwen_context_vlm_only", "qwen_latent_locked_context",+ "qwen_latent_lock_neutral_fill", "qwen_regularize_context_mask",+ "qwen_use_projection_write_masks", "qwen_reject_residual_fallback",+ "sg_auto_view_sequence",+), False)+TEXTURING_DEFAULTS = {+ **GRADUATED_FEATURE_DEFAULTS, **EXPERIMENTAL_FEATURE_DEFAULTS,+}+++def experiments_enabled(context=None):+ """Fail closed when the addon is absent, including background helpers."""+ try:+ if context is None:+ import bpy+ context = bpy.context+ addon = context.preferences.addons.get(__package__)+ return bool(addon and addon.preferences.enable_texturing_experiments)+ except (AttributeError, ImportError, KeyError, ReferenceError):+ return False+++def experimental_enabled(scene, name, context=None):+ """Saved switches are effective only while the application gate permits."""+ if name not in EXPERIMENTAL_FEATURE_DEFAULTS:+ raise ValueError(f"Not a texturing experiment: {name}")+ return experiments_enabled(context) and bool(getattr(scene, name, False))-def all_rework_features_disabled(scene):- """Return True when *scene* is configured for the legacy baseline."""- return all(- getattr(scene, name, default) == default- for name, default in TEXTURING_REWORK_DEFAULTS.items()- )+def active_experiments(scene, context=None):+ if not experiments_enabled(context):+ return []+ return [name for name in EXPERIMENTAL_FEATURE_DEFAULTS if getattr(scene, name, False)]diff --git a/stablegen/texturing/confidence.py b/stablegen/texturing/confidence.pyindex 18f21d7..10a43ee 100644--- a/stablegen/texturing/confidence.py+++ b/stablegen/texturing/confidence.py@@ -1,4 +1,4 @@-"""Confidence, ownership, and sequencing primitives for sequential texturing.+"""Confidence and sequencing primitives for sequential texturing.The functions in this module intentionally avoid Blender imports. The liveshader graph and the baked pipeline use the same rules, while unit tests can@@ -13,29 +13,6 @@ from typing import Iterable, Sequenceimport numpy as np-def _gaussian_blur(image, sigma):- """Use OpenCV when available, with a deterministic NumPy test fallback."""- sigma = max(0.1, float(sigma))- try:- import cv2- return cv2.GaussianBlur(image, (0, 0), sigma)- except ImportError:- radius = max(1, int(math.ceil(3.0 * sigma)))- coordinates = np.arange(-radius, radius + 1, dtype=np.float32)- kernel = np.exp(-(coordinates * coordinates) / (2.0 * sigma * sigma))- kernel /= kernel.sum()-- def convolve_axis(values, axis):- pad = [(0, 0)] * values.ndim- pad[axis] = (radius, radius)- padded = np.pad(values, pad, mode="reflect")- return np.apply_along_axis(- lambda row: np.convolve(row, kernel, mode="valid"),- axis,- padded,- )-- return convolve_axis(convolve_axis(image, 0), 1)def acquisition_quality(@@ -49,7 +26,7 @@ def acquisition_quality(Each factor describes the camera that originally produced the colour.Calling this function on a re-rendered/copying camera is therefore a policy- error; copied pixels retain their prior owner quality instead.+ error; copied pixels retain their prior source quality instead."""factors = [visibility,@@ -85,113 +62,17 @@ def best_source_quality(qualities, write_masks=None):return np.max(accepted, axis=0)-def resolve_ownership(- qualities,- write_masks=None,- *,- trust_threshold=0.7,- replacement_margin=0.05,- allow_trusted_replacement=False,- initial_priority_strength=0.0,-):- """Resolve a single high-frequency source owner for every sample.- Uncovered and untrusted samples remain replaceable. Trusted samples lock- unless quality upgrades are explicitly enabled. Initial-view priority is- applied only as extra replacement margin for an already-trusted early- owner; it never changes acquisition quality or promotes grazing coverage.- """- q = np.asarray(qualities, dtype=np.float32)- if q.ndim < 1:- raise ValueError("qualities must contain a camera axis")- if write_masks is None:- writes = np.ones_like(q, dtype=bool)- else:- writes = np.asarray(write_masks) > 0- if writes.shape != q.shape:- raise ValueError("write_masks must match qualities")-- q = np.where(writes, np.clip(q, 0.0, 1.0), 0.0)- sample_shape = q.shape[1:]- owner = np.full(sample_shape, -1, dtype=np.int32)- owner_quality = np.zeros(sample_shape, dtype=np.float32)- threshold = float(np.clip(trust_threshold, 0.0, 1.0))- base_margin = max(0.0, float(replacement_margin))- priority = float(np.clip(initial_priority_strength, 0.0, 1.0))- count = q.shape[0]-- for camera_index in range(count):- new_q = q[camera_index]- has_write = writes[camera_index] & (new_q > 0.0)- uncovered = owner < 0- owner_trusted = owner_quality >= threshold-- # Earlier reliable owners receive an additional margin. This is- # deliberately indexed by the current owner, not by the candidate.- if count > 1:- owner_rank = np.clip(owner, 0, count - 1) / float(count - 1)- else:- owner_rank = np.zeros(sample_shape, dtype=np.float32)- priority_margin = priority * (1.0 - owner_rank) * 0.25- quality_upgrade = new_q > owner_quality + base_margin + priority_margin-- replace = has_write & (- uncovered- | (~owner_trusted)- | (bool(allow_trusted_replacement) & quality_upgrade)- )- owner[replace] = camera_index- owner_quality[replace] = new_q[replace]- coverage = owner >= 0- trusted = coverage & (owner_quality >= threshold)- return {- "owner": owner,- "owner_quality": owner_quality,- "trusted": trusted,- "coverage": coverage,- }---def trusted_repair_masks(owner_quality, visible_target, trust_threshold=0.7):+def trusted_repair_masks(source_quality, visible_target, trust_threshold=0.7):"""Return explicit trusted and repair masks without inspecting RGB."""- quality = np.asarray(owner_quality, dtype=np.float32)+ quality = np.asarray(source_quality, dtype=np.float32)visible = np.asarray(visible_target) > 0trusted = visible & (quality >= float(trust_threshold))repair = visible & ~trustedreturn trusted, repair-def low_frequency_seam_blend(images, owner, transition_mask, sigma=8.0):- """Blend only low-frequency colour inside a narrow ownership transition.-- High-frequency detail always comes from the discrete owner image. The- returned image changes only the low-pass component in ``transition_mask``.- """- stack = np.asarray(images)- owner = np.asarray(owner, dtype=np.int32)- transition = np.asarray(transition_mask) > 0- if stack.ndim != 4 or stack.shape[-1] < 3:- raise ValueError("images must be camera x height x width x channels")- if owner.shape != stack.shape[1:3]:- raise ValueError("owner dimensions must match images")-- yy, xx = np.indices(owner.shape)- safe_owner = np.clip(owner, 0, stack.shape[0] - 1)- hard = stack[safe_owner, yy, xx].astype(np.float32)- low_stack = np.stack([- _gaussian_blur(image.astype(np.float32), sigma)- for image in stack- ])- owner_low = low_stack[safe_owner, yy, xx]- average_low = np.mean(low_stack, axis=0)- result = hard.copy()- result[transition] = np.clip(- hard[transition] - owner_low[transition] + average_low[transition],- 0,- 255 if np.issubdtype(stack.dtype, np.integer) else 1.0,- )- return result.astype(stack.dtype)def camera_direction_from_matrix(matrix_rows) -> np.ndarray:diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.pyindex bffae11..575bae7 100644--- a/stablegen/texturing/generator.py+++ b/stablegen/texturing/generator.py@@ -1,3 +1,4 @@+from ..feature_flags import experimental_enabled"""ComfyUI texture generation operator (core pipeline)."""import os@@ -54,7 +55,7 @@ from .pose_lock import (restore_active_texturing_frame,set_active_texturing_frame,)-from ..feature_flags import TEXTURING_REWORK_DEFAULTS+from ..feature_flags import active_experimentsimport websocket@@ -94,12 +95,12 @@ class Regenerate(bpy.types.Operator):return Truedef execute(self, context):- """- Executes the operator.- :param context: Blender context.- :return: {'FINISHED'}"""-+ Executes the operator.+ :param context: Blender context.+ :return: {'FINISHED'}+ """+self._original_overwrite_material = context.scene.overwrite_material# Set the flag to reprojectcontext.scene.generation_mode = 'regenerate_selected'@@ -124,7 +125,7 @@ class Regenerate(bpy.types.Operator):for obj in self._to_texture:if not obj.active_material or not obj.active_material.use_nodes:continue-+nodes = obj.active_material.node_tree.nodesfor node in nodes:# OSL script nodes (internal or external)@@ -146,13 +147,13 @@ class Regenerate(bpy.types.Operator):# Switch to modal and wait for completionprint("[StableGen] Going modal")return {'RUNNING_MODAL'}-+def modal(self, context, event):- """- Handles modal events.- :param context: Blender context.- :param event: Blender event.- :return: {'PASS_THROUGH'}+ """+ Handles modal events.+ :param context: Blender context.+ :param event: Blender event.+ :return: {'PASS_THROUGH'}"""if event.type == 'TIMER':running = False@@ -192,10 +193,10 @@ class Reproject(bpy.types.Operator):return Truedef execute(self, context):- """- Executes the operator.- :param context: Blender context.- :return: {'FINISHED'}+ """+ Executes the operator.+ :param context: Blender context.+ :return: {'FINISHED'}"""if context.scene.texture_objects == 'all':to_texture = [obj for obj in bpy.context.view_layer.objects if obj.type == 'MESH' and not obj.hide_get()]@@ -226,7 +227,7 @@ class Reproject(bpy.types.Operator):f"generated image.")print(f"[StableGen] {image_path} does not exist")return {'CANCELLED'}-+self._original_method = context.scene.generation_methodself._original_overwrite_material = context.scene.overwrite_material# Set the flag to reproject@@ -347,12 +348,12 @@ class Reproject(bpy.types.Operator):self.report({'INFO'}, "Reprojection complete.")return {'FINISHED'}return {'PASS_THROUGH'}-+class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):"""Generate textures using ComfyUI (to all mesh objects using all cameras in the scene)-+- Multiple modes are available. Choose by setting Generation Mode in the UI.- This includes texture generation and projection to the mesh objects.- By default, the generated textures will only be visible in the Rendered viewport shading mode."""@@ -463,7 +464,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):bpy.app.timers.register(_callback)self._wait_event.wait()self._wait_event.clear()-+def _get_qwen_context_colors(self, context):fallback = (1.0, 0.0, 1.0)background = (1.0, 0.0, 1.0)@@ -522,7 +523,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):object_ids.astype(np.int32) * 256 + material_ids.astype(np.int32))- if getattr(context.scene, 'qwen_regularize_context_mask', False):+ if experimental_enabled(context.scene, 'qwen_regularize_context_mask'):repair_mask = regularize_repair_mask(repair_mask,threshold=127,@@ -580,7 +581,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):def _reject_qwen_fallback_writes(self, context, camera_id, image_path, fallback_color):"""Keep residual sentinel pixels out of the projection material."""- if not getattr(context.scene, "qwen_reject_residual_fallback", False):+ if not experimental_enabled(context.scene, 'qwen_reject_residual_fallback'):returnif context.scene.qwen_context_render_mode not in {'REPLACE_STYLE', 'ADDITIONAL'}:return@@ -753,10 +754,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):return Truedef execute(self, context):- """- Executes the operator.- :param context: Blender context.- :return: {'RUNNING_MODAL'}+ """+ Executes the operator.+ :param context: Blender context.+ :return: {'RUNNING_MODAL'}"""if ComfyUIGenerate._is_running:self.cancel_generate(context)@@ -766,11 +767,11 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):# Clear the upload cache at the start of a new generationself._uploaded_images_cache.clear()-+# Timestamp for output directoryif context.scene.generation_mode == 'standard':context.scene.output_timestamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")-+# If UV inpainting and we're in prompt collection mode, collect prompts first.if context.scene.generation_method == 'uv_inpaint' and self.show_prompt_dialog:self._object_prompts[self.current_object_name] = self.current_object_prompt@@ -782,21 +783,18 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):else:self.show_prompt_dialog = False-+context.scene.generation_status = 'running'context.scene.sg_last_gen_error = Falsecontext.scene.sg_last_gen_error_message = ""ComfyUIGenerate._is_running = Trueprint("[StableGen] Executing ComfyUI Generation")- enabled_experiments = [- name for name, default in TEXTURING_REWORK_DEFAULTS.items()- if getattr(context.scene, name, default) != default- ]+ enabled_experiments = active_experiments(context.scene, context)if enabled_experiments:print("[StableGen] Texturing experiments enabled: " + ", ".join(enabled_experiments))else:- print("[StableGen] Texturing feature set: legacy rigging-branch baseline")+ print("[StableGen] Standard texturing; no research options active")if context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein') and not context.scene.generation_mode == 'project_only':context.scene.generation_method = 'sequential' # Force sequential for edit models@@ -810,7 +808,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):self._original_resolution_percentage = render.resolution_percentageself._original_resolution_x = render.resolution_xself._original_resolution_y = render.resolution_y- if getattr(context.scene, 'sg_rework_full_resolution_scale', False):+ if experimental_enabled(context.scene, 'sg_rework_full_resolution_scale'):render.resolution_percentage = 100resolution_x = render.resolution_x@@ -836,9 +834,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):upper_bound = int(target_px * 1.2)lower_bound = int(target_px * 0.8)- use_aligned_search = getattr(- context.scene, 'sg_rework_aligned_resolution', False- )+ use_aligned_search = experimental_enabled(context.scene, 'sg_rework_aligned_resolution')if context.scene.auto_rescale and ((total_pixels > upper_bound or total_pixels < lower_bound) or (resolution_x % align_step != 0 or resolution_y % align_step != 0)):if use_aligned_search:render.resolution_x, render.resolution_y = choose_aligned_resolution(@@ -868,7 +864,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):render.resolution_x = self._original_resolution_xrender.resolution_y = self._original_resolution_yreturn {'CANCELLED'}- use_camera_plan = getattr(context.scene, 'sg_rework_camera_plan', False)+ use_camera_plan = Trueorder_names = []if context.scene.sg_use_custom_camera_order and len(context.scene.sg_camera_order) > 0:order_names = [item.name for item in context.scene.sg_camera_order]@@ -904,14 +900,13 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):pose_locked = self._begin_texturing_pose_lock(context, pose_lock_targets)- if (not pose_locked- and getattr(context.scene, 'sg_rework_consistent_frame', False)):+ if (not pose_locked):self._original_texturing_frame = context.scene.frame_currentcontext.scene.frame_set(int(getattr(context.scene, 'sg_texturing_frame', 1)))if (context.scene.generation_mode == 'standard'and not order_names- and getattr(context.scene, 'sg_auto_view_sequence', False)):+ and experimental_enabled(context.scene, 'sg_auto_view_sequence')):anchor_name = getattr(context.scene, 'sg_anchor_camera', '')if not anchor_name and context.scene.camera:anchor_name = context.scene.camera.name@@ -1038,7 +1033,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):self._selected_camera_ids = [i for i, cam in enumerate(self._cameras) if cam in bpy.context.selected_objects] #TESTif len(self._selected_camera_ids) == 0:self._selected_camera_ids = list(range(len(self._cameras))) # All cameras selected if none are selected-+# Check if there is at least one ControlNet unitcontrolnet_units = getattr(context.scene, "controlnet_units", [])if not controlnet_units and not (context.scene.use_flux_lora and context.scene.model_architecture == 'flux1') and context.scene.model_architecture != 'flux2_klein':@@ -1051,11 +1046,11 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):render.resolution_y = self._original_resolution_yself._restore_texturing_pose(context)return {'CANCELLED'}-+# If there are curves within the scene, warn the userif any(obj.type == 'CURVE' for obj in bpy.context.view_layer.objects):self.report({'WARNING'}, "Curves detected in the scene. Consider using 'Convert Curves to Mesh' in the Tools section.")-+if context.scene.generation_mode == 'project_only':print(f"[StableGen] Reprojecting images for {len(self._cameras)} cameras")elif context.scene.generation_mode == 'standard':@@ -1126,14 +1121,14 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):# UV inpainting mode preparationif context.scene.generation_method == 'uv_inpaint':# Check if there are baked textures for all objects-+if self.show_prompt_dialog:# Start the prompt collection process with the first objectif not self._object_prompts: # Only if prompts haven't been collectedself.current_object_name = self._to_texture[0].nameself._restore_texturing_pose(context)return context.window_manager.invoke_props_dialog(self, width=400)-+# Continue with normal execution if all prompts are collectedfor obj in self._to_texture:# Use get_file_path to check for baked texture existence@@ -1149,7 +1144,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):texture_resolution=2048,)bake_texture(context, obj, texture_resolution=2048, output_dir=get_dir_path(context, "baked"))-+# Check if the material is compatible (uses projection shader)active_material = obj.active_materialif not active_material or not active_material.use_nodes:@@ -1180,7 +1175,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):render.resolution_y = self._original_resolution_yself._restore_texturing_pose(context)return {'CANCELLED'}-+# Export visibility masks for each objectself._stage = f"Computing Visibility ({obj.name})"export_visibility(context, None, obj)@@ -1203,7 +1198,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):ref_rgb=ref_np,scene=context.scene,)-+self.prompt_text = context.scene.comfyui_promptself._progress = 0.0@@ -1242,25 +1237,25 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):# Add modal timercontext.window_manager.modal_handler_add(self)- self._timer = context.window_manager.event_timer_add(0.5, window=context.window)- print("[StableGen] Starting thread")+ self._timer = context.window_manager.event_timer_add(0.5, window=context.window)+ print("[StableGen] Starting thread")if context.scene.generation_method == 'grid':self._thread = threading.Thread(target=self.async_generate, args=(context,))else:_start_cam = self._current_image # 0 normally, first_selected for sequential regenself._thread = threading.Thread(target=self.async_generate, args=(context, _start_cam))-+self._thread.start()return {'RUNNING_MODAL'}def modal(self, context, event):- """- Handles modal events.- :param context: Blender context.- :param event: Blender event.- :return: {'PASS_THROUGH'}+ """+ Handles modal events.+ :param context: Blender context.+ :param event: Blender event.+ :return: {'PASS_THROUGH'}"""if event.type == 'TIMER':redraw_ui(context)@@ -1282,7 +1277,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):# after the worker exits, before either success or error can# return from the operator.try:- if (getattr(context.scene, 'sg_rework_reset_controls', False)+ if (Trueor not self._error):self._reset_projection_state(context)except Exception as reset_error:@@ -1314,7 +1309,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):return {'CANCELLED'}if not context.scene.generation_mode == 'project_only':self.report({'INFO'}, "Generation complete.")-+# If viewport rendering mode is 'Rendered' and mode is 'regenerate_selected', switch to 'Solid' and then back to 'Rendered' to refresh the viewportif context.scene.generation_mode == 'regenerate_selected' and context.area.spaces.active.shading.type == 'RENDERED':context.area.spaces.active.shading.type = 'SOLID'@@ -1343,15 +1338,15 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):bpy.ops.wm.save_as_mainfile(filepath=blend_file_path, copy=True)remove_empty_dirs(context)return {'FINISHED'}-+# Handle prompt collection for UV inpaintingif context.scene.generation_method == 'uv_inpaint' and self.show_prompt_dialog:- current_index = next((i for i, obj in enumerate(self._to_texture)+ current_index = next((i for i, obj in enumerate(self._to_texture)if obj.name == self.current_object_name), -1)-+# Store the current promptself._object_prompts[self.current_object_name] = self.current_object_prompt-+# Move to next object or finishif current_index < len(self._to_texture) - 1:self.current_object_name = self._to_texture[current_index + 1].name@@ -1365,40 +1360,6 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):def _reset_projection_state(self, context):"""Restore final display controls after every worker termination."""- if not getattr(context.scene, 'sg_rework_reset_controls', False):- # Rigging-branch behavior: update only the original OSL/native- # inputs. This intentionally does not touch the normalized- # SharpW nodes or rebake attributes; the corrected behavior is a- # separate opt-in experiment.- applicable = (- getattr(self, '_generation_method_on_start', None) == 'sequential'- or context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')- )- if context.scene.discard_factor_generation_only and applicable:- angle = context.scene.discard_factor_after_generation- for obj in getattr(self, '_to_texture', ()):- material = getattr(obj, 'active_material', None)- if not material or not material.use_nodes:- continue- for node in material.node_tree.nodes:- if node.type == 'SCRIPT' and 'AngleThreshold' in node.inputs:- node.inputs['AngleThreshold'].default_value = angle- elif (node.type == 'MATH' and node.operation == 'LESS_THAN'- and node.label.startswith('AngleThreshold-')):- node.inputs[1].default_value = angle- if context.scene.weight_exponent_generation_only and applicable:- exponent = context.scene.weight_exponent_after_generation- for obj in getattr(self, '_to_texture', ()):- material = getattr(obj, 'active_material', None)- if not material or not material.use_nodes:- continue- for node in material.node_tree.nodes:- if node.type == 'SCRIPT' and 'Power' in node.inputs:- node.inputs['Power'].default_value = exponent- elif (node.type == 'MATH' and node.operation == 'POWER'- and node.label == 'power_weight'):- node.inputs[1].default_value = exponent- returnapplicable = (getattr(self, '_generation_method_on_start', None) == 'sequential'@@ -1436,12 +1397,12 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):angle_threshold=reset_angle,power_exponent=reset_exponent,)-+def cancel_generate(self, context):- """- Cancels the generation process using api.interupt().- :param context: Blender context.- :return: None+ """+ Cancels the generation process using api.interupt().+ :param context: Blender context.+ :return: None"""server_address = context.preferences.addons[_ADDON_PKG].preferences.server_addressclient_id = str(uuid.uuid4())@@ -1606,7 +1567,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):and context.scene.qwen_refine_use_depth)or (getattr(context.scene, 'sg_rework_projection_guard', False)and context.scene.generation_method == 'sequential')- or (getattr(context.scene, 'qwen_regularize_context_mask', False)+ or (experimental_enabled(context.scene, 'qwen_regularize_context_mask')and context.scene.generation_method == 'sequential'))if need_depth and context.scene.generation_method != 'uv_inpaint':@@ -1742,10 +1703,10 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):returndef async_generate(self, context, camera_id = None):- """- Asynchronously generates the image using ComfyUI.- :param context: Blender context.- :return: None+ """+ Asynchronously generates the image using ComfyUI.+ :param context: Blender context.+ :return: None"""self._error = Noneself._pbr_maps = {} # camera_key → {map_name: file_path}@@ -1868,7 +1829,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):else:self._stage = "Uploading to Server"self._progress = 0-+# Generate the imageif context.scene.generation_method in ('refine', 'local_edit'):if context.scene.model_architecture == 'flux1':@@ -1990,7 +1951,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):image_path = get_file_path(context, "generated", camera_id=camera_id, material_id=self._material_id)else: # Grid mode initial generationimage_path = get_file_path(context, "generated", filename="generated_image_grid") # Save grid to a specific name-+with open(image_path, 'wb') as f:f.write(image)@@ -2005,11 +1966,11 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):fallback_color,)-+# Use hack to re-generate the image using IPAdapter to match IPAdapter styleif camera_id == 0 and (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate' or context.scene.generation_method in ('refine', 'local_edit'))\and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate and not context.scene.use_ipadapter and context.scene.sequential_ipadapter_mode == 'first':-+# Restore original strengthsif context.scene.sequential_ipadapter_regenerate_wo_controlnet:for i, unit in enumerate(context.scene.controlnet_units):@@ -2109,7 +2070,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):with open(image_path, 'wb') as f:f.write(image)self._threads_left = 0-+except Exception as e:self._error = str(e)traceback.print_exc()@@ -2179,7 +2140,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):# generation-only Qwen write masks. This is intentionally# opt-in so the default remains byte-for-byte compatible with# the rigging-branch sequential material behavior.- if getattr(context.scene, 'sg_rework_final_display', False):+ if experimental_enabled(context.scene, 'sg_rework_final_display'):original_method = context.scene.generation_methodtry:context.scene.generation_method = 'separate'@@ -2201,7 +2162,6 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):)if getattr(context.scene, 'pbr_auto_lighting', False):_pbr_setup_studio_lights(context, self._to_texture)- self._freeze_projection_ownership(context)return Noneself._stage = "Projecting Image"redraw_ui(context)@@ -2230,10 +2190,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):if getattr(context.scene, 'pbr_auto_lighting', False):_pbr_setup_studio_lights(context, self._to_texture)- self._freeze_projection_ownership(context)return None-+if context.scene.view_blend_use_color_match and self._to_texture:self._stage = "Matching Colors"# Use the first object in the target list as the color reference@@ -2253,7 +2212,12 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):scene=context.scene,)- bpy.app.timers.register(image_project_callback)+ # Keep the worker alive until projection finishes. Otherwise modal+ # cleanup can restore sequential mode before this callback executes,+ # causing it to skip the entire reproject (and hide projection errors).+ self._run_on_main_thread(image_project_callback)+ if self._error:+ return# Update seed based on control parameterif context.scene.control_after_generate == 'increment':@@ -2263,29 +2227,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):elif context.scene.control_after_generate == 'randomize':context.scene.seed = np.random.randint(0, 1000000)- def _freeze_projection_ownership(self, context):- """Bake live camera ownership into production UV textures when enabled."""- ownership_active = bool(- getattr(context.scene, 'sg_texel_ownership', False)- )- if not (ownership_active- and getattr(context.scene, 'sg_freeze_ownership_after_generation', False)):- return- self._stage = "Freezing Texture Ownership"- output_dir = get_dir_path(context, "baked")- prepare_baking(context)- for obj in self._to_texture:- if bake_texture(- context,- obj,- texture_resolution=2048,- view_transform='Standard',- output_dir=output_dir,- ):- baked_path = os.path.join(output_dir, f"{obj.name}.png")- flatten_projection_material_for_refine(context, obj, baked_path)- obj["sg_ownership_frozen"] = True- obj["sg_ownership_texture"] = baked_path+def draw(self, context):layout = self.layout@@ -2309,84 +2251,14 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):return self.execute(context)return context.window_manager.invoke_props_dialog(self, width=400)return self.execute(context)-- def _export_depthmap_legacy(self, context, camera_id=None):- """Rigging-branch depth exporter, intentionally kept unchanged."""- print("[StableGen] Exporting depth map")- original_engine = bpy.context.scene.render.engine- original_view_transform = bpy.context.scene.view_settings.view_transform- original_film_transparent = bpy.context.scene.render.film_transparent- original_use_compositing = bpy.context.scene.render.use_compositing- original_filepath = bpy.context.scene.render.filepath-- ensure_texturing_frame(- bpy.context.scene, honor_consistent=False- )-- output_dir = get_dir_path(context, "controlnet")["depth"]- output_file = f"depth_map{camera_id}" if camera_id is not None else "depth_map"-- if not os.path.exists(output_dir):- os.makedirs(output_dir)-- view_layer = bpy.context.view_layer- bpy.context.scene.render.engine = 'BLENDER_WORKBENCH'- bpy.context.scene.display_settings.display_device = 'sRGB'- bpy.context.scene.view_settings.view_transform = 'Raw'-- original_pass_z = view_layer.use_pass_z- view_layer.use_pass_z = True-- bpy.context.scene.render.use_compositing = True- bpy.context.scene.use_nodes = True- node_tree = get_compositor_node_tree(bpy.context.scene)- nodes = node_tree.nodes- links = node_tree.links- compositor_state = _prepare_compositor_render(context.scene, node_tree)-- bpy.context.scene.render.image_settings.file_format = 'PNG'-- for node in nodes:- nodes.remove(node)-- render_layers_node = nodes.new(type="CompositorNodeRLayers")- render_layers_node.location = (0, 0)-- normalize_node = nodes.new(type="CompositorNodeNormalize")- normalize_node.location = (200, 0)- links.new(render_layers_node.outputs["Depth"], normalize_node.inputs[0])-- invert_node = nodes.new(type="CompositorNodeInvert")- invert_node.location = (400, 0)- color_input = invert_node.inputs["Color"] if "Color" in invert_node.inputs else invert_node.inputs[1]- links.new(normalize_node.outputs[0], color_input)-- output_node = nodes.new(type="CompositorNodeOutputFile")- output_node.location = (600, 0)- configure_output_node_paths(output_node, output_dir, output_file)- links.new(invert_node.outputs[0], output_node.inputs[0])- try:- bpy.ops.render.render(write_still=True)- finally:- _finish_compositor_render(node_tree, compositor_state)- bpy.context.scene.view_settings.view_transform = 'Standard'- print(f"[StableGen] Depth map saved to: {os.path.join(output_dir, output_file)}.png")-- bpy.context.scene.render.engine = original_engine- bpy.context.scene.view_settings.view_transform = original_view_transform- bpy.context.scene.render.film_transparent = original_film_transparent- bpy.context.scene.render.use_compositing = original_use_compositing- bpy.context.scene.render.filepath = original_filepath- view_layer.use_pass_z = original_pass_z-- def _export_depthmap_impl(self, context, camera_id=None):- """- Exports the depth map of the scene.- :param context: Blender context.- :param camera_id: ID of the camera.- :return: None+ def _export_depthmap_impl(self, context, camera_id=None, guard_scale=1):+ """+ Exports the depth map of the scene.+ :param context: Blender context.+ :param camera_id: ID of the camera.+ :return: None"""print("[StableGen] Exporting depth map")ensure_texturing_frame(context.scene)@@ -2452,7 +2324,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):nodes = node_tree.nodeslinks = node_tree.linkscompositor_state = _prepare_compositor_render(context.scene, node_tree)-+# Ensure animation format is not selectedbpy.context.scene.render.image_settings.file_format = 'PNG'@@ -2509,7 +2381,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):)use_part_ids = (use_projection_guard- or getattr(context.scene, 'qwen_regularize_context_mask', False)+ or experimental_enabled(context.scene, 'qwen_regularize_context_mask'))has_object_ids = use_part_ids and _add_index_output("IndexOB", f"object_id{camera_id}", -200@@ -2591,7 +2463,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):bpy.context.scene.view_settings.view_transform = 'Standard'print(f"[StableGen] Depth map saved to: {os.path.join(output_dir, output_file)}.png")-+# Restore original settingsbpy.context.scene.render.engine = original_enginebpy.context.scene.view_settings.view_transform = original_view_transform@@ -2601,25 +2473,6 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):view_layer.use_pass_z = original_pass_zdef export_depthmap(self, context, camera_id=None):- use_legacy_depth = not any((- getattr(context.scene, 'sg_rework_safe_render_state', False),- getattr(context.scene, 'sg_rework_projection_guard', False),- getattr(context.scene, 'qwen_regularize_context_mask', False),- getattr(context.scene, 'sg_rework_consistent_frame', False),- ))- if use_legacy_depth:- # The reworked depth/ID exporter deliberately disables output- # dithering because categorical ID passes must remain exact. Some- # files produced while that path was active therefore retain a- # scene dither value of zero. The legacy Workbench exporter used- # Blender's default 1.0 dither, which changes roughly ten percent- # of 8-bit depth samples by one LSB and makes its PNGs materially- # larger. Normalize only the all-off compatibility call, then- # restore the user's scene value so old/new depth inputs are- # deterministic even when the source .blend was previously used- # with rework features.- with _legacy_render_dither(context.scene):- return self._export_depthmap_legacy(context, camera_id=camera_id)meshes = [obj for obj in context.view_layer.objects if obj.type == 'MESH']with _RenderStateTransaction(context, meshes):return self._export_depthmap_impl(context, camera_id=camera_id)@@ -2632,9 +2485,6 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator)::param camera_id: ID of the camera.:return: None"""- if not getattr(context.scene, 'sg_rework_safe_render_state', False):- with _legacy_render_dither(context.scene):- return self._export_normal_impl(context, camera_id=camera_id)meshes = [obj for obj in context.view_layer.objects if obj.type == 'MESH']with _RenderStateTransaction(context, meshes):return self._export_normal_impl(context, camera_id=camera_id)@@ -2856,7 +2706,7 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):context.scene.sequential_ipadapter_mode == 'recent' and(context.scene.sequential_ipadapter or context.scene.model_architecture in ('qwen_image_edit', 'flux2_klein')))-+temp_image_path = Noneupload_path = local_path@@ -2870,11 +2720,11 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):if desaturate > 0.0:enhancer = ImageEnhance.Color(img)img = enhancer.enhance(1.0 - desaturate)-+if contrast > 0.0:enhancer = ImageEnhance.Contrast(img)img = enhancer.enhance(1.0 - contrast)-+# Save to a temporary file for uploadtemp_dir = get_dir_path(context, "temp")os.makedirs(temp_dir, exist_ok=True)diff --git a/stablegen/texturing/graph_validation.py b/stablegen/texturing/graph_validation.pyindex d6cd079..f7c9b26 100644--- a/stablegen/texturing/graph_validation.py+++ b/stablegen/texturing/graph_validation.py@@ -72,14 +72,22 @@ def qwen_reference_latent_slots(context_mode: str,is_initial_image: bool,global_style_vlm_only: bool,+ context_vlm_only: bool = False,) -> tuple[str, ...]:"""Return Qwen image slots that should receive spatial reference latents.- Image 3 remains connected to ``TextEncodeQwenImageEditPlus`` when the- VLM-only experiment is active; omitting it here removes only its manual- full-resolution ReferenceLatent conditioning.+ Omitted slots remain connected to ``TextEncodeQwenImageEditPlus``.+ These experiments remove only manual full-resolution ReferenceLatent+ conditioning. Image 2 is context only on later views in a context mode;+ initial/external style references must keep their existing behavior."""slots = ["image1", "image2", "image3"]+ if (+ context_vlm_only+ and context_mode in {"REPLACE_STYLE", "ADDITIONAL"}+ and not is_initial_image+ ):+ slots.remove("image2")if (global_style_vlm_onlyand context_mode == "ADDITIONAL"@@ -97,6 +105,7 @@ def attach_qwen_latent_lock(context_image_name: str,repair_mask_name: str,start_node_id: int = 650,+ neutral_fill: bool = False,) -> dict[str, str]:"""Attach sampler-level Qwen context inpainting to ``prompt``.@@ -109,6 +118,12 @@ def attach_qwen_latent_lock(slots are dynamically reordered between Replace Style and Additionalmodes; keeping the latent-lock path separate prevents semantic slot changesfrom silently changing which image is protected.++ Optional neutral fill removes the repair sentinel before VAE encoding.+ Encoding magenta directly can contaminate protected boundary latents even+ when the sampler mask is correct. The inpaint encoder uses neutral gray in+ repair pixels; grow_mask_by=0 and the explicit mask node preserve the same+ protected region as the original experiment."""sampler_node_id = str(sampler_node_id)vae_node_id = str(vae_node_id)@@ -163,6 +178,13 @@ def attach_qwen_latent_lock("class_type": "ImageToMask","_meta": {"title": "Qwen Latent Lock - Image to Mask"},}+ if neutral_fill:+ prompt[context_encode]["class_type"] = "VAEEncodeForInpaint"+ prompt[context_encode]["inputs"].update({+ "mask": [image_to_mask, 0],+ "grow_mask_by": 0,+ })+ prompt[context_encode]["_meta"]["title"] = "Qwen Latent Lock - Neutral Repair Fill"prompt[set_noise_mask] = {"inputs": {"samples": [context_encode, 0],diff --git a/stablegen/texturing/pose_lock.py b/stablegen/texturing/pose_lock.pyindex 992351d..89fbb0e 100644--- a/stablegen/texturing/pose_lock.py+++ b/stablegen/texturing/pose_lock.py@@ -79,8 +79,7 @@ def ensure_texturing_frame(if active_frame is not None:target = int(active_frame)elif (force_configured- or (honor_consistent- and getattr(scene, 'sg_rework_consistent_frame', False))):+ or (honor_consistent)):target = int(getattr(scene, 'sg_texturing_frame', legacy_frame))else:target = int(legacy_frame)diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.pyindex 4137225..f044c59 100644--- a/stablegen/texturing/projection.py+++ b/stablegen/texturing/projection.py@@ -1,3 +1,4 @@+from ..feature_flags import experimental_enabledimport bpyimport osfrom math import atan, tan, pi@@ -15,8 +16,6 @@ def _is_projection_mesh(obj):"""Consistent render/visibility filter for production geometry."""if obj.type != 'MESH' or obj.hide_get():return False- if not getattr(bpy.context.scene, 'sg_rework_projection_geometry', False):- return Trueif obj.hide_render:return Falseif obj.get("sg_rig_helper", False) or obj.get("sg_exclude_texturing", False):@@ -48,51 +47,15 @@ def _scene_projection_scale(context):)-def _ensure_lowpass_texture(image_path, sigma=8.0):- """Create/update a low-pass companion used only for ownership seams."""- if not image_path or not os.path.exists(image_path):- return None- root, extension = os.path.splitext(image_path)- sigma_value = max(0.1, float(sigma))- sigma_key = f"{sigma_value:.2f}".replace('.', '_')- output_path = f"{root}_sg_lowpass_s{sigma_key}{extension or '.png'}"- try:- if (os.path.exists(output_path)- and os.path.getmtime(output_path) >= os.path.getmtime(image_path)):- return output_path- import cv2- source = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)- if source is None:- return None- result = source.copy()- channels = result[:, :, :3] if result.ndim == 3 else result- blurred = cv2.GaussianBlur(- channels, (0, 0), sigmaX=sigma_value- )- if result.ndim == 3:- result[:, :, :3] = blurred- else:- result = blurred- cv2.imwrite(output_path, result)- return output_path- except Exception as error:- print(f"[StableGen] Low-frequency seam texture failed: {error}")- return Nonedef _camera_world_location(camera):"""Return camera position in world space (including parent transforms)."""- if getattr(bpy.context.scene, 'sg_rework_projection_geometry', False):- return camera.matrix_world.translation.copy()- return camera.location.copy()+ return camera.matrix_world.translation.copy()def _scene_ray_epsilon(context):"""Scale ray tolerances to the scene instead of assuming metre-sized assets."""- if not getattr(context.scene, 'sg_rework_projection_geometry', False):- # The legacy native graph used +0.01 ray length and +0.001 hit- # tolerance; callers multiply this base by ten for ray length.- return 0.001corners = []for obj in context.view_layer.objects:if not _is_projection_mesh(obj):@@ -197,8 +160,6 @@ def _bake_visibility_weights(filmh = filmw / aspectcamera_type = (camera.data.type- if getattr(scene, 'sg_rework_projection_geometry', False)- else 'PERSP')ortho_half_h = max(float(camera.data.ortho_scale) * 0.5, 1e-8)ortho_half_w = ortho_half_h * aspect@@ -209,15 +170,15 @@ def _bake_visibility_weights(np.array(cam_right, dtype=np.float64),np.array(cam_up_vec, dtype=np.float64),filmw, filmh,- float(camera.data.shift_x) if getattr(scene, 'sg_rework_projection_geometry', False) else 0.0,- float(camera.data.shift_y) if getattr(scene, 'sg_rework_projection_geometry', False) else 0.0,+ float(camera.data.shift_x),+ float(camera.data.shift_y),cam_loc, # keep mathutils Vector for BVH callscamera_type, ortho_half_w, ortho_half_h,))# Build scene-wide BVH for occlusion (matches ShaderNodeRaycast behaviour,# which checks ALL visible scene geometry, not just the current object).- use_corrected_geometry = getattr(scene, 'sg_rework_projection_geometry', False)+ use_corrected_geometry = Truedepsgraph = context.evaluated_depsgraph_get() if use_corrected_geometry else Nonescene_bm = bmesh.new()vert_offset = 0@@ -684,7 +645,6 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,shift_x_amount.operation = 'MULTIPLY'shift_x_amount.inputs[1].default_value = (2.0 * float(camera.data.shift_x)- if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0)links.new(filmw.outputs[0], shift_x_amount.inputs[0])centered_x = nodes.new("ShaderNodeMath")@@ -696,7 +656,6 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,shift_y_amount.operation = 'MULTIPLY'shift_y_amount.inputs[1].default_value = (2.0 * float(camera.data.shift_y)- if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0)links.new(filmh.outputs[0], shift_y_amount.inputs[0])centered_y = nodes.new("ShaderNodeMath")@@ -979,7 +938,6 @@ def create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_shift_x_amount.operation = 'MULTIPLY'shift_x_amount.inputs[1].default_value = (2.0 * float(camera.data.shift_x)- if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0)links.new(filmw.outputs[0], shift_x_amount.inputs[0])centered_x = nodes.new("ShaderNodeMath")@@ -991,7 +949,6 @@ def create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_shift_y_amount.operation = 'MULTIPLY'shift_y_amount.inputs[1].default_value = (2.0 * float(camera.data.shift_y)- if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0)links.new(filmh.outputs[0], shift_y_amount.inputs[0])centered_y = nodes.new("ShaderNodeMath")@@ -1096,6 +1053,8 @@ def project_image(stop_index=1000000,cameras=None,view_plan=None,+ force_rebuild=False,+ reuse_projection_uv=False,):"""Projects an image onto all mesh objects using UV Project Modifier.@@ -1395,11 +1354,6 @@ def project_image(v_off = -200 * idxall_w_outputs.append(_get_weight_output(weight_nodes[idx], v_off))- # Keep these unmodified source-camera acquisition qualities for- # ownership. Initial-view priority is applied later only as- # replacement resistance for a trusted owner; it must never turn- # poor grazing coverage into trusted context.- acquisition_outputs = list(all_w_outputs)# ── Step 3: Find per-pixel maximum ────────────────────────max_node = nodes_collection.new("ShaderNodeMath")@@ -1459,254 +1413,6 @@ def project_image(# Replace weight_nodes with sharpened-normalised nodesweight_nodes = powered_nodes- # Binary Qwen write masks and per-texel ownership solve different- # problems. Write masks prevent a later generated view from writing- # protected context; ownership selects exactly one camera for- # high-frequency detail and therefore creates harder territories.- # Keep ownership genuinely opt-in so disabling the UI toggle- # restores continuous weighted blending without disabling Qwen's- # protection masks.- use_confidence_ownership = bool(- getattr(context.scene, 'sg_texel_ownership', False)- )- legacy_blend = getattr(- context.scene, 'sg_ownership_blend_mode', 'OWNER'- ) == 'LEGACY'- if use_confidence_ownership and not legacy_blend:- # Sequential single-owner detail. Untrusted owners remain- # replaceable; trusted owners lock unless explicit quality- # upgrades are enabled.- owner_color = shaders[0]- owner_low = lowpass_tex_image_nodes[0]- seam_low = owner_low- owner_quality = acquisition_outputs[0]- margin = max(- 0.0,- float(getattr(context.scene, 'sg_texel_replacement_margin', 0.05)),- )- trust_threshold = float(getattr(- context.scene, 'qwen_trust_threshold', 0.7- ))- allow_upgrade = bool(getattr(- context.scene, 'sg_allow_trusted_replacement', False- ))- priority_strength = (- float(getattr(context.scene, 'early_priority_strength', 0.5))- if (getattr(context.scene, 'early_priority', False)- and getattr(context.scene, 'sg_rework_initial_view_priority', False))- else 0.0- )-- owner_camera = nodes_collection.new("ShaderNodeValue")- owner_camera.outputs[0].default_value = 0.0- owner_camera.label = "SGOwnerCamera-0"- owner_priority = nodes_collection.new("ShaderNodeValue")- owner_priority.outputs[0].default_value = priority_strength * 0.25- owner_priority.label = "SGOwnerPriority-0"-- for idx in range(1, len(shaders)):- new_quality = acquisition_outputs[idx]- old_owner_low = owner_low-- owner_trusted = nodes_collection.new("ShaderNodeMath")- owner_trusted.operation = 'GREATER_THAN'- owner_trusted.inputs[1].default_value = trust_threshold - 1e-7- owner_trusted.label = f"OwnerTrusted-{idx}"- links.new(owner_quality, owner_trusted.inputs[0])-- owner_untrusted = nodes_collection.new("ShaderNodeMath")- owner_untrusted.operation = 'SUBTRACT'- owner_untrusted.inputs[0].default_value = 1.0- links.new(owner_trusted.outputs[0], owner_untrusted.inputs[1])-- candidate_valid = nodes_collection.new("ShaderNodeMath")- candidate_valid.operation = 'GREATER_THAN'- candidate_valid.inputs[1].default_value = 0.0- links.new(new_quality, candidate_valid.inputs[0])-- replace_untrusted = nodes_collection.new("ShaderNodeMath")- replace_untrusted.operation = 'MULTIPLY'- links.new(owner_untrusted.outputs[0], replace_untrusted.inputs[0])- links.new(candidate_valid.outputs[0], replace_untrusted.inputs[1])-- margin_node = nodes_collection.new("ShaderNodeMath")- margin_node.operation = 'ADD'- margin_node.location = (x_offset - 200, y_offset - 180 * idx)- margin_node.inputs[1].default_value = margin- margin_node.label = f"OwnerMargin-{idx}"- links.new(owner_quality, margin_node.inputs[0])-- priority_margin = nodes_collection.new("ShaderNodeMath")- priority_margin.operation = 'ADD'- links.new(margin_node.outputs[0], priority_margin.inputs[0])- links.new(owner_priority.outputs[0], priority_margin.inputs[1])-- replace = nodes_collection.new("ShaderNodeMath")- replace.operation = 'GREATER_THAN'- replace.location = (x_offset, y_offset - 180 * idx)- replace.label = f"OwnerReplace-{idx}"- links.new(new_quality, replace.inputs[0])- links.new(priority_margin.outputs[0], replace.inputs[1])-- replace_trusted = nodes_collection.new("ShaderNodeMath")- replace_trusted.operation = 'MULTIPLY'- replace_trusted.inputs[1].default_value = 1.0 if allow_upgrade else 0.0- links.new(replace.outputs[0], replace_trusted.inputs[0])-- replace_or_empty = nodes_collection.new("ShaderNodeMath")- replace_or_empty.operation = 'MAXIMUM'- replace_or_empty.location = (x_offset + 100, y_offset - 180 * idx)- replace_or_empty.label = f"OwnerAccept-{idx}"- links.new(replace_untrusted.outputs[0], replace_or_empty.inputs[0])- links.new(replace_trusted.outputs[0], replace_or_empty.inputs[1])-- select_color = nodes_collection.new("ShaderNodeMixRGB")- select_color.location = (x_offset + 200, y_offset - 180 * idx)- select_color.label = f"TexelOwner-{idx}"- links.new(replace_or_empty.outputs[0], select_color.inputs["Fac"])- links.new(owner_color.outputs[0], select_color.inputs["Color1"])- links.new(shaders[idx].outputs[0], select_color.inputs["Color2"])-- select_low = nodes_collection.new("ShaderNodeMixRGB")- select_low.label = f"LowFrequencyOwner-{idx}"- links.new(replace_or_empty.outputs[0], select_low.inputs["Fac"])- links.new(seam_low.outputs[0], select_low.inputs["Color1"])- links.new(lowpass_tex_image_nodes[idx].outputs[0], select_low.inputs["Color2"])-- if getattr(context.scene, 'sg_ownership_blend_mode', 'OWNER') == 'OWNER':- difference = nodes_collection.new("ShaderNodeMath")- difference.operation = 'SUBTRACT'- links.new(new_quality, difference.inputs[0])- links.new(owner_quality, difference.inputs[1])- absolute_difference = nodes_collection.new("ShaderNodeMath")- absolute_difference.operation = 'ABSOLUTE'- links.new(difference.outputs[0], absolute_difference.inputs[0])- near_boundary = nodes_collection.new("ShaderNodeMath")- near_boundary.operation = 'LESS_THAN'- near_boundary.inputs[1].default_value = float(getattr(- context.scene, 'sg_ownership_seam_width', 0.08- ))- links.new(absolute_difference.outputs[0], near_boundary.inputs[0])- candidate_trusted = nodes_collection.new("ShaderNodeMath")- candidate_trusted.operation = 'GREATER_THAN'- candidate_trusted.inputs[1].default_value = trust_threshold - 1e-7- links.new(new_quality, candidate_trusted.inputs[0])- both_trusted = nodes_collection.new("ShaderNodeMath")- both_trusted.operation = 'MULTIPLY'- links.new(owner_trusted.outputs[0], both_trusted.inputs[0])- links.new(candidate_trusted.outputs[0], both_trusted.inputs[1])- seam_factor = nodes_collection.new("ShaderNodeMath")- seam_factor.operation = 'MULTIPLY'- links.new(near_boundary.outputs[0], seam_factor.inputs[0])- links.new(both_trusted.outputs[0], seam_factor.inputs[1])- low_average = nodes_collection.new("ShaderNodeMixRGB")- low_average.inputs["Fac"].default_value = 0.5- links.new(owner_low.outputs[0], low_average.inputs["Color1"])- links.new(lowpass_tex_image_nodes[idx].outputs[0], low_average.inputs["Color2"])- blended_seam_low = nodes_collection.new("ShaderNodeMixRGB")- blended_seam_low.label = f"LowFrequencySeam-{idx}"- links.new(seam_factor.outputs[0], blended_seam_low.inputs["Fac"])- links.new(select_low.outputs[0], blended_seam_low.inputs["Color1"])- links.new(low_average.outputs[0], blended_seam_low.inputs["Color2"])- next_seam_low = blended_seam_low- else:- next_seam_low = select_low-- confidence_delta = nodes_collection.new("ShaderNodeMath")- confidence_delta.operation = 'SUBTRACT'- confidence_delta.location = (x_offset + 200, y_offset - 180 * idx - 90)- links.new(new_quality, confidence_delta.inputs[0])- links.new(owner_quality, confidence_delta.inputs[1])- selected_delta = nodes_collection.new("ShaderNodeMath")- selected_delta.operation = 'MULTIPLY'- selected_delta.location = (x_offset + 350, y_offset - 180 * idx - 90)- links.new(confidence_delta.outputs[0], selected_delta.inputs[0])- links.new(replace_or_empty.outputs[0], selected_delta.inputs[1])- selected_confidence = nodes_collection.new("ShaderNodeMath")- selected_confidence.operation = 'ADD'- selected_confidence.location = (x_offset + 500, y_offset - 180 * idx - 90)- selected_confidence.label = f"OwnerConfidence-{idx}"- links.new(owner_quality, selected_confidence.inputs[0])- links.new(selected_delta.outputs[0], selected_confidence.inputs[1])-- camera_delta = nodes_collection.new("ShaderNodeMath")- camera_delta.operation = 'SUBTRACT'- camera_delta.inputs[0].default_value = float(idx)- links.new(owner_camera.outputs[0], camera_delta.inputs[1])- selected_camera_delta = nodes_collection.new("ShaderNodeMath")- selected_camera_delta.operation = 'MULTIPLY'- links.new(camera_delta.outputs[0], selected_camera_delta.inputs[0])- links.new(replace_or_empty.outputs[0], selected_camera_delta.inputs[1])- selected_camera = nodes_collection.new("ShaderNodeMath")- selected_camera.operation = 'ADD'- selected_camera.label = f"SGOwnerCamera-{idx}"- links.new(owner_camera.outputs[0], selected_camera.inputs[0])- links.new(selected_camera_delta.outputs[0], selected_camera.inputs[1])-- candidate_priority = priority_strength * 0.25 * (- 1.0 - idx / float(max(len(shaders) - 1, 1))- )- priority_delta = nodes_collection.new("ShaderNodeMath")- priority_delta.operation = 'SUBTRACT'- priority_delta.inputs[0].default_value = candidate_priority- links.new(owner_priority.outputs[0], priority_delta.inputs[1])- selected_priority_delta = nodes_collection.new("ShaderNodeMath")- selected_priority_delta.operation = 'MULTIPLY'- links.new(priority_delta.outputs[0], selected_priority_delta.inputs[0])- links.new(replace_or_empty.outputs[0], selected_priority_delta.inputs[1])- selected_priority = nodes_collection.new("ShaderNodeMath")- selected_priority.operation = 'ADD'- selected_priority.label = f"SGOwnerPriority-{idx}"- links.new(owner_priority.outputs[0], selected_priority.inputs[0])- links.new(selected_priority_delta.outputs[0], selected_priority.inputs[1])-- owner_color = select_color- owner_low = nodes_collection.new("ShaderNodeMixRGB")- owner_low.label = f"SelectedOwnerLow-{idx}"- links.new(replace_or_empty.outputs[0], owner_low.inputs["Fac"])- links.new(old_owner_low.outputs[0], owner_low.inputs["Color1"])- links.new(lowpass_tex_image_nodes[idx].outputs[0], owner_low.inputs["Color2"])- seam_low = next_seam_low- owner_quality = selected_confidence.outputs[0]- owner_camera = selected_camera- owner_priority = selected_priority-- selected_confidence.label = "SGOwnerQuality"- selected_camera.label = "SGOwnerCamera"-- if getattr(context.scene, 'sg_ownership_blend_mode', 'OWNER') == 'OWNER':- detail = nodes_collection.new("ShaderNodeMixRGB")- detail.blend_type = 'SUBTRACT'- detail.inputs["Fac"].default_value = 1.0- detail.label = "OwnedHighFrequencyDetail"- links.new(owner_color.outputs[0], detail.inputs["Color1"])- links.new(owner_low.outputs[0], detail.inputs["Color2"])- recompose = nodes_collection.new("ShaderNodeMixRGB")- recompose.blend_type = 'ADD'- recompose.inputs["Fac"].default_value = 1.0- recompose.use_clamp = True- recompose.label = "LowFrequencySeamComposite"- links.new(detail.outputs[0], recompose.inputs["Color1"])- links.new(seam_low.outputs[0], recompose.inputs["Color2"])- owner_color = recompose-- final_mix = nodes_collection.new("ShaderNodeMixRGB")- final_mix.location = (x_offset + 450, y_offset)- final_mix.inputs["Color2"].default_value = (- *context.scene.fallback_color, 1.0- )- links.new(owner_color.outputs[0], final_mix.inputs["Color1"])- if last_node:- links.new(last_node.outputs[0], final_mix.inputs["Color2"])- uncovered = nodes_collection.new("ShaderNodeMath")- uncovered.operation = 'COMPARE'- uncovered.inputs[1].default_value = 0.0- uncovered.inputs[2].default_value = 0.0- uncovered.label = "OwnerUncovered"- links.new(owner_quality, uncovered.inputs[0])- links.new(uncovered.outputs[0], final_mix.inputs["Fac"])- return final_mix, selected_confidence-new_shaders = []new_weight_nodes = []i = 0@@ -1718,7 +1424,6 @@ def project_image(sum_node.operation = 'ADD'legacy_priority = (context.scene.early_priority- and not getattr(context.scene, 'sg_rework_initial_view_priority', False))sum_node.location = ((x_offset - 800, y_offset + vert_offset)@@ -1913,8 +1618,7 @@ def project_image(# ── Optional: bake per-vertex visibility weights ──────────────────use_baked_weights = (getattr(context.scene, 'bake_visibility_weights', False)- or (getattr(context.scene, 'sg_rework_projection_geometry', False)- and any(camera.data.type == 'ORTHO' for camera in cameras))+ or (any((camera.data.type == 'ORTHO' for camera in cameras))))if use_baked_weights:# Always compute weights for ALL cameras (ignore stop_index).@@ -2001,12 +1705,11 @@ def project_image(rework_requires_rebuild = any((- getattr(context.scene, 'sg_rework_projection_rebuild', False),+ force_rebuild,getattr(context.scene, 'sg_rework_projection_guard', False),- getattr(context.scene, 'sg_texel_ownership', False),getattr(context.scene, 'qwen_use_confidence_context', False),- getattr(context.scene, 'qwen_use_projection_write_masks', False),- getattr(context.scene, 'sg_rework_sdxl_registration', False),+ experimental_enabled(context.scene, 'qwen_use_projection_write_masks'),+ context.scene.model_architecture == 'sdxl',))legacy_incremental_update = (((context.scene.generation_method == 'sequential' and stop_index > 0)@@ -2074,7 +1777,7 @@ def project_image(continueelif not is_local_edit:# Rebuild mode is required for per-view assets that only exist- # after generation (write masks, guards, and ownership inputs).+ # after generation (write masks, guards, and confidence inputs).# Clear existing nodesfor node in nodes:nodes.remove(node)@@ -2101,7 +1804,6 @@ def project_image(use_native_raycast = bpy.app.version >= (5, 1, 0)tex_image_nodes = []- lowpass_tex_image_nodes = []uv_map_nodes = []subtract_nodes = []normalize_nodes = []@@ -2264,28 +1966,6 @@ def project_image(tex_image.label = f"{i}-{mat_id}"tex_image_nodes.append(tex_image)- lowpass_node = tex_image- if (getattr(context.scene, 'sg_texel_ownership', False)- and getattr(context.scene, 'sg_ownership_blend_mode', 'OWNER') == 'OWNER'- and i <= stop_index and tex_image.image is not None):- source_path = bpy.path.abspath(tex_image.image.filepath)- lowpass_path = _ensure_lowpass_texture(- source_path,- getattr(context.scene, 'sg_ownership_lowpass_sigma', 8.0),- )- if lowpass_path:- lowpass_image = get_or_load_image(- lowpass_path,- force_reload=context.scene.overwrite_material,- )- if lowpass_image:- lowpass_node = nodes.new("ShaderNodeTexImage")- lowpass_node.image = lowpass_image- lowpass_node.extension = 'CLIP'- lowpass_node.label = f"LowPass-{i}-{mat_id}"- lowpass_node.location = (200, -200 * i)- lowpass_tex_image_nodes.append(lowpass_node)-# Add UV map / attribute node# Use ShaderNodeAttribute to read from the corner-domain attributeuv_map_node = nodes.new("ShaderNodeAttribute")@@ -2452,12 +2132,10 @@ def project_image(if "CameraShiftX" in script_angle.inputs:script_angle.inputs["CameraShiftX"].default_value = (camera.data.shift_x- if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0)if "CameraShiftY" in script_angle.inputs:script_angle.inputs["CameraShiftY"].default_value = (camera.data.shift_y- if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0)script_angle.label = f"Angle-{i}-{mat_id}"@@ -2499,12 +2177,10 @@ def project_image(if "CameraShiftX" in script_feather.inputs:script_feather.inputs["CameraShiftX"].default_value = (camera.data.shift_x- if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0)if "CameraShiftY" in script_feather.inputs:script_feather.inputs["CameraShiftY"].default_value = (camera.data.shift_y- if getattr(context.scene, 'sg_rework_projection_geometry', False) else 0.0)scripts_to_connect.append(script_feather)@@ -2636,16 +2312,11 @@ def project_image(and context.scene.generation_method == 'sequential'and context.scene.qwen_generation_method == 'generate'and context.scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}- and getattr(context.scene, 'qwen_use_projection_write_masks', False)+ and experimental_enabled(context.scene, 'qwen_use_projection_write_masks'))qwen_write_weight = Noneuse_sdxl_write_mask = (- getattr(context.scene, 'sg_rework_sdxl_registration', False)- and- i > 0- and i <= stop_index- and context.scene.model_architecture == 'sdxl'- and context.scene.generation_method == 'sequential'+ i > 0 and i <= stop_index and (context.scene.model_architecture == 'sdxl') and (context.scene.generation_method == 'sequential'))if (use_qwen_write_mask or use_sdxl_write_mask) and script_nodes_outputs:current_weight = script_nodes_outputs[-1]@@ -2677,12 +2348,12 @@ def project_image(guard_weight = _create_projection_guard_weight(i, mat_id)if guard_weight is not None:# A projection guard marks depth/object/material boundaries- # as unsafe for ownership, but it must not delete the last+ # as unsafe for projection, but it must not delete the last# available coverage. Complex character meshes can have# dense ID boundaries around hair, facial parts, fingers,# clothing openings, and adjacent mesh pieces. If every# camera is hard-zeroed at the same surface point, the- # ownership graph falls through to the material's black+ # weighted graph falls through to the material's black# fallback. Keep a tiny, untrusted confidence floor: safe# views still beat it overwhelmingly, while the best weak# source fills a texel only when no guarded source exists.@@ -2752,8 +2423,7 @@ def project_image(confidence_quality_nodes.append(confidence_quality)# Expose a confidence-only max chain for context rendering. This- # node never selects or mixes RGB, so disabling texel ownership keeps- # the continuous weighted material while still providing a genuine+ # node does not mix RGB. Continuous weighted blending retains a separate# best-source trust signal to Qwen.if confidence_context_active and confidence_quality_nodes:best_quality = nodes.new("ShaderNodeMath")@@ -2794,9 +2464,6 @@ def project_image(# Connect UV → Texture (needed for both paths)uv_output = "Vector" if uv_map_node.type == 'ATTRIBUTE' else "UV"links.new(uv_map_node.outputs[uv_output], tex_image.inputs["Vector"])- lowpass_tex = lowpass_tex_image_nodes[i]- if lowpass_tex is not tex_image:- links.new(uv_map_node.outputs[uv_output], lowpass_tex.inputs["Vector"])if use_baked_weights or use_native_raycast:# Baked-weights path: all links already made during creation.@@ -2947,7 +2614,7 @@ def get_or_load_image(filepath, force_reload=False):def reset_projection_material_nodes(material, angle_threshold, exponent):- """Reset display controls without changing stored ownership confidence."""+ """Reset display controls without changing stored source confidence."""if not material or not material.use_nodes:return Falsenodes = material.node_tree.nodesdiff --git a/stablegen/texturing/rendering.py b/stablegen/texturing/rendering.pyindex 26e0beb..b6a9088 100644--- a/stablegen/texturing/rendering.py+++ b/stablegen/texturing/rendering.py@@ -35,9 +35,6 @@ def _prepare_compositor_render(scene, node_tree):``_finish_compositor_render``."""nodes = node_tree.nodes- if not getattr(scene, 'sg_rework_safe_render_state', False):- nodes.clear()- return Nonestate = {"pointers": {node.as_pointer() for node in nodes},"muted_outputs": [],@@ -614,11 +611,6 @@ def _render_edge_feather_mask_impl(context, to_export, camera, camera_index, feadef render_edge_feather_mask(context, to_export, camera, camera_index, feather_width=30, softness=1.0):- if not getattr(context.scene, 'sg_rework_safe_render_state', False):- return _render_edge_feather_mask_impl(- context, to_export, camera, camera_index,- feather_width=feather_width, softness=softness,- )all_meshes = [obj for obj in context.scene.objects if obj.type == 'MESH']with _RenderStateTransaction(context, all_meshes):return _render_edge_feather_mask_impl(@@ -1132,12 +1124,6 @@ def _export_emit_image_impl(context, to_export, camera_id=None, bg_color=(0.5, 0def export_emit_image(context, to_export, camera_id=None, bg_color=(0.5, 0.5, 0.5), view_transform='Standard', fallback_color=(0,0,0)):- if not getattr(context.scene, 'sg_rework_safe_render_state', False):- with _legacy_render_dither(context.scene):- return _export_emit_image_impl(- context, to_export, camera_id=camera_id, bg_color=bg_color,- view_transform=view_transform, fallback_color=fallback_color,- )with _RenderStateTransaction(context, to_export):with _temporary_render_copies(context, to_export) as (copies, _mapping):return _export_emit_image_impl(@@ -1228,11 +1214,6 @@ def _export_render_impl(context, camera_id=None, output_dir=None, filename=None)def export_render(context, camera_id=None, output_dir=None, filename=None):- if not getattr(context.scene, 'sg_rework_safe_render_state', False):- with _legacy_render_dither(context.scene):- return _export_render_impl(- context, camera_id=camera_id, output_dir=output_dir, filename=filename- )objects = [obj for obj in context.view_layer.objects if obj.type == 'MESH']with _RenderStateTransaction(context, objects):return _export_render_impl(@@ -1339,11 +1320,6 @@ def _export_viewport_impl(context, camera_id=None, output_dir=None, filename=Nondef export_viewport(context, camera_id=None, output_dir=None, filename=None):"""Viewport export with full scene-state restoration on every exit path."""- if not getattr(context.scene, 'sg_rework_safe_render_state', False):- with _legacy_render_dither(context.scene):- return _export_viewport_impl(- context, camera_id=camera_id, output_dir=output_dir, filename=filename- )objects = [obj for obj in context.view_layer.objects if obj.type == 'MESH']with _RenderStateTransaction(context, objects):return _export_viewport_impl(@@ -1523,16 +1499,10 @@ def _export_visibility_impl(context, to_export, obj=None, camera_visibility=None# Reworked sequential materials expose source acquisition quality# independently from RGB fusion. Prefer that max-quality signal; old- # ownership graphs remain supported as a compatibility fallback.source_quality = next((node for node in nodes if node.label == 'SGBestSourceQuality'),None,)- if source_quality is None:- source_quality = next(- (node for node in nodes if node.label == 'SGOwnerQuality'),- None,- )if source_quality is not None:trusted = nodes.new("ShaderNodeMath")trusted.operation = 'GREATER_THAN'@@ -1798,12 +1768,6 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None,context, to_export, obj=obj, camera_visibility=camera_visibility,prepare_only=True, camera_render=camera_render, camera_id=camera_id,)- if not getattr(context.scene, 'sg_rework_safe_render_state', False):- with _legacy_render_dither(context.scene):- return _export_visibility_impl(- context, to_export, obj=obj, camera_visibility=camera_visibility,- prepare_only=False, camera_render=camera_render, camera_id=camera_id,- )with _RenderStateTransaction(context, objects):with _temporary_render_copies(context, objects) as (copies, mapping):mapped_obj = mapping.get(obj) if obj is not None else Nonediff --git a/stablegen/texturing/view_plan.py b/stablegen/texturing/view_plan.pyindex 85f492a..ba496a7 100644--- a/stablegen/texturing/view_plan.py+++ b/stablegen/texturing/view_plan.py@@ -113,18 +113,6 @@ def initial_view_prior(index: int, count: int, strength: float) -> float:return 1.0 - (0.75 * strength * rank)-def should_replace_owner(- currently_covered: bool,- owner_confidence: float,- new_confidence: float,- replacement_margin: float,-) -> bool:- """Reference rule used by the shader-node ownership implementation."""- return (- not currently_covered- or float(new_confidence)- > float(owner_confidence) + max(0.0, float(replacement_margin))- )@dataclass(frozen=True)diff --git a/stablegen/texturing/workflows.py b/stablegen/texturing/workflows.pyindex 2035305..361fedd 100644--- a/stablegen/texturing/workflows.py+++ b/stablegen/texturing/workflows.py@@ -1,3 +1,4 @@+from ..feature_flags import experimental_enabledimport bpyimport osimport json@@ -81,12 +82,11 @@ def _generation_prompt(scene):class _TexturingWorkflowMixin:def _queue_prompt(self, prompt, client_id, server_address):"""Validate every dynamically edited texturing graph at submission."""- if getattr(bpy.context.scene, 'sg_rework_workflow_validation', False):- issues = validate_workflow_graph(prompt)- if issues:- message = "Invalid texturing workflow: " + "; ".join(issues)- self.operator._error = message- raise ValueError(message)+ issues = validate_workflow_graph(prompt)+ if issues:+ message = "Invalid texturing workflow: " + "; ".join(issues)+ self.operator._error = message+ raise ValueError(message)return super()._queue_prompt(prompt, client_id, server_address)"""Texturing workflow methods for WorkflowManager."""@@ -123,18 +123,6 @@ class _TexturingWorkflowMixin:f"({len(img_bytes)} bytes): {e} — returning raw bytes.")return img_bytes- if not getattr(bpy.context.scene, 'sg_rework_sdxl_registration', False):- # Rigging-branch behavior used a fixed eight-pixel crop regardless- # of the call-site default.- legacy_border = 8- width, height = img.size- if width > 2 * legacy_border and height > 2 * legacy_border:- img = img.crop((- legacy_border,- legacy_border,- width - legacy_border,- height - legacy_border,- ))# Corrected mode never crops because projection registration is not# adjusted for a changed image extent.w, h = img.size@@ -591,31 +579,30 @@ class _TexturingWorkflowMixin:# --- Reference Latent chain (Qwen unzoom fix) ---self._build_qwen_reference_latent_chain(prompt, NODES)- if getattr(context.scene, 'sg_rework_qwen_workflow', False):- prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed- prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps- prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg- prompt[NODES['sampler']]['inputs']['sampler_name'] = context.scene.sampler- prompt[NODES['sampler']]['inputs']['scheduler'] = context.scene.scheduler- prompt[NODES['sampler']]['inputs']['denoise'] = 1.0-- if is_nunchaku:- prompt[NODES['unet_loader']] = {- "inputs": {- "model_name": context.scene.model_name,- "cpu_offload": "auto",- "num_blocks_on_gpu": 1,- "use_pin_memory": "enable",- },- "class_type": "NunchakuQwenImageDiTLoader",- "_meta": {"title": "Nunchaku Qwen-Image DiT Loader"},- }- else:- prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_name+ prompt[NODES['sampler']]['inputs']['seed'] = context.scene.seed+ prompt[NODES['sampler']]['inputs']['steps'] = context.scene.steps+ prompt[NODES['sampler']]['inputs']['cfg'] = context.scene.cfg+ prompt[NODES['sampler']]['inputs']['sampler_name'] = context.scene.sampler+ prompt[NODES['sampler']]['inputs']['scheduler'] = context.scene.scheduler+ prompt[NODES['sampler']]['inputs']['denoise'] = 1.0++ if is_nunchaku:+ prompt[NODES['unet_loader']] = {+ "inputs": {+ "model_name": context.scene.model_name,+ "cpu_offload": "auto",+ "num_blocks_on_gpu": 1,+ "use_pin_memory": "enable",+ },+ "class_type": "NunchakuQwenImageDiTLoader",+ "_meta": {"title": "Nunchaku Qwen-Image DiT Loader"},+ }+ else:+ prompt[NODES['unet_loader']]['inputs']['unet_name'] = context.scene.model_namegraph_issues = (validate_workflow_graph(prompt, (NODES['pos_prompt'], NODES['neg_prompt'])- ) if getattr(context.scene, 'sg_rework_workflow_validation', False) else [])+ ))if graph_issues:self.operator._error = "Invalid Qwen refine workflow: " + "; ".join(graph_issues)return {"error": "invalid_workflow"}@@ -874,8 +861,6 @@ class _TexturingWorkflowMixin:# VL processing and the reference latent chain see ~1 MP.style_slot = (qwen_style_semantic_slot(context_mode, is_initial_image)- if getattr(context.scene, 'sg_rework_qwen_workflow', False)- else 'image2')prompt[NODES['pos_prompt']]['inputs'][style_slot] = [scale_node_key, 0]prompt[NODES['neg_prompt']]['inputs'][style_slot] = [scale_node_key, 0]@@ -902,9 +887,7 @@ class _TexturingWorkflowMixin:# visibility repair mask authoritative inside the sampler. It is# available only for later sequential views that actually have a# context render; the initial view keeps the legacy depth-start latent.- latent_lock_enabled = bool(getattr(- context.scene, 'qwen_latent_locked_context', False- ))+ latent_lock_enabled = bool(experimental_enabled(context.scene, 'qwen_latent_locked_context'))latent_lock_active = (latent_lock_enabledand not is_initial_image@@ -930,6 +913,7 @@ class _TexturingWorkflowMixin:vae_node_id=NODES['vae_loader'],context_image_name=context_render_info['name'],repair_mask_name=repair_mask_info['name'],+ neutral_fill=bool(experimental_enabled(context.scene, 'qwen_latent_lock_neutral_fill')),)print("[StableGen] Qwen latent-locked context active for camera "@@ -975,7 +959,7 @@ class _TexturingWorkflowMixin:graph_issues = (validate_workflow_graph(prompt, (NODES['pos_prompt'], NODES['neg_prompt'])- ) if getattr(context.scene, 'sg_rework_workflow_validation', False) else [])+ ))if graph_issues:self.operator._error = "Invalid Qwen edit workflow: " + "; ".join(graph_issues)return {"error": "invalid_workflow"}@@ -2386,6 +2370,9 @@ class _TexturingWorkflowMixin:if not context.scene.generation_method == 'uv_inpaint':prompt = self._refine_build_controlnet_chain(prompt, context, controlnet_info, NODES)else:+ # UV textures do not use ControlNet; the template's union selector+ # references a loader that only the ControlNet builder creates.+ prompt.pop('239', None)if context.scene.differential_diffusion:prompt[NODES['sampler']]["inputs"]["positive"] = [NODES['inpaint_conditioning'], 0]prompt[NODES['sampler']]["inputs"]["negative"] = [NODES['inpaint_conditioning'], 1]@@ -2529,25 +2516,18 @@ class _TexturingWorkflowMixin:# Set the input for the clip skip nodeprompt[NODES['clip_skip']]["inputs"]["clip"] = final_lora_clip_out- # If using IPAdapter, set the model input- _is_original_render_ipadapter = (- context.scene.sequential_ipadapter- and context.scene.sequential_ipadapter_mode == 'original_render'- and context.scene.generation_method == 'local_edit'- )- _is_trellis2_input_ipadapter = (- context.scene.sequential_ipadapter- and context.scene.sequential_ipadapter_mode == 'trellis2_input'- )- if (context.scene.use_ipadapter or _is_original_render_ipadapter or _is_trellis2_input_ipadapter or (context.scene.sequential_ipadapter and self.operator._current_image > 0)) and context.scene.generation_method != 'uv_inpaint':- # Set the model input for IPAdapter- prompt[NODES['ipadapter_loader']]["inputs"]["model"] = current_model_out- current_model_out = [NODES['ipadapter'], 0]+ # Prepare IPAdapter's upstream model, but route through it only when+ # refine() has an actual reference image. Otherwise its nodes are removed.+ prompt[NODES['ipadapter_loader']]["inputs"]["model"] = current_model_outif context.scene.differential_diffusion and NODES['differential_diffusion'] in prompt and context.scene.generation_method not in ('refine', 'local_edit'):# Set model input for differential diffusionprompt[NODES['differential_diffusion']]["inputs"]["model"] = current_model_outcurrent_model_out = [NODES['differential_diffusion'], 0]+ else:+ # Local/global img2img refinement does not use Differential Diffusion.+ # Its template input points at IPAdapter, which may be removed later.+ prompt.pop(NODES['differential_diffusion'], None)# Set the model for sampler nodeprompt[NODES['sampler']]["inputs"]["model"] = current_model_out@@ -2556,6 +2536,11 @@ class _TexturingWorkflowMixin:def _configure_refinement_mode(self, prompt, context, render_info, mask_info, NODES):"""Configures the prompt based on the specific refinement mode."""+ if not render_info or not render_info.get('name'):+ raise ValueError('Refinement input image is missing or could not be uploaded to ComfyUI')+ if context.scene.generation_method in ('uv_inpaint', 'sequential') and (+ not mask_info or not mask_info.get('name')):+ raise ValueError('Inpainting visibility mask is missing or could not be uploaded to ComfyUI')# Configure based on generation methodif context.scene.generation_method in ('refine', 'local_edit'):prompt[NODES['vae_encode']]["inputs"]["pixels"] = [NODES['render_image'], 0] # Use render directly@@ -2572,16 +2557,9 @@ class _TexturingWorkflowMixin:prompt[NODES['mask_image']]["inputs"]["image"] = mask_info['name']prompt[NODES['input_image']]["inputs"]["image"] = render_info['name']- if getattr(context.scene, 'sg_rework_sdxl_registration', False):- # One authoritative processed mask drives every inpaint consumer.- final_mask = sdxl_final_mask_reference(context.scene.blur_mask, NODES)- prompt[NODES['inpaint_conditioning']]["inputs"]["mask"] = final_mask- prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = final_mask- elif not context.scene.blur_mask:- # Exact pre-rework graph mutation. With blur enabled, retain- # the template's original mask links.- prompt[NODES['inpaint_conditioning']]["inputs"]["mask"] = [NODES['grow_mask'], 0]- prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = [NODES['grow_mask'], 0]+ final_mask = sdxl_final_mask_reference(context.scene.blur_mask, NODES)+ prompt[NODES['inpaint_conditioning']]["inputs"]["mask"] = final_mask+ prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = final_mask# Set blur parametersprompt[NODES['blur']]["inputs"]["sigma"] = context.scene.blur_mask_sigma@@ -2681,12 +2659,15 @@ class _TexturingWorkflowMixin:# Build the ControlNet chainprompt, final = self._build_controlnet_chain_extended(context, prompt, pos_input, neg_input, vae_input,- controlnet_info+ controlnet_info or {})# Connect final outputs to KSamplerprompt[NODES['sampler']]["inputs"]["positive"] = [final, 0]- prompt[NODES['sampler']]["inputs"]["negative"] = [final, 1]+ prompt[NODES['sampler']]["inputs"]["negative"] = (+ [neg_input, 1 if neg_input == NODES['inpaint_conditioning'] else 0]+ if final == pos_input else [final, 1]+ )return promptdiff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.pyindex 4e22456..7c1159b 100644--- a/stablegen/ui/panel.py+++ b/stablegen/ui/panel.py@@ -7,7 +7,7 @@ import mathfrom ..utils import sg_modal_activefrom ..core import get_addon_prefsfrom .presets import PRESETS, GEN_PARAMETERS-from ..feature_flags import all_rework_features_disabled+from ..feature_flags import experiments_enabled, active_experimentsfrom . import queue as _queue_mod_ADDON_PKG = __package__.rsplit('.', 1)[0]@@ -1337,100 +1337,58 @@ class StableGenPanel(bpy.types.Panel):row = content_box.row()row.prop(scene, "early_priority_strength", text="Priority Strength")- row = content_box.row()- row.prop(scene, "sg_texel_ownership", text="Per-Texel View Ownership", toggle=True, icon="UV")- if scene.sg_texel_ownership:- row = content_box.row()- row.prop(scene, "sg_texel_replacement_margin", text="Replacement Margin")- row = content_box.row()- row.prop(scene, "sg_allow_trusted_replacement", text="Allow Trusted Quality Upgrades", toggle=True)- row = content_box.row()- row.prop(scene, "sg_ownership_blend_mode", text="Detail Fusion")- if scene.sg_ownership_blend_mode == 'OWNER':- row = content_box.row()- row.prop(scene, "sg_ownership_seam_width", text="Seam Width")- row = content_box.row()- row.prop(scene, "sg_ownership_lowpass_sigma", text="Low-Pass Radius")- row = content_box.row()- row.prop(scene, "sg_freeze_ownership_after_generation", text="Freeze Ownership to UV", toggle=True)-- row = content_box.row()- row.prop(scene, "sg_auto_view_sequence", text="Overlap-Aware View Sequence", toggle=True)- if scene.sg_auto_view_sequence:- row = content_box.row()- row.prop(scene, "sg_anchor_camera", text="Anchor Camera")-row = content_box.row()row.prop(scene, "sg_texturing_frame", text="Texturing Frame")row = content_box.row()row.prop(scene, "bake_visibility_weights", text="Bake Visibility (Transform-Stable)", toggle=True, icon="MESH_DATA")- row = content_box.row()- row.prop(scene, "sg_silhouette_margin", text="Silhouette Margin (px)")-- row = content_box.row()- row.prop(scene, "sg_silhouette_depth", text="Silhouette Depth Threshold")-- row = content_box.row()- row.prop(scene, "sg_silhouette_rays", text="Silhouette Rays")-- row = content_box.row()- row.prop(scene, "sg_allow_backface_projection", text="Allow Backface Projection")-- experiments = content_box.box()- experiments.label(text="Texturing Rework Experiments (all opt-in)", icon="EXPERIMENTAL")- status = experiments.row(align=True)- if all_rework_features_disabled(scene):- status.label(text="Legacy baseline active", icon="CHECKMARK")- else:- status.alert = True- status.label(text="One or more experiments active", icon="INFO")- status.operator(- "stablegen.reset_texturing_experiments",- text="Disable All",- icon="LOOP_BACK",- )- experiments.prop(scene, "sg_rework_camera_plan", text="Canonical Camera Plan", toggle=True)- experiments.prop(scene, "sg_rework_aligned_resolution", text="Improved Aligned Resolution", toggle=True)- experiments.prop(scene, "sg_rework_full_resolution_scale", text="Force 100% Guide Resolution", toggle=True)- experiments.prop(scene, "sg_rework_acquisition_quality", text="Acquisition Quality Weighting", toggle=True)- experiments.prop(scene, "sg_rework_initial_view_priority", text="Confidence-Aware Initial View Priority", toggle=True)- experiments.prop(scene, "sg_rework_projection_guard", text="Depth/Part Projection Guard", toggle=True)- experiments.prop(scene, "sg_rework_projection_rebuild", text="Rebuild Sequential Projection Graph", toggle=True)- experiments.prop(scene, "sg_rework_projection_geometry", text="Projection Geometry Corrections", toggle=True)- experiments.prop(scene, "sg_rework_consistent_frame", text="Consistent Texturing Frame", toggle=True)- experiments.prop(scene, "sg_rework_reset_controls", text="Corrected Angle/Exponent Reset", toggle=True)- experiments.prop(scene, "sg_rework_sdxl_registration", text="Corrected SDXL Mask Registration", toggle=True)- experiments.prop(scene, "sg_rework_safe_render_state", text="Transactional Render State", toggle=True)- experiments.prop(scene, "sg_rework_workflow_validation", text="Workflow Graph Validation", toggle=True)- experiments.prop(scene, "sg_rework_qwen_workflow", text="Corrected Qwen Workflow Routing", toggle=True)- row = experiments.row()- row.enabled = bool(- scene.model_architecture.startswith('qwen')- and scene.qwen_generation_method == 'generate'- and scene.qwen_context_render_mode == 'ADDITIONAL'- )- row.prop(- scene,- "qwen_global_style_vlm_only",- text="Global Style Reference: VLM Only (Qwen Additional)",- toggle=True,- )- row = experiments.row()- row.enabled = bool(- scene.model_architecture.startswith('qwen')- and scene.qwen_generation_method == 'generate'- and scene.generation_method == 'sequential'- and scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}- )- row.prop(- scene,- "qwen_latent_locked_context",- text="Latent-Locked Context Inpainting (Qwen Sequential)",- toggle=True,+ row = (content_box.split(factor=0.5, align=False) if width_mode == 'wide'+ else content_box.row(align=True))+ row.prop(scene, "sg_allow_backface_projection", text="Allow Backface Projection", toggle=True)+ if width_mode == 'narrow':+ row = content_box.row(align=True)+ row.prop(scene, "sg_rework_acquisition_quality", text="Acquisition Quality Weighting", toggle=True)+ content_box.prop(scene, "sg_rework_projection_guard", text="Depth/Part Projection Guard", toggle=True)+ content_box.prop(scene, "sg_silhouette_margin", text="Silhouette Margin (px)")+ content_box.prop(scene, "sg_silhouette_depth", text="Silhouette Depth Threshold")++ if _show_diffusion_sections and experiments_enabled(context):+ experiments = draw_collapsible_section(+ advanced_params_box, "show_texturing_experiments",+ "Experimental Texturing", icon="EXPERIMENTAL",)- experiments.prop(scene, "sg_rework_final_display", text="Continuous Final Display Rebuild", toggle=True)+ if experiments:+ experiments.label(text=f"{len(active_experiments(scene, context))} research options active")+ experiments.operator("stablegen.reset_texturing_experiments", text="Reset Experiments", icon="LOOP_BACK")+ experiments.prop(scene, "sg_rework_aligned_resolution", toggle=True)+ experiments.prop(scene, "sg_rework_full_resolution_scale", toggle=True)+ experiments.prop(scene, "sg_rework_final_display", toggle=True)+ experiments.prop(scene, "sg_auto_view_sequence", toggle=True)+ if scene.sg_auto_view_sequence:+ experiments.prop(scene, "sg_anchor_camera")+ qwen_exp = experiments.column()+ qwen_exp.enabled = scene.model_architecture.startswith('qwen') and scene.qwen_generation_method == 'generate'+ style = qwen_exp.row()+ style.enabled = scene.qwen_context_render_mode == 'ADDITIONAL'+ style.prop(scene, "qwen_global_style_vlm_only", toggle=True)+ context_exp = qwen_exp.column()+ context_exp.enabled = scene.generation_method == 'sequential' and scene.qwen_context_render_mode in {'REPLACE_STYLE', 'ADDITIONAL'}+ context_exp.prop(scene, "qwen_context_vlm_only", toggle=True)+ context_exp.prop(scene, "qwen_latent_locked_context", toggle=True)+ neutral = context_exp.row()+ neutral.enabled = scene.qwen_latent_locked_context+ neutral.prop(scene, "qwen_latent_lock_neutral_fill", toggle=True)+ regularize = context_exp.column()+ regularize.enabled = scene.qwen_use_confidence_context+ regularize.prop(scene, "qwen_regularize_context_mask", toggle=True)+ if scene.qwen_regularize_context_mask:+ for key in ("qwen_mask_min_island_area", "qwen_mask_min_hole_area", "qwen_mask_min_strip_width", "qwen_mask_uncertainty_dilation", "qwen_mask_keep_largest_components"):+ regularize.prop(scene, key)+ context_exp.prop(scene, "qwen_use_projection_write_masks", text="Restrict Projection to Write Mask", toggle=True)+ context_exp.prop(scene, "qwen_reject_residual_fallback", toggle=True)+ if scene.qwen_reject_residual_fallback:+ context_exp.prop(scene, "qwen_residual_fallback_tolerance")# --- Output & Material Settings ---if _show_diffusion_sections:@@ -1711,20 +1669,6 @@ class StableGenPanel(bpy.types.Panel):threshold_row.prop(scene, "qwen_trust_threshold", text="Trusted Quality")- context_box.prop(- scene,- "qwen_regularize_context_mask",- text="Regularize Context Boundary",- toggle=True,- )- if scene.qwen_regularize_context_mask:- regularize_box = context_box.box()- regularize_box.label(text="Binary Boundary Regularization")- regularize_box.prop(scene, "qwen_mask_min_island_area", text="Min Trusted Island")- regularize_box.prop(scene, "qwen_mask_min_hole_area", text="Min Repair Hole")- regularize_box.prop(scene, "qwen_mask_min_strip_width", text="Min Context Strip")- regularize_box.prop(scene, "qwen_mask_uncertainty_dilation", text="Uncertainty Dilate")- regularize_box.prop(scene, "qwen_mask_keep_largest_components", text="Largest Components")else:dilation_row = context_box.row()dilation_row.prop(scene, "qwen_context_fallback_dilation", text="Legacy Fallback Dilate (px)")@@ -1736,29 +1680,6 @@ class StableGenPanel(bpy.types.Panel):row = context_box.row()row.prop(scene, "qwen_context_cleanup_value_adjust", text="Value Adjust")- protection_row = context_box.row()- protection_row.prop(- scene,- "qwen_use_projection_write_masks",- text="Restrict Projection to Write Mask",- toggle=True,- icon="LOCKED",- )- residual_row = context_box.row()- residual_row.prop(- scene,- "qwen_reject_residual_fallback",- text="Reject Residual Magenta",- toggle=True,- )- if scene.qwen_reject_residual_fallback:- row = context_box.row()- row.prop(- scene,- "qwen_residual_fallback_tolerance",- text="Residual Magenta Tol.",- )-elif scene.model_architecture == 'sdxl' or scene.model_architecture == 'flux1':# IPAdapter Parametersif not scene.generation_method == 'uv_inpaint':@@ -2326,7 +2247,7 @@ class StableGenPanel(bpy.types.Panel):op2 = row.operator("stablegen.debug_feather_preview", text="Feather Preview", icon="MOD_SMOOTH")row = debug_box.row()- row.operator("stablegen.debug_ownership_diagnostic", text="Ownership Diagnostics", icon="SHADING_RENDERED")+ row.operator("stablegen.debug_confidence_diagnostic", text="Confidence Diagnostics", icon="SHADING_RENDERED")row = debug_box.row()row.operator(diff --git a/stablegen/ui/presets.py b/stablegen/ui/presets.pyindex 8dd79ac..1027d23 100644--- a/stablegen/ui/presets.py+++ b/stablegen/ui/presets.py@@ -4,7 +4,7 @@ import mathimport bpy # pylint: disable=import-errorimport mathutils # pylint: disable=import-errorfrom ..utils import sg_modal_active-from ..feature_flags import TEXTURING_REWORK_DEFAULTS+from ..feature_flags import TEXTURING_DEFAULTS, EXPERIMENTAL_FEATURE_DEFAULTS, experiments_enabledPRESETS = {"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}]},@@ -51,217 +51,214 @@ PRESETS["QWEN 2509 FULL STEPS (EXPERIMENTAL)"] = {"lora_units": [],}-# Built-in presets intentionally start from the pre-rework behavior. Users can-# enable experiments after applying a preset; custom presets persist explicit-# feature choices through GEN_PARAMETERS below.-EXPERIMENTAL_FEATURE_DEFAULTS = dict(TEXTURING_REWORK_DEFAULTS)+# Regular controls are available without enabling research features.+PRESETS["QWEN PRECISE+"] = {+ **PRESETS["QWEN PRECISE"],+ "description": (+ "Qwen Precise with the evaluated combination of three context and projection controls for sequential multi-view texturing. "+ "Confidence-Gated Context (CGC) keeps reliable existing texture as context and marks low-quality regions for repair. "+ "Acquisition Quality Weighting (AQW) favors source views with better projected detail and acquisition quality when blending textures. "+ "Depth/Part Projection Guard (DPPG) reduces projection contributions near depth, object and material boundaries to limit foreground silhouettes leaking onto rear surfaces. "+ "Retains Qwen Precise's 4-step Lightning setup, sampler and context settings; uses a 0.50 trust threshold, a 3 px silhouette margin and backface projection. "+ "Experimental options are off. Intended to improve context reliability and projection consistency, but fine patterns and material continuity can still vary, and some assets may look better with standard Qwen Precise."+ ),+ "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,+}+# Global list of all generation parameter names to check for a preset.GEN_PARAMETERS = [- "control_after_generate",- "model_architecture",- "steps",- "cfg",- "sampler",- "scheduler",- "fallback_color",- "discard_factor",- "discard_factor_generation_only",- "discard_factor_after_generation",- "weight_exponent",- "weight_exponent_generation_only",- "weight_exponent_after_generation",- "view_blend_use_color_match",- "view_blend_color_match_method",- "view_blend_color_match_strength",- "clip_skip",- "auto_rescale",- "auto_rescale_target_mp",- "overwrite_material",- "generation_method",- "refine_images",- "refine_steps",- "refine_sampler",- "refine_scheduler",- "denoise",- "refine_cfg",- "refine_prompt",- "refine_upscale_method",- "sequential_smooth",- "sequential_custom_camera_order",- "sequential_factor",- "sequential_factor_smooth",- "sequential_factor_smooth_2",- "sequential_ipadapter",- "sequential_ipadapter_mode",- "sequential_desaturate_factor",- "sequential_contrast_factor",- "sequential_ipadapter_regenerate",- "ipadapter_weight_type",- "ipadapter_strength",- "ipadapter_start",- "ipadapter_end",- "early_priority",- "early_priority_strength",- "sg_texel_ownership",- "sg_texel_replacement_margin",- "sg_allow_trusted_replacement",- "sg_ownership_blend_mode",- "sg_ownership_seam_width",- "sg_ownership_lowpass_sigma",- "sg_auto_view_sequence",- "sg_anchor_camera",- "sg_texturing_frame",- "sg_freeze_ownership_after_generation",- "sg_rework_camera_plan",- "sg_rework_aligned_resolution",- "sg_rework_full_resolution_scale",- "sg_rework_safe_render_state",- "sg_rework_reset_controls",- "sg_rework_sdxl_registration",- "sg_rework_acquisition_quality",- "sg_rework_initial_view_priority",- "sg_rework_projection_guard",- "sg_rework_projection_rebuild",- "sg_rework_projection_geometry",- "sg_rework_consistent_frame",- "sg_rework_workflow_validation",- "sg_rework_qwen_workflow",- "qwen_global_style_vlm_only",- "qwen_latent_locked_context",- "sg_rework_final_display",- "differential_diffusion",- "differential_noise",- "blur_mask",- "blur_mask_radius",- "blur_mask_sigma",- "grow_mask_by",- "canny_threshold_low",- "canny_threshold_high",- "qwen_guidance_map_type",- "qwen_voronoi_mode",- "qwen_use_external_style_image",- "qwen_external_style_image",- "qwen_context_render_mode",- "qwen_external_style_initial_only",- "qwen_use_custom_prompts",- "qwen_custom_prompt_initial",- "qwen_custom_prompt_seq_none",- "qwen_custom_prompt_seq_replace",- "qwen_custom_prompt_seq_additional",- "qwen_guidance_fallback_color",- "qwen_guidance_background_color",- "qwen_context_cleanup",- "qwen_context_cleanup_hue_tolerance",- "qwen_context_cleanup_value_adjust",- "qwen_context_fallback_dilation",- "qwen_use_confidence_context",- "qwen_regularize_context_mask",- "qwen_use_projection_write_masks",- "qwen_reject_residual_fallback",- "qwen_trust_threshold",- "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_residual_fallback_tolerance",- "qwen_prompt_gray_background",- "qwen_rescale_alignment",- "qwen_generation_method",- "qwen_refine_use_prev_ref",- "qwen_refine_use_depth",- "qwen_timestep_zero_ref",- "refine_angle_ramp_active",- "refine_angle_ramp_pos_0",- "refine_angle_ramp_pos_1",- "visibility_vignette",- "visibility_vignette_width",- "visibility_vignette_softness",- "visibility_vignette_blur",- "sg_silhouette_margin",- "sg_silhouette_depth",- "sg_silhouette_rays",- "sg_allow_backface_projection",- "refine_feather_ramp_pos_0",- "refine_feather_ramp_pos_1",- "refine_edge_feather_projection",- "refine_edge_feather_width",- "refine_edge_feather_softness",- # --- TRELLIS.2 ---- "trellis2_texture_mode",- "trellis2_initial_image_arch",- "trellis2_camera_count",- "trellis2_placement_mode",- "trellis2_auto_prompts",- "trellis2_exclude_bottom",- "trellis2_exclude_bottom_angle",- "trellis2_auto_aspect",- "trellis2_occlusion_mode",- "trellis2_consider_existing",- "trellis2_delete_cameras",- "trellis2_coverage_target",- "trellis2_max_auto_cameras",- "trellis2_fan_angle",- "trellis2_resolution",- "trellis2_precision",- "trellis2_attn_backend",- "trellis2_seed",- "trellis2_ss_guidance",- "trellis2_ss_steps",- "trellis2_shape_guidance",- "trellis2_shape_steps",- "trellis2_tex_guidance",- "trellis2_tex_steps",- "trellis2_max_tokens",- "trellis2_texture_size",- "trellis2_decimation",- "trellis2_remesh",- "trellis2_decimate_method",- "trellis2_remesh_method",- "trellis2_post_processing_enabled",- "trellis2_autorig_enabled",- "trellis2_autorig_use_transfer",- "trellis2_autorig_use_skeleton",- "trellis2_autorig_use_postprocess",- "trellis2_autorig_cleanup_cross_limb_weights",- "trellis2_autorig_garment_mode",- "trellis2_autorig_bone_display_type",- "trellis2_autorig_bone_heuristic",- "trellis2_autorig_top_k",- "trellis2_autorig_top_p",- "trellis2_autorig_temperature",- "trellis2_autorig_repetition_penalty",- "trellis2_autorig_num_beams",- "trellis2_autorig_model_ckpt",- "trellis2_autorig_hf_path",-- "trellis2_bg_removal",- "trellis2_background_color",- "trellis2_import_scale",- "trellis2_clamp_elevation",- "trellis2_max_elevation",- "trellis2_min_elevation",- "trellis2_auto_lighting",-- # --- General workflow settings (not prompt/seed/model/paths) ---- "use_ipadapter",- "sequential_ipadapter_regenerate_wo_controlnet",- "allow_modify_existing_textures",- "ask_object_prompts",- "weight_exponent_mask",- "mask_blocky",- "architecture_mode",- "use_camera_prompts",- "sg_use_custom_camera_order",- "generation_mode",- "texture_objects",- "use_flux_lora",- "qwen_use_trellis2_style",- "qwen_trellis2_style_initial_only",- "trellis2_skip_texture",- "pbr_decomposition",- "pbr_albedo_saturation_mode",+ 'control_after_generate',+ 'model_architecture',+ 'steps',+ 'cfg',+ 'sampler',+ 'scheduler',+ 'fallback_color',+ 'discard_factor',+ 'discard_factor_generation_only',+ 'discard_factor_after_generation',+ 'weight_exponent',+ 'weight_exponent_generation_only',+ 'weight_exponent_after_generation',+ 'view_blend_use_color_match',+ 'view_blend_color_match_method',+ 'view_blend_color_match_strength',+ 'clip_skip',+ 'auto_rescale',+ 'auto_rescale_target_mp',+ 'overwrite_material',+ 'generation_method',+ 'refine_images',+ 'refine_steps',+ 'refine_sampler',+ 'refine_scheduler',+ 'denoise',+ 'refine_cfg',+ 'refine_prompt',+ 'refine_upscale_method',+ 'sequential_smooth',+ 'sequential_custom_camera_order',+ 'sequential_factor',+ 'sequential_factor_smooth',+ 'sequential_factor_smooth_2',+ 'sequential_ipadapter',+ 'sequential_ipadapter_mode',+ 'sequential_desaturate_factor',+ 'sequential_contrast_factor',+ 'sequential_ipadapter_regenerate',+ 'ipadapter_weight_type',+ 'ipadapter_strength',+ 'ipadapter_start',+ 'ipadapter_end',+ 'early_priority',+ 'early_priority_strength',+ 'sg_auto_view_sequence',+ 'sg_anchor_camera',+ 'sg_texturing_frame',+ 'sg_rework_aligned_resolution',+ 'sg_rework_full_resolution_scale',+ 'sg_rework_acquisition_quality',+ 'sg_rework_projection_guard',+ 'qwen_global_style_vlm_only',+ 'qwen_context_vlm_only',+ 'qwen_latent_locked_context',+ 'qwen_latent_lock_neutral_fill',+ 'sg_rework_final_display',+ 'differential_diffusion',+ 'differential_noise',+ 'blur_mask',+ 'blur_mask_radius',+ 'blur_mask_sigma',+ 'grow_mask_by',+ 'canny_threshold_low',+ 'canny_threshold_high',+ 'qwen_guidance_map_type',+ 'qwen_voronoi_mode',+ 'qwen_use_external_style_image',+ 'qwen_external_style_image',+ 'qwen_context_render_mode',+ 'qwen_external_style_initial_only',+ 'qwen_use_custom_prompts',+ 'qwen_custom_prompt_initial',+ 'qwen_custom_prompt_seq_none',+ 'qwen_custom_prompt_seq_replace',+ 'qwen_custom_prompt_seq_additional',+ 'qwen_guidance_fallback_color',+ 'qwen_guidance_background_color',+ 'qwen_context_cleanup',+ 'qwen_context_cleanup_hue_tolerance',+ 'qwen_context_cleanup_value_adjust',+ 'qwen_context_fallback_dilation',+ 'qwen_use_confidence_context',+ 'qwen_regularize_context_mask',+ 'qwen_use_projection_write_masks',+ 'qwen_reject_residual_fallback',+ 'qwen_trust_threshold',+ '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_residual_fallback_tolerance',+ 'qwen_prompt_gray_background',+ 'qwen_rescale_alignment',+ 'qwen_generation_method',+ 'qwen_refine_use_prev_ref',+ 'qwen_refine_use_depth',+ 'qwen_timestep_zero_ref',+ 'refine_angle_ramp_active',+ 'refine_angle_ramp_pos_0',+ 'refine_angle_ramp_pos_1',+ 'visibility_vignette',+ 'visibility_vignette_width',+ 'visibility_vignette_softness',+ 'visibility_vignette_blur',+ 'sg_silhouette_margin',+ 'sg_silhouette_depth',+ 'sg_silhouette_rays',+ 'sg_allow_backface_projection',+ 'refine_feather_ramp_pos_0',+ 'refine_feather_ramp_pos_1',+ 'refine_edge_feather_projection',+ 'refine_edge_feather_width',+ 'refine_edge_feather_softness',+ 'trellis2_texture_mode',+ 'trellis2_initial_image_arch',+ 'trellis2_camera_count',+ 'trellis2_placement_mode',+ 'trellis2_auto_prompts',+ 'trellis2_exclude_bottom',+ 'trellis2_exclude_bottom_angle',+ 'trellis2_auto_aspect',+ 'trellis2_occlusion_mode',+ 'trellis2_consider_existing',+ 'trellis2_delete_cameras',+ 'trellis2_coverage_target',+ 'trellis2_max_auto_cameras',+ 'trellis2_fan_angle',+ 'trellis2_resolution',+ 'trellis2_precision',+ 'trellis2_attn_backend',+ 'trellis2_seed',+ 'trellis2_ss_guidance',+ 'trellis2_ss_steps',+ 'trellis2_shape_guidance',+ 'trellis2_shape_steps',+ 'trellis2_tex_guidance',+ 'trellis2_tex_steps',+ 'trellis2_max_tokens',+ 'trellis2_texture_size',+ 'trellis2_decimation',+ 'trellis2_remesh',+ 'trellis2_decimate_method',+ 'trellis2_remesh_method',+ 'trellis2_post_processing_enabled',+ 'trellis2_autorig_enabled',+ 'trellis2_autorig_use_transfer',+ 'trellis2_autorig_use_skeleton',+ 'trellis2_autorig_use_postprocess',+ 'trellis2_autorig_cleanup_cross_limb_weights',+ 'trellis2_autorig_garment_mode',+ 'trellis2_autorig_bone_display_type',+ 'trellis2_autorig_bone_heuristic',+ 'trellis2_autorig_top_k',+ 'trellis2_autorig_top_p',+ 'trellis2_autorig_temperature',+ 'trellis2_autorig_repetition_penalty',+ 'trellis2_autorig_num_beams',+ 'trellis2_autorig_model_ckpt',+ 'trellis2_autorig_hf_path',+ 'trellis2_bg_removal',+ 'trellis2_background_color',+ 'trellis2_import_scale',+ 'trellis2_clamp_elevation',+ 'trellis2_max_elevation',+ 'trellis2_min_elevation',+ 'trellis2_auto_lighting',+ 'use_ipadapter',+ 'sequential_ipadapter_regenerate_wo_controlnet',+ 'allow_modify_existing_textures',+ 'ask_object_prompts',+ 'weight_exponent_mask',+ 'mask_blocky',+ 'architecture_mode',+ 'use_camera_prompts',+ 'sg_use_custom_camera_order',+ 'generation_mode',+ 'texture_objects',+ 'use_flux_lora',+ 'qwen_use_trellis2_style',+ 'qwen_trellis2_style_initial_only',+ 'trellis2_skip_texture',+ 'pbr_decomposition',+ 'pbr_albedo_saturation_mode',]# ── Preset diff preview helpers ──────────────────────────────────────────@@ -280,6 +277,8 @@ def get_preset_items(self, context):# Classify each preset into its architecture group.groups = {} # group_key -> list of (identifier, name, description)for key, preset in PRESETS.items():+ if '(EXPERIMENTAL)' in key and not experiments_enabled(context):+ continueif preset.get('architecture_mode') == 'trellis2':grp = 'trellis2'else:@@ -324,11 +323,14 @@ def update_parameters(self, context):# Compare current values with every stock preset's stored valuesfor name, preset in PRESETS.items():+ if '(EXPERIMENTAL)' in name and not experiments_enabled(context):+ continue+ expected = preset if preset.get('custom', False) else {**TEXTURING_DEFAULTS, **preset}# First check regular parametersif all((lambda v1, v2: math.isclose(v1, v2, rel_tol=1e-7, abs_tol=0.0) if isinstance(v1, (int, float)) and isinstance(v2, (int, float)) else v1 == v2)- (current.get(key), normalize_value(key, preset.get(key)))- for key in GEN_PARAMETERS if key in preset+ (current.get(key), normalize_value(key, expected.get(key)))+ for key in GEN_PARAMETERS if key in expected):units_match = True@@ -446,18 +448,18 @@ class ResetQwenPrompt(bpy.types.Operator):class ResetTexturingExperiments(bpy.types.Operator):- """Restore the explicit rigging-branch compatibility baseline."""+ """Reset research settings without changing graduated controls."""bl_idname = "stablegen.reset_texturing_experiments"bl_label = "Disable All Texturing Experiments"- bl_description = "Set every texturing rework feature to its legacy-compatible default"+ bl_description = "Reset experimental texturing settings; keep regular features and their values"bl_options = {'REGISTER', 'UNDO'}def execute(self, context):- for name, default in TEXTURING_REWORK_DEFAULTS.items():+ for name, default in EXPERIMENTAL_FEATURE_DEFAULTS.items():if hasattr(context.scene, name):setattr(context.scene, name, default)- self.report({'INFO'}, "All texturing experiments disabled; legacy baseline active")+ self.report({'INFO'}, "Experimental settings reset; regular texturing settings retained")return {'FINISHED'}class ApplyPreset(bpy.types.Operator):@@ -472,11 +474,14 @@ class ApplyPreset(bpy.types.Operator):def execute(self, context):preset = context.scene.stablegen_preset+ if '(EXPERIMENTAL)' in preset and not experiments_enabled(context):+ self.report({'ERROR'}, "Enable experimental texturing in add-on preferences first")+ return {'CANCELLED'}if preset in PRESETS:values = PRESETS[preset]if not values.get("custom", False):- for key, value in EXPERIMENTAL_FEATURE_DEFAULTS.items():+ for key, value in TEXTURING_DEFAULTS.items():if hasattr(context.scene, key):setattr(context.scene, key, value)