Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
add silhouette feathering to local edit, allow for high weight exponents by normalising weights, futher improvements to camera adding, add qwen voronoi mode, add debug tools
sakalond68cbf3a1f470
diff --git a/stablegen/__init__.py b/stablegen/__init__.pyindex 481ae9c..b69fb11 100644--- a/stablegen/__init__.py+++ b/stablegen/__init__.py@@ -1,7 +1,8 @@""" This script registers the addon. """import bpy # pylint: disable=import-errorfrom .stablegen import StableGenPanel, ApplyPreset, SavePreset, DeletePreset, get_preset_items, update_parameters, ResetQwenPrompt-from .render_tools import BakeTextures, AddCameras, CloneCamera, MirrorCamera, ToggleCameraLabels, SwitchMaterial, ExportOrbitGIF, CollectCameraPrompts, CameraPromptItem+from .render_tools import BakeTextures, AddCameras, CloneCamera, MirrorCamera, ToggleCameraLabels, SwitchMaterial, ExportOrbitGIF, CollectCameraPrompts, CameraPromptItem+from .debug_tools import debug_classes as _debug_classesfrom .utils import AddHDRI, ApplyModifiers, CurvesToMeshfrom .generator import ComfyUIGenerate, Reproject, Regenerate, MirrorReprojectimport os@@ -201,6 +202,28 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):default=False) # type: ignore+ overlay_color: bpy.props.FloatVectorProperty(+ name="Overlay Color",+ description="Color used for the camera aspect-ratio crop rectangle and floating view labels in the viewport",+ subtype='COLOR',+ size=3,+ min=0.0, max=1.0,+ default=(0.3, 0.5, 1.0),+ update=lambda self, ctx: [a.tag_redraw() for a in ctx.screen.areas if a.type == 'VIEW_3D'] if ctx.screen else None+ ) # type: ignore++ enable_debug: bpy.props.BoolProperty(+ name="Enable Debug Settings",+ description="Show diagnostic tools in the main panel for visualising projection weights, blending and coverage",+ default=False+ ) # type: ignore++ show_advanced: bpy.props.BoolProperty(+ name="Advanced Preferences",+ description="Show advanced preferences",+ default=False+ ) # type: ignore+def draw(self, context):"""Draws the preferences panel.@@ -241,6 +264,17 @@ class StableGenAddonPreferences(bpy.types.AddonPreferences):rows=rows)+ # --- Advanced Preferences ---+ layout.separator()+ adv_box = layout.box()+ row = adv_box.row()+ row.prop(self, "show_advanced",+ icon='TRIA_DOWN' if self.show_advanced else 'TRIA_RIGHT',+ emboss=False, text="Advanced Preferences")+ if self.show_advanced:+ adv_box.prop(self, "overlay_color")+ adv_box.prop(self, "enable_debug")+class CheckServerStatus(bpy.types.Operator):"""Checks if the ComfyUI server is reachable."""bl_idname = "stablegen.check_server_status"@@ -1108,6 +1142,8 @@ def load_handler(dummy):classes_to_append = [CheckServerStatus, RefreshCheckpointList, RefreshLoRAList, STABLEGEN_UL_ControlNetMappingList, ControlNetModelMappingItem, RefreshControlNetMappings, StableGenAddonPreferences, ControlNetUnit, LoRAUnit, AddControlNetUnit, RemoveControlNetUnit, AddLoRAUnit, RemoveLoRAUnit]for cls in classes_to_append:classes.append(cls)+for cls in _debug_classes:+ classes.append(cls)def register():"""@@ -1446,7 +1482,7 @@ def register():bpy.types.Scene.denoise = bpy.props.FloatProperty(name="Denoise",description="Denoise level for refining",- default=1.0,+ default=0.8,min=0.0,max=1.0,update=update_parameters@@ -1677,7 +1713,7 @@ def register():)bpy.types.Scene.visibility_vignette_softness = bpy.props.FloatProperty(name="Vignette Softness",- description="Exponent shaping feather falloff (<1 = softer, >1 = sharper)",+ description="Exponent shaping feather falloff (<1 = sharper transition, >1 = softer/wider transition)",default=0.5,min=0.1,max=5.0,@@ -1730,6 +1766,38 @@ def register():update=update_parameters)+ bpy.types.Scene.refine_edge_feather_projection = bpy.props.BoolProperty(+ name="Edge Feather (Projection)",+ description="Add a screen-space distance-transform ramp at the projection "+ "silhouette boundary as an additional multiplier on top of the "+ "angle×feather weight. Interior surfaces keep full strength; "+ "only the geometric edge is softened",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.refine_edge_feather_width = bpy.props.IntProperty(+ name="Edge Feather Width",+ description="Width in pixels of the transition band at projection boundaries. "+ "Larger values produce a wider blend zone",+ default=30,+ min=1,+ max=200,+ update=update_parameters+ )+ bpy.types.Scene.refine_edge_feather_softness = bpy.props.FloatProperty(+ name="Edge Feather Softness",+ description="Rounds off the sharp corners at both ends of the linear feather ramp "+ "using a Gaussian blur. 0 = raw linear ramp (hard kinks at edge and "+ "interior boundary). 1 = moderate smoothing. Higher values give "+ "progressively gentler transitions without shifting the ramp position",+ default=1.0,+ min=0.0,+ max=5.0,+ step=10,+ precision=2,+ update=update_parameters+ )+bpy.types.Scene.differential_diffusion = bpy.props.BoolProperty(name="Differential Diffusion",description="Replace standard inpainting with a differential diffusion based workflow\n\n - Generally works better and reduces artifacts.\n - Using a Smooth Visibilty Map is recommended for Sequential Mode.",@@ -1809,6 +1877,20 @@ def register():update=update_parameters)+ bpy.types.Scene.qwen_voronoi_mode = bpy.props.BoolProperty(+ name="Voronoi Projection",+ description=(+ "Instead of zeroing weights of non-generated cameras, keep natural "+ "angle-based weights and project magenta from cameras that have not "+ "been generated yet. Use a high Weight Exponent to achieve Voronoi-"+ "like segmentation where each surface point is dominated by its "+ "closest camera. This eliminates the need for low discard-over-angle "+ "thresholds"+ ),+ default=False,+ update=update_parameters+ )+bpy.types.Scene.qwen_context_render_mode = bpy.props.EnumProperty(name="Context Render",description="How to use the RGB context render in sequential mode for Qwen",@@ -2129,6 +2211,9 @@ def unregister():del bpy.types.Scene.visibility_vignettedel bpy.types.Scene.visibility_vignette_widthdel bpy.types.Scene.visibility_vignette_softness+ del bpy.types.Scene.refine_edge_feather_projection+ del bpy.types.Scene.refine_edge_feather_width+ del bpy.types.Scene.refine_edge_feather_softnessdel bpy.types.Scene.differential_diffusiondel bpy.types.Scene.differential_noisedel bpy.types.Scene.blur_mask@@ -2162,6 +2247,7 @@ def unregister():del bpy.types.Scene.early_prioritydel bpy.types.Scene.texture_objectsdel bpy.types.Scene.qwen_guidance_map_type+ del bpy.types.Scene.qwen_voronoi_modedel bpy.types.Scene.qwen_context_render_modedel bpy.types.Scene.qwen_use_external_style_imagedel bpy.types.Scene.qwen_external_style_imagediff --git a/stablegen/debug_tools.py b/stablegen/debug_tools.pynew file mode 100644index 0000000..7cc5735--- /dev/null+++ b/stablegen/debug_tools.py@@ -0,0 +1,761 @@+"""+Debug / diagnostic operators for StableGen.++These operators help visualise the projection, blending and visibility+behaviour without running any AI generation. They are gated behind the+*Enable Debug Settings* toggle in the addon preferences.++IMPORTANT: The projection operators (Solid Colors, Grid Pattern, Visibility+Material) call the *real* project_image() and export_visibility() functions+so the debug output is guaranteed to match the actual generation pipeline.+"""++import bpy+import os+import colorsys+import numpy as np+from mathutils import Vector++from .project import (+ project_image,+ create_native_raycast_visibility,+ create_native_feather,+ _SG_BUFFER_UV_NAME,+ _copy_uv_to_attribute,+)+from .render_tools import (+ export_visibility,+ _get_camera_resolution,+)+from .utils import get_file_path, get_generation_dirs, ensure_dirs_exist+++# ─── Shared helpers ──────────────────────────────────────────────────────++def _get_cameras(context):+ """Return scene cameras sorted by name."""+ cams = [o for o in context.scene.objects if o.type == 'CAMERA']+ cams.sort(key=lambda x: x.name)+ return cams+++def _get_target_meshes(context):+ """Selected meshes, or all meshes in the scene."""+ sel = [o for o in context.selected_objects if o.type == 'MESH']+ return sel if sel else [o for o in context.scene.objects if o.type == 'MESH']+++def _common_poll(cls, context):+ """Shared poll for all debug operators."""+ prefs = context.preferences.addons.get(__package__)+ if not prefs or not prefs.preferences.enable_debug:+ return False+ if not _get_target_meshes(context):+ return False+ if not _get_cameras(context):+ return False+ # Block while another heavy modal is running+ for w in context.window_manager.windows:+ for op in w.modal_operators:+ if op.bl_idname in ('OBJECT_OT_test_stable', 'OBJECT_OT_bake_textures',+ 'OBJECT_OT_add_cameras'):+ return False+ return True+++def _saturated_colors(n):+ """Return *n* maximally-saturated, evenly-spaced RGB tuples."""+ return [colorsys.hsv_to_rgb(i / max(n, 1), 1.0, 1.0) for i in range(n)]+++def _save_solid_image(path, width, height, color_rgba):+ """Create and save a solid-colour PNG at *path*."""+ img = bpy.data.images.new("_sg_dbg_tmp", width=width, height=height, alpha=True)+ n = width * height+ px = np.empty(n * 4, dtype=np.float32)+ px[0::4] = color_rgba[0]+ px[1::4] = color_rgba[1]+ px[2::4] = color_rgba[2]+ px[3::4] = color_rgba[3]+ img.pixels.foreach_set(px)+ img.filepath_raw = path+ img.file_format = 'PNG'+ img.save()+ bpy.data.images.remove(img)+++def _save_grid_image(path, width, height, color_rgb, grid_size=64):+ """Create and save a checkerboard grid PNG at *path*."""+ img = bpy.data.images.new("_sg_dbg_tmp", width=width, height=height, alpha=True)+ r, g, b = color_rgb+ px = np.empty((height, width, 4), dtype=np.float32)+ # Build checkerboard mask+ ys = np.arange(height)[:, None] # (H, 1)+ xs = np.arange(width)[None, :] # (1, W)+ checker = ((xs // grid_size) % 2) == ((ys // grid_size) % 2)+ px[:, :, 0] = np.where(checker, r, r * 0.4)+ px[:, :, 1] = np.where(checker, g, g * 0.4)+ px[:, :, 2] = np.where(checker, b, b * 0.4)+ px[:, :, 3] = 1.0+ img.pixels.foreach_set(px.ravel())+ img.filepath_raw = path+ img.file_format = 'PNG'+ img.save()+ bpy.data.images.remove(img)+++def _apply_uv_projections(context, cameras, meshes, mat_id):+ """Create UV projections for each camera on each mesh, storing them+ as named attributes. Returns True on success."""+ for i, camera in enumerate(cameras):+ for obj in meshes:+ bpy.ops.object.select_all(action='DESELECT')+ context.view_layer.objects.active = obj+ obj.select_set(True)+ bpy.ops.object.make_single_user(object=True, obdata=True)+ if obj.data.users > 1:+ obj.data = obj.data.copy()+ obj.data.name = f"{obj.name}_data"+ obj.data.update()++ buffer_uv = obj.data.uv_layers.get(_SG_BUFFER_UV_NAME)+ if not buffer_uv:+ buffer_uv = obj.data.uv_layers.new(name=_SG_BUFFER_UV_NAME)++ mod = obj.modifiers.new(name="UVProject", type='UV_PROJECT')+ mod.projectors[0].object = camera+ mod.uv_layer = buffer_uv.name+ cam_res_x, cam_res_y = _get_camera_resolution(camera, context.scene)+ aspect = cam_res_x / cam_res_y+ mod.aspect_x = aspect if aspect > 1 else 1+ mod.aspect_y = 1 / aspect if aspect < 1 else 1+ obj.data.uv_layers.active = buffer_uv+ bpy.ops.object.modifier_apply(modifier=mod.name)++ attr_name = f"ProjectionUV_{i}_{mat_id}"+ _copy_uv_to_attribute(obj, _SG_BUFFER_UV_NAME, attr_name)++ original_uv = obj.data.uv_layers[0]+ if original_uv.name == _SG_BUFFER_UV_NAME and len(obj.data.uv_layers) > 1:+ original_uv = obj.data.uv_layers[1]+ obj.data.uv_layers.active = original_uv++ # Clean up buffer UV+ for obj in meshes:+ buf = obj.data.uv_layers.get(_SG_BUFFER_UV_NAME)+ if buf:+ obj.data.uv_layers.remove(buf)+ return True+++def _get_active_camera(context):+ """Return the camera the user intends to preview and its index in the+ sorted camera list. Detection: selected camera → scene camera → first."""+ cameras = _get_cameras(context)+ # Active object is a camera+ if context.active_object and context.active_object.type == 'CAMERA' and context.active_object in cameras:+ cam = context.active_object+ return cam, cameras.index(cam)+ # Any selected object is a camera+ for obj in context.selected_objects:+ if obj.type == 'CAMERA' and obj in cameras:+ return obj, cameras.index(obj)+ # Scene active camera+ if context.scene.camera and context.scene.camera in cameras:+ return context.scene.camera, cameras.index(context.scene.camera)+ return cameras[0], 0+++def _get_selected_cameras(context):+ """Return cameras among selected objects, falling back to all cameras."""+ cameras = _get_cameras(context)+ selected = [o for o in context.selected_objects if o.type == 'CAMERA' and o in cameras]+ return selected if selected else cameras+++def _hide_unselected_cameras(context, keep_cameras):+ """Temporarily unlink cameras not in *keep_cameras* from scene collections.+ Returns a mapping {camera: [collections]} for _restore_cameras()."""+ all_cams = [o for o in context.scene.objects if o.type == 'CAMERA']+ hidden = {}+ for cam in all_cams:+ if cam not in keep_cameras:+ hidden[cam] = list(cam.users_collection)+ for col in hidden[cam]:+ col.objects.unlink(cam)+ return hidden+++def _restore_cameras(hidden):+ """Re-link cameras that were hidden by _hide_unselected_cameras()."""+ for cam, collections in hidden.items():+ for col in collections:+ if cam.name not in col.objects:+ col.objects.link(cam)+++# ═════════════════════════════════════════════════════════════════════════+# 1. Draw Solid Colors (calls the real project_image)+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugSolidColors(bpy.types.Operator):+ """Project solid saturated colours (one per camera) through the real+ project_image() pipeline. Useful for understanding how views are+ being blended. No ComfyUI connection required"""+ bl_idname = "stablegen.debug_solid_colors"+ bl_label = "Draw Solid Colors"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ return _common_poll(cls, context)++ def execute(self, context):+ cameras = _get_cameras(context)+ meshes = _get_target_meshes(context)+ n_cams = len(cameras)+ colors = _saturated_colors(n_cams)++ # Ensure output dirs exist+ dirs = get_generation_dirs(context)+ ensure_dirs_exist(dirs)++ mat_id = 0++ # Write a solid-colour PNG for every camera at the path project_image expects+ for i, cam in enumerate(cameras):+ path = get_file_path(context, "generated", camera_id=i, material_id=mat_id)+ rx, ry = _get_camera_resolution(cam, context.scene)+ _save_solid_image(path, rx, ry, (*colors[i], 1.0))++ # Override scene settings so project_image() performs a full+ # fresh build: UV projections + new material tree. Without this,+ # sequential mode skips UV projections and enters the+ # "update-existing" branch which produces a blank material.+ orig_overwrite = context.scene.overwrite_material+ orig_gen_method = context.scene.generation_method+ orig_gen_mode = context.scene.generation_mode+ context.scene.overwrite_material = True+ context.scene.generation_method = 'separate'+ context.scene.generation_mode = 'standard'+ try:+ project_image(context, meshes, mat_id)+ finally:+ context.scene.overwrite_material = orig_overwrite+ context.scene.generation_method = orig_gen_method+ context.scene.generation_mode = orig_gen_mode++ # Rename materials for easy identification / cleanup+ for obj in meshes:+ if obj.active_material:+ obj.active_material.name = "SG_Debug_SolidColors"++ self.report({'INFO'}, f"Solid-colour projection applied ({n_cams} cameras)")+ return {'FINISHED'}+++# ═════════════════════════════════════════════════════════════════════════+# 2. Projection Grid Pattern (calls the real project_image)+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugGridPattern(bpy.types.Operator):+ """Project a numbered checkerboard grid (one per camera) through the real+ project_image() pipeline to reveal UV distortion, stretching and alignment"""+ bl_idname = "stablegen.debug_grid_pattern"+ bl_label = "Projection Grid Pattern"+ bl_options = {'REGISTER', 'UNDO'}++ grid_size: bpy.props.IntProperty(+ name="Grid Cell Size",+ description="Size of each checkerboard cell in pixels",+ default=64, min=8, max=512+ ) # type: ignore++ @classmethod+ def poll(cls, context):+ return _common_poll(cls, context)++ def execute(self, context):+ cameras = _get_cameras(context)+ meshes = _get_target_meshes(context)+ n_cams = len(cameras)+ colors = _saturated_colors(n_cams)++ dirs = get_generation_dirs(context)+ ensure_dirs_exist(dirs)++ mat_id = 0++ for i, cam in enumerate(cameras):+ path = get_file_path(context, "generated", camera_id=i, material_id=mat_id)+ rx, ry = _get_camera_resolution(cam, context.scene)+ _save_grid_image(path, rx, ry, colors[i], self.grid_size)++ orig_overwrite = context.scene.overwrite_material+ orig_gen_method = context.scene.generation_method+ orig_gen_mode = context.scene.generation_mode+ context.scene.overwrite_material = True+ context.scene.generation_method = 'separate'+ context.scene.generation_mode = 'standard'+ try:+ project_image(context, meshes, mat_id)+ finally:+ context.scene.overwrite_material = orig_overwrite+ context.scene.generation_method = orig_gen_method+ context.scene.generation_mode = orig_gen_mode++ for obj in meshes:+ if obj.active_material:+ obj.active_material.name = "SG_Debug_GridPattern"++ self.report({'INFO'}, f"Grid pattern projection applied ({n_cams} cameras)")+ return {'FINISHED'}+++# ═════════════════════════════════════════════════════════════════════════+# 3. Apply Visibility Material (calls the real export_visibility)+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugVisibilityMaterial(bpy.types.Operator):+ """Project solid colours then apply export_visibility() to visualise+ which areas each camera can see. Uses selected cameras (or all if+ none are selected). No ComfyUI connection required"""+ bl_idname = "stablegen.debug_visibility_material"+ bl_label = "Apply Visibility Material"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ return _common_poll(cls, context)++ def execute(self, context):+ selected_cams = _get_selected_cameras(context)+ meshes = _get_target_meshes(context)++ # Temporarily hide unselected cameras so project_image only sees+ # the ones the user cares about.+ hidden = _hide_unselected_cameras(context, selected_cams)++ try:+ # Re-query cameras (only the kept ones are visible now)+ active_cams = _get_cameras(context)+ n_cams = len(active_cams)+ colors = _saturated_colors(n_cams)++ dirs = get_generation_dirs(context)+ ensure_dirs_exist(dirs)++ mat_id = 0++ for i, cam in enumerate(active_cams):+ path = get_file_path(context, "generated",+ camera_id=i, material_id=mat_id)+ rx, ry = _get_camera_resolution(cam, context.scene)+ _save_solid_image(path, rx, ry, (*colors[i], 1.0))++ orig_overwrite = context.scene.overwrite_material+ orig_gen_method = context.scene.generation_method+ orig_gen_mode = context.scene.generation_mode+ context.scene.overwrite_material = True+ context.scene.generation_method = 'separate'+ context.scene.generation_mode = 'standard'+ try:+ project_image(context, meshes, mat_id)+ finally:+ context.scene.overwrite_material = orig_overwrite+ context.scene.generation_method = orig_gen_method+ context.scene.generation_mode = orig_gen_mode++ # Transform projection material into visibility mask+ result = export_visibility(context, meshes, prepare_only=True)+ if not result:+ self.report({'WARNING'}, "export_visibility failed.")+ return {'CANCELLED'}+ finally:+ _restore_cameras(hidden)++ self.report({'INFO'},+ f"Visibility material applied ({n_cams} camera(s)). "+ "Inspect in Material Preview or Rendered mode.")+ return {'FINISHED'}+++# ═════════════════════════════════════════════════════════════════════════+# 4. Project Coverage Heatmap+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugCoverageHeatmap(bpy.types.Operator):+ """Create a heatmap material showing total angle-based weight coverage+ across all cameras. Red = low coverage, green = high coverage"""+ bl_idname = "stablegen.debug_coverage_heatmap"+ bl_label = "Project Coverage Heatmap"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ return _common_poll(cls, context)++ def execute(self, context):+ cameras = _get_cameras(context)+ meshes = _get_target_meshes(context)+ mat_id = "dbg_heatmap"++ # Switch to Cycles for Raycast nodes+ context.scene.render.engine = 'CYCLES'+ if bpy.app.version < (5, 1, 0):+ context.scene.cycles.device = 'CPU'+ if hasattr(context.scene.cycles, 'shading_system'):+ context.scene.cycles.shading_system = True+ else:+ context.scene.cycles.use_osl = True++ _apply_uv_projections(context, cameras, meshes, mat_id)++ for obj in meshes:+ mat = bpy.data.materials.new(name="SG_Debug_Heatmap")+ obj.data.materials.clear()+ obj.data.materials.append(mat)+ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links+ for n in list(nodes):+ nodes.remove(n)++ output = nodes.new("ShaderNodeOutputMaterial")+ output.location = (2000, 0)+ geometry = nodes.new("ShaderNodeNewGeometry")+ geometry.location = (-600, 0)++ use_native = bpy.app.version >= (5, 1, 0)++ # Sum angle weights from all cameras+ sum_node = None+ for i, cam in enumerate(cameras):+ if use_native:+ result = create_native_raycast_visibility(+ nodes, links, cam, geometry, context, i, mat_id, 1000000)+ w_node = result[0]+ else:+ w_node = nodes.new("ShaderNodeValue")+ w_node.outputs[0].default_value = 1.0+ w_node.location = (-400, -800 * i)++ if sum_node is None:+ sum_node = w_node+ else:+ add = nodes.new("ShaderNodeMath")+ add.operation = 'ADD'+ add.location = (600 + i * 100, -100 * i)+ links.new(sum_node.outputs[0], add.inputs[0])+ links.new(w_node.outputs[0], add.inputs[1])+ sum_node = add++ # Normalise by camera count+ div = nodes.new("ShaderNodeMath")+ div.operation = 'DIVIDE'+ div.location = (1200, 0)+ div.inputs[1].default_value = max(len(cameras), 1)+ links.new(sum_node.outputs[0], div.inputs[0])++ # Color ramp: 0 → red, 0.5 → yellow, 1 → green+ ramp = nodes.new("ShaderNodeValToRGB")+ ramp.location = (1400, 0)+ ramp.color_ramp.interpolation = 'LINEAR'+ elements = ramp.color_ramp.elements+ elements[0].position = 0.0+ elements[0].color = (1.0, 0.0, 0.0, 1.0) # red+ elements[1].position = 1.0+ elements[1].color = (0.0, 1.0, 0.0, 1.0) # green+ mid = elements.new(0.5)+ mid.color = (1.0, 1.0, 0.0, 1.0) # yellow++ links.new(div.outputs[0], ramp.inputs["Fac"])++ # Emission so it's visible in solid mode too+ emit = nodes.new("ShaderNodeEmission")+ emit.location = (1700, 0)+ links.new(ramp.outputs["Color"], emit.inputs["Color"])+ links.new(emit.outputs[0], output.inputs["Surface"])++ self.report({'INFO'}, f"Coverage heatmap applied ({len(cameras)} cameras)")+ return {'FINISHED'}+++# ═════════════════════════════════════════════════════════════════════════+# 5. Per-Camera Weight Preview+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugPerCameraWeight(bpy.types.Operator):+ """Show the selected camera's raw angle weight as grayscale emission.+ White = full weight, black = zero weight.+ Select a camera object first, or the active scene camera is used"""+ bl_idname = "stablegen.debug_per_camera_weight"+ bl_label = "Per-Camera Weight Preview"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ return _common_poll(cls, context)++ def execute(self, context):+ cam, idx = _get_active_camera(context)+ meshes = _get_target_meshes(context)+ mat_id = "dbg_weight"++ context.scene.render.engine = 'CYCLES'+ if bpy.app.version < (5, 1, 0):+ context.scene.cycles.device = 'CPU'+ if hasattr(context.scene.cycles, 'shading_system'):+ context.scene.cycles.shading_system = True+ else:+ context.scene.cycles.use_osl = True++ use_native = bpy.app.version >= (5, 1, 0)++ for obj in meshes:+ mat = bpy.data.materials.new(name=f"SG_Debug_Weight_{cam.name}")+ obj.data.materials.clear()+ obj.data.materials.append(mat)+ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links+ for n in list(nodes):+ nodes.remove(n)++ output = nodes.new("ShaderNodeOutputMaterial")+ output.location = (1400, 0)+ geometry = nodes.new("ShaderNodeNewGeometry")+ geometry.location = (-600, 0)++ if use_native:+ result = create_native_raycast_visibility(+ nodes, links, cam, geometry, context, idx, mat_id, 1000000)+ w_node = result[0]+ else:+ w_node = nodes.new("ShaderNodeValue")+ w_node.outputs[0].default_value = 1.0++ emit = nodes.new("ShaderNodeEmission")+ emit.location = (1200, 0)+ links.new(w_node.outputs[0], emit.inputs["Strength"])+ emit.inputs["Color"].default_value = (1, 1, 1, 1)+ links.new(emit.outputs[0], output.inputs["Surface"])++ context.scene.camera = cam+ self.report({'INFO'}, f"Weight preview for {cam.name}")+ return {'FINISHED'}+++# ═════════════════════════════════════════════════════════════════════════+# 6. Feather / Vignette Preview+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugFeatherPreview(bpy.types.Operator):+ """Show the selected camera's feather / vignette falloff as grayscale.+ White = full (centre), black = feathered-out (edge).+ Select a camera object first, or the active scene camera is used"""+ bl_idname = "stablegen.debug_feather_preview"+ bl_label = "Feather / Vignette Preview"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ return _common_poll(cls, context)++ def execute(self, context):+ cam, idx = _get_active_camera(context)+ meshes = _get_target_meshes(context)+ mat_id = "dbg_feather"++ context.scene.render.engine = 'CYCLES'+ if bpy.app.version < (5, 1, 0):+ context.scene.cycles.device = 'CPU'+ if hasattr(context.scene.cycles, 'shading_system'):+ context.scene.cycles.shading_system = True+ else:+ context.scene.cycles.use_osl = True++ use_native = bpy.app.version >= (5, 1, 0)++ for obj in meshes:+ mat = bpy.data.materials.new(name=f"SG_Debug_Feather_{cam.name}")+ obj.data.materials.clear()+ obj.data.materials.append(mat)+ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links+ for n in list(nodes):+ nodes.remove(n)++ output = nodes.new("ShaderNodeOutputMaterial")+ output.location = (1400, 0)+ geometry = nodes.new("ShaderNodeNewGeometry")+ geometry.location = (-600, 0)++ if use_native:+ result = create_native_raycast_visibility(+ nodes, links, cam, geometry, context, idx, mat_id, 1000000)+ _, _, normalize_node, _, _, camera_fov_node, camera_aspect_node, camera_dir_node, camera_up_node = result+ feather_node = create_native_feather(+ nodes, links, normalize_node, camera_fov_node,+ camera_aspect_node, camera_dir_node, camera_up_node,+ context, idx, mat_id)+ else:+ feather_node = nodes.new("ShaderNodeValue")+ feather_node.outputs[0].default_value = 1.0++ emit = nodes.new("ShaderNodeEmission")+ emit.location = (1200, 0)+ links.new(feather_node.outputs[0], emit.inputs["Strength"])+ emit.inputs["Color"].default_value = (1, 1, 1, 1)+ links.new(emit.outputs[0], output.inputs["Surface"])++ context.scene.camera = cam+ self.report({'INFO'}, f"Feather preview for {cam.name}")+ return {'FINISHED'}+++# ═════════════════════════════════════════════════════════════════════════+# 7. UV Seam Visualiser+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugUVSeamViz(bpy.types.Operator):+ """Visualize UV projection overlap and seam boundaries.+ Each camera's projected area is a unique color; overlapping regions+ appear as a combined/lighter shade"""+ bl_idname = "stablegen.debug_uv_seam_viz"+ bl_label = "UV Seam Visualizer"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ return _common_poll(cls, context)++ def execute(self, context):+ cameras = _get_cameras(context)+ meshes = _get_target_meshes(context)+ mat_id = "dbg_seam"++ context.scene.render.engine = 'CYCLES'+ if bpy.app.version < (5, 1, 0):+ context.scene.cycles.device = 'CPU'+ if hasattr(context.scene.cycles, 'shading_system'):+ context.scene.cycles.shading_system = True+ else:+ context.scene.cycles.use_osl = True++ _apply_uv_projections(context, cameras, meshes, mat_id)++ use_native = bpy.app.version >= (5, 1, 0)+ colors = _saturated_colors(len(cameras))++ for obj in meshes:+ mat = bpy.data.materials.new(name="SG_Debug_UVSeams")+ obj.data.materials.clear()+ obj.data.materials.append(mat)+ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links+ for n in list(nodes):+ nodes.remove(n)++ output = nodes.new("ShaderNodeOutputMaterial")+ output.location = (2400, 0)+ geometry = nodes.new("ShaderNodeNewGeometry")+ geometry.location = (-600, 0)++ # For each camera: create a visibility mask, scale by unique colour,+ # then ADD all together.+ sum_node = None+ for i, cam in enumerate(cameras):+ if use_native:+ result = create_native_raycast_visibility(+ nodes, links, cam, geometry, context, i, mat_id, 1000000)+ w = result[0]+ else:+ w = nodes.new("ShaderNodeValue")+ w.outputs[0].default_value = 1.0+ w.location = (-400, -800 * i)++ # Multiply weight by the camera's unique colour+ colour_node = nodes.new("ShaderNodeRGB")+ colour_node.location = (800, -300 * i)+ colour_node.outputs[0].default_value = (*colors[i], 1.0)++ scale = nodes.new("ShaderNodeMixRGB")+ scale.blend_type = 'MULTIPLY'+ scale.location = (1000, -300 * i)+ scale.inputs["Fac"].default_value = 1.0+ links.new(colour_node.outputs[0], scale.inputs["Color1"])+ # Weight as grayscale colour+ w_rgb = nodes.new("ShaderNodeCombineColor")+ w_rgb.location = (900, -300 * i - 100)+ links.new(w.outputs[0], w_rgb.inputs[0])+ links.new(w.outputs[0], w_rgb.inputs[1])+ links.new(w.outputs[0], w_rgb.inputs[2])+ links.new(w_rgb.outputs[0], scale.inputs["Color2"])++ if sum_node is None:+ sum_node = scale+ else:+ add = nodes.new("ShaderNodeMixRGB")+ add.blend_type = 'ADD'+ add.location = (1400 + i * 200, -150 * i)+ add.inputs["Fac"].default_value = 1.0+ links.new(sum_node.outputs[0], add.inputs["Color1"])+ links.new(scale.outputs[0], add.inputs["Color2"])+ sum_node = add++ emit = nodes.new("ShaderNodeEmission")+ emit.location = (2100, 0)+ if sum_node:+ links.new(sum_node.outputs[0], emit.inputs["Color"])+ links.new(emit.outputs[0], output.inputs["Surface"])++ self.report({'INFO'}, f"UV seam overlay applied ({len(cameras)} cameras)")+ return {'FINISHED'}+++# ═════════════════════════════════════════════════════════════════════════+# 8. Restore Original Material+# ═════════════════════════════════════════════════════════════════════════++class SG_OT_DebugRestoreMaterial(bpy.types.Operator):+ """Remove all debug materials from selected (or all) mesh objects and+ leave the object without a material so the user can re-assign"""+ bl_idname = "stablegen.debug_restore_material"+ bl_label = "Remove Debug Materials"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ prefs = context.preferences.addons.get(__package__)+ if not prefs or not prefs.preferences.enable_debug:+ return False+ return bool(_get_target_meshes(context))++ def execute(self, context):+ meshes = _get_target_meshes(context)+ removed = 0+ for obj in meshes:+ for slot in obj.material_slots:+ if slot.material and slot.material.name.startswith("SG_Debug_"):+ bpy.data.materials.remove(slot.material)+ removed += 1+ obj.data.materials.clear()+ self.report({'INFO'}, f"Removed {removed} debug material(s)")+ return {'FINISHED'}+++# ─── Registration list ───────────────────────────────────────────────────++debug_classes = [+ SG_OT_DebugSolidColors,+ SG_OT_DebugGridPattern,+ SG_OT_DebugVisibilityMaterial,+ SG_OT_DebugCoverageHeatmap,+ SG_OT_DebugPerCameraWeight,+ SG_OT_DebugFeatherPreview,+ SG_OT_DebugUVSeamViz,+ SG_OT_DebugRestoreMaterial,+]diff --git a/stablegen/generator.py b/stablegen/generator.pyindex e3a15c5..ebdb1d8 100644--- a/stablegen/generator.py+++ b/stablegen/generator.py@@ -17,7 +17,7 @@ import colorsysfrom PIL import Image, ImageEnhancefrom .util.helpers import prompt_text, prompt_text_img2img, prompt_text_qwen_image_edit # pylint: disable=relative-beyond-top-level-from .render_tools import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap, export_render, export_viewport, _SGCameraResolution, _get_camera_resolution, _sg_restore_square_display, _sg_remove_crop_overlay, _sg_ensure_crop_overlay, _sg_hide_label_overlay, _sg_restore_label_overlay # pylint: disable=relative-beyond-top-level+from .render_tools import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap, export_render, export_viewport, render_edge_feather_mask, _SGCameraResolution, _get_camera_resolution, _sg_restore_square_display, _sg_remove_crop_overlay, _sg_ensure_crop_overlay, _sg_hide_label_overlay, _sg_restore_label_overlay # pylint: disable=relative-beyond-top-levelfrom .utils import get_last_material_index, get_generation_dirs, get_file_path, get_dir_path, remove_empty_dirs, get_compositor_node_tree, configure_output_node_paths, get_eevee_engine_id # pylint: disable=relative-beyond-top-levelfrom .project import project_image, reinstate_compare_nodes # pylint: disable=relative-beyond-top-levelfrom .workflows import WorkflowManager@@ -669,6 +669,15 @@ class ComfyUIGenerate(bpy.types.Operator):bpy.context.scene.camera = camerawith _SGCameraResolution(context, camera):export_emit_image(context, self._to_texture, camera_id=i)+ # Render per-camera geometry silhouette mask for edge feathering+ if context.scene.refine_edge_feather_projection and (+ context.scene.generation_method == 'local_edit'+ or (context.scene.model_architecture.startswith('qwen')+ and context.scene.qwen_generation_method == 'local_edit')):+ render_edge_feather_mask(+ context, self._to_texture, camera, i,+ feather_width=context.scene.refine_edge_feather_width,+ softness=context.scene.refine_edge_feather_softness)# UV inpainting mode preparationif context.scene.generation_method == 'uv_inpaint':diff --git a/stablegen/project.py b/stablegen/project.pyindex 3462d0f..7dcd157 100644--- a/stablegen/project.py+++ b/stablegen/project.py@@ -532,6 +532,22 @@ def create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_return final_feather++_SG_VORONOI_PLACEHOLDER_NAME = "_SG_Voronoi_Placeholder"++def _get_voronoi_placeholder(color=(1.0, 0.0, 1.0)):+ """Get or create a 1x1 solid-colour image used as placeholder for+ non-generated cameras in Voronoi projection mode. The colour is+ updated every call so it always matches the current setting."""+ img = bpy.data.images.get(_SG_VORONOI_PLACEHOLDER_NAME)+ if img is None:+ img = bpy.data.images.new(_SG_VORONOI_PLACEHOLDER_NAME, width=1, height=1)+ img.colorspace_settings.name = 'Non-Color'+ img.pack()+ img.pixels[:] = [color[0], color[1], color[2], 1.0]+ return img++def project_image(context, to_project, mat_id, stop_index=1000000):"""Projects an image onto all mesh objects using UV Project Modifier.@@ -556,6 +572,21 @@ def project_image(context, to_project, mat_id, stop_index=1000000):Returns:A tuple (final_shader, final_weight_node)."""++ def _combine_angle_feather(nodes_col, lnk, cr_angle_out, cr_feather_out, loc):+ """Combine angle-ramp and feather-ramp outputs into a single+ visibility weight: ``angle_vis × feather_vis``.++ Returns the output node of the final MULTIPLY.+ """+ x, y = loc+ mult = nodes_col.new("ShaderNodeMath")+ mult.operation = 'MULTIPLY'+ mult.location = (x, y)+ lnk.new(cr_angle_out, mult.inputs[0])+ lnk.new(cr_feather_out, mult.inputs[1])+ return mult+# Compute offsets based on recursion levelis_local_edit = (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit'))if is_local_edit:@@ -580,7 +611,9 @@ def project_image(context, to_project, mat_id, stop_index=1000000):if is_local_edit:w_node = weight_nodes[0]if isinstance(w_node, tuple):- angle_node, feather_node = w_node+ angle_node = w_node[0]+ feather_node = w_node[1]+ ef_node = w_node[2] if len(w_node) >= 3 else None# Create Ramps (Output Visibility: 0=Invis, 1=Vis)# Angle Ramp@@ -603,19 +636,30 @@ def project_image(context, to_project, mat_id, stop_index=1000000):cr_feather.color_ramp.interpolation = 'LINEAR'links.new(feather_node.outputs[0], cr_feather.inputs[0])- # Multiply (Intersection of Visibility)- mult = nodes_collection.new("ShaderNodeMath")- mult.operation = 'MULTIPLY'- mult.location = (x_offset - 300, y_offset)- links.new(cr_angle.outputs[0], mult.inputs[0])- links.new(cr_feather.outputs[0], mult.inputs[1])+ # Combine angle and feather visibility+ mult = _combine_angle_feather(+ nodes_collection, links,+ cr_angle.outputs[0], cr_feather.outputs[0],+ loc=(x_offset - 300, y_offset)+ )++ # Optionally multiply by edge-feather mask+ if ef_node is not None:+ ef_mult = nodes_collection.new("ShaderNodeMath")+ ef_mult.operation = 'MULTIPLY'+ ef_mult.location = (x_offset - 200, y_offset - 80)+ links.new(mult.outputs[0], ef_mult.inputs[0])+ links.new(ef_node.outputs[0], ef_mult.inputs[1])+ weight_out = ef_mult+ else:+ weight_out = mult# Invert (Convert Visibility to Mix Factor: 1=Vis->0=Proj, 0=Invis->1=Orig)invert = nodes_collection.new("ShaderNodeMath")invert.operation = 'SUBTRACT'invert.location = (x_offset - 150, y_offset)invert.inputs[0].default_value = 1.0- links.new(mult.outputs[0], invert.inputs[1])+ links.new(weight_out.outputs[0], invert.inputs[1])compare_node = invert # For returnlinks.new(invert.outputs[0], final_mix.inputs["Fac"])@@ -665,6 +709,165 @@ def project_image(context, to_project, mat_id, stop_index=1000000):links.new(final_mix.outputs[0], final_principled.inputs[0])return final_principled, compare_node+ # ── Helper: extract final weight output from a weight_node item ────+ def _get_weight_output(w_item, v_offset):+ """Process a weight_node item (tuple or plain node) through ramps+ and return the output socket. Used by the normalization pre-pass."""+ if isinstance(w_item, tuple):+ angle_node = w_item[0]+ feather_node = w_item[1]+ ef_node = w_item[2] if len(w_item) >= 3 else None++ # Angle Ramp+ cr_angle = nodes_collection.new("ShaderNodeValToRGB")+ cr_angle.location = (x_offset - 1100, y_offset + v_offset)+ cr_angle.color_ramp.elements[0].position = context.scene.refine_angle_ramp_pos_0 if context.scene.refine_angle_ramp_active else 0.0+ cr_angle.color_ramp.elements[0].color = (0, 0, 0, 1)+ cr_angle.color_ramp.elements[1].position = context.scene.refine_angle_ramp_pos_1 if context.scene.refine_angle_ramp_active else 0.0+ cr_angle.color_ramp.elements[1].color = (1, 1, 1, 1)+ cr_angle.color_ramp.interpolation = 'LINEAR'+ links.new(angle_node.outputs[0], cr_angle.inputs[0])++ # Feather Ramp+ cr_feather = nodes_collection.new("ShaderNodeValToRGB")+ cr_feather.location = (x_offset - 1100, y_offset + v_offset - 200)+ cr_feather.color_ramp.elements[0].position = context.scene.refine_feather_ramp_pos_0 if context.scene.visibility_vignette else 0.0+ cr_feather.color_ramp.elements[0].color = (0, 0, 0, 1)+ cr_feather.color_ramp.elements[1].position = context.scene.refine_feather_ramp_pos_1 if context.scene.visibility_vignette else 0.0+ cr_feather.color_ramp.elements[1].color = (1, 1, 1, 1)+ cr_feather.color_ramp.interpolation = 'LINEAR'+ links.new(feather_node.outputs[0], cr_feather.inputs[0])++ # Combine angle × feather+ m = _combine_angle_feather(+ nodes_collection, links,+ cr_angle.outputs[0], cr_feather.outputs[0],+ loc=(x_offset - 900, y_offset + v_offset)+ )++ # Optionally multiply by edge-feather mask+ if ef_node is not None:+ ef_mult = nodes_collection.new("ShaderNodeMath")+ ef_mult.operation = 'MULTIPLY'+ ef_mult.location = (x_offset - 800, y_offset + v_offset - 80)+ links.new(m.outputs[0], ef_mult.inputs[0])+ links.new(ef_node.outputs[0], ef_mult.inputs[1])+ return ef_mult.outputs[0]++ return m.outputs[0]+ else:+ return w_item.outputs[0]++ # ── Max-relative weight normalization (level 0 only) ──────────────+ # At high weight exponents, pow(cos(θ), exp) can underflow to 0 in+ # float32 for every camera, making the w_A/(w_A+w_B) ratio become+ # 0/0 → black. To fix this robustly we:+ # 1. Temporarily set each per-camera Power to 1.0 so the weight+ # outputs become the *base* values (binary_gates × |cos(θ)|)+ # that never underflow.+ # 2. Normalize those base weights by the per-pixel maximum so the+ # best camera gets 1.0.+ # 3. Re-apply the user exponent to the normalized [0,1] values+ # where underflow is impossible.+ # Mathematically: pow(cos/max_cos, exp) == pow(cos, exp)/pow(max_cos, exp),+ # so the blending ratios are identical to the original formula.+ if level == 0 and len(shaders) > 1:+ # ── Step 1: Neutralize per-camera Power (set to 1.0) ──────+ user_exponent = None+ for idx in range(len(weight_nodes)):+ w = weight_nodes[idx]+ node = w[0] if isinstance(w, tuple) else w++ # Skip disabled cameras (stop_index → LESS_THAN always-0)+ if node.type == 'MATH' and node.operation == 'LESS_THAN':+ continue++ # Native raycast path:+ # final_weight (MULTIPLY, label Angle-*) →+ # inputs[1] → power_node (POWER, label power_weight)+ if (node.type == 'MATH' and node.operation == 'MULTIPLY'+ and node.label.startswith('Angle-')):+ if node.inputs[1].links:+ pn = node.inputs[1].links[0].from_node+ if (pn.type == 'MATH' and pn.operation == 'POWER'+ and pn.label == 'power_weight'):+ if user_exponent is None:+ user_exponent = pn.inputs[1].default_value+ pn.inputs[1].default_value = 1.0++ # OSL path: ShaderNodeScript with "Power" input+ elif node.type == 'SCRIPT' and "Power" in node.inputs:+ if user_exponent is None:+ user_exponent = node.inputs["Power"].default_value+ node.inputs["Power"].default_value = 1.0++ if user_exponent is None:+ user_exponent = 1.0++ # ── Step 2: Get base weight outputs (now power = 1) ───────+ all_w_outputs = []+ for idx in range(len(weight_nodes)):+ v_off = -200 * idx+ all_w_outputs.append(_get_weight_output(weight_nodes[idx], v_off))++ # ── Step 3: Find per-pixel maximum ────────────────────────+ max_node = nodes_collection.new("ShaderNodeMath")+ max_node.operation = 'MAXIMUM'+ max_node.location = (x_offset - 1500, y_offset - 600)+ max_node.label = "WeightMax"+ links.new(all_w_outputs[0], max_node.inputs[0])+ if len(all_w_outputs) > 1:+ links.new(all_w_outputs[1], max_node.inputs[1])+ else:+ max_node.inputs[1].default_value = 0.0++ for idx in range(2, len(all_w_outputs)):+ next_max = nodes_collection.new("ShaderNodeMath")+ next_max.operation = 'MAXIMUM'+ next_max.location = (x_offset - 1500 + 150 * (idx - 1),+ y_offset - 600)+ next_max.label = "WeightMax"+ links.new(max_node.outputs[0], next_max.inputs[0])+ links.new(all_w_outputs[idx], next_max.inputs[1])+ max_node = next_max++ # Clamp max to epsilon to prevent 0/0 division+ safe_max = nodes_collection.new("ShaderNodeMath")+ safe_max.operation = 'MAXIMUM'+ safe_max.location = (max_node.location[0] + 150, y_offset - 600)+ safe_max.inputs[1].default_value = 1e-7+ safe_max.label = "SafeMax"+ links.new(max_node.outputs[0], safe_max.inputs[0])++ # ── Step 4: Normalize + re-apply exponent ─────────────────+ powered_nodes = []+ for idx, w_out in enumerate(all_w_outputs):+ # norm_w = base_w / max(base_w)+ div = nodes_collection.new("ShaderNodeMath")+ div.operation = 'DIVIDE'+ div.location = (safe_max.location[0] + 200,+ y_offset - 120 * idx)+ div.label = f"NormW-{idx}"+ links.new(w_out, div.inputs[0])+ links.new(safe_max.outputs[0], div.inputs[1])++ # sharp_w = pow(norm_w, user_exponent)+ # (inputs are in [0, 1] → no underflow possible)+ if user_exponent != 1.0:+ pw = nodes_collection.new("ShaderNodeMath")+ pw.operation = 'POWER'+ pw.location = (div.location[0] + 200,+ div.location[1])+ pw.label = f"SharpW-{idx}"+ pw.inputs[1].default_value = user_exponent+ links.new(div.outputs[0], pw.inputs[0])+ powered_nodes.append(pw)+ else:+ powered_nodes.append(div)++ # Replace weight_nodes with sharpened-normalised nodes+ weight_nodes = powered_nodes+new_shaders = []new_weight_nodes = []i = 0@@ -678,7 +881,9 @@ def project_image(context, to_project, mat_id, stop_index=1000000):def get_weight_output(w_item):if isinstance(w_item, tuple):- angle_node, feather_node = w_item+ angle_node = w_item[0]+ feather_node = w_item[1]+ ef_node = w_item[2] if len(w_item) >= 3 else None# Create Ramps (Output Visibility: 0=Invis, 1=Vis)# Angle Ramp@@ -701,12 +906,22 @@ def project_image(context, to_project, mat_id, stop_index=1000000):cr_feather.color_ramp.interpolation = 'LINEAR'links.new(feather_node.outputs[0], cr_feather.inputs[0])- # Multiply (Intersection of Visibility)- m = nodes_collection.new("ShaderNodeMath")- m.operation = 'MULTIPLY'- m.location = (x_offset - 900, y_offset + vert_offset)- links.new(cr_angle.outputs[0], m.inputs[0])- links.new(cr_feather.outputs[0], m.inputs[1])+ # Combine angle and feather visibility+ m = _combine_angle_feather(+ nodes_collection, links,+ cr_angle.outputs[0], cr_feather.outputs[0],+ loc=(x_offset - 900, y_offset + vert_offset)+ )++ # Optionally multiply by edge-feather mask+ if ef_node is not None:+ ef_mult = nodes_collection.new("ShaderNodeMath")+ ef_mult.operation = 'MULTIPLY'+ ef_mult.location = (x_offset - 800, y_offset + vert_offset - 80)+ links.new(m.outputs[0], ef_mult.inputs[0])+ links.new(ef_node.outputs[0], ef_mult.inputs[1])+ return ef_mult.outputs[0]+return m.outputs[0]else:return w_item.outputs[0]@@ -978,6 +1193,49 @@ def project_image(context, to_project, mat_id, stop_index=1000000):camera_direction_nodes = []camera_up_nodes = []+ def _create_edge_feather_weight(cam_index, mat_id_inner):+ """Load the edge-feathered visibility mask for camera *cam_index*+ and return a shader Math node whose output[0] gives a 0..1 float+ weight (0 = edge/invisible, 1 = interior/full), or *None* on failure.++ The mask is UV-projected through the same camera UV attribute+ that projects the generated image.+ """+ vis_dir = get_dir_path(context, "inpaint")["visibility"]+ ef_path = os.path.join(vis_dir, f"render{cam_index}_edgefeather.png")+ if not os.path.exists(ef_path):+ print(f"[StableGen] Edge-feather mask not found: {ef_path}")+ return None+ ef_image = get_or_load_image(ef_path, force_reload=context.scene.overwrite_material)+ if ef_image is None:+ return None++ # Image Texture node to sample the mask via camera UV+ mask_tex = nodes.new("ShaderNodeTexImage")+ mask_tex.image = ef_image+ mask_tex.extension = 'CLIP'+ mask_tex.label = f"EdgeFeather-{cam_index}-{mat_id_inner}"+ mask_tex.location = (-500, -200 * cam_index - 150)++ # Connect to the same camera UV attribute+ uv_node = uv_map_nodes[cam_index]+ uv_out = "Vector" if uv_node.type == 'ATTRIBUTE' else "UV"+ links.new(uv_node.outputs[uv_out], mask_tex.inputs["Vector"])++ # Color→Float conversion via a pass-through Math node+ to_float = nodes.new("ShaderNodeMath")+ to_float.operation = 'MULTIPLY'+ to_float.inputs[1].default_value = 1.0+ to_float.location = (-300, -200 * cam_index - 150)+ to_float.label = f"EF_Weight-{cam_index}"+ links.new(mask_tex.outputs[0], to_float.inputs[0])+ return to_float++ # Voronoi mode flag: keep natural weights for non-generated cameras+ voronoi_active = (context.scene.model_architecture == 'qwen_image_edit'+ and getattr(context.scene, 'qwen_voronoi_mode', False)+ and context.scene.generation_method == 'sequential')+for i, camera in enumerate(cameras):# Add image texture nodetex_image = nodes.new("ShaderNodeTexImage")@@ -990,6 +1248,13 @@ def project_image(context, to_project, mat_id, stop_index=1000000):image = get_or_load_image(image_path, force_reload=context.scene.overwrite_material)if image:tex_image.image = image+ elif voronoi_active:+ # Voronoi mode: assign a solid placeholder matching the Qwen+ # guidance fallback colour so non-generated cameras contribute+ # that colour instead of black.+ voronoi_color = tuple(context.scene.qwen_guidance_fallback_color)+ tex_image.image = _get_voronoi_placeholder(voronoi_color)+ tex_image.interpolation = 'Closest'tex_image.location = (0, -200 * i)tex_image.extension = 'CLIP'@@ -1024,13 +1289,21 @@ def project_image(context, to_project, mat_id, stop_index=1000000):nodes, links, normalize_node, camera_fov_node, camera_aspect_node,camera_dir_node, camera_up_node, context, i, mat_id)- final_weight_node = (angle_weight, feather_weight)+ # Optionally add edge-feather mask as third multiplier+ if context.scene.refine_edge_feather_projection and i <= stop_index:+ ef_node = _create_edge_feather_weight(i, mat_id)+ if ef_node is not None:+ final_weight_node = (angle_weight, feather_weight, ef_node)+ else:+ final_weight_node = (angle_weight, feather_weight)+ else:+ final_weight_node = (angle_weight, feather_weight)else:final_weight_node = angle_weightscript_nodes.append(scripts_to_connect)- if i > stop_index:+ if i > stop_index and not voronoi_active:less_than = nodes.new("ShaderNodeMath")less_than.operation = 'LESS_THAN'less_than.location = (-200, (-800) * i)@@ -1087,7 +1360,7 @@ def project_image(context, to_project, mat_id, stop_index=1000000):# Add Feather scriptscript_feather = nodes.new("ShaderNodeScript")script_feather.location = (-400, (-800) * i - 200) # Offset slightly-+# Load OSL script into internal text block for portabilityfeather_osl_text = get_or_create_osl_text("feather.osl")if feather_osl_text:@@ -1096,7 +1369,7 @@ def project_image(context, to_project, mat_id, stop_index=1000000):else:script_feather.mode = 'EXTERNAL'script_feather.filepath = os.path.join(os.path.dirname(__file__), "feather.osl")-+if context.scene.visibility_vignette: # Only set if feathering is activescript_feather.inputs["EdgeFeather"].default_value = context.scene.visibility_vignette_widthscript_feather.inputs["EdgeGamma"].default_value = context.scene.visibility_vignette_softness@@ -1106,15 +1379,22 @@ def project_image(context, to_project, mat_id, stop_index=1000000):script_feather.label = f"Feather-{i}-{mat_id}"scripts_to_connect.append(script_feather)- # Pass tuple of (Angle, Feather) to build_mix_tree- final_weight_node = (script_angle, script_feather)+ # Optionally add edge-feather mask as third multiplier+ if context.scene.refine_edge_feather_projection and i <= stop_index:+ ef_node = _create_edge_feather_weight(i, mat_id)+ if ef_node is not None:+ final_weight_node = (script_angle, script_feather, ef_node)+ else:+ final_weight_node = (script_angle, script_feather)+ else:+ final_weight_node = (script_angle, script_feather)else:# Just use Angle script output directlyfinal_weight_node = script_anglescript_nodes.append(scripts_to_connect)- if i > stop_index:+ if i > stop_index and not voronoi_active:# Connect a temporary less than node to the script nodeless_than = nodes.new("ShaderNodeMath")less_than.operation = 'LESS_THAN'diff --git a/stablegen/render_tools.py b/stablegen/render_tools.pyindex 6d83665..05b9dd9 100644--- a/stablegen/render_tools.py+++ b/stablegen/render_tools.py@@ -100,6 +100,244 @@ def apply_vignette_to_mask(mask_file_path, feather_width=0.15, gamma=1.0, blur=Tf"(ksize={ksize}, fw={feather_width}, gamma={gamma}, blur={blur})")++def create_edge_feathered_mask(mask_path, feather_width=30):+ """Create an edge-feathered version of a visibility mask for projection blending.++ Uses a distance transform on the binary mask so that:+ - Interior pixels (far from any edge) → 1.0 (full new texture)+ - Edge pixels (near visibility boundary) → ramp 0→1 over *feather_width* px+ - Invisible pixels → 0.0 (keep original texture)++ The result is saved next to the original with an ``_edgefeather`` suffix.+ Returns the output path, or *None* on failure.+ """+ if not isinstance(mask_path, str) or not os.path.exists(mask_path):+ print(f"[StableGen] Edge-feather: mask not found: {mask_path}")+ return None++ mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)+ if mask is None:+ print(f"[StableGen] Edge-feather: failed to read mask: {mask_path}")+ return None++ # Threshold to hard binary (visible = white, invisible = black)+ _, binary = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)++ # Distance transform: each white pixel → distance to nearest black pixel+ dist = cv2.distanceTransform(binary, cv2.DIST_L2, 5)++ # Normalise into [0, 1] ramp over feather_width pixels+ feathered = np.clip(dist / max(feather_width, 1), 0.0, 1.0)++ feathered_u8 = (feathered * 255).astype(np.uint8)++ output_path = mask_path.replace('.png', '_edgefeather.png')+ cv2.imwrite(output_path, feathered_u8)+ print(f"[StableGen] Edge-feather mask saved: {output_path} (width={feather_width}px)")+ return output_path+++def render_edge_feather_mask(context, to_export, camera, camera_index, feather_width=30, softness=1.0):+ """Render a geometry silhouette from *camera* and apply distance-transform+ edge feathering.++ All target objects render as white (Emission), non-target mesh objects are+ hidden, and the world is set to black. The resulting binary silhouette is+ distance-transformed so that interior pixels = 1.0, boundary pixels ramp+ 0→1 over *feather_width* pixels, and background = 0.0.++ The final mask is saved to ``inpaint/visibility/render{camera_index}_edgefeather.png``.+ Returns the output path, or *None* on failure.+ """+ output_dir = get_dir_path(context, "inpaint")["visibility"]+ os.makedirs(output_dir, exist_ok=True)+ raw_file = f"render{camera_index}_geomask"++ # ── Save original state ─────────────────────────────────────────────────+ original_camera = context.scene.camera+ original_engine = context.scene.render.engine+ original_transparent = context.scene.render.film_transparent+ original_samples = context.scene.cycles.samples+ original_view_transform = bpy.context.scene.view_settings.view_transform++ world = context.scene.world+ if not world:+ world = bpy.data.worlds.new("World")+ context.scene.world = world+ original_use_nodes = world.use_nodes+ original_color = world.color.copy()+ original_bg_node_color = None+ original_bg_node_strength = None+ if world.use_nodes and world.node_tree:+ for wn in world.node_tree.nodes:+ if wn.type == 'BACKGROUND':+ original_bg_node_color = tuple(wn.inputs["Color"].default_value)+ original_bg_node_strength = wn.inputs["Strength"].default_value+ break++ # ── Camera ──────────────────────────────────────────────────────────────+ context.scene.camera = camera++ # ── Replace target-object materials with white Emission ─────────────────+ saved_materials = {}+ saved_active_materials = {}+ temp_materials = []+ for obj in to_export:+ saved_materials[obj] = list(obj.data.materials)+ saved_active_materials[obj] = obj.active_material++ mat = bpy.data.materials.new(name="_SG_EdgeFeather_Temp")+ mat.use_nodes = True+ mat.node_tree.nodes.clear()+ emission = mat.node_tree.nodes.new("ShaderNodeEmission")+ emission.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0)+ emission.inputs["Strength"].default_value = 1.0+ out_node = mat.node_tree.nodes.new("ShaderNodeOutputMaterial")+ mat.node_tree.links.new(emission.outputs[0], out_node.inputs["Surface"])++ obj.data.materials.clear()+ obj.data.materials.append(mat)+ temp_materials.append(mat)++ # ── Hide non-target mesh objects ────────────────────────────────────────+ hidden_restore = {}+ for obj in context.scene.objects:+ if obj.type == 'MESH' and obj not in to_export:+ hidden_restore[obj] = obj.hide_render+ obj.hide_render = True++ # ── World → black background ────────────────────────────────────────────+ if bpy.app.version >= (5, 0, 0):+ world.use_nodes = True+ if world.node_tree:+ for wn in world.node_tree.nodes:+ if wn.type == 'BACKGROUND':+ wn.inputs["Color"].default_value = (0.0, 0.0, 0.0, 1.0)+ wn.inputs["Strength"].default_value = 1.0+ break+ else:+ world.color = (0, 0, 0)+ world.use_nodes = False++ # ── Render settings ─────────────────────────────────────────────────────+ context.scene.render.engine = 'CYCLES'+ context.scene.render.film_transparent = False+ context.scene.cycles.samples = 1+ bpy.context.scene.display_settings.display_device = 'sRGB'+ bpy.context.scene.view_settings.view_transform = 'Raw'++ view_layer = context.view_layer+ view_layer.use_pass_emit = True+ view_layer.use_pass_environment = True++ # ── Compositor ──────────────────────────────────────────────────────────+ context.scene.use_nodes = True+ node_tree = get_compositor_node_tree(context.scene)+ comp_nodes = node_tree.nodes+ comp_links = node_tree.links+ comp_nodes.clear()++ render_layers = comp_nodes.new('CompositorNodeRLayers')+ try:+ mix_node = comp_nodes.new('CompositorNodeMixRGB')+ except Exception:+ mix_node = comp_nodes.new('ShaderNodeMixRGB')+ mix_node.blend_type = 'ADD'+ mix_node.inputs[0].default_value = 1+ output_node = comp_nodes.new('CompositorNodeOutputFile')+ configure_output_node_paths(output_node, output_dir, raw_file)++ if bpy.app.version < (5, 0, 0):+ comp_links.new(render_layers.outputs['Emit'], mix_node.inputs[1])+ comp_links.new(render_layers.outputs['Env'], mix_node.inputs[2])+ else:+ comp_links.new(render_layers.outputs['Emission'], mix_node.inputs[1])+ comp_links.new(render_layers.outputs['Environment'], mix_node.inputs[2])+ comp_links.new(mix_node.outputs[0], output_node.inputs[0])++ # ── Render ──────────────────────────────────────────────────────────────+ bpy.ops.render.render(write_still=True)++ # ── Determine actual output path ────────────────────────────────────────+ frame_suffix = "0001" if bpy.app.version < (5, 0, 0) else ""+ raw_path = os.path.join(output_dir, f"{raw_file}{frame_suffix}.png")++ # ── Restore materials ───────────────────────────────────────────────────+ for obj, mats in saved_materials.items():+ obj.data.materials.clear()+ if saved_active_materials[obj]:+ obj.data.materials.append(saved_active_materials[obj])+ for m in mats:+ if m != saved_active_materials[obj]:+ obj.data.materials.append(m)+ for mat in temp_materials:+ if mat and mat.name in bpy.data.materials:+ bpy.data.materials.remove(mat)++ # ── Restore non-target visibility ───────────────────────────────────────+ for obj, was_hidden in hidden_restore.items():+ obj.hide_render = was_hidden++ # ── Restore render / world settings ─────────────────────────────────────+ context.scene.camera = original_camera+ context.scene.render.engine = original_engine+ context.scene.render.film_transparent = original_transparent+ context.scene.cycles.samples = original_samples+ bpy.context.scene.view_settings.view_transform = original_view_transform+ world.use_nodes = original_use_nodes+ world.color = original_color+ if original_bg_node_color is not None and world.node_tree:+ for wn in world.node_tree.nodes:+ if wn.type == 'BACKGROUND':+ wn.inputs["Color"].default_value = original_bg_node_color+ wn.inputs["Strength"].default_value = original_bg_node_strength+ break++ # ── Distance-transform edge feathering ──────────────────────────────────+ if not os.path.exists(raw_path):+ print(f"[StableGen] Edge-feather: raw mask not found after render: {raw_path}")+ return None++ mask_img = cv2.imread(raw_path, cv2.IMREAD_GRAYSCALE)+ if mask_img is None:+ print(f"[StableGen] Edge-feather: failed to read raw mask: {raw_path}")+ return None++ _, binary = cv2.threshold(mask_img, 127, 255, cv2.THRESH_BINARY)+ dist = cv2.distanceTransform(binary, cv2.DIST_L2, 5)+ linear = np.clip(dist / max(feather_width, 1), 0.0, 1.0).astype(np.float32)++ # Gaussian-blur the linear ramp to round off the kinks at both ends.+ # The linear ramp has sharp slope discontinuities at dist=0 (edge) and+ # dist=feather_width (interior plateau). A small Gaussian blur smooths+ # these transitions without shifting the ramp position or compressing the+ # transition zone the way smoothstep does.+ # softness == 0 → raw linear ramp (kinks preserved)+ # softness == 1 → moderate rounding (sigma ≈ 25% of feather width)+ # softness > 1 → stronger rounding / wider smooth zone+ if softness > 0.01:+ blur_sigma = softness * feather_width * 0.25+ feathered = cv2.GaussianBlur(linear, (0, 0), sigmaX=blur_sigma)+ feathered = np.clip(feathered, 0.0, 1.0)+ else:+ feathered = linear++ feathered_u8 = (np.clip(feathered, 0.0, 1.0) * 255).astype(np.uint8)++ ef_path = os.path.join(output_dir, f"render{camera_index}_edgefeather.png")+ cv2.imwrite(ef_path, feathered_u8)++ # Clean up raw mask+ try:+ os.remove(raw_path)+ except OSError:+ pass++ print(f"[StableGen] Edge-feather mask saved: {ef_path} (width={feather_width}px, softness={softness:.2f})")+ return ef_path++def apply_uv_inpaint_texture(context, obj, baked_image_path):"""Apply a UV inpainted/baked texture to the active material.@@ -927,13 +1165,16 @@ def expand_mask_to_blocks(mask_file_path, block_size=8):return None-def export_visibility(context, to_export, obj=None, camera_visibility=None):+def export_visibility(context, to_export, obj=None, camera_visibility=None, prepare_only=False):"""Exports the visibility of the mesh by temporarily altering the shading nodes.:param context: Blender context.:param filepath: Path to the output file.:param obj: Blender object.:param camera_visibility: Camera object for visibility calculation.+ :param prepare_only: If True, only prepare the visibility material without+ baking/rendering and without restoring the original materials.+ Used by debug tools to inspect the material in the viewport.:return: None"""# Store original materials and create temporary ones@@ -985,8 +1226,13 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None):# Determine which input to used based on existence of BSDF node before the outputif output.inputs[0].links and output.inputs[0].links[0].from_node.type == 'BSDF_PRINCIPLED':- color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node- input = output.inputs[0].links[0].from_node.inputs[0]+ principled = output.inputs[0].links[0].from_node+ if not principled.inputs[0].links:+ # Principled BSDF exists but nothing is connected to its+ # Base Color – this is not a projection material.+ return False+ color_mix = principled.inputs[0].links[0].from_node+ input = principled.inputs[0]else:color_mix = output.inputs[0].links[0].from_nodeinput = output.inputs[0]@@ -1052,6 +1298,83 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None):node.inputs[1].default_value = context.scene.weight_exponent if context.scene.weight_exponent_mask else 1.0except Exception as e:print(f" - Warning: Failed to set Power for native node '{node.name}'. Error: {e}")++ # When the normalization chain exists (multi-camera), the node+ # chain is: power_weight(exp=1) → base_weight → NormW(÷max) →+ # SharpW(pow exp) → mix tree.+ # For the visibility map we need the *original* un-normalized+ # weight: pow(cos(θ), target_exp) × binary_gates.+ # We achieve this by:+ # 1. Setting power_weight to target_exp (restores original weight)+ # 2. Making SharpW a passthrough (exp=1) and rerouting its input+ # from NormW's source (the base weight) so the DIVIDE-by-max+ # is bypassed entirely.+ has_norm_nodes = any(+ n.type == 'MATH' and n.operation == 'DIVIDE'+ and n.label.startswith('NormW-')+ for n in nodes+ )+ if has_norm_nodes:+ target_exp = context.scene.weight_exponent if context.scene.weight_exponent_mask else 1.0+ for node in nodes:+ # Restore per-camera power to the desired exponent+ if (node.type == 'MATH' and node.operation == 'POWER'+ and node.label == 'power_weight'):+ try:+ node.inputs[1].default_value = target_exp+ except Exception as e:+ print(f" - Warning: Failed to set power_weight '{node.name}'. Error: {e}")+ elif node.type == 'SCRIPT' and "Power" in node.inputs:+ try:+ node.inputs["Power"].default_value = target_exp+ except Exception as e:+ print(f" - Warning: Failed to set OSL Power '{node.name}'. Error: {e}")++ # Bypass NormW+SharpW: reroute SharpW to read from+ # NormW's source (the base weight), set exponent to 1.0+ elif (node.type == 'MATH' and node.operation == 'POWER'+ and node.label.startswith('SharpW-')):+ try:+ # SharpW.inputs[0] ← NormW.outputs[0]+ # NormW.inputs[0] ← base_weight_output+ # Reroute: SharpW.inputs[0] ← base_weight_output+ if node.inputs[0].links:+ norm_node = node.inputs[0].links[0].from_node+ if (norm_node.label.startswith('NormW-')+ and norm_node.inputs[0].links):+ base_out = norm_node.inputs[0].links[0].from_socket+ links.remove(node.inputs[0].links[0])+ links.new(base_out, node.inputs[0])+ node.inputs[1].default_value = 1.0+ except Exception as e:+ print(f" - Warning: Failed to bypass SharpW '{node.name}'. Error: {e}")++ # Also bypass standalone NormW nodes (when user_exponent+ # was 1.0 at build time, there's no SharpW — the NormW+ # DIVIDE node is used directly in the mix tree).+ elif (node.type == 'MATH' and node.operation == 'DIVIDE'+ and node.label.startswith('NormW-')):+ try:+ # Check if this NormW feeds directly into the+ # mix tree (no SharpW after it).+ feeds_sharp = False+ for link in node.outputs[0].links:+ if (link.to_node.type == 'MATH'+ and link.to_node.operation == 'POWER'+ and link.to_node.label.startswith('SharpW-')):+ feeds_sharp = True+ break+ if not feeds_sharp:+ # This NormW feeds the mix tree directly.+ # Reroute its downstream links to its source.+ if node.inputs[0].links:+ base_out = node.inputs[0].links[0].from_socket+ for link in list(node.outputs[0].links):+ to_socket = link.to_socket+ links.remove(link)+ links.new(base_out, to_socket)+ except Exception as e:+ print(f" - Warning: Failed to bypass NormW '{node.name}'. Error: {e}")return True@@ -1066,6 +1389,13 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None):if not prepare_material(obj):return False+ if prepare_only:+ # Debug mode: leave the visibility material applied for viewport inspection+ # Rename the temp materials so they are identifiable as debug materials+ for obj_key, temp_mat in temporary_materials.items():+ temp_mat.name = f"SG_Debug_Visibility_{obj_key.name}"+ return True+# Bake or render the textureif not camera_visibility:output_dir = get_dir_path(context, "uv_inpaint")["visibility"]@@ -1119,6 +1449,43 @@ def export_visibility(context, to_export, obj=None, camera_visibility=None):# Camera Placement Helper Functions# =========================================================++def _existing_camera_directions(mesh_center):+ """Return unit-direction vectors from *mesh_center* toward each existing+ camera in the scene. Used by 'Consider existing cameras' to treat+ pre-existing cameras as already-placed directions."""+ dirs = []+ center = np.array(mesh_center, dtype=float)+ for obj in bpy.data.objects:+ if obj.type == 'CAMERA':+ pos = np.array(obj.location, dtype=float)+ d = pos - center+ norm = np.linalg.norm(d)+ if norm > 1e-6:+ dirs.append(d / norm)+ return dirs+++def _filter_near_existing(directions, existing_dirs, min_angle_deg=30.0):+ """Remove directions that are within *min_angle_deg* of any existing+ camera direction. Both *directions* and *existing_dirs* should be+ lists of unit-length numpy arrays."""+ if not existing_dirs or not directions:+ return directions+ cos_thresh = math.cos(math.radians(min_angle_deg))+ existing_np = np.array(existing_dirs) # (M, 3)+ filtered = []+ for d in directions:+ d_np = np.asarray(d, dtype=float)+ n = np.linalg.norm(d_np)+ if n < 1e-12:+ continue+ d_unit = d_np / n+ dots = existing_np @ d_unit # (M,)+ if dots.max() < cos_thresh:+ filtered.append(d)+ return filtered+def _fibonacci_sphere_points(n):"""Generate *n* approximately evenly-spaced unit vectors on a sphereusing a Fibonacci spiral. Returns list of (x, y, z) tuples."""@@ -1363,7 +1730,8 @@ def _compute_pca_axes(verts):def _greedy_coverage_directions(normals, areas, max_cameras=12,- coverage_target=0.95, n_candidates=200):+ coverage_target=0.95, n_candidates=200,+ existing_dirs=None):"""Greedy set-cover: iteratively pick the camera direction that adds themost newly-visible surface area (back-face culling only, no occlusion,for speed). Returns (selected_directions, final_coverage_fraction)."""@@ -1378,6 +1746,10 @@ def _greedy_coverage_directions(normals, areas, max_cameras=12,visibility = normals @ candidates.T > 0.26 # (n_faces, n_candidates)covered = np.zeros(len(areas), dtype=bool)+ # Pre-seed coverage from existing cameras+ if existing_dirs:+ for edir in existing_dirs:+ covered |= normals @ np.asarray(edir, dtype=float) > 0.26selected = []for _ in range(max_cameras):@@ -1442,7 +1814,8 @@ def _ray_occluded(bvh_trees, origin, direction, max_dist):def _greedy_select_from_visibility(vis, areas, max_cameras, coverage_target,- candidates):+ candidates, existing_dirs=None,+ normals=None):"""Run greedy set-cover on a pre-computed visibility matrix.Parameters@@ -1452,6 +1825,10 @@ def _greedy_select_from_visibility(vis, areas, max_cameras, coverage_target,max_cameras : intcoverage_target : floatcandidates : ndarray (n_candidates, 3)+ existing_dirs : list[ndarray] or None+ Directions of existing cameras to pre-seed coverage.+ normals : ndarray (n_faces, 3) or None+ Face normals, required when *existing_dirs* is given.Returns-------@@ -1462,6 +1839,10 @@ def _greedy_select_from_visibility(vis, areas, max_cameras, coverage_target,return [], 0.0covered = np.zeros(len(areas), dtype=bool)+ # Pre-seed coverage from existing cameras+ if existing_dirs and normals is not None:+ for edir in existing_dirs:+ covered |= normals @ np.asarray(edir, dtype=float) > 0.26selected = []for _ in range(max_cameras):@@ -1526,8 +1907,42 @@ def _occ_filter_faces_generator(normals, areas, centers, bvh_trees,return exterior+def _occ_vis_count_generator(normals, areas, centers, bvh_trees,+ n_candidates=200):+ """Generator: count how many candidate directions can see each face.++ Like ``_occ_filter_faces_generator`` but returns per-face visibility+ *counts* instead of a boolean mask. This enables continuous weighting+ rather than binary keep/remove filtering.++ Yields progress floats in [0, 1]. Final result (via+ ``StopIteration.value``) is an int array ``(n_faces,)`` with the number+ of unoccluded candidate directions per face.+ """+ n_faces = len(normals)+ candidates = np.array(_fibonacci_sphere_points(n_candidates))+ backface_vis = normals @ candidates.T > 0.26 # (F, C)+ vis_count = np.zeros(n_faces, dtype=int)+ epsilon = 0.001+ BATCH = 5++ for j in range(n_candidates):+ cam_dir = candidates[j]+ for i in range(n_faces):+ if not backface_vis[i, j]:+ continue+ origin = centers[i] + normals[i] * epsilon+ if not _ray_occluded(bvh_trees, origin, cam_dir, 1e6):+ vis_count[i] += 1+ if (j + 1) % BATCH == 0 or j == n_candidates - 1:+ yield (j + 1) / n_candidates++ return vis_count++def _occ_fom_generator(normals, areas, centers, bvh_trees,- max_cameras, coverage_target, n_candidates=200):+ max_cameras, coverage_target, n_candidates=200,+ existing_dirs=None):"""Generator: Full Occlusion Matrix approach.Yields progress floats in [0, 1]. Final result is available via@@ -1557,11 +1972,13 @@ def _occ_fom_generator(normals, areas, centers, bvh_trees,yield (j + 1) / n_candidatesreturn _greedy_select_from_visibility(- vis, areas, max_cameras, coverage_target, candidates)+ vis, areas, max_cameras, coverage_target, candidates,+ existing_dirs=existing_dirs, normals=normals)def _occ_tpr_generator(normals, areas, centers, bvh_trees,- max_cameras, coverage_target, n_candidates=200):+ max_cameras, coverage_target, n_candidates=200,+ existing_dirs=None):"""Generator: Two-Pass Refinement approach.Yields progress floats in [0, 1]. Final result is available via@@ -1577,6 +1994,10 @@ def _occ_tpr_generator(normals, areas, centers, bvh_trees,# ── Pass 1: fast greedy (back-face only, instant) ─────────────────covered_bf = np.zeros(len(areas), dtype=bool)+ # Pre-seed coverage from existing cameras+ if existing_dirs:+ for edir in existing_dirs:+ covered_bf |= normals @ np.asarray(edir, dtype=float) > 0.26selected_indices = []for _ in range(max_cameras):@@ -1929,7 +2350,9 @@ 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()- shader.uniform_float("color", (1.0, 0.55, 0.0, 0.9))+ _prefs = bpy.context.preferences.addons.get(__package__)+ _oc = _prefs.preferences.overlay_color if _prefs else (0.3, 0.5, 1.0)+ shader.uniform_float("color", (_oc[0], _oc[1], _oc[2], 0.9))gpu.state.line_width_set(2.0)gpu.state.blend_set('ALPHA')batch.draw(shader)@@ -1958,7 +2381,9 @@ def _sg_draw_view_labels():font_id = 0blf.size(font_id, 13)- blf.color(font_id, 1.0, 0.85, 0.35, 0.95)+ _prefs = bpy.context.preferences.addons.get(__package__)+ _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 textprompt_lookup = {item.name: item.prompt for item in scene.camera_prompts@@ -2123,7 +2548,7 @@ class AddCameras(bpy.types.Operator):('greedy_coverage', "Auto (Greedy Coverage)", "Iteratively add cameras that maximise new visible surface. Automatically determines the number of cameras needed"),('fan_from_camera', "Fan from Camera", "Spread cameras in an arc around the active camera's orbit position"),],- default='orbit_ring'+ default='normal_weighted') # type: ignorenum_cameras: bpy.props.IntProperty(@@ -2145,8 +2570,14 @@ class AddCameras(bpy.types.Operator):) # type: ignorepurge_others: bpy.props.BoolProperty(- name="Remove Other Cameras",- description="Delete all existing cameras except the active/reference camera before adding new ones",+ name="Remove Existing Cameras",+ description="Delete ALL existing cameras (including active) before adding new ones",+ default=True+ ) # type: ignore++ consider_existing: bpy.props.BoolProperty(+ name="Consider Existing Cameras",+ description="Treat existing cameras as already-placed directions so auto modes avoid duplicating their coverage",default=True) # type: ignore@@ -2208,6 +2639,13 @@ class AddCameras(bpy.types.Operator):default=False) # type: ignore+ review_placement: bpy.props.BoolProperty(+ name="Review Camera Placement",+ description="After placing cameras, fly through each one for review. "+ "When disabled the cameras are created immediately without the interactive fly-through",+ default=True+ ) # type: ignore+occlusion_mode: bpy.props.EnumProperty(name="Occlusion Handling",description="How to account for self-occlusion when choosing camera directions",@@ -2218,6 +2656,14 @@ class AddCameras(bpy.types.Operator):"Build a complete BVH-validated visibility matrix before greedy selection. Most accurate but slower"),('two_pass', "Two-Pass Refinement","Fast back-face pass, then targeted BVH refinement only for faces with zero true coverage"),+ ('vis_weighted', "Visibility-Weighted",+ "Weight faces by their visibility fraction from 200 directions. "+ "Mostly-occluded faces have reduced influence on camera placement (linear). "+ "Only affects Normal-Weighted mode; other modes fall back to Full Occlusion Matrix"),+ ('vis_interactive', "Interactive Visibility",+ "Like Visibility-Weighted but with a real-time preview: scroll to adjust "+ "the occlusion balance and see cameras reposition instantly. "+ "Only affects Normal-Weighted mode; other modes fall back to Full Occlusion Matrix"),],default='none') # type: ignore@@ -2232,6 +2678,13 @@ class AddCameras(bpy.types.Operator):_occ_gen = None_occ_progress = 0.0_occ_state = None+ # Interactive visibility preview state+ _vis_preview_phase = False+ _vis_count = None+ _vis_n_candidates = 200+ _vis_balance = 0.2+ _vis_state = None+ _vis_directions = Nonedef draw(self, context):"""Custom dialog layout for the placement mode selector."""@@ -2256,7 +2709,10 @@ class AddCameras(bpy.types.Operator):if self.exclude_bottom:layout.prop(self, "exclude_bottom_angle")layout.prop(self, "auto_prompts")+ layout.prop(self, "review_placement")layout.prop(self, "purge_others")+ if not self.purge_others and is_auto:+ layout.prop(self, "consider_existing")def draw_callback(self, context):# ── Occlusion progress display ───────────────────────────────────@@ -2288,6 +2744,37 @@ class AddCameras(bpy.types.Operator):blf.color(font_id, 1.0, 1.0, 1.0, 1.0)return+ # ── Interactive visibility preview HUD ───────────────────────────+ if self._vis_preview_phase:+ font_id = 0+ region = context.region+ rw, rh = region.width, region.height+ balance = self._vis_balance++ msg = f"Occlusion Balance: {balance:.0%}"+ blf.size(font_id, 22)+ tw, _th = blf.dimensions(font_id, msg)+ blf.position(font_id, (rw - tw) / 2, rh * 0.13, 0)+ blf.color(font_id, 1.0, 0.85, 0.35, 0.95)+ blf.draw(font_id, msg)++ n_cams = len(self._cameras) if self._cameras else 0+ info = f"{n_cams} cameras"+ blf.size(font_id, 16)+ iw, _ih = blf.dimensions(font_id, info)+ blf.position(font_id, (rw - iw) / 2, rh * 0.13 - 26, 0)+ blf.color(font_id, 0.9, 0.9, 0.9, 0.9)+ blf.draw(font_id, info)++ hint = "Scroll \u2191\u2193 to adjust | ENTER to confirm | ESC to cancel"+ blf.size(font_id, 13)+ hw, _hh = blf.dimensions(font_id, hint)+ blf.position(font_id, (rw - hw) / 2, rh * 0.13 - 48, 0)+ blf.color(font_id, 0.7, 0.7, 0.7, 0.8)+ blf.draw(font_id, hint)+ blf.color(font_id, 1.0, 1.0, 1.0, 1.0)+ return+# ── Fly-through HUD ──────────────────────────────────────────────try:count = len(self._cameras)@@ -2321,10 +2808,10 @@ class AddCameras(bpy.types.Operator):blf.color(font_id, 1.0, 1.0, 1.0, 1.0)def execute(self, context):- # --- Delete other cameras if requested ---+ # --- Delete existing cameras if requested ---if self.purge_others:scene = context.scene- to_remove = [obj for obj in bpy.data.objects if obj.type == 'CAMERA' and obj != scene.camera]+ to_remove = [obj for obj in bpy.data.objects if obj.type == 'CAMERA']for cam in to_remove:for col in list(cam.users_collection):col.objects.unlink(cam)@@ -2332,6 +2819,7 @@ class AddCameras(bpy.types.Operator):for cam_data in list(bpy.data.cameras):if not cam_data.users:bpy.data.cameras.remove(cam_data)+ scene.camera = None# --- Validate mesh requirement for mesh-based modes ---if self.placement_mode in ('hemisphere', 'normal_weighted', 'pca_axes', 'greedy_coverage'):@@ -2434,6 +2922,14 @@ class AddCameras(bpy.types.Operator):mesh_names = ', '.join(o.name for o in target_meshes)self.report({'INFO'}, f"Target meshes ({len(target_meshes)}): {mesh_names}")+ # --- Collect existing camera directions (for "consider existing") ---+ existing_dirs = None+ if not self.purge_others and self.consider_existing:+ existing_dirs = _existing_camera_directions(mesh_center)+ if existing_dirs:+ self.report({'INFO'},+ f"Considering {len(existing_dirs)} existing camera(s)")+# --- Determine directions ---if self.placement_mode == 'greedy_coverage':normals, areas, centers = _get_mesh_face_data(target_meshes)@@ -2446,21 +2942,25 @@ class AddCameras(bpy.types.Operator):directions, coverage = _greedy_coverage_directions(normals, areas,max_cameras=self.max_auto_cameras,- coverage_target=self.coverage_target)+ coverage_target=self.coverage_target,+ existing_dirs=existing_dirs)directions = [np.array(d) for d in directions]self.report({'INFO'},f"Greedy coverage (no occlusion): "f"{len(directions)} cameras, {coverage*100:.1f}% coverage")else:+ # Greedy doesn't use K-means; vis modes fall back to FOM+ eff_occ = occ if occ in ('full_matrix', 'two_pass') else 'full_matrix'# ── Async occlusion via modal ────────────────────────depsgraph = context.evaluated_depsgraph_get()bvh_trees = _build_bvh_trees(target_meshes, depsgraph)- gen_func = (_occ_fom_generator if occ == 'full_matrix'+ gen_func = (_occ_fom_generator if eff_occ == 'full_matrix'else _occ_tpr_generator)self._occ_gen = gen_func(normals, areas, centers, bvh_trees,max_cameras=self.max_auto_cameras,- coverage_target=self.coverage_target)+ coverage_target=self.coverage_target,+ existing_dirs=existing_dirs)self._occ_phase = Trueself._occ_progress = 0.0self._occ_state = {@@ -2483,6 +2983,8 @@ class AddCameras(bpy.types.Operator):# Remove directions that point more than the threshold below the horizonthreshold_z = -math.cos(self.exclude_bottom_angle)directions = [d for d in directions if d[2] >= threshold_z]+ if existing_dirs:+ directions = _filter_near_existing(directions, existing_dirs)elif self.placement_mode == 'normal_weighted':normals, areas, centers = _get_mesh_face_data(target_meshes)if self.exclude_bottom:@@ -2490,7 +2992,32 @@ class AddCameras(bpy.types.Operator):normals, areas, centers, self.exclude_bottom_angle)occ = self.occlusion_mode- if occ != 'none':+ if occ in ('vis_weighted', 'vis_interactive'):+ # Visibility-count generator (shared by both modes)+ depsgraph = context.evaluated_depsgraph_get()+ bvh_trees = _build_bvh_trees(target_meshes, depsgraph)+ self._occ_gen = _occ_vis_count_generator(+ normals, areas, centers, bvh_trees)+ self._occ_phase = True+ self._occ_progress = 0.0+ rt = 'vis_kmeans' if occ == 'vis_weighted' else 'vis_interactive'+ self._occ_state = {+ 'result_type': rt,+ 'normals': normals,+ 'areas': areas,+ 'centers': centers,+ 'num_cameras': self.num_cameras,+ 'verts_world': verts_world,+ 'mesh_center': mesh_center,+ 'cam_settings': cam_settings,+ 'temp_cam_data': temp_cam_data,+ 'existing_dirs': existing_dirs,+ }+ context.window_manager.modal_handler_add(self)+ self._timer = context.window_manager.event_timer_add(+ 0.01, window=context.window)+ return {'RUNNING_MODAL'}+ elif occ != 'none':depsgraph = context.evaluated_depsgraph_get()bvh_trees = _build_bvh_trees(target_meshes, depsgraph)self._occ_gen = _occ_filter_faces_generator(@@ -2507,6 +3034,7 @@ class AddCameras(bpy.types.Operator):'mesh_center': mesh_center,'cam_settings': cam_settings,'temp_cam_data': temp_cam_data,+ 'existing_dirs': existing_dirs,}context.window_manager.modal_handler_add(self)self._timer = context.window_manager.event_timer_add(@@ -2516,6 +3044,8 @@ class AddCameras(bpy.types.Operator):k = min(self.num_cameras, len(normals))cluster_dirs = _kmeans_on_sphere(normals, areas, k)directions = [cluster_dirs[i] for i in range(len(cluster_dirs))]+ if existing_dirs:+ directions = _filter_near_existing(directions, existing_dirs)elif self.placement_mode == 'pca_axes':normals, areas, centers = _get_mesh_face_data(target_meshes)if self.exclude_bottom:@@ -2523,7 +3053,8 @@ class AddCameras(bpy.types.Operator):normals, areas, centers, self.exclude_bottom_angle)occ = self.occlusion_mode- if occ != 'none':+ # PCA doesn't use K-means; vis modes fall back to filter+ if occ not in ('none',):depsgraph = context.evaluated_depsgraph_get()bvh_trees = _build_bvh_trees(target_meshes, depsgraph)self._occ_gen = _occ_filter_faces_generator(@@ -2542,6 +3073,7 @@ class AddCameras(bpy.types.Operator):'mesh_center': mesh_center,'cam_settings': cam_settings,'temp_cam_data': temp_cam_data,+ 'existing_dirs': existing_dirs,}context.window_manager.modal_handler_add(self)self._timer = context.window_manager.event_timer_add(@@ -2557,6 +3089,8 @@ class AddCameras(bpy.types.Operator):threshold_z = -math.cos(self.exclude_bottom_angle)directions = [d for d in directions if d[2] >= threshold_z]directions = directions[:min(self.num_cameras, len(directions))]+ if existing_dirs:+ directions = _filter_near_existing(directions, existing_dirs)# Finalize: sort, aspect ratio, camera creation, auto promptsself._finalize_auto_cameras(@@ -2564,9 +3098,14 @@ class AddCameras(bpy.types.Operator):cam_settings, temp_cam_data)# --- Start fly-through review ---- if not self._start_fly_review(context):- return {'CANCELLED'}- return {'RUNNING_MODAL'}+ if self.review_placement:+ if not self._start_fly_review(context):+ return {'CANCELLED'}+ return {'RUNNING_MODAL'}+ else:+ # Skip review — just finish immediately+ self._finish_without_review(context)+ return {'FINISHED'}# -------------------------------------------------------# Auto-mode finalization helpers@@ -2630,6 +3169,98 @@ class AddCameras(bpy.types.Operator):self.report({'INFO'},f"Auto-prompts: assigned view labels to "f"{len(self._cameras)} cameras")+ elif not self.auto_prompts:+ # Clear any pre-existing auto-prompts so stale labels don't persist+ context.scene.camera_prompts.clear()+ context.scene.use_camera_prompts = False+ for cam_obj in self._cameras:+ if 'sg_view_label' in cam_obj:+ del cam_obj['sg_view_label']+ _sg_remove_label_overlay()++ def _update_vis_cameras(self, context):+ """Regenerate cameras based on current visibility balance setting."""+ # Remove existing preview cameras+ for cam in list(self._cameras):+ cam_data = cam.data+ bpy.data.objects.remove(cam, do_unlink=True)+ if cam_data and not cam_data.users:+ bpy.data.cameras.remove(cam_data)+ self._cameras.clear()++ state = self._vis_state+ vis_count = self._vis_count+ n_cand = self._vis_n_candidates+ vis_fraction = vis_count.astype(float) / n_cand+ balance = self._vis_balance++ exterior = vis_count > 0+ normals = state['normals'][exterior]+ areas_base = state['areas'][exterior]+ vf = vis_fraction[exterior]+ # weight = area × (vis_fraction + balance × (1 - vis_fraction))+ # balance=0: weight = area × vis_fraction (full vis-weighting)+ # balance=1: weight = area (no vis-weighting, all exterior equal)+ weighted_areas = areas_base * (vf + balance * (1.0 - vf))++ existing_dirs = state.get('existing_dirs')+ k = min(state['num_cameras'], len(normals))+ if k > 0 and len(normals) > 0:+ cluster_dirs = _kmeans_on_sphere(normals, weighted_areas, k)+ directions = [cluster_dirs[i] for i in range(len(cluster_dirs))]+ if existing_dirs:+ directions = _filter_near_existing(directions, existing_dirs)+ else:+ directions = []++ # Sort directions+ ref_dir = None+ rv3d = context.region_data+ if rv3d:+ view_dir = rv3d.view_rotation @ mathutils.Vector((0, 0, -1))+ ref_dir = np.array([-view_dir.x, -view_dir.y, -view_dir.z])+ directions = _sort_directions_spatially(directions, ref_dir)+ self._vis_directions = directions++ # Quick camera creation (without full finalize overhead)+ if directions:+ cam_settings = state['cam_settings']+ fov_x, fov_y = _get_fov(cam_settings, context)+ self._create_cameras_from_directions(+ context, directions, state['mesh_center'],+ state['verts_world'], cam_settings, fov_x, fov_y)+ if self._cameras:+ context.scene.camera = self._cameras[0]++ n_ext = int(exterior.sum())+ context.area.header_text_set(+ f"Occlusion Balance: {balance:.0%} | "+ f"{len(directions)} cameras, {n_ext} visible faces | "+ f"Scroll to adjust | ENTER to confirm | ESC to cancel")++ def _cleanup_vis_preview(self, context):+ """Clean up interactive visibility preview state."""+ # Delete preview cameras+ for cam in list(self._cameras):+ cam_data = cam.data+ bpy.data.objects.remove(cam, do_unlink=True)+ if cam_data and not cam_data.users:+ bpy.data.cameras.remove(cam_data)+ self._cameras.clear()++ # Clean up temp camera data+ state = self._vis_state+ if state and state.get('temp_cam_data'):+ bpy.data.cameras.remove(state['temp_cam_data'])++ self._vis_preview_phase = False+ self._vis_state = None+ self._vis_count = None+ context.area.header_text_set(None)+ if AddCameras._draw_handle:+ bpy.types.SpaceView3D.draw_handler_remove(+ AddCameras._draw_handle, 'WINDOW')+ AddCameras._draw_handle = Nonedef _start_fly_review(self, context, add_modal_handler=True):"""Frame the first camera and start fly-through review.@@ -2665,6 +3296,18 @@ class AddCameras(bpy.types.Operator):bpy.ops.view3d.fly('INVOKE_DEFAULT')return True+ def _finish_without_review(self, context):+ """Clean up draw handler and restore state without fly-through."""+ if AddCameras._draw_handle:+ bpy.types.SpaceView3D.draw_handler_remove(+ AddCameras._draw_handle, 'WINDOW')+ AddCameras._draw_handle = None+ if self._cameras:+ context.scene.camera = self._cameras[0]+ _sg_restore_label_overlay()+ self.report({'INFO'},+ f"Cameras added successfully ({len(self._cameras)} cameras).")+# -------------------------------------------------------# Placement methods# -------------------------------------------------------@@ -2934,6 +3577,48 @@ class AddCameras(bpy.types.Operator)::min(state['num_cameras'],len(directions))]+ elif result_type == 'vis_kmeans':+ # Visibility-weighted K-means: weight by fraction+ vis_count = done.value+ n_cand = 200+ vis_fraction = vis_count.astype(float) / n_cand+ exterior = vis_count > 0+ normals = state['normals'][exterior]+ areas_base = state['areas'][exterior]+ weighted_areas = areas_base * vis_fraction[exterior]+ n_ext = int(exterior.sum())+ n_removed = len(vis_count) - n_ext+ self.report({'INFO'},+ f"Visibility-weighted: {n_ext} visible faces, "+ f"{n_removed} fully occluded removed")+ k = min(state['num_cameras'], len(normals))+ if k > 0 and len(normals) > 0:+ cluster_dirs = _kmeans_on_sphere(+ normals, weighted_areas, k)+ directions = [cluster_dirs[i]+ for i in range(len(cluster_dirs))]+ else:+ directions = []++ elif result_type == 'vis_interactive':+ # Enter interactive preview phase+ vis_count = done.value+ self._vis_count = vis_count+ self._vis_n_candidates = 200+ self._vis_balance = 0.2+ self._vis_preview_phase = True+ self._vis_state = state+ self._occ_state = None+ self._update_vis_cameras(context)+ return {'RUNNING_MODAL'}++ # Angular dedup against existing cameras (filter paths)+ ex_dirs = state.get('existing_dirs')+ if ex_dirs and result_type in (+ 'filter_kmeans', 'filter_pca', 'vis_kmeans'):+ directions = _filter_near_existing(+ directions, ex_dirs)+# Finalize cameras (sort, aspect, create, prompts)self._finalize_auto_cameras(context, directions,@@ -2942,13 +3627,78 @@ class AddCameras(bpy.types.Operator):self._occ_state = None# Transition to fly-through review+ if self.review_placement:+ if not self._start_fly_review(+ context, add_modal_handler=False):+ return {'CANCELLED'}+ # Stay in modal for the fly-through phase+ else:+ self._finish_without_review(context)+ return {'FINISHED'}+ return {'RUNNING_MODAL'}++ # Let Blender process UI events during occlusion+ return {'RUNNING_MODAL'}++ # ── Interactive visibility preview phase ─────────────────────────+ if self._vis_preview_phase:+ if event.type in {'ESC', 'RIGHTMOUSE'} and event.value == 'PRESS':+ self._cleanup_vis_preview(context)+ self.report({'WARNING'}, "Interactive visibility cancelled.")+ return {'CANCELLED'}++ changed = False+ if event.type == 'WHEELUPMOUSE':+ self._vis_balance = min(1.0, self._vis_balance + 0.05)+ changed = True+ elif event.type == 'WHEELDOWNMOUSE':+ self._vis_balance = max(0.0, self._vis_balance - 0.05)+ changed = True+ elif event.type == 'NUMPAD_PLUS' and event.value == 'PRESS':+ self._vis_balance = min(1.0, self._vis_balance + 0.05)+ changed = True+ elif event.type == 'NUMPAD_MINUS' and event.value == 'PRESS':+ self._vis_balance = max(0.0, self._vis_balance - 0.05)+ changed = True++ if changed:+ self._update_vis_cameras(context)+ for area in context.screen.areas:+ if area.type == 'VIEW_3D':+ area.tag_redraw()+ return {'RUNNING_MODAL'}++ if event.type in {'RET', 'SPACE'} and event.value == 'PRESS':+ # Confirm: finalize with current directions+ self._vis_preview_phase = False+ context.area.header_text_set(None)++ # Delete preview cameras+ for cam in list(self._cameras):+ cam_data = cam.data+ bpy.data.objects.remove(cam, do_unlink=True)+ if cam_data and not cam_data.users:+ bpy.data.cameras.remove(cam_data)+ self._cameras.clear()++ state = self._vis_state+ self._finalize_auto_cameras(+ context, self._vis_directions,+ state['verts_world'], state['mesh_center'],+ state['cam_settings'], state['temp_cam_data'])+ self._vis_state = None+ self._vis_count = None++ # Transition to fly-through or finish+ if self.review_placement:if not self._start_fly_review(context, add_modal_handler=False):return {'CANCELLED'}- # Stay in modal for the fly-through phase+ else:+ self._finish_without_review(context)+ return {'FINISHED'}return {'RUNNING_MODAL'}- # Let Blender process UI events during occlusionreturn {'RUNNING_MODAL'}# ── Fly-through review phase ─────────────────────────────────────diff --git a/stablegen/stablegen.py b/stablegen/stablegen.pyindex e903a13..a951ac3 100644--- a/stablegen/stablegen.py+++ b/stablegen/stablegen.py@@ -7,19 +7,19 @@ import math # pylint: disable=import-error# Stock presetsPRESETS = {- "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, "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": 1.0, "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, "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}]},- "MODEL IS IMPORTANT": {"description": "Same as default, but is more guided by the model", "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, "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": 1.0, "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, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.75, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},- "CHARACTERS": {"description": "Optimized settings for character 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": 80.0, "weight_exponent": 3.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": 1.0, "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.1, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "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, "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}]},- "CHARACTERS (ALTERNATIVE MASKING)": {"description": "Optimized for character generation. Uses alternative masking parameters to be more consistent between images, but may produce more artifacts. Try if \"Characters\" fails.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "weight_exponent": 3.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": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.5, "sequential_factor_smooth": 0.3499999940395355, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "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": 10, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "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}]},- "QUICK DRAFT": {"description": "Optimized for speed", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 4, "cfg": 1.0, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "grid", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "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.1, "sequential_ipadapter": True, "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": 2, "blur_mask_sigma": 1.0, "grow_mask_by": 2, "canny_threshold_low": 0, "canny_threshold_high": 80, "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': 'Hyper-SDXL-4steps-lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},- "UV INPAINTING": {"description": "Recommended UV Inpainting setup. It is recommended to bake texutures manually before running the generation to fine-tune unwrapping and avoid lag when generating.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 10, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "uv_inpaint", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "3,0,1,2", "sequential_factor": 0.6000000238418579, "sequential_factor_smooth": 0.11000001430511475, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "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": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]}, # No ControlNet for UV Inpainting by default- "ARCHITECTURE": {"description": "Prioritizes only the most straight-on camera for each point. This means details generated on flat surfaces will not get blurred by getting generated differently from two or more viewpoints. Does not use visibility masking. Each picture will get generated as new, consistency depends on IPAdapter + geometry.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "weight_exponent": 10.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "separate", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": False, "sequential_custom_camera_order": "", "sequential_factor": 0.75, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "ipadapter_weight_type": "style", "ipadapter_strength": 0.800000011920929, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": False, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},- "QWEN EDIT PRECISE": {"description": "Precise detail when camera overlap is good. Relies on context renders plus the prompt, so sparse coverage can still introduce artifacts.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "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": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},- "QWEN EDIT SAFE": {"description": "Safer fallback when coverage is limited. Uses the previous view (recent mode) instead of context renders to keep global look coherent, at the cost of some fine-detail persistence.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 6.0, "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": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},- "QWEN EDIT ALT": {"description": "Balanced option that mixes additional context renders with sequential references to smooth out coverage while keeping detail reasonable.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "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": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "recent", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "ADDITIONAL", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "early_priority": True, "early_priority_strength": 0.5, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},- "QWEN EDIT PRECISE (NUNCHAKU)": {"description": "Precise detail using Nunchaku. Meant to be used with the Nunchaku model which has the 4-step Lightning LoRA included. Requires Nunchaku nodes.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "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": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "lora_units": []},- "QWEN EDIT SAFE (NUNCHAKU)": {"description": "Safer fallback using Nunchaku. Meant to be used with the Nunchaku model which has the 4-step Lightning LoRA included. Requires Nunchaku nodes.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 6.0, "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": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "lora_units": []},- "QWEN EDIT ALT (NUNCHAKU)": {"description": "Balanced option using Nunchaku. Meant to be used with the Nunchaku model which has the 4-step Lightning LoRA included. Requires Nunchaku nodes.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "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": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "recent", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "ADDITIONAL", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "early_priority": True, "early_priority_strength": 0.5, "lora_units": []},+ "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, "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, "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}]},+ "MODEL IS IMPORTANT": {"description": "Same as default, but is more guided by the model", "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, "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, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.75, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},+ "CHARACTERS": {"description": "Optimized settings for character 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": 80.0, "weight_exponent": 3.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.1, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "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, "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}]},+ "CHARACTERS (ALTERNATIVE MASKING)": {"description": "Optimized for character generation. Uses alternative masking parameters to be more consistent between images, but may produce more artifacts. Try if \"Characters\" fails.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "weight_exponent": 3.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.5, "sequential_factor_smooth": 0.3499999940395355, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "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": 10, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "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}]},+ "QUICK DRAFT": {"description": "Optimized for speed", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 4, "cfg": 1.0, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "grid", "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.1, "sequential_ipadapter": True, "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": 2, "blur_mask_sigma": 1.0, "grow_mask_by": 2, "canny_threshold_low": 0, "canny_threshold_high": 80, "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': 'Hyper-SDXL-4steps-lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},+ "UV INPAINTING": {"description": "Recommended UV Inpainting setup. It is recommended to bake texutures manually before running the generation to fine-tune unwrapping and avoid lag when generating.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 10, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "uv_inpaint", "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": "3,0,1,2", "sequential_factor": 0.6000000238418579, "sequential_factor_smooth": 0.11000001430511475, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "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": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]}, # No ControlNet for UV Inpainting by default+ "ARCHITECTURE": {"description": "Prioritizes only the most straight-on camera for each point. This means details generated on flat surfaces will not get blurred by getting generated differently from two or more viewpoints. Does not use visibility masking. Each picture will get generated as new, consistency depends on IPAdapter + geometry.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 80.0, "weight_exponent": 10.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "generation_method": "separate", "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": False, "sequential_custom_camera_order": "", "sequential_factor": 0.75, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "ipadapter_weight_type": "style", "ipadapter_strength": 0.800000011920929, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": False, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}], "lora_units": [{'model_name': 'sdxl_lightning_8step_lora.safetensors', 'model_strength': 1.0, 'clip_strength': 1.0}]},+ "QWEN EDIT PRECISE": {"description": "Precise detail when camera overlap is good. Relies on context renders plus the prompt, so sparse coverage can still introduce artifacts.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "qwen_voronoi_mode": False, "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.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},+ "QWEN EDIT SAFE": {"description": "Safer fallback when coverage is limited. Uses the previous view (recent mode) instead of context renders to keep global look coherent, at the cost of some fine-detail persistence.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 6.0, "qwen_voronoi_mode": False, "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.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},+ "QWEN EDIT ALT": {"description": "Balanced option that mixes additional context renders with sequential references to smooth out coverage while keeping detail reasonable.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "qwen_voronoi_mode": False, "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.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "recent", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "ADDITIONAL", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "early_priority": True, "early_priority_strength": 0.5, "lora_units": [{'model_name': 'Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors', 'model_strength': 1.0, 'clip_strength': 0.0}]},+ "QWEN EDIT PRECISE (NUNCHAKU)": {"description": "Precise detail using Nunchaku. Meant to be used with the Nunchaku model which has the 4-step Lightning LoRA included. Requires Nunchaku nodes.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "qwen_voronoi_mode": False, "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.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.0, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "REPLACE_STYLE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "lora_units": []},+ "QWEN EDIT SAFE (NUNCHAKU)": {"description": "Safer fallback using Nunchaku. Meant to be used with the Nunchaku model which has the 4-step Lightning LoRA included. Requires Nunchaku nodes.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 6.0, "qwen_voronoi_mode": False, "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.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "early_priority": False, "early_priority_strength": 0.5, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "NONE", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "lora_units": []},+ "QWEN EDIT ALT (NUNCHAKU)": {"description": "Balanced option using Nunchaku. Meant to be used with the Nunchaku model which has the 4-step Lightning LoRA included. Requires Nunchaku nodes.", "control_after_generate": "fixed", "model_architecture": "qwen_image_edit", "steps": 4, "cfg": 1.0, "sampler": "euler", "scheduler": "simple", "fallback_color": mathutils.Color((0.0, 0.0, 0.0)), "discard_factor": 70.0, "discard_factor_generation_only": True, "discard_factor_after_generation": 90.0, "weight_exponent": 3.0, "qwen_voronoi_mode": False, "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.699999988079071, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "recent", "sequential_desaturate_factor": 0.0, "sequential_contrast_factor": 0.10000000149011612, "sequential_ipadapter_regenerate": False, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "qwen_guidance_map_type": "depth", "qwen_use_external_style_image": False, "qwen_external_style_image": "", "qwen_context_render_mode": "ADDITIONAL", "qwen_external_style_initial_only": False, "qwen_use_custom_prompts": False, "qwen_custom_prompt_initial": "Change the format of image 1 to '{main_prompt}'", "qwen_custom_prompt_seq_none": "Change and transfer the format of '{main_prompt}' in image 1 to the style from image 2", "qwen_custom_prompt_seq_replace": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas.", "qwen_custom_prompt_seq_additional": "Change and transfer the format of image 1 to '{main_prompt}'. Replace all solid magenta areas in image 2. Replace the background with solid gray. The style from image 2 should smoothly continue into the previously magenta areas. Image 3 represents the overall style of the object.", "qwen_guidance_fallback_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_guidance_background_color": mathutils.Color((1.0, 0.0, 1.0)), "qwen_context_cleanup": False, "qwen_context_cleanup_hue_tolerance": 0.0, "qwen_context_cleanup_value_adjust": 0.0, "qwen_context_fallback_dilation": 1, "qwen_rescale_alignment": True, "early_priority": True, "early_priority_strength": 0.5, "lora_units": []},}# Global list of all generation parameter names to check for a preset.@@ -76,6 +76,7 @@ GEN_PARAMETERS = ["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",@@ -598,6 +599,9 @@ class StableGenPanel(bpy.types.Panel):split = content_box.split(factor=0.5)split.label(text="Context Render:")split.prop(scene, "qwen_context_render_mode", text="")++ row = content_box.row()+ row.prop(scene, "qwen_voronoi_mode", text="Voronoi Projection", toggle=True, icon="MESH_GRID")elif scene.qwen_generation_method in ('refine', 'local_edit'):row = content_box.row()@@ -815,6 +819,16 @@ class StableGenPanel(bpy.types.Panel):row = box.row()row.prop(scene, "visibility_vignette_blur", text="Blur Mask", icon="SURFACE_NSPHERE")+ # Edge Feather Projection Controls+ box = mode_specific_outer_box.box()+ row = box.row()+ row.prop(scene, "refine_edge_feather_projection", text="Edge Feather (Projection)", icon="MOD_EDGESPLIT")+ if scene.refine_edge_feather_projection:+ row = box.row()+ row.prop(scene, "refine_edge_feather_width", text="Feather Width (px)")+ row = box.row()+ row.prop(scene, "refine_edge_feather_softness", text="Feather Softness")+# Qwen Refine Mode Parameterselif scene.model_architecture.startswith('qwen') and scene.qwen_generation_method == 'refine':row = mode_specific_outer_box.row()@@ -970,6 +984,16 @@ class StableGenPanel(bpy.types.Panel):row = box.row()row.prop(scene, "visibility_vignette_blur", text="Blur Mask", icon="SURFACE_NSPHERE")+ # Edge Feather Projection Controls+ box = mode_specific_outer_box.box()+ row = box.row()+ row.prop(scene, "refine_edge_feather_projection", text="Edge Feather (Projection)", icon="MOD_EDGESPLIT")+ if scene.refine_edge_feather_projection:+ row = box.row()+ row.prop(scene, "refine_edge_feather_width", text="Feather Width (px)")+ row = box.row()+ row.prop(scene, "refine_edge_feather_softness", text="Feather Softness")+row = mode_specific_outer_box.row()row.prop(scene, "sequential_ipadapter", text="Use IPAdapter for Local Edit", toggle=True, icon="MODIFIER")if scene.sequential_ipadapter:@@ -1106,6 +1130,39 @@ class StableGenPanel(bpy.types.Panel):row = tools_box.row()row.operator("object.stablegen_mirror_reproject", text="Mirror Last Projection", icon="MOD_MIRROR")+ # --- Debug Tools ---+ prefs = context.preferences.addons.get(__package__)+ 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")++ 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="COLORSET_01_VEC")+ 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")+layout.separator()