Skip to content

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

add interactive projection inspection and replayable diagnostics

sakalond066763199dc4
diff --git a/stablegen/cameras/overlays.py b/stablegen/cameras/overlays.py
index 29b34c2..3e94c76 100644
--- a/stablegen/cameras/overlays.py
+++ b/stablegen/cameras/overlays.py
@@ -17,6 +17,15 @@ _ADDON_PKG = __package__.rsplit('.', 1)[0]
_sg_crop_draw_handle = None
+def _sg_camera_overlay_color(camera):
+ """Use the solid-projection diagnostic color when assigned to this camera."""
+ color = camera.get('_sg_debug_projection_color')
+ if color is not None:
+ return color
+ prefs = bpy.context.preferences.addons.get(_ADDON_PKG)
+ return prefs.preferences.overlay_color if prefs else (0.3, 0.5, 1.0)
+
+
def _sg_draw_crop_overlays():
"""SpaceView3D draw callback: renders a coloured rectangle inside each
camera's pyramid to visualise the actual (non-square) crop region."""
@@ -72,8 +81,7 @@ def _sg_draw_crop_overlays():
indices = [(0, 1), (1, 2), (2, 3), (3, 0)]
batch = batch_for_shader(shader, 'LINES', {"pos": coords}, indices=indices)
shader.bind()
- _prefs = bpy.context.preferences.addons.get(_ADDON_PKG)
- _oc = _prefs.preferences.overlay_color if _prefs else (0.3, 0.5, 1.0)
+ _oc = _sg_camera_overlay_color(obj)
shader.uniform_float("color", (_oc[0], _oc[1], _oc[2], 0.9))
gpu.state.line_width_set(2.0)
gpu.state.blend_set('ALPHA')
@@ -112,9 +120,6 @@ def _sg_draw_view_labels():
font_id = 0
blf.size(font_id, 13)
- _prefs = bpy.context.preferences.addons.get(_ADDON_PKG)
- _oc = _prefs.preferences.overlay_color if _prefs else (0.3, 0.5, 1.0)
- blf.color(font_id, _oc[0], _oc[1], _oc[2], 0.95)
# Build a lookup of camera name -> prompt text
prompt_lookup = {item.name: item.prompt for item in scene.camera_prompts
@@ -129,6 +134,8 @@ def _sg_draw_view_labels():
co_2d = location_3d_to_region_2d(region, rv3d, obj.location)
if co_2d is None:
continue
+ _oc = _sg_camera_overlay_color(obj)
+ blf.color(font_id, _oc[0], _oc[1], _oc[2], 0.95)
# Offset slightly below the camera marker
blf.position(font_id, co_2d.x - blf.dimensions(font_id, label)[0] * 0.5,
co_2d.y - 20, 0)
diff --git a/stablegen/debug_tools.py b/stablegen/debug_tools.py
index fcc928f..5b3dbeb 100644
--- a/stablegen/debug_tools.py
+++ b/stablegen/debug_tools.py
@@ -13,10 +13,19 @@ so the debug output is guaranteed to match the actual generation pipeline.
import bpy
import os
import colorsys
+import glob
+import json
import numpy as np
import sys
+import tempfile
+import shutil
+import subprocess
+from datetime import datetime
+from pathlib import Path
+from types import SimpleNamespace
from contextlib import contextmanager
from mathutils import Vector
+from bpy_extras import view3d_utils
from .texturing.projection import (
project_image,
@@ -25,9 +34,19 @@ from .texturing.projection import (
_SG_BUFFER_UV_NAME,
_copy_uv_to_attribute,
)
-from .texturing.rendering import export_visibility
-from .cameras.geometry import _get_camera_resolution
-from .utils import get_file_path, get_generation_dirs, ensure_dirs_exist, sg_modal_active
+from .texturing.rendering import export_emit_image, export_visibility
+from .cameras.geometry import _get_camera_resolution, _SGCameraResolution
+from .utils import (
+ get_file_path,
+ get_generation_dirs,
+ ensure_dirs_exist,
+ sg_modal_active,
+)
+from .texturing.view_plan import (
+ generation_cameras,
+ order_cameras,
+ order_cameras_from_manifest,
+)
from .mesh_gen.rig_display import (
convert_armature_bones_to_fortune,
fortune_conversion_risks,
@@ -535,6 +554,32 @@ def _restore_cameras(hidden):
col.objects.link(cam)
+@contextmanager
+def _debug_projection_output(context):
+ """Keep diagnostic textures separate from generated images and GPU caches."""
+ scene = context.scene
+ source = get_generation_dirs(context)['revision']
+ debug_root = os.path.join(source, 'debug')
+ os.makedirs(debug_root, exist_ok=True)
+ output = tempfile.mkdtemp(prefix='projection_', dir=debug_root)
+ manifest = os.path.join(source, 'view_plan.json')
+ if os.path.isfile(manifest):
+ shutil.copy2(manifest, os.path.join(output, 'view_plan.json'))
+ # Keep the same per-view masks as the generation being diagnosed.
+ visibility = os.path.join(source, 'inpaint', 'visibility')
+ if os.path.isdir(visibility):
+ shutil.copytree(visibility, os.path.join(output, 'inpaint', 'visibility'))
+ previous = scene.get('_sg_debug_output')
+ scene['_sg_debug_output'] = output
+ try:
+ yield
+ finally:
+ if previous is None:
+ del scene['_sg_debug_output']
+ else:
+ scene['_sg_debug_output'] = previous
+
+
@contextmanager
def _debug_projection_build_state(scene):
"""Build diagnostics with the finished material's display controls.
@@ -553,6 +598,7 @@ def _debug_projection_build_state(scene):
"generation_mode": scene.generation_mode,
"discard_factor": scene.discard_factor,
"weight_exponent": scene.weight_exponent,
+ "sequential_ipadapter_regenerate": scene.sequential_ipadapter_regenerate,
}
if getattr(scene, "output_timestamp", ""):
scene.discard_factor = getattr(
@@ -564,6 +610,8 @@ def _debug_projection_build_state(scene):
scene.overwrite_material = True
scene.generation_method = 'separate'
scene.generation_mode = 'standard'
+ # Diagnostic images replace every camera, including the initial reference.
+ scene.sequential_ipadapter_regenerate = False
try:
yield
finally:
@@ -588,7 +636,11 @@ class SG_OT_DebugSolidColors(bpy.types.Operator):
return _common_poll(cls, context)
def execute(self, context):
- cameras = _get_cameras(context)
+ with _debug_projection_output(context):
+ return self._execute_projection(context)
+
+ def _execute_projection(self, context):
+ cameras = _interactive_generation_cameras(context)
meshes = _get_target_meshes(context)
n_cams = len(cameras)
colors = _saturated_colors(n_cams)
@@ -661,6 +713,13 @@ class SG_OT_DebugSolidColors(bpy.types.Operator):
if obj.active_material:
obj.active_material.name = "SG_Debug_SolidColors"
+ for camera, color in zip(cameras, colors):
+ camera['_sg_debug_projection_color'] = color
+ for screen in bpy.data.screens:
+ for area in screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+
self.report(
{'INFO'},
f"Solid-colour sequential projection validated ({n_cams} cameras)",
@@ -690,7 +749,11 @@ class SG_OT_DebugGridPattern(bpy.types.Operator):
return _common_poll(cls, context)
def execute(self, context):
- cameras = _get_cameras(context)
+ with _debug_projection_output(context):
+ return self._execute_projection(context)
+
+ def _execute_projection(self, context):
+ cameras = _interactive_generation_cameras(context)
meshes = _get_target_meshes(context)
n_cams = len(cameras)
colors = _saturated_colors(n_cams)
@@ -1488,6 +1551,9 @@ class SG_OT_DebugRestoreMaterial(bpy.types.Operator):
removed += 1
obj.data.materials.clear()
self.report({'INFO'}, f"Removed {removed} debug material(s)")
+ for camera in _get_cameras(context):
+ if '_sg_debug_projection_color' in camera:
+ del camera['_sg_debug_projection_color']
return {'FINISHED'}
@@ -1628,6 +1694,224 @@ class SG_OT_DebugConfidenceDiagnostic(bpy.types.Operator):
return {'FINISHED'}
+class SG_OT_DebugDPPGMaterial(bpy.types.Operator):
+ """Color the actual DPPG guard and feather signals on the projected mesh.
+
+ Red is hard-guard attenuation; blue is feather attenuation. Only views
+ with a nonzero pre-guard source weight are counted, so clipped or alpha-zero
+ images cannot paint misleading rejection outside their valid footprint.
+ """
+ bl_idname = 'stablegen.debug_dppg_material'
+ bl_label = 'DPPG Mask Material'
+ bl_description = 'Visualize hard-guard attenuation in red and feather attenuation in blue'
+ bl_options = {'REGISTER', 'UNDO'}
+
+ scope: bpy.props.EnumProperty(
+ name='Cameras',
+ items=[('ALL', 'All cameras', 'Show the strongest effect from any valid camera'),
+ ('ACTIVE', 'Active camera', 'Show only the selected or scene camera')],
+ default='ALL',
+ ) # type: ignore
+ stage: bpy.props.EnumProperty(
+ name='Stage',
+ items=[('CURRENT', 'Current effective masks',
+ 'Show guards and feathering after coverage rescue and occlusion limits'),
+ ('BEFORE_RESCUE', 'Before coverage rescue',
+ 'Show the original DPPG guard and feather fields')],
+ default='CURRENT',
+ ) # type: ignore
+
+ @classmethod
+ def poll(cls, context):
+ return _common_poll(cls, context)
+
+ def invoke(self, context, _event):
+ return context.window_manager.invoke_props_dialog(self)
+
+ def draw(self, _context):
+ layout = self.layout
+ layout.prop(self, 'scope')
+ layout.prop(self, 'stage')
+
+ @staticmethod
+ def _indexed_nodes(nodes, prefix):
+ found = {}
+ for node in nodes:
+ label = node.label
+ if not label.startswith(prefix):
+ continue
+ index = label[len(prefix):].split('-', 1)[0]
+ if index.isdigit():
+ found[int(index)] = node
+ return found
+
+ @staticmethod
+ def _math(nodes, links, operation, label, a, b):
+ node = nodes.new('ShaderNodeMath')
+ node.operation = operation
+ node.label = label
+ for index, value in enumerate((a, b)):
+ if isinstance(value, (float, int)):
+ node.inputs[index].default_value = value
+ else:
+ links.new(value, node.inputs[index])
+ return node.outputs[0]
+
+ def _build_material(self, source_mat, selected_index):
+ mat = source_mat.copy()
+ mat.name = f'SG_Debug_DPPG_{source_mat.name}'
+ mat['sg_dppg_source_material'] = source_mat.name
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ guards = self._indexed_nodes(nodes, 'ProjectionGuardWeight-')
+ guard_switches = self._indexed_nodes(nodes, 'ProjectionGuardWeightSwitch-')
+ guarded = self._indexed_nodes(nodes, 'DepthPartGuarded-')
+ raw_feathers = self._indexed_nodes(nodes, 'ProjectionGuardFeather-')
+ feather_switches = self._indexed_nodes(nodes, 'ProjectionGuardFeatherSwitch-')
+ rescue_floors = self._indexed_nodes(nodes, 'GuardRescueFloor-')
+ guard_floors = self._indexed_nodes(nodes, 'ProjectionGuardFloor-')
+ rescue_feathers = self._indexed_nodes(nodes, 'GuardRescueFeather-')
+ occlusion_feathers = self._indexed_nodes(nodes, 'GuardOcclusionFade-')
+ indices = sorted(guards)
+ if self.scope == 'ACTIVE':
+ indices = [index for index in indices if index == selected_index]
+ red, blue = None, None
+ used = 0
+ for index in indices:
+ guarded_node = guarded.get(index)
+ if (guarded_node is None or not guarded_node.inputs[0].links):
+ continue
+ raw_source = guarded_node.inputs[0].links[0].from_socket
+ valid = self._math(nodes, links, 'GREATER_THAN',
+ f'SGDebugDPPGValid-{index}', raw_source, 0.000001)
+ if self.stage == 'CURRENT':
+ guard_node = (rescue_floors.get(index) or guard_floors.get(index)
+ or guard_switches.get(index) or guards[index])
+ feather_node = (occlusion_feathers.get(index)
+ or rescue_feathers.get(index) or feather_switches.get(index)
+ or raw_feathers.get(index))
+ else:
+ guard_node = guard_switches.get(index) or guards[index]
+ feather_node = feather_switches.get(index) or raw_feathers.get(index)
+ guard_loss = self._math(nodes, links, 'SUBTRACT',
+ f'SGDebugDPPGGuardLoss-{index}', 1.0,
+ guard_node.outputs[0])
+ guard_loss = self._math(nodes, links, 'MULTIPLY',
+ f'SGDebugDPPGGuardValid-{index}', valid, guard_loss)
+ if feather_node is not None:
+ feather_loss = self._math(nodes, links, 'SUBTRACT',
+ f'SGDebugDPPGFeatherLoss-{index}', 1.0,
+ feather_node.outputs[0])
+ feather_loss = self._math(nodes, links, 'MULTIPLY',
+ f'SGDebugDPPGFeatherValid-{index}', valid, feather_loss)
+ else:
+ feather_loss = None
+ red = (self._math(nodes, links, 'MAXIMUM', 'SGDebugDPPGMaxGuard', red, guard_loss)
+ if red is not None else guard_loss)
+ if feather_loss is not None:
+ blue = (self._math(nodes, links, 'MAXIMUM', 'SGDebugDPPGMaxFeather', blue, feather_loss)
+ if blue is not None else feather_loss)
+ used += 1
+ if not used:
+ bpy.data.materials.remove(mat)
+ return None, 0
+ # A small neutral floor keeps unaffected mesh visible. Signal intensity
+ # is otherwise proportional to the actual attenuation (0..1).
+ red = self._math(nodes, links, 'MULTIPLY', 'SGDebugDPPGRed', red, 0.92)
+ red = self._math(nodes, links, 'ADD', 'SGDebugDPPGRedBase', red, 0.08)
+ if blue is not None:
+ blue = self._math(nodes, links, 'MULTIPLY', 'SGDebugDPPGBlue', blue, 0.92)
+ blue = self._math(nodes, links, 'ADD', 'SGDebugDPPGBlueBase', blue, 0.08)
+ color = nodes.new('ShaderNodeCombineXYZ')
+ color.label = 'SGDebugDPPGColor: red guard, blue feather'
+ links.new(red, color.inputs['X'])
+ color.inputs['Y'].default_value = 0.08
+ if blue is not None:
+ links.new(blue, color.inputs['Z'])
+ else:
+ color.inputs['Z'].default_value = 0.08
+ emission = nodes.new('ShaderNodeEmission')
+ emission.label = 'SGDebugDPPGEmission'
+ links.new(color.outputs[0], emission.inputs['Color'])
+ output = next((node for node in nodes
+ if node.type == 'OUTPUT_MATERIAL' and node.is_active_output), None)
+ if output is None:
+ output = nodes.new('ShaderNodeOutputMaterial')
+ links.new(emission.outputs[0], output.inputs['Surface'])
+ return mat, used
+
+ def execute(self, context):
+ cameras = _interactive_generation_cameras(context)
+ selected = _interactive_selected_camera(context, cameras)
+ camera = selected or (context.scene.camera if context.scene.camera in cameras else None)
+ selected_index = cameras.index(camera) if camera in cameras else 0
+ material_copies = {}
+ assignments = []
+ cameras_seen = 0
+ for obj in _get_target_meshes(context):
+ for slot in obj.material_slots:
+ source = slot.material
+ if source is None or not source.use_nodes:
+ continue
+ original_name = source.get('sg_dppg_source_material')
+ if original_name:
+ source = bpy.data.materials.get(original_name) or source
+ key = source.as_pointer()
+ if key not in material_copies:
+ material_copies[key] = self._build_material(source, selected_index)
+ clone, count = material_copies[key]
+ if clone is not None:
+ assignments.append((slot, clone))
+ cameras_seen = max(cameras_seen, count)
+ if not assignments:
+ self.report({'WARNING'}, 'No DPPG guard fields found in the target projection materials; Reproject with DPPG enabled')
+ return {'CANCELLED'}
+ for slot, clone in assignments:
+ slot.material = clone
+ for screen in bpy.data.screens:
+ for area in screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+ self.report({'INFO'},
+ f'DPPG mask material applied to {len(assignments)} slot(s); '
+ f'{cameras_seen} camera field(s), red=guard, blue=feather. View in Material Preview.')
+ return {'FINISHED'}
+
+
+class SG_OT_DebugRestoreDPPGMaterial(bpy.types.Operator):
+ """Restore the projection materials saved by DPPG Mask Material."""
+ bl_idname = 'stablegen.debug_restore_dppg_material'
+ bl_label = 'Restore Projection Material'
+ bl_options = {'REGISTER', 'UNDO'}
+
+ @classmethod
+ def poll(cls, context):
+ if not _common_poll(cls, context):
+ return False
+ return any(slot.material and slot.material.get('sg_dppg_source_material')
+ for obj in _get_target_meshes(context) for slot in obj.material_slots)
+
+ def execute(self, context):
+ restored = 0
+ old_materials = set()
+ for obj in _get_target_meshes(context):
+ for slot in obj.material_slots:
+ debug_mat = slot.material
+ if debug_mat is None:
+ continue
+ source_name = debug_mat.get('sg_dppg_source_material')
+ source = bpy.data.materials.get(source_name) if source_name else None
+ if source is None:
+ continue
+ slot.material = source
+ old_materials.add(debug_mat)
+ restored += 1
+ for material in old_materials:
+ if material.users == 0:
+ bpy.data.materials.remove(material)
+ self.report({'INFO'}, f'Restored {restored} projection material slot(s)')
+ return {'FINISHED'}
+
+
# ═════════════════════════════════════════════════════════════════════════
# 11. Debug Make Solid
# ═════════════════════════════════════════════════════════════════════════
@@ -1876,8 +2160,1015 @@ class SG_OT_DebugMakeSolid(bpy.types.Operator):
return {'CANCELLED'}
+# ═════════════════════════════════════════════════════════════════════════
+# Interactive discard / Qwen context check
+# ═════════════════════════════════════════════════════════════════════════
+
+_INTERACTIVE_DISCARD_SETTINGS = (
+ 'discard_factor',
+ 'qwen_prompt_gray_background',
+ 'qwen_guidance_background_color',
+ 'qwen_guidance_fallback_color',
+ 'qwen_use_confidence_context',
+ 'qwen_trust_threshold',
+ 'qwen_context_fallback_dilation',
+ 'qwen_context_cleanup',
+ 'qwen_context_cleanup_hue_tolerance',
+ 'qwen_context_cleanup_value_adjust',
+)
+
+_INTERACTIVE_DISCARD_BUILD_SETTINGS = (
+ 'overwrite_material',
+ 'generation_method',
+ 'generation_mode',
+ 'qwen_generation_method',
+ 'qwen_voronoi_mode',
+)
+
+_MAGENTA_EDIT_ARCHITECTURES = {
+ 'qwen_image_edit',
+ 'qwen_image_21',
+ 'flux2_klein',
+}
+
+
+def _copy_scene_value(value):
+ """Copy scalar and Blender vector values into assignment-safe Python data."""
+ try:
+ if not isinstance(value, (str, bytes)) and hasattr(value, '__len__'):
+ return tuple(value)
+ except TypeError:
+ pass
+ return value
+
+
+def _interactive_generation_root(context, meshes, material_id):
+ """Resolve the source run from projection images, independent of Save As."""
+ roots = {}
+ for obj in meshes:
+ material = obj.active_material
+ if not material or not material.use_nodes:
+ continue
+ for node in material.node_tree.nodes:
+ if node.type != 'TEX_IMAGE' or node.image is None:
+ continue
+ parts = node.label.split('-')
+ if (len(parts) != 2 or not parts[0].isdigit()
+ or parts[1] != str(material_id)):
+ continue
+ path = os.path.normpath(bpy.path.abspath(
+ node.image.filepath, library=node.image.library
+ ))
+ if not os.path.isfile(path):
+ continue
+ folder = os.path.dirname(path)
+ if os.path.basename(folder).lower() != 'generated':
+ continue
+ root = os.path.dirname(folder)
+ roots[os.path.normcase(root)] = root
+ if len(roots) > 1:
+ raise RuntimeError('Selected projection materials reference multiple generation runs')
+ return next(iter(roots.values()), get_generation_dirs(context)['revision'])
+
+
+def _interactive_generation_cameras(context, revision=None):
+ """Resolve the same persisted camera order used by the latest generation."""
+ scene = context.scene
+ cameras = list(generation_cameras(scene))
+ order_names = []
+ if scene.sg_use_custom_camera_order and len(scene.sg_camera_order) > 0:
+ order_names = [item.name for item in scene.sg_camera_order]
+ cameras = order_cameras(cameras, order_names)
+
+ manifest_path = os.path.join(
+ revision or get_generation_dirs(context)['revision'], 'view_plan.json'
+ )
+ try:
+ with open(manifest_path, 'r', encoding='utf-8') as stream:
+ cameras = list(order_cameras_from_manifest(cameras, json.load(stream)))
+ except (FileNotFoundError, OSError, ValueError, TypeError):
+ pass
+ return cameras
+
+
+def _interactive_selected_camera(context, cameras):
+ selected = [
+ obj for obj in context.selected_objects
+ if obj.type == 'CAMERA' and obj in cameras
+ ]
+ if len(selected) != 1:
+ return None
+ return selected[0]
+
+
+def _interactive_preview_layout(context_size, generated_size, max_width,
+ max_height, gap, title_height):
+ """Return image rectangles, fitting both cards while preserving aspect."""
+ context_aspect = context_size[0] / max(1, context_size[1])
+ generated_aspect = generated_size[0] / max(1, generated_size[1])
+ if context_aspect > 1 or generated_aspect > 1:
+ # The generated view sits below the live context; both share a width.
+ width = max(1, min(max_width,
+ (max_height - gap - 2 * title_height)
+ / (1 / context_aspect + 1 / generated_aspect)))
+ context_height = width / context_aspect
+ generated_height = width / generated_aspect
+ return ((0, generated_height + title_height + gap, width, context_height),
+ (0, 0, width, generated_height))
+ height = max(1, min(max_height - title_height,
+ (max_width - gap) / (context_aspect + generated_aspect)))
+ context_width = height * context_aspect
+ return ((0, 0, context_width, height),
+ (context_width + gap, 0, height * generated_aspect, height))
+
+
+class SG_OT_InteractiveDiscardCheck(bpy.types.Operator):
+ """Preview the sequential context passed to an image-edit architecture."""
+
+ bl_idname = 'stablegen.interactive_discard_check'
+ bl_label = 'Interactive Discard Check'
+ bl_description = (
+ "Preview the selected camera's magenta context while tuning discard "
+ "and Context Render Options; Apply keeps the values and Cancel restores them"
+ )
+ bl_options = {'REGISTER'}
+
+ _active = None
+ status = ''
+ preview_image_name = ''
+
+ def _load_generated_preview(self, context):
+ self._generated_preview_image_name = ''
+ self._generated_preview_texture = None
+ path = get_file_path(context, 'generated', camera_id=self._camera_index,
+ material_id=self._material_id)
+ if not os.path.isfile(path):
+ return
+ try:
+ # Own a separate datablock so its display color space cannot alter
+ # the image used by the actual projection material.
+ image = bpy.data.images.load(path, check_existing=False)
+ image.name = 'SG Investigated Camera Last Generated'
+ image.colorspace_settings.name = 'Non-Color'
+ self._generated_preview_image_name = image.name
+ except RuntimeError as error:
+ print(f'[StableGen] Could not load comparison image: {error}')
+
+ def _start_preview_overlay(self, context):
+ area = context.area
+ if area is None or area.type != 'VIEW_3D':
+ area = next((area for area in context.window.screen.areas
+ if area.type == 'VIEW_3D'), None)
+ self._preview_area_pointer = area.as_pointer() if area else None
+ self._preview_texture = None
+ self._load_generated_preview(context)
+ self._preview_draw_handle = bpy.types.SpaceView3D.draw_handler_add(
+ self._draw_preview_overlay, (), 'WINDOW', 'POST_PIXEL'
+ )
+
+ def _stop_preview_overlay(self):
+ handle = getattr(self, '_preview_draw_handle', None)
+ if handle is not None:
+ bpy.types.SpaceView3D.draw_handler_remove(handle, 'WINDOW')
+ self._preview_draw_handle = None
+ self._preview_texture = None
+ self._generated_preview_texture = None
+ image = bpy.data.images.get(getattr(self, '_generated_preview_image_name', ''))
+ if image is not None:
+ bpy.data.images.remove(image)
+ self._generated_preview_image_name = ''
+
+ def _draw_preview_overlay(self):
+ context = bpy.context
+ area, region = context.area, context.region
+ if (type(self)._active is not self or area is None or region is None
+ or area.as_pointer() != self._preview_area_pointer
+ or region.type != 'WINDOW'):
+ return
+ image = bpy.data.images.get(type(self).preview_image_name)
+ if image is None or not all(image.size):
+ return
+
+ import blf
+ import gpu
+ from .texturing.gallery import _draw_rect_2d, _draw_texture_2d
+
+ # Leave room for overlapping toolbars and the settings sidebar. Refit
+ # on every redraw so resizing the viewport keeps the image in view.
+ left, right = 0, region.width
+ for other in area.regions:
+ if other.type in {'TOOLS', 'UI'} and other.width > 1:
+ x = other.x - region.x
+ if x <= 0:
+ left = max(left, x + other.width)
+ elif x < region.width:
+ right = min(right, x)
+ margin = 16 * context.preferences.system.ui_scale
+ available_width = right - left - 2 * margin
+ available_height = region.height - 2 * margin - 28
+ if available_width <= 0 or available_height <= 0:
+ return
+ generated = bpy.data.images.get(self._generated_preview_image_name)
+ generated_size = generated.size if generated and all(generated.size) else image.size
+ gap = 16 * context.preferences.system.ui_scale
+ title_height = 26
+ rectangles = _interactive_preview_layout(
+ image.size, generated_size, available_width * 0.45,
+ available_height * 0.80, gap, title_height,
+ )
+ x, y = left + margin, margin
+ if self._preview_texture is None:
+ self._preview_texture = gpu.texture.from_image(image)
+ if generated is not None and self._generated_preview_texture is None:
+ self._generated_preview_texture = gpu.texture.from_image(generated)
+ old_blend = gpu.state.blend_get()
+ old_depth = gpu.state.depth_test_get()
+ try:
+ gpu.state.depth_test_set('NONE')
+ cards = ((self._preview_texture, 'Context preview'),
+ (self._generated_preview_texture, 'Last generated'))
+ for (dx, dy, width, height), (texture, title) in zip(rectangles, cards):
+ card_x, card_y = x + dx, y + dy
+ _draw_rect_2d(card_x - 4, card_y - 4, card_x + width + 4,
+ card_y + height + title_height,
+ (0.025, 0.025, 0.025, 0.95))
+ if texture is not None:
+ _draw_texture_2d(texture, card_x, card_y,
+ card_x + width, card_y + height)
+ else:
+ blf.size(0, 12)
+ blf.color(0, 0.8, 0.8, 0.8, 1)
+ blf.position(0, card_x + 8, card_y + height / 2, 0)
+ blf.draw(0, 'No generated image')
+ blf.size(0, 13)
+ blf.color(0, 1, 1, 1, 1)
+ blf.position(0, card_x + 4, card_y + height + 7, 0)
+ blf.draw(0, title)
+ finally:
+ gpu.state.depth_test_set(old_depth)
+ gpu.state.blend_set(old_blend)
+
+ @classmethod
+ def poll(cls, context):
+ scene = context.scene
+ if cls._active is not None:
+ cls.poll_message_set('Interactive Discard Check is already running')
+ return False
+ if scene.model_architecture not in _MAGENTA_EDIT_ARCHITECTURES:
+ cls.poll_message_set('Requires an image-edit architecture with magenta context')
+ return False
+ if scene.generation_method != 'sequential':
+ cls.poll_message_set('Requires Sequential generation')
+ return False
+ if scene.qwen_generation_method != 'generate':
+ cls.poll_message_set('Requires the Qwen Generate workflow')
+ return False
+ if scene.qwen_context_render_mode not in {'REPLACE_STYLE', 'ADDITIONAL'}:
+ cls.poll_message_set('Enable a magenta Context Render mode first')
+ return False
+ if not scene.output_timestamp:
+ cls.poll_message_set('No completed generation is available')
+ return False
+ if sg_modal_active(context):
+ cls.poll_message_set('Another StableGen operation is running')
+ return False
+ cameras = _interactive_generation_cameras(context)
+ if _interactive_selected_camera(context, cameras) is None:
+ cls.poll_message_set('Select exactly one generated camera')
+ return False
+ return bool(cameras)
+
+ def _tag_redraw(self, context):
+ for window in context.window_manager.windows:
+ if not window.screen:
+ continue
+ for area in window.screen.areas:
+ area.tag_redraw()
+
+ def _settings_key(self, scene):
+ result = []
+ for name in _INTERACTIVE_DISCARD_SETTINGS:
+ value = getattr(scene, name)
+ result.append((name, _copy_scene_value(value)))
+ return tuple(result)
+
+ def _snapshot_materials(self):
+ self._material_states = {}
+ preview_materials = {}
+ for obj in self._meshes:
+ materials = [slot.material for slot in obj.material_slots]
+ self._material_states[obj] = (materials, obj.active_material_index)
+ if not materials:
+ continue
+ active_index = min(obj.active_material_index, len(materials) - 1)
+ original = materials[active_index]
+ if original is None:
+ continue
+ preview = preview_materials.get(original)
+ if preview is None:
+ preview = original.copy()
+ preview.name = f'SG_DiscardPreview_{original.name}'
+ preview_materials[original] = preview
+ obj.material_slots[active_index].material = preview
+ self._preview_materials = list(preview_materials.values())
+
+ def _restore_materials(self):
+ for obj, (materials, active_index) in self._material_states.items():
+ if obj.name not in bpy.data.objects:
+ continue
+ obj.data.materials.clear()
+ for material in materials:
+ obj.data.materials.append(material)
+ if materials:
+ obj.active_material_index = min(active_index, len(materials) - 1)
+ for material in self._preview_materials:
+ if material and material.name in bpy.data.materials:
+ bpy.data.materials.remove(material)
+
+ def _artifact_paths(self, context):
+ context_path = get_file_path(
+ context, 'inpaint', subtype='render', camera_id=self._camera_index
+ )
+ mask_path = get_file_path(
+ context, 'inpaint', subtype='visibility', camera_id=self._camera_index
+ )
+ stem, extension = os.path.splitext(mask_path)
+ return (
+ context_path,
+ mask_path,
+ f'{stem}_repair{extension}',
+ f'{stem}_trusted{extension}',
+ )
+
+ def _snapshot_artifacts(self, context):
+ self._artifact_states = {}
+ for path in self._artifact_paths(context):
+ try:
+ with open(path, 'rb') as stream:
+ self._artifact_states[path] = stream.read()
+ except FileNotFoundError:
+ self._artifact_states[path] = None
+
+ def _restore_artifacts(self):
+ for path, content in self._artifact_states.items():
+ if content is None:
+ try:
+ os.remove(path)
+ except FileNotFoundError:
+ pass
+ else:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, 'wb') as stream:
+ stream.write(content)
+
+ def _reload_preview_image(self, context, path):
+ image = bpy.data.images.get(type(self).preview_image_name)
+ if image is None:
+ image = bpy.data.images.load(path, check_existing=False)
+ image.name = 'SG Interactive Context Preview'
+ type(self).preview_image_name = image.name
+ else:
+ image.filepath = path
+ image.reload()
+ # The POST_PIXEL image shader displays the PNG's encoded RGB directly,
+ # matching the gallery overlay and avoiding a second scene view transform.
+ image.colorspace_settings.name = 'Non-Color'
+ self._preview_texture = None
+ self._tag_redraw(context)
+
+ def _refresh_preview(self, context):
+ scene = context.scene
+ type(self).status = (
+ f'Updating {self._camera.name} '
+ f'({self._camera_index + 1}/{len(self._cameras)})…'
+ )
+ self._tag_redraw(context)
+
+ # These values affect how project_image builds the diagnostic graph,
+ # but are infrastructure rather than user choices in this tool.
+ scene.overwrite_material = True
+ scene.generation_method = 'sequential'
+ scene.generation_mode = 'standard'
+ scene.qwen_generation_method = 'generate'
+ scene.qwen_voronoi_mode = False
+ scene.camera = self._camera
+
+ project_image(
+ context,
+ self._meshes,
+ self._material_id,
+ stop_index=self._camera_index - 1,
+ cameras=self._cameras,
+ force_rebuild=True,
+ reuse_projection_uv=True,
+ )
+
+ visibility_camera = (
+ self._cameras[self._camera_index - 1]
+ if self._camera_index > 0 else self._camera
+ )
+ fallback = tuple(scene.qwen_guidance_fallback_color)
+ background = tuple(scene.qwen_guidance_background_color)
+ if scene.model_architecture == 'qwen_image_21':
+ background = (0.5, 0.5, 0.5)
+
+ # Blender's write_still render also writes to scene.render.filepath in
+ # addition to the compositor target. Route that incidental output to a
+ # private sink so preview refreshes never overwrite the user's render.
+ original_render_filepath = scene.render.filepath
+ scene.render.filepath = self._render_sink
+ try:
+ with _SGCameraResolution(context, self._camera):
+ export_visibility(
+ context,
+ self._meshes,
+ camera_visibility=visibility_camera,
+ camera_render=self._camera,
+ camera_id=self._camera_index,
+ )
+ export_emit_image(
+ context,
+ self._meshes,
+ camera_id=self._camera_index,
+ bg_color=background,
+ fallback_color=fallback,
+ )
+ finally:
+ scene.render.filepath = original_render_filepath
+ self._clean_render_sink()
+
+ # Reuse the production post-processing implementation without writing
+ # confidence-manifest metadata during a temporary inspection.
+ from .texturing.generator import ComfyUIGenerate
+ helper = SimpleNamespace(
+ _uploaded_images_cache={},
+ _record_confidence_artifacts=lambda *args, **kwargs: None,
+ )
+ if scene.qwen_use_confidence_context:
+ ComfyUIGenerate._apply_qwen_binary_context_mask(
+ helper, context, self._camera_index, fallback
+ )
+ else:
+ ComfyUIGenerate._dilate_qwen_context_fallback(
+ helper, context, self._camera_index, fallback
+ )
+
+ context_path = get_file_path(
+ context, 'inpaint', subtype='render', camera_id=self._camera_index
+ )
+ if not os.path.exists(context_path):
+ raise RuntimeError('Context preview render was not created')
+ self._reload_preview_image(context, context_path)
+ type(self).status = (
+ f'{self._camera.name}: cameras 1–{self._camera_index} projected; '
+ f'camera {self._camera_index + 1} and later blanked'
+ if self._camera_index > 0 else
+ f'{self._camera.name}: every generated camera is blanked'
+ )
+ self._tag_redraw(context)
+
+ def _restore_selection(self, context):
+ try:
+ bpy.ops.object.select_all(action='DESELECT')
+ except Exception:
+ pass
+ for obj in self._selected_objects:
+ if obj.name in bpy.data.objects:
+ obj.select_set(True)
+ if self._active_object and self._active_object.name in bpy.data.objects:
+ context.view_layer.objects.active = self._active_object
+
+ def _restore_render_state(self, scene):
+ scene.render.engine = self._render_snapshot['engine']
+ scene.render.filepath = self._render_snapshot['filepath']
+ cycles = getattr(scene, 'cycles', None)
+ if cycles is None:
+ return
+ for name, value in self._render_snapshot['cycles'].items():
+ if value is not None and hasattr(cycles, name):
+ setattr(cycles, name, value)
+
+ def _remove_temporary_images(self):
+ for image in list(bpy.data.images):
+ if image.as_pointer() in self._image_pointers:
+ continue
+ if image.source == 'FILE' and image.users == 0:
+ bpy.data.images.remove(image)
+
+ def _clean_render_sink(self):
+ for path in glob.glob(f'{self._render_sink}*'):
+ try:
+ os.remove(path)
+ except FileNotFoundError:
+ pass
+
+ def _finish(self, context, apply):
+ self._stop_preview_overlay()
+ if self._timer is not None:
+ context.window_manager.event_timer_remove(self._timer)
+ self._timer = None
+
+ if not apply:
+ for name, value in self._setting_snapshot.items():
+ setattr(context.scene, name, value)
+ for name, value in self._build_snapshot.items():
+ setattr(context.scene, name, value)
+
+ context.scene.camera = self._original_camera
+ self._restore_materials()
+ try:
+ self._restore_artifacts()
+ finally:
+ self._restore_output_scope(context.scene)
+ self._restore_render_state(context.scene)
+ self._restore_selection(context)
+ self._clean_render_sink()
+
+ image = bpy.data.images.get(type(self).preview_image_name)
+ if image is not None:
+ bpy.data.images.remove(image)
+ self._remove_temporary_images()
+ type(self).preview_image_name = ''
+ type(self)._active = None
+ type(self).status = ''
+
+ if apply:
+ from .ui.presets import update_parameters
+ update_parameters(None, context)
+ else:
+ context.scene.stablegen_preset = self._original_preset
+ context.scene.active_preset = self._original_active_preset
+ self._tag_redraw(context)
+
+ def _restore_output_scope(self, scene):
+ previous = getattr(self, '_generation_output_previous', None)
+ if previous is None:
+ if '_sg_discard_output' in scene:
+ del scene['_sg_discard_output']
+ else:
+ scene['_sg_discard_output'] = previous
+
+ def invoke(self, context, _event):
+ cameras = _interactive_generation_cameras(context)
+ camera = _interactive_selected_camera(context, cameras)
+ if camera is None:
+ self.report({'ERROR'}, 'Select exactly one generated camera')
+ return {'CANCELLED'}
+
+ selected_meshes = [
+ obj for obj in context.selected_objects
+ if obj.type == 'MESH' and not obj.hide_get()
+ ]
+ meshes = selected_meshes or [
+ obj for obj in context.view_layer.objects
+ if obj.type == 'MESH' and not obj.hide_get()
+ ]
+ if not meshes:
+ self.report({'ERROR'}, 'No visible mesh objects to preview')
+ return {'CANCELLED'}
+
+ projection_ids = set()
+ for obj in meshes:
+ for attribute in obj.data.attributes:
+ if not attribute.name.startswith('ProjectionUV_'):
+ continue
+ try:
+ projection_ids.add(int(attribute.name.rsplit('_', 1)[1]))
+ except (ValueError, IndexError):
+ pass
+ material_id = max(projection_ids, default=-1)
+ if material_id < 0:
+ self.report({'ERROR'}, 'No StableGen projection material was found')
+ return {'CANCELLED'}
+
+ meshes = [
+ obj for obj in meshes
+ if obj.active_material is not None
+ and obj.data.attributes.get(f'ProjectionUV_0_{material_id}') is not None
+ ]
+ if not meshes:
+ self.report({'ERROR'}, 'No meshes use the latest StableGen projection')
+ return {'CANCELLED'}
+
+ try:
+ revision = _interactive_generation_root(context, meshes, material_id)
+ except RuntimeError as error:
+ self.report({'ERROR'}, str(error))
+ return {'CANCELLED'}
+ # Use this run's manifest as well as its images; the copied .blend's
+ # name may point at a different or nonexistent output directory.
+ cameras = _interactive_generation_cameras(context, revision=revision)
+ camera_index = cameras.index(camera)
+ for index in range(camera_index):
+ path = os.path.join(revision, 'generated',
+ f'generated_image{index}-{material_id}-0001.png')
+ if not os.path.isfile(path):
+ self.report({'ERROR'}, f'Missing generated image for camera {index + 1}: {path}')
+ return {'CANCELLED'}
+
+ self._cameras = tuple(cameras)
+ self._camera = camera
+ self._camera_index = camera_index
+ self._meshes = tuple(meshes)
+ self._material_id = material_id
+ self._setting_snapshot = {
+ name: _copy_scene_value(getattr(context.scene, name))
+ for name in _INTERACTIVE_DISCARD_SETTINGS
+ }
+ self._build_snapshot = {
+ name: _copy_scene_value(getattr(context.scene, name))
+ for name in _INTERACTIVE_DISCARD_BUILD_SETTINGS
+ }
+ self._original_preset = context.scene.stablegen_preset
+ self._original_active_preset = context.scene.active_preset
+ self._original_camera = context.scene.camera
+ cycles = getattr(context.scene, 'cycles', None)
+ self._render_snapshot = {
+ 'engine': context.scene.render.engine,
+ 'filepath': context.scene.render.filepath,
+ 'cycles': {
+ name: getattr(cycles, name, None) if cycles is not None else None
+ for name in ('device', 'shading_system', 'use_osl')
+ },
+ }
+ self._image_pointers = {
+ image.as_pointer() for image in bpy.data.images
+ }
+ sink_handle, self._render_sink = tempfile.mkstemp(
+ prefix='stablegen_interactive_discard_', suffix='.png'
+ )
+ os.close(sink_handle)
+ os.remove(self._render_sink)
+ self._selected_objects = tuple(context.selected_objects)
+ self._active_object = context.view_layer.objects.active
+ self._last_settings_key = None
+ self._finish_requested = None
+ self._timer = None
+
+ self._generation_output_previous = context.scene.get('_sg_discard_output')
+ context.scene['_sg_discard_output'] = revision
+ try:
+ self._snapshot_materials()
+ self._snapshot_artifacts(context)
+ except Exception as error:
+ self._restore_output_scope(context.scene)
+ self.report({'ERROR'}, f'Could not prepare discard preview: {error}')
+ try:
+ self._restore_materials()
+ except Exception:
+ pass
+ return {'CANCELLED'}
+
+ type(self)._active = self
+ type(self).status = 'Preparing context preview…'
+ self._start_preview_overlay(context)
+ self._timer = context.window_manager.event_timer_add(
+ 0.35, window=context.window
+ )
+ context.window_manager.modal_handler_add(self)
+ self._tag_redraw(context)
+ return {'RUNNING_MODAL'}
+
+ def execute(self, context):
+ """Start the same modal session when called through EXEC_DEFAULT."""
+ return self.invoke(context, None)
+
+ def modal(self, context, event):
+ if self._finish_requested is not None:
+ apply = self._finish_requested == 'APPLY'
+ self._finish(context, apply)
+ self.report(
+ {'INFO'},
+ 'Interactive discard settings applied' if apply
+ else 'Interactive discard preview cancelled',
+ )
+ return {'FINISHED'} if apply else {'CANCELLED'}
+
+ if event.type in {'ESC', 'RIGHTMOUSE'}:
+ self._finish(context, False)
+ self.report({'INFO'}, 'Interactive discard preview cancelled')
+ return {'CANCELLED'}
+
+ # Blender 5.1's Event RNA has no timer attribute. Accept TIMER events
+ # there; the settings key prevents duplicate renders from other timers.
+ if event.type == 'TIMER' and getattr(event, 'timer', self._timer) == self._timer:
+ settings_key = self._settings_key(context.scene)
+ if settings_key != self._last_settings_key:
+ self._last_settings_key = settings_key
+ try:
+ self._refresh_preview(context)
+ except Exception as error:
+ type(self).status = f'Preview error: {error}'
+ import traceback
+ traceback.print_exc()
+ self._tag_redraw(context)
+ return {'PASS_THROUGH'}
+
+ def cancel(self, context):
+ if type(self)._active is self:
+ self._finish(context, False)
+
+
+class SG_OT_InteractiveDiscardApply(bpy.types.Operator):
+ bl_idname = 'stablegen.interactive_discard_apply'
+ bl_label = 'Apply Settings'
+ bl_description = 'Keep the previewed settings and restore the original scene materials'
+
+ @classmethod
+ def poll(cls, _context):
+ return SG_OT_InteractiveDiscardCheck._active is not None
+
+ def execute(self, _context):
+ SG_OT_InteractiveDiscardCheck._active._finish_requested = 'APPLY'
+ return {'FINISHED'}
+
+
+class SG_OT_InteractiveDiscardCancel(bpy.types.Operator):
+ bl_idname = 'stablegen.interactive_discard_cancel'
+ bl_label = 'Cancel'
+ bl_description = 'Restore the settings and scene state from before the preview'
+
+ @classmethod
+ def poll(cls, _context):
+ return SG_OT_InteractiveDiscardCheck._active is not None
+
+ def execute(self, _context):
+ SG_OT_InteractiveDiscardCheck._active._finish_requested = 'CANCEL'
+ return {'FINISHED'}
+
+
# ─── Registration list ───────────────────────────────────────────────────
+class SG_OT_DebugProjectionLine(bpy.types.Operator):
+ """Draw a line over the projected model and export reproducible view-weight diagnostics."""
+
+ bl_idname = 'stablegen.debug_projection_line'
+ bl_label = 'Projection Line Diagnostics'
+ bl_description = ('Click two points in the 3D viewport; compare ordinary '
+ 'camera weighting, DPPG guards, and coverage rescue along the line')
+ bl_options = {'REGISTER'}
+
+ _active = None
+ status = ''
+ last_report = ''
+
+ @classmethod
+ def poll(cls, context):
+ return _common_poll(cls, context) and cls._active is None
+
+ def _viewport(self, context, x, y):
+ for area in context.window.screen.areas:
+ if area.type != 'VIEW_3D':
+ continue
+ for region in area.regions:
+ if (region.type == 'WINDOW' and region.x <= x < region.x + region.width
+ and region.y <= y < region.y + region.height):
+ return area, region
+ return None, None
+
+ def _draw_line(self):
+ if len(self._points) == 0:
+ return
+ import gpu
+ from gpu_extras.batch import batch_for_shader
+ area = bpy.context.area
+ if area is None or area.as_pointer() != self._area_ptr:
+ return
+ region = next((r for r in area.regions if r.type == 'WINDOW'), None)
+ if region is None:
+ return
+ points = self._points + [self._mouse]
+ coords = [(p[0] - region.x, p[1] - region.y) for p in points]
+ shader = gpu.shader.from_builtin('UNIFORM_COLOR')
+ batch = batch_for_shader(shader, 'LINE_STRIP', {'pos': coords})
+ gpu.state.line_width_set(4)
+ shader.bind()
+ shader.uniform_float('color', (1, 1, 1, 1))
+ batch.draw(shader)
+ gpu.state.line_width_set(1)
+
+ def _cleanup(self, context):
+ if getattr(self, '_draw', None) is not None:
+ bpy.types.SpaceView3D.draw_handler_remove(self._draw, 'WINDOW')
+ self._draw = None
+ if getattr(self, '_timer', None) is not None:
+ context.window_manager.event_timer_remove(self._timer)
+ self._timer = None
+ for area in context.window.screen.areas:
+ if area.type == 'VIEW_3D':
+ area.tag_redraw()
+ if self._active is self:
+ type(self)._active = None
+
+ def invoke(self, context, _event):
+ if any((slot.material and slot.material.use_nodes and
+ (slot.material.get('sg_surface_blend') or any(
+ node.label.startswith('SurfaceBlendWeight-')
+ for node in slot.material.node_tree.nodes)))
+ for obj in context.scene.objects if obj.type == 'MESH' and not obj.hide_render
+ for slot in obj.material_slots):
+ self.report({'ERROR'}, 'Current material uses baked Surface Blend weights; reproject with Boundary Crossfade or Local Unsharpen for this comparison')
+ return {'CANCELLED'}
+ if context.scene.generation_method == 'local_edit' or (
+ context.scene.model_architecture.startswith('qwen')
+ and context.scene.qwen_generation_method == 'local_edit'):
+ self.report({'ERROR'}, 'Line diagnostics currently require an ordinary multi-view projection, not a local edit pass')
+ return {'CANCELLED'}
+ if not any(_projection_line_has_sources(obj) for obj in context.scene.objects
+ if obj.type == 'MESH' and not obj.hide_render):
+ self.report({'ERROR'}, 'No StableGen projected material found on visible meshes')
+ return {'CANCELLED'}
+ self._points = []
+ self._mouse = (0, 0)
+ self._area_ptr = None
+ self._draw = bpy.types.SpaceView3D.draw_handler_add(
+ self._draw_line, (), 'WINDOW', 'POST_PIXEL')
+ self._timer = None
+ self._process = None
+ self._log = None
+ type(self)._active = self
+ type(self).status = 'Click two points in a 3D viewport; Esc cancels'
+ context.window_manager.modal_handler_add(self)
+ return {'RUNNING_MODAL'}
+
+ def _capture(self, context):
+ area = next(a for a in context.window.screen.areas
+ if a.as_pointer() == self._area_ptr)
+ region = next(r for r in area.regions if r.type == 'WINDOW')
+ space = area.spaces.active
+ depsgraph = context.evaluated_depsgraph_get()
+ count = 192
+ p0, p1 = self._points
+ samples = []
+ for i in range(count):
+ t = i / (count - 1)
+ x = p0[0] + t * (p1[0] - p0[0]) - region.x
+ y = p0[1] + t * (p1[1] - p0[1]) - region.y
+ origin = view3d_utils.region_2d_to_origin_3d(region, space.region_3d, (x, y))
+ direction = view3d_utils.region_2d_to_vector_3d(region, space.region_3d, (x, y))
+ hit, point, normal, face, obj, _matrix = context.scene.ray_cast(
+ depsgraph, origin, direction, distance=1e7)
+ samples.append({'t': t, 'screen': [x, y],
+ 'point': list(point) if hit and obj and _projection_line_has_sources(obj) else None,
+ 'normal': list(normal) if hit and obj and _projection_line_has_sources(obj) else None,
+ 'face': int(face) if hit else None,
+ 'object': obj.name if hit and obj else None})
+ if not any(s['point'] for s in samples):
+ raise RuntimeError('The line did not cross a visible StableGen projected mesh')
+ cameras = _interactive_generation_cameras(context)
+ if not cameras:
+ raise RuntimeError('No generation cameras found')
+ meshes = [o for o in context.scene.objects if o.type == 'MESH'
+ and _projection_line_has_sources(o)]
+ material_id = _projection_line_material_id(meshes[0])
+ root = _interactive_generation_root(context, meshes, material_id)
+ run_root = Path(root) / 'debug' / ('projection_line_' + datetime.now().strftime('%Y%m%d_%H%M%S'))
+ run_root.mkdir(parents=True, exist_ok=False)
+ replay_source = Path(__file__).parent / 'texturing' / 'projection_line_diagnostics.py'
+ shutil.copy2(replay_source, run_root / 'replay.py')
+ view = space.region_3d
+ matrix = view.view_matrix.inverted()
+ manifest = {
+ 'schema': 'stablegen.projection-line.v1',
+ 'snapshot': 'snapshot.blend',
+ 'source_blend': bpy.data.filepath,
+ 'frame': context.scene.frame_current,
+ 'cameras': [c.name for c in cameras],
+ 'line_screen_global': [list(p) for p in self._points],
+ 'view': {'matrix_world': [list(row) for row in matrix],
+ 'lens': float(space.lens), 'perspective': view.view_perspective,
+ 'view_distance': float(view.view_distance),
+ 'viewport_size': [region.width, region.height]},
+ 'render_width': 1024,
+ 'render_height': max(256, round(1024 * region.height / max(1, region.width))),
+ 'samples': samples,
+ 'settings': {name: _copy_scene_value(getattr(context.scene, name))
+ for name in (
+ 'weight_exponent', 'discard_angle',
+ 'sg_rework_projection_guard', 'sg_guard_feather_method',
+ 'sg_silhouette_margin', 'sg_silhouette_feather',
+ 'sg_projection_guard_scale', 'sg_guard_directional',
+ 'sg_guard_foreground_margin', 'sg_guard_coverage_rescue')
+ if hasattr(context.scene, name)},
+ 'comparison': 'current material graph versus the same graph with DPPG guard/feather outputs bypassed',
+ }
+ (run_root / 'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
+ # Make linked images resolve from the copy without changing the user's
+ # scene. Save As(copy=True) leaves the live document at its original path.
+ old_paths = []
+ try:
+ for image in bpy.data.images:
+ if image.source == 'FILE' and image.filepath and image.library is None:
+ old_paths.append((image, image.filepath))
+ image.filepath = bpy.path.abspath(image.filepath, library=image.library)
+ bpy.ops.wm.save_as_mainfile(filepath=str(run_root / manifest['snapshot']), copy=True)
+ finally:
+ for image, filepath in old_paths:
+ image.filepath = filepath
+ return run_root
+
+ def modal(self, context, event):
+ if self._process is not None:
+ if event.type == 'ESC' and event.value == 'PRESS':
+ self._process.terminate()
+ self._process.wait(timeout=5)
+ self._log.close()
+ self._cleanup(context)
+ type(self).status = 'Diagnostic cancelled; files kept in ' + str(self._root)
+ return {'CANCELLED'}
+ if event.type != 'TIMER' or getattr(event, 'timer', self._timer) != self._timer:
+ return {'RUNNING_MODAL'}
+ code = self._process.poll()
+ if code is None:
+ return {'RUNNING_MODAL'}
+ self._log.close()
+ report = self._root / 'index.html'
+ self._cleanup(context)
+ if code == 0 and report.is_file():
+ type(self).last_report = str(report)
+ type(self).status = 'Report ready: ' + str(report)
+ self.report({'INFO'}, 'Projection line report ready: ' + str(report))
+ return {'FINISHED'}
+ type(self).status = 'Diagnostic failed; see ' + str(self._root / 'run.log')
+ self.report({'ERROR'}, type(self).status)
+ return {'CANCELLED'}
+ if event.type in {'ESC', 'RIGHTMOUSE'} and event.value == 'PRESS':
+ self._cleanup(context)
+ type(self).status = ''
+ return {'CANCELLED'}
+ self._mouse = (event.mouse_x, event.mouse_y)
+ area, _region = self._viewport(context, *self._mouse)
+ if area and self._area_ptr is None:
+ self._area_ptr = area.as_pointer()
+ if area:
+ area.tag_redraw()
+ if event.type == 'LEFTMOUSE' and event.value == 'PRESS' and area:
+ if area.as_pointer() != self._area_ptr:
+ return {'RUNNING_MODAL'}
+ self._points.append(self._mouse)
+ if len(self._points) < 2:
+ return {'RUNNING_MODAL'}
+ try:
+ self._root = self._capture(context)
+ self._draw and bpy.types.SpaceView3D.draw_handler_remove(self._draw, 'WINDOW')
+ self._draw = None
+ self._log = (self._root / 'run.log').open('w', encoding='utf-8')
+ self._process = subprocess.Popen(
+ [bpy.app.binary_path, '--background', str(self._root / 'snapshot.blend'),
+ '--python', str(self._root / 'replay.py'), '--',
+ str(self._root / 'manifest.json')],
+ stdout=self._log, stderr=subprocess.STDOUT,
+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
+ self._timer = context.window_manager.event_timer_add(.5, window=context.window)
+ type(self).status = 'Rendering projection contributions in background…'
+ except Exception as error:
+ self._cleanup(context)
+ type(self).status = str(error)
+ self.report({'ERROR'}, str(error))
+ return {'CANCELLED'}
+ return {'RUNNING_MODAL'}
+ return {'RUNNING_MODAL'}
+
+
+def _projection_line_has_sources(obj):
+ if obj.type != 'MESH':
+ return False
+ for slot in obj.material_slots:
+ if not slot.material or not slot.material.use_nodes:
+ continue
+ for node in slot.material.node_tree.nodes:
+ pieces = node.label.split('-') if node.type == 'TEX_IMAGE' else []
+ if (len(pieces) == 2 and all(part.isdigit() for part in pieces)
+ and node.image is not None):
+ return True
+ return False
+
+
+def _projection_line_material_id(obj):
+ for slot in obj.material_slots:
+ if slot.material and slot.material.use_nodes:
+ for node in slot.material.node_tree.nodes:
+ pieces = node.label.split('-') if node.type == 'TEX_IMAGE' else []
+ if (len(pieces) == 2 and all(part.isdigit() for part in pieces)
+ and node.image is not None):
+ return int(pieces[1])
+ raise RuntimeError('Projected material ID not found')
+
+
+class SG_OT_DebugOpenProjectionLine(bpy.types.Operator):
+ bl_idname = 'stablegen.debug_open_projection_line'
+ bl_label = 'Open Projection Line Report'
+ bl_options = {'REGISTER'}
+
+ @classmethod
+ def poll(cls, _context):
+ return bool(SG_OT_DebugProjectionLine.last_report
+ and Path(SG_OT_DebugProjectionLine.last_report).is_file())
+
+ def execute(self, _context):
+ bpy.ops.wm.url_open(url=Path(SG_OT_DebugProjectionLine.last_report).as_uri())
+ return {'FINISHED'}
+
debug_classes = [
SG_OT_DebugForceGenerationIdle,
SG_OT_DebugSolidColors,
@@ -1892,5 +3183,12 @@ debug_classes = [
SG_OT_DebugClearSkinningWeights,
SG_OT_DebugRestoreMaterial,
SG_OT_DebugConfidenceDiagnostic,
+ SG_OT_DebugDPPGMaterial,
+ SG_OT_DebugRestoreDPPGMaterial,
SG_OT_DebugMakeSolid,
+ SG_OT_InteractiveDiscardCheck,
+ SG_OT_InteractiveDiscardApply,
+ SG_OT_InteractiveDiscardCancel,
+ SG_OT_DebugProjectionLine,
+ SG_OT_DebugOpenProjectionLine,
]
diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.py
index 975a534..3288fa7 100644
--- a/stablegen/texturing/projection.py
+++ b/stablegen/texturing/projection.py
@@ -1835,9 +1835,28 @@ def project_image(
for area in context.screen.areas:
area.tag_redraw()
- # Apply projection to all mesh objects for each camera
+ # Apply projection to all mesh objects for each camera. Interactive
+ # diagnostics can reuse the attributes created by the original generation;
+ # this keeps a live preview from repeatedly applying UV Project modifiers.
+ if reuse_projection_uv:
+ missing = [
+ f"{obj.name}:ProjectionUV_{i}_{mat_id}"
+ for i, _camera in enumerate(cameras)
+ for obj in to_project
+ if obj.data.attributes.get(f"ProjectionUV_{i}_{mat_id}") is None
+ ]
+ if missing:
+ sample = ", ".join(missing[:3])
+ raise RuntimeError(
+ "Existing projection UV data is missing (" + sample + "). "
+ "Run texture generation or Reproject Textures first."
+ )
+
+ # Apply projection to all mesh objects for each camera.
for i, camera in enumerate(cameras):
for x, obj in enumerate(to_project):
+ if reuse_projection_uv:
+ continue
# We can skip the UV Projection step in sequential mode for i > 0
if context.scene.generation_method != 'sequential' or stop_index == 0:
# Deselect all objects
@@ -1901,11 +1920,12 @@ def project_image(
original_uv_map = obj.data.uv_layers[1]
obj.data.uv_layers.active = original_uv_map
- # Clean up buffer UV map from all objects
- for obj in to_project:
- buffer_uv = obj.data.uv_layers.get(_SG_BUFFER_UV_NAME)
- if buffer_uv:
- obj.data.uv_layers.remove(buffer_uv)
+ # Clean up the temporary buffer only when this call created projection UVs.
+ if not reuse_projection_uv:
+ for obj in to_project:
+ buffer_uv = obj.data.uv_layers.get(_SG_BUFFER_UV_NAME)
+ if buffer_uv:
+ obj.data.uv_layers.remove(buffer_uv)
# ── Optional: bake per-vertex visibility weights ──────────────────
use_baked_weights = (
@@ -1928,7 +1948,15 @@ def project_image(
and obj.data.attributes.get(f"_SG_ProjectionDepth_{cam_idx}_{mat_id}") is None)
for obj in to_project for cam_idx in range(len(cameras))
)
- if not is_sequential or stop_index == 0 or missing_bake:
+ if reuse_projection_uv and missing_bake:
+ # Saved projection materials from before transform-stable weights
+ # can legitimately have reusable ProjectionUV attributes without
+ # the newer _SG_VisWeight attributes. An interactive preview must
+ # stay non-destructive, so use the dynamic raycast graph rather
+ # than baking new mesh data merely to inspect the context.
+ use_baked_weights = False
+ if (not reuse_projection_uv
+ and (not is_sequential or stop_index == 0 or missing_bake)):
_bake_visibility_weights(context, to_project, cameras, mat_id)
# Switch to Cycles (needed for Raycast shader node on all versions)
@@ -2905,6 +2933,7 @@ def project_image(
subtract_node = nodes.new("ShaderNodeMath")
subtract_node.operation = 'SUBTRACT'
subtract_node.inputs[0].default_value = mat_id
+ subtract_node.label = 'SGMaterialIndex'
subtract_node.location = (-1000, 0)
return True
diff --git a/stablegen/texturing/projection_line_diagnostics.py b/stablegen/texturing/projection_line_diagnostics.py
new file mode 100644
index 0000000..7370320
--- /dev/null
+++ b/stablegen/texturing/projection_line_diagnostics.py
@@ -0,0 +1,440 @@
+"""Replayable, shader-derived contribution probes for StableGen projections.
+
+This module deliberately has no imports from the add-on: a copy of this file
+can be run with ``blender --background snapshot.blend --python replay.py --
+manifest.json`` even when the source checkout is no longer available.
+"""
+
+import csv
+import html
+import json
+import math
+import os
+import sys
+from array import array
+from pathlib import Path
+
+import bpy
+from bpy_extras.object_utils import world_to_camera_view
+from mathutils import Matrix, Vector
+
+
+def _projection_image_nodes(material):
+ if not material or not material.use_nodes:
+ return {}
+ result = {}
+ for node in material.node_tree.nodes:
+ if node.type != 'TEX_IMAGE' or node.image is None:
+ continue
+ pieces = node.label.split('-')
+ if len(pieces) == 2 and pieces[0].isdigit() and pieces[1].isdigit():
+ result[int(pieces[0])] = node
+ return result
+
+
+def _constant(tree, value):
+ node = tree.nodes.new('ShaderNodeValue')
+ node.label = 'Line diagnostic DPPG bypass'
+ node.outputs[0].default_value = value
+ return node.outputs[0]
+
+
+def bypass_dppg(material):
+ """Bypass just the guard fields in an already-built projection graph."""
+ tree = material.node_tree
+ one, zero = _constant(tree, 1.0), _constant(tree, 0.0)
+ counts = {'hard_guard': 0, 'feather': 0, 'occlusion': 0, 'influence': 0}
+ for node in list(tree.nodes):
+ if node.label.startswith('ProjectionGuardWeight-'):
+ replacement, key = one, 'hard_guard'
+ elif node.label.startswith('ProjectionGuardFeather-'):
+ replacement, key = one, 'feather'
+ elif node.name.startswith('SGOcclusionFeather-'):
+ replacement, key = one, 'occlusion'
+ elif (node.name.startswith('SGOcclusionInfluence-')
+ or node.name.startswith('SGFeatherInfluence-')):
+ replacement, key = zero, 'influence'
+ else:
+ continue
+ for link in list(node.outputs[0].links):
+ tree.links.new(replacement, link.to_socket)
+ counts[key] += 1
+ return counts
+
+
+def disable_coverage_rescue(material):
+ """Keep DPPG guards/feathers, but make rescue retain them at full strength."""
+ tree = material.node_tree
+ one = _constant(tree, 1.0)
+ count = 0
+ for node in list(tree.nodes):
+ if node.label != 'GuardRescueStrength':
+ continue
+ for link in list(node.outputs[0].links):
+ tree.links.new(one, link.to_socket)
+ count += 1
+ return count
+
+
+def _prepare_materials(scene, mode):
+ """Keep geometry and the complete mix tree; substitute one-hot colors."""
+ if mode not in ('current', 'guard_only', 'ordinary'):
+ raise ValueError(mode)
+ probes = []
+ modification_counts = {'dppg_bypass_links': {}, 'rescue_bypass_links': 0}
+ for obj in scene.objects:
+ if obj.type != 'MESH' or obj.hide_render:
+ continue
+ for slot in obj.material_slots:
+ original = slot.material
+ if original is None:
+ continue
+ clone = original.copy()
+ clone.name = 'SG line probe ' + original.name
+ slot.material = clone
+ sources = _projection_image_nodes(clone)
+ tree = clone.node_tree if clone.use_nodes else None
+ if tree is None:
+ clone.use_nodes = True
+ tree = clone.node_tree
+ if clone.get('sg_surface_blend') or any(
+ n.label.startswith('SurfaceBlendWeight-') for n in tree.nodes):
+ raise RuntimeError('Surface Blend stores DPPG in baked fields; this graph-bypass comparison does not apply')
+ if mode == 'ordinary':
+ counts = bypass_dppg(clone)
+ for key, value in counts.items():
+ bypass = modification_counts['dppg_bypass_links']
+ bypass[key] = bypass.get(key, 0) + value
+ elif mode == 'guard_only':
+ modification_counts['rescue_bypass_links'] += disable_coverage_rescue(clone)
+ # The base-case fallback is a constant Color2 on the final MixRGB.
+ # Make it black so a missing view contributes zero to every probe.
+ for node in tree.nodes:
+ if (node.type == 'MIX_RGB' and node.inputs['Color1'].is_linked
+ and node.inputs['Fac'].is_linked
+ and not node.inputs['Color2'].is_linked):
+ node.inputs['Color2'].default_value = (0, 0, 0, 1)
+ output = next((n for n in tree.nodes
+ if n.type == 'OUTPUT_MATERIAL' and n.is_active_output), None)
+ if output is None:
+ output = tree.nodes.new('ShaderNodeOutputMaterial')
+ source = (output.inputs['Surface'].links[0].from_socket
+ if output.inputs['Surface'].links else None)
+ emit = tree.nodes.new('ShaderNodeEmission')
+ emit.label = 'Line diagnostic: final projection color'
+ emit.inputs['Strength'].default_value = 1.0
+ if source is not None and sources:
+ tree.links.new(source, emit.inputs['Color'])
+ else:
+ emit.inputs['Color'].default_value = (0, 0, 0, 1)
+ tree.links.new(emit.outputs[0], output.inputs['Surface'])
+ for index, node in sources.items():
+ rgb = tree.nodes.new('ShaderNodeRGB')
+ rgb.label = f'Line diagnostic: view {index}'
+ rgb.outputs[0].default_value = (0, 0, 0, 1)
+ for link in list(node.outputs['Color'].links):
+ tree.links.new(rgb.outputs[0], link.to_socket)
+ probes.append((index, rgb))
+ if not probes:
+ raise RuntimeError('No StableGen projection image nodes found in visible mesh materials')
+ return probes, modification_counts
+
+
+def _render_setup(scene, manifest, directory):
+ scene.render.engine = 'CYCLES'
+ scene.cycles.device = 'CPU'
+ scene.cycles.samples = 4
+ scene.cycles.seed = 0
+ if hasattr(scene.cycles, 'use_animated_seed'):
+ scene.cycles.use_animated_seed = False
+ scene.render.resolution_x = int(manifest.get('render_width', 1024))
+ scene.render.resolution_y = int(manifest.get('render_height', 768))
+ scene.render.resolution_percentage = 100
+ scene.render.image_settings.file_format = 'OPEN_EXR'
+ scene.render.image_settings.color_mode = 'RGBA'
+ scene.render.image_settings.color_depth = '32'
+ scene.render.film_transparent = True
+ scene.render.use_file_extension = True
+ scene.view_settings.view_transform = 'Raw'
+ scene.render.filepath = str(directory / 'probe')
+ scene.render.use_compositing = False
+ scene.render.use_sequencer = False
+ for light in scene.objects:
+ if light.type == 'LIGHT':
+ light.hide_render = True
+ camera = bpy.data.cameras.new('SG line diagnostic camera')
+ orthographic = manifest['view'].get('perspective') == 'ORTHO'
+ camera.type = 'ORTHO' if orthographic else 'PERSP'
+ if orthographic:
+ camera.ortho_scale = float(manifest['view'].get('view_distance', 10.0)) * 1.5
+ else:
+ camera.lens = float(manifest['view']['lens'])
+ camera_obj = bpy.data.objects.new('SG line diagnostic camera', camera)
+ scene.collection.objects.link(camera_obj)
+ camera_obj.matrix_world = Matrix(manifest['view']['matrix_world'])
+ scene.camera = camera_obj
+ # Preserve the capture direction but widen the frame if the line reaches
+ # beyond the original viewport bounds.
+ points = [Vector(s['point']) for s in manifest['samples'] if s.get('point')]
+ for _ in range(12):
+ projected = [world_to_camera_view(scene, camera_obj, p) for p in points]
+ if all(p.z > 0 and .035 < p.x < .965 and .035 < p.y < .965
+ for p in projected):
+ break
+ if orthographic:
+ camera.ortho_scale *= 1.25
+ else:
+ camera.lens *= .8
+ return camera_obj
+
+
+def _read_exr(path, width, height):
+ image = bpy.data.images.load(str(path), check_existing=False)
+ try:
+ pixels = array('f', [0]) * (width * height * 4)
+ image.pixels.foreach_get(pixels)
+ return pixels
+ finally:
+ bpy.data.images.remove(image)
+
+
+def _sample_render(scene, camera, manifest, pixels):
+ width, height = scene.render.resolution_x, scene.render.resolution_y
+ depsgraph = bpy.context.evaluated_depsgraph_get()
+ out = []
+ for sample in manifest['samples']:
+ if not sample.get('point'):
+ out.append(None)
+ continue
+ uv = world_to_camera_view(scene, camera, Vector(sample['point']))
+ x, y = int(uv.x * width), int(uv.y * height)
+ if uv.z <= 0 or x < 0 or x >= width or y < 0 or y >= height:
+ out.append(None)
+ continue
+ # A different foreground surface can otherwise yield plausible but
+ # false weights for a stored point near an occlusion boundary.
+ target = Vector(sample['point'])
+ if camera.data.type == 'ORTHO':
+ origin = target + camera.matrix_world.to_quaternion() @ Vector((0, 0, 1000))
+ else:
+ origin = camera.matrix_world.translation
+ ray = target - origin
+ distance = ray.length
+ hit, location, _normal, _face, obj, _matrix = scene.ray_cast(
+ depsgraph, origin, ray.normalized(),
+ distance=distance + max(.005, distance * .002))
+ if (not hit or obj is None or obj.name != sample['object']
+ or (location - target).length > max(.005, distance * .002)):
+ out.append(None)
+ continue
+ offset = 4 * (y * width + x)
+ out.append(tuple(max(0.0, min(1.0, pixels[offset + c]))
+ for c in range(3)))
+ return out
+
+
+def _measure(manifest, directory, mode):
+ # Reload for each condition so every counterfactual starts from the same
+ # saved material, never from a partly modified prior probe.
+ bpy.ops.wm.open_mainfile(filepath=manifest['snapshot'])
+ scene = bpy.context.scene
+ scene.frame_set(int(manifest['frame']))
+ camera = _render_setup(scene, manifest, directory)
+ probes, modification_counts = _prepare_materials(scene, mode)
+ count = len(manifest['cameras'])
+ data = [[0.0] * count if s.get('point') else None
+ for s in manifest['samples']]
+ for start in range(0, count, 3):
+ for index, rgb in probes:
+ rgb.outputs[0].default_value = tuple(
+ 1.0 if index == start + channel else 0.0
+ for channel in range(3)) + (1.0,)
+ scene.render.filepath = str(directory / f'probe_{mode}_{start:03d}')
+ print(f'[SG line] {mode}, views {start + 1}-{min(start + 3, count)}', flush=True)
+ bpy.ops.render.render(write_still=True)
+ path = Path(scene.render.filepath + '.exr')
+ pixels = _read_exr(path, scene.render.resolution_x, scene.render.resolution_y)
+ triplets = _sample_render(scene, camera, manifest, pixels)
+ for row, rgb_values in zip(data, triplets):
+ if row is not None and rgb_values is not None:
+ for channel, value in enumerate(rgb_values):
+ if start + channel < count:
+ row[start + channel] = value
+ path.unlink(missing_ok=True)
+ return data, modification_counts
+
+
+def _svg(data, labels, title, palette, signed=False):
+ width, left, right, top = 1000, 62, 20, 35
+ bottom = 62 + 16 * math.ceil(len(labels) / 4)
+ height = top + 205 + bottom
+ inner_w, inner_h = width - left - right, height - top - bottom
+ parts = [f'<svg viewBox="0 0 {width} {height}" role="img" aria-label="{html.escape(title)}">',
+ f'<rect width="{width}" height="{height}" fill="#20242a"/>',
+ f'<text x="{left}" y="23" fill="#fff" font-size="17">{html.escape(title)}</text>']
+ marks = (-1, -.5, 0, .5, 1) if signed else (0, .25, .5, .75, 1)
+ for mark in marks:
+ y = top + inner_h * (1 - mark) / (2 if signed else 1)
+ parts.append(f'<path d="M{left} {y:.1f}H{width-right}" stroke="#50545b" stroke-width="1"/>')
+ parts.append(f'<text x="{left-9}" y="{y+4:.1f}" text-anchor="end" fill="#b9bcc4" font-size="12">{mark:+.2f}</text>')
+ parts.append(f'<text x="{left}" y="{top+inner_h+22}" fill="#b9bcc4" font-size="12">Start</text>')
+ parts.append(f'<text x="{width-right}" y="{top+inner_h+22}" text-anchor="end" fill="#b9bcc4" font-size="12">End</text>')
+ for i, label in enumerate(labels):
+ segments, points = [], []
+ for sample_index, row in enumerate(data):
+ if row is None or i >= len(row) or row[i] is None:
+ if points:
+ segments.append(points)
+ points = []
+ continue
+ x = left + inner_w * sample_index / max(1, len(data)-1)
+ value = max(-1, min(1, row[i])) if signed else max(0, min(1, row[i]))
+ y = top + inner_h * (1 - value) / (2 if signed else 1)
+ points.append(f'{x:.1f},{y:.1f}')
+ if points:
+ segments.append(points)
+ color = palette[i % len(palette)]
+ for segment in segments:
+ parts.append(f'<polyline points="{" ".join(segment)}" fill="none" stroke="{color}" stroke-width="2"/>')
+ parts.append(f'<text x="{left + (i % 4)*220}" y="{height-17 - (i//4)*16}" fill="{color}" font-size="12">{html.escape(label)}</text>')
+ parts.append('</svg>')
+ return '\n'.join(parts)
+
+
+def _write_report(manifest, directory, current, guard_only, ordinary, modifications):
+ palette = ['#ff7575', '#80aaff', '#84e19d', '#e9c777', '#b08bff',
+ '#80dfe9', '#f69bd5', '#b7da78', '#ffad80', '#8f91eb']
+ labels = manifest['cameras']
+ rows = []
+ graphs = {name: [] for name in ('current', 'guard_only', 'ordinary',
+ 'guard_effect', 'rescue_effect', 'total_dppg_effect')}
+ for index, sample in enumerate(manifest['samples']):
+ a, b, c = current[index], guard_only[index], ordinary[index]
+ if a is None or b is None or c is None:
+ for graph in graphs.values():
+ graph.append(None)
+ rows.append({'sample': index, 't': sample['t'],
+ 'status': 'miss' if sample.get('point') is None else 'not_visible_in_replay'})
+ continue
+ guard_effect = [guard - usual for guard, usual in zip(b, c)]
+ rescue_effect = [full - guard for full, guard in zip(a, b)]
+ total_effect = [full - usual for full, usual in zip(a, c)]
+ values = {'current': a, 'guard_only': b, 'ordinary': c,
+ 'guard_effect': guard_effect, 'rescue_effect': rescue_effect,
+ 'total_dppg_effect': total_effect}
+ for name, graph in graphs.items():
+ graph.append(values[name])
+ rows.append({'sample': index, 't': sample['t'], 'status': 'hit',
+ 'object': sample['object'], 'face': sample['face'],
+ 'world_point': sample['point'], 'world_normal': sample['normal'],
+ **values, 'current_total': sum(a), 'guard_only_total': sum(b),
+ 'ordinary_total': sum(c),
+ # Preserve the original two-stage fields for older analysis scripts.
+ 'dppg_on': a, 'dppg_off': c,
+ 'off_minus_on': [usual - full for full, usual in zip(a, c)],
+ 'on_total': sum(a), 'off_total': sum(c)})
+ handoffs = []
+ for previous, following in zip(rows, rows[1:]):
+ if previous['status'] != 'hit' or following['status'] != 'hit':
+ continue
+ for camera_index, camera_name in enumerate(labels):
+ changes = {stage: following[stage][camera_index] - previous[stage][camera_index]
+ for stage in ('ordinary', 'guard_only', 'current')}
+ handoffs.append({'from_sample': previous['sample'], 'to_sample': following['sample'],
+ 'camera_index': camera_index, 'camera': camera_name,
+ **changes,
+ 'guard_effect': changes['guard_only'] - changes['ordinary'],
+ 'rescue_effect': changes['current'] - changes['guard_only']})
+ result = {'schema': 'stablegen.projection-line.v2', 'manifest': 'manifest.json',
+ 'camera_order': labels, **modifications, 'samples': rows,
+ 'handoffs': handoffs,
+ 'attribution_order': ['ordinary', 'guard_only', 'current'],
+ 'effect_definitions': {
+ 'guard_effect': 'guard_only - ordinary',
+ 'rescue_effect': 'current - guard_only',
+ 'total_dppg_effect': 'current - ordinary'}}
+ (directory / 'results.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
+ with (directory / 'samples.csv').open('w', newline='', encoding='utf-8') as stream:
+ fieldnames = ['sample', 't', 'status', 'object', 'face', 'world_x', 'world_y', 'world_z',
+ 'ordinary_total', 'guard_only_total', 'current_total']
+ for mode in graphs:
+ fieldnames.extend(f'{mode}_view_{i:03d}' for i in range(len(labels)))
+ writer = csv.DictWriter(stream, fieldnames=fieldnames)
+ writer.writeheader()
+ for row in rows:
+ flat = {key: row.get(key, '') for key in fieldnames[:5]}
+ if row['status'] == 'hit':
+ flat.update(zip(('world_x', 'world_y', 'world_z'), row['world_point']))
+ flat.update(ordinary_total=row['ordinary_total'],
+ guard_only_total=row['guard_only_total'],
+ current_total=row['current_total'])
+ for mode in graphs:
+ values = row[mode]
+ for i, value in enumerate(values):
+ flat[f'{mode}_view_{i:03d}'] = value
+ writer.writerow(flat)
+ valid = [r for r in rows if r['status'] == 'hit']
+ biggest = sorted(valid, key=lambda r: max((abs(v) for v in r['total_dppg_effect']), default=0), reverse=True)[:8]
+ peak = ''.join('<tr><td>{}</td><td>{:.3f}</td><td>{}</td><td>{:.3f}</td><td>{:.3f}</td><td>{:.3f}</td></tr>'.format(
+ r['sample'], r['t'], html.escape(r['object']),
+ max(abs(v) for v in r['guard_effect']),
+ max(abs(v) for v in r['rescue_effect']),
+ max(abs(v) for v in r['total_dppg_effect']))
+ for r in biggest)
+ steepest = sorted(handoffs, key=lambda h: abs(h['current']), reverse=True)[:10]
+ handoff_table = ''.join(
+ '<tr><td>{}–{}</td><td>{}</td><td>{:+.3f}</td><td>{:+.3f}</td><td>{:+.3f}</td><td>{:+.3f}</td><td>{:+.3f}</td></tr>'.format(
+ h['from_sample'], h['to_sample'], html.escape(h['camera']),
+ h['ordinary'], h['guard_only'], h['current'],
+ h['guard_effect'], h['rescue_effect']) for h in steepest)
+ settings = ''.join(f'<tr><td>{html.escape(str(key))}</td><td>{html.escape(str(value))}</td></tr>'
+ for key, value in manifest.get('settings', {}).items())
+ page = f'''<!doctype html><html><head><meta charset="utf-8"><title>StableGen projection line</title>
+<style>body{{background:#15181d;color:#e6e9ef;font:14px system-ui;margin:30px auto;max-width:1100px}}
+svg{{width:100%;height:auto;border:1px solid #41464e;margin:10px 0}}a{{color:#87baff}}
+table{{border-collapse:collapse}}td,th{{border:1px solid #555;padding:6px 12px}}</style></head><body>
+<h1>Projection line: view-weight attribution</h1>
+<p>{len(valid)} of {len(rows)} positions hit the model. Each colored curve is one camera's contribution to the final projected color. Gaps mean the line missed the model; contribution sums can be below one where fallback/coverage remains.</p>
+<p><b>Read the stages in order:</b> Ordinary weighting keeps the saved camera angles, exponent, image alpha and mix but bypasses DPPG guards and feather. DPPG guards only restores the saved guards and feather with coverage rescue disabled. Current setup uses the complete saved graph. Thus <b>guard effect = guards only − ordinary</b>, and <b>coverage rescue effect = current − guards only</b>. Positive values give that camera more ownership; negative values take ownership away. Effects are an ordered counterfactual decomposition, so interactions are assigned to the later rescue stage.</p>
+<p><a href="samples.csv">CSV samples</a> · <a href="results.json">Full JSON</a> · <a href="manifest.json">Replay manifest</a> · <a href="replay.py">Replay script</a> · <a href="run.log">Run log</a></p>
+<h2>Camera ownership at each stage</h2>
+{_svg(graphs['ordinary'], labels, '1. Ordinary weighting (DPPG bypassed)', palette)}
+{_svg(graphs['guard_only'], labels, '2. DPPG guards and feather, no coverage rescue', palette)}
+{_svg(graphs['current'], labels, '3. Current setup, including coverage rescue', palette)}
+<h2>What each DPPG stage changes</h2>
+{_svg(graphs['guard_effect'], labels, 'DPPG guard effect: stage 2 minus stage 1', palette, signed=True)}
+{_svg(graphs['rescue_effect'], labels, 'Coverage rescue effect: stage 3 minus stage 2', palette, signed=True)}
+<p>These curves measure camera ownership, not differences in the cameras' source-image colors. A visible color seam can remain even when the ownership transition is smooth.</p>
+<h2>Sharpest camera handoffs</h2>
+<p>Each row is one camera's ownership change between adjacent line samples. The ordinary column shows any sharp transition already present before DPPG. The final two columns show how DPPG guards and coverage rescue changed that same transition; their sum with ordinary equals current.</p>
+<table><tr><th>Samples</th><th>Camera</th><th>Ordinary change</th><th>Guard-only change</th><th>Current change</th><th>Guard effect on change</th><th>Rescue effect on change</th></tr>{handoff_table}</table>
+<h2>Largest total ownership changes</h2><table><tr><th>Sample</th><th>Along line</th><th>Object</th><th>Guard effect</th><th>Rescue effect</th><th>Total DPPG effect</th></tr>{peak}</table>
+<h2>Captured settings</h2><table><tr><th>Setting</th><th>Value</th></tr>{settings}</table>
+<p>Reproduce: <code>blender --background snapshot.blend --python replay.py -- manifest.json</code></p>
+</body></html>'''
+ (directory / 'index.html').write_text(page, encoding='utf-8')
+
+
+def replay(manifest_path):
+ manifest_path = Path(manifest_path).resolve()
+ directory = manifest_path.parent
+ manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
+ snapshot = Path(manifest['snapshot'])
+ manifest['snapshot'] = str((directory / snapshot).resolve() if not snapshot.is_absolute()
+ else snapshot)
+ if not Path(manifest['snapshot']).is_file():
+ raise FileNotFoundError(manifest['snapshot'])
+ ordinary, ordinary_mods = _measure(manifest, directory, 'ordinary')
+ guard_only, guard_mods = _measure(manifest, directory, 'guard_only')
+ current, _ = _measure(manifest, directory, 'current')
+ modifications = {'dppg_bypass_links': ordinary_mods['dppg_bypass_links'],
+ 'rescue_bypass_links': guard_mods['rescue_bypass_links']}
+ _write_report(manifest, directory, current, guard_only, ordinary, modifications)
+ print(f'[SG line] Report ready: {directory / "index.html"}', flush=True)
+
+
+if __name__ == '__main__':
+ args = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else []
+ if len(args) != 1:
+ raise SystemExit('Usage: blender --background snapshot.blend --python replay.py -- manifest.json')
+ replay(args[0])
diff --git a/stablegen/texturing/rendering.py b/stablegen/texturing/rendering.py
index e3afbf0..3f37cd0 100644
--- a/stablegen/texturing/rendering.py
+++ b/stablegen/texturing/rendering.py
@@ -1483,7 +1483,8 @@ def expand_mask_to_blocks(mask_file_path, block_size=8):
def _export_visibility_impl(context, to_export, obj=None, camera_visibility=None,
- prepare_only=False, camera_render=None, camera_id=None):
+ prepare_only=False, camera_render=None, camera_id=None,
+ output_object_name=None):
"""
Exports the visibility of the mesh by temporarily altering the shading nodes.
:param context: Blender context.
@@ -1766,9 +1767,12 @@ def _export_visibility_impl(context, to_export, obj=None, camera_visibility=None
# Bake or render the texture
if not camera_visibility:
output_dir = get_dir_path(context, "uv_inpaint")["visibility"]
- output_file = f"{obj.name}_baked_visibility"
+ output_file = f"{output_object_name or obj.name}_baked_visibility"
prepare_baking(context)
- bake_texture(context, obj, suffix="_visibility", texture_resolution=1024, view_transform='Raw', output_dir=output_dir)
+ if not bake_texture(context, obj, suffix="_visibility", texture_resolution=1024,
+ view_transform='Raw', output_dir=output_dir,
+ output_name=output_file):
+ raise RuntimeError(f"Could not bake visibility for {output_object_name or obj.name}")
# Use openCV to normalize the image
image_path = os.path.join(output_dir, f"{output_file}.png")
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
@@ -1821,6 +1825,7 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None,
camera_visibility=camera_visibility,
prepare_only=False, camera_render=camera_render,
camera_id=camera_id,
+ output_object_name=obj.name if obj is not None else None,
)
@@ -2544,7 +2549,8 @@ def unwrap(obj, method, overlap_only, texture_resolution=2048):
bpy.ops.uv.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
-def bake_texture(context, obj, texture_resolution, suffix = "", view_transform = 'Standard', output_dir = None):
+def bake_texture(context, obj, texture_resolution, suffix = "", view_transform = 'Standard', output_dir = None,
+ output_name=None):
"""
Bakes the texture of the given object.
:param context: Blender context.
@@ -2574,7 +2580,7 @@ def bake_texture(context, obj, texture_resolution, suffix = "", view_transform =
source_uv_name = _first_source_uv_name(obj)
bake_uv = _set_bake_uv_active(obj)
- image_name = f"{obj.name}_baked{suffix}"
+ image_name = output_name or f"{obj.name}_baked{suffix}"
old_image = bpy.data.images.get(image_name)
if old_image is not None and old_image.users == 0:
bpy.data.images.remove(old_image)
@@ -2661,7 +2667,9 @@ def bake_texture(context, obj, texture_resolution, suffix = "", view_transform =
if output_dir is None:
output_dir = get_dir_path(context, "baked")
os.makedirs(output_dir, exist_ok=True)
- if suffix == "":
+ if output_name is not None:
+ image.filepath_raw = os.path.join(output_dir, f"{output_name}.png")
+ elif suffix == "":
image.filepath_raw = os.path.join(output_dir, f"{obj.name}.png")
else:
image.filepath_raw = os.path.join(
diff --git a/stablegen/ui/panel.py b/stablegen/ui/panel.py
index ae89855..16ba3a9 100644
--- a/stablegen/ui/panel.py
+++ b/stablegen/ui/panel.py
@@ -2302,6 +2302,95 @@ class StableGenPanel(bpy.types.Panel):
row = tools_box.row()
row.operator("object.stablegen_reproject", text="Reproject Textures", icon="FILE_REFRESH")
+ from ..debug_tools import SG_OT_InteractiveDiscardCheck
+ discard_check = SG_OT_InteractiveDiscardCheck._active
+ if discard_check is None:
+ row = tools_box.row()
+ row.operator(
+ "stablegen.interactive_discard_check",
+ text="Interactive Discard Check",
+ icon="CAMERA_DATA",
+ )
+ else:
+ preview_box = tools_box.box()
+ header = preview_box.row()
+ header.label(text="Interactive Discard Check", icon="CAMERA_DATA")
+ if SG_OT_InteractiveDiscardCheck.status:
+ preview_box.label(text=SG_OT_InteractiveDiscardCheck.status)
+
+ preview_box.prop(scene, "discard_factor", text="Discard Angle", slider=True)
+ context_box = preview_box.box()
+ context_box.label(text="Context Render Options")
+
+ if scene.model_architecture != 'qwen_image_21':
+ context_box.prop(
+ scene,
+ "qwen_prompt_gray_background",
+ text="Prompt: Gray Background",
+ toggle=True,
+ )
+
+ colors_box = context_box.box()
+ colors_box.label(text="Context Render Colors")
+ if scene.model_architecture != 'qwen_image_21':
+ colors_box.prop(
+ scene, "qwen_guidance_background_color", text="Background"
+ )
+ colors_box.prop(
+ scene, "qwen_guidance_fallback_color", text="Fallback"
+ )
+
+ context_box.prop(
+ scene,
+ "qwen_use_confidence_context",
+ text="Confidence-Gated Context",
+ toggle=True,
+ icon="MOD_MASK",
+ )
+ if scene.qwen_use_confidence_context:
+ context_box.prop(
+ scene, "qwen_trust_threshold", text="Trusted Quality", slider=True
+ )
+ else:
+ context_box.prop(
+ scene,
+ "qwen_context_fallback_dilation",
+ text="Legacy Fallback Dilate (px)",
+ slider=True,
+ )
+ context_box.prop(
+ scene,
+ "qwen_context_cleanup",
+ text="Legacy Cleanup",
+ toggle=True,
+ icon="BRUSH_DATA",
+ )
+ if scene.qwen_context_cleanup:
+ context_box.prop(
+ scene,
+ "qwen_context_cleanup_hue_tolerance",
+ text="Hue Tol (°)",
+ slider=True,
+ )
+ context_box.prop(
+ scene,
+ "qwen_context_cleanup_value_adjust",
+ text="Value Adjust",
+ slider=True,
+ )
+
+ actions = preview_box.row(align=True)
+ actions.operator(
+ "stablegen.interactive_discard_apply",
+ text="Apply Settings",
+ icon="CHECKMARK",
+ )
+ actions.operator(
+ "stablegen.interactive_discard_cancel",
+ text="Cancel",
+ icon="LOOP_BACK",
+ )
+
row = tools_box.row()
row.operator("object.stablegen_mirror_reproject", text="Mirror Last Projection", icon="MOD_MIRROR")
if width_mode == 'narrow':
@@ -2320,80 +2409,61 @@ class StableGenPanel(bpy.types.Panel):
if prefs and prefs.preferences.enable_debug:
layout.separator()
debug_box = layout.box()
- row = debug_box.row()
- row.alignment = 'CENTER'
- row.label(text="Debug / Diagnostics", icon="GHOST_ENABLED")
+ title = debug_box.row()
+ title.alignment = 'CENTER'
+ title.label(text="Debug / Diagnostics", icon="GHOST_ENABLED")
from ..texturing.regression import SG_OT_TexturingRegression
+ from ..debug_tools import SG_OT_DebugProjectionLine
+
+ columns = 1 if width_mode == 'narrow' else 2
+ debug_box.label(text="Projection")
+ grid = debug_box.grid_flow(row_major=True, columns=columns,
+ even_columns=True, even_rows=True, align=True)
+ grid.operator('stablegen.debug_solid_colors', text='Solid Colors', icon='COLOR')
+ grid.operator('stablegen.debug_grid_pattern', text='Grid Pattern', icon='MESH_GRID')
+ grid.operator('stablegen.debug_coverage_heatmap', text='Coverage Heatmap', icon='AREA_SWAP')
+ grid.operator('stablegen.debug_visibility_material', text='Visibility Material', icon='HIDE_OFF')
+ grid.operator('stablegen.debug_per_camera_weight', text='Camera Weight', icon='CAMERA_DATA')
+ grid.operator('stablegen.debug_feather_preview', text='Feather Preview', icon='MOD_SMOOTH')
+ grid.operator('stablegen.debug_confidence_diagnostic', text='Confidence', icon='SHADING_RENDERED')
+ grid.operator('stablegen.debug_uv_seam_viz', text='UV Seams', icon='UV')
+
+ grid = debug_box.grid_flow(row_major=True, columns=columns,
+ even_columns=True, even_rows=True, align=True)
+ grid.operator('stablegen.debug_dppg_material', text='DPPG Masks', icon='MATERIAL_DATA')
+ grid.operator('stablegen.debug_restore_dppg_material', text='Restore Projection', icon='LOOP_BACK')
+ grid.operator('stablegen.debug_projection_line', text='Projection Line', icon='IPO_LINEAR')
+ grid.operator('stablegen.debug_open_projection_line', text='Open Line Report', icon='URL')
+ if SG_OT_DebugProjectionLine.status:
+ debug_box.label(text=SG_OT_DebugProjectionLine.status)
+
+ debug_box.separator(factor=0.5)
+ debug_box.label(text="Workflow Tests")
if SG_OT_TexturingRegression._active is not None:
debug_box.label(text=SG_OT_TexturingRegression.status)
- debug_box.operator("stablegen.stop_texturing_regression", icon="CANCEL")
+ debug_box.operator('stablegen.stop_texturing_regression', icon='CANCEL')
else:
- debug_box.operator("stablegen.texturing_regression", icon="SEQUENCE")
-
- row = debug_box.row()
- row.operator("stablegen.export_retarget_debug_bundle",
- text="Export Retarget Test Bundle",
- icon="EXPORT")
-
- row = debug_box.row()
- row.operator("stablegen.debug_solid_colors", text="Draw Solid Colors", icon="COLOR")
- if width_mode == 'narrow':
- row = debug_box.row()
- row.operator("stablegen.debug_grid_pattern", text="Grid Pattern", icon="MESH_GRID")
-
- row = debug_box.row()
- row.operator("stablegen.debug_coverage_heatmap", text="Coverage Heatmap", icon="AREA_SWAP")
- if width_mode == 'narrow':
- row = debug_box.row()
- row.operator("stablegen.debug_visibility_material", text="Visibility Material", icon="HIDE_OFF")
-
- row = debug_box.row()
- row.operator("stablegen.debug_uv_seam_viz", text="UV Seam Visualizer", icon="UV")
- if width_mode == 'narrow':
- row = debug_box.row()
- row.operator("stablegen.debug_restore_material", text="Remove Debug Mats", icon="TRASH")
-
- row = debug_box.row()
- op = row.operator("stablegen.debug_per_camera_weight", text="Per-Camera Weight", icon="CAMERA_DATA")
- if width_mode == 'narrow':
- row = debug_box.row()
- op2 = row.operator("stablegen.debug_feather_preview", text="Feather Preview", icon="MOD_SMOOTH")
-
- row = debug_box.row()
- row.operator("stablegen.debug_confidence_diagnostic", text="Confidence Diagnostics", icon="SHADING_RENDERED")
-
- row = debug_box.row()
- row.operator(
- "stablegen.debug_skinning_weights",
- text="Skinning Weight Colors",
- icon="GROUP_VERTEX",
- )
- if width_mode == 'narrow':
- row = debug_box.row()
- row.operator(
- "stablegen.debug_clear_skinning_weights",
- text="Clear Skin Colors",
- icon="X",
- )
-
- row = debug_box.row()
- row.operator(
- "stablegen.debug_convert_fortune_rig",
- text="Convert Existing Rig to Fortune",
- icon="ARMATURE_DATA",
- )
-
- row = debug_box.row()
- row.operator("stablegen.debug_make_solid", text="Debug Make Solid", icon="MOD_REMESH")
-
- row = debug_box.row()
- row.operator(
- "stablegen.debug_force_generation_idle",
- text="Force Generation Idle",
- icon="CANCEL",
- )
-
+ debug_box.operator('stablegen.texturing_regression', icon='SEQUENCE')
+ debug_box.operator('stablegen.export_retarget_debug_bundle',
+ text='Export Retarget Test Bundle', icon='EXPORT')
+
+ debug_box.separator(factor=0.5)
+ debug_box.label(text="Mesh and Rig")
+ grid = debug_box.grid_flow(row_major=True, columns=columns,
+ even_columns=True, even_rows=True, align=True)
+ grid.operator('stablegen.debug_skinning_weights', text='Skin Weights', icon='GROUP_VERTEX')
+ grid.operator('stablegen.debug_clear_skinning_weights', text='Clear Skin Colors', icon='X')
+ debug_box.operator('stablegen.debug_convert_fortune_rig',
+ text='Convert Existing Rig to Fortune', icon='ARMATURE_DATA')
+ debug_box.operator('stablegen.debug_make_solid', text='Debug Make Solid', icon='MOD_REMESH')
+
+ debug_box.separator(factor=0.5)
+ debug_box.label(text="Recovery")
+ grid = debug_box.grid_flow(row_major=True, columns=columns,
+ even_columns=True, even_rows=True, align=True)
+ grid.operator('stablegen.debug_restore_material', text='Remove Debug Mats', icon='TRASH')
+ grid.operator('stablegen.debug_force_generation_idle', text='Force Generation Idle', icon='CANCEL')
# --- Narrow panel hint ---
if width_mode == 'narrow':
hint_row = layout.row()
diff --git a/stablegen/utils.py b/stablegen/utils.py
index f77fb34..69ce5a0 100644
--- a/stablegen/utils.py
+++ b/stablegen/utils.py
@@ -16,6 +16,7 @@ _SG_BLOCKED_MODALS = frozenset({
'OBJECT_OT_stablegen_regenerate',
'OBJECT_OT_stablegen_mirror_reproject',
'OBJECT_OT_export_orbit_gif',
+ 'STABLEGEN_OT_interactive_discard_check',
})
# Temporary bypass flag – set True to allow internal operator calls
@@ -236,25 +237,32 @@ class CurvesToMesh(bpy.types.Operator):
return {'FINISHED'}
def get_last_material_index(obj):
- """
- Get the index of the last material of the object.
- The index is hidden inside default value of (the only) subtract node.
- If there are no subtract nodes, return -1.
- :param obj: Blender object.
- :return: Index of the last material.
- """
-
+ """Read projection IDs, never infer them from active shader arithmetic."""
highest_index = -1
-
- if obj.data.materials:
- for mat in obj.data.materials:
- if mat and mat.use_nodes:
- for node in mat.node_tree.nodes:
- if node.type == 'MATH' and node.operation == 'SUBTRACT':
- if node.inputs[0].default_value > highest_index:
- highest_index = node.inputs[0].default_value
-
- return int(highest_index)
+ for mat in getattr(obj.data, 'materials', ()):
+ if not mat or not mat.use_nodes:
+ continue
+ indices = []
+ legacy = []
+ for node in mat.node_tree.nodes:
+ if node.type == 'TEX_IMAGE':
+ # Existing .blend files label projected images camera-material.
+ parts = node.label.split('-')
+ if len(parts) == 2 and all(part.isdigit() for part in parts):
+ indices.append(int(parts[1]))
+ if node.type == 'MATH' and node.operation == 'SUBTRACT':
+ value = float(node.inputs[0].default_value)
+ if value < 0 or not value.is_integer():
+ continue
+ if node.label == 'SGMaterialIndex' and not node.inputs[0].is_linked:
+ indices.append(int(value))
+ elif (not node.label and not any(socket.is_linked for socket in node.inputs)
+ and not any(socket.is_linked for socket in node.outputs)):
+ # Old versions stored the ID in an unlabeled, detached node.
+ legacy.append(int(value))
+ if indices or legacy:
+ highest_index = max(highest_index, max(indices or legacy))
+ return highest_index
def get_generation_dirs(context):
"""
@@ -281,9 +289,17 @@ def get_generation_dirs(context):
regression_output = context.scene.get('_sg_regression_output')
if regression_output:
revision_dir = regression_output
- masked_output = context.scene.get("_sg_masked_output")
+ masked_output = context.scene.get('_sg_masked_output')
if masked_output:
revision_dir = masked_output
+ # Interactive inspection follows the run referenced by the material, which
+ # can differ from the current .blend name after Save As. Removed on exit.
+ discard_output = context.scene.get('_sg_discard_output')
+ if discard_output:
+ revision_dir = discard_output
+ debug_output = context.scene.get('_sg_debug_output')
+ if debug_output:
+ revision_dir = debug_output
return {
"revision": revision_dir,