Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
remove 8 uv map / camera limit
sakalond6ca84af1502f
diff --git a/stablegen/generator.py b/stablegen/generator.pyindex f7cf035..c4b9500 100644--- a/stablegen/generator.py+++ b/stablegen/generator.py@@ -502,8 +502,6 @@ class ComfyUIGenerate(bpy.types.Operator):else:print(f"Regenerating images for {len(self._selected_camera_ids)} selected cameras")- uv_slots_needed = len(self._cameras)-if context.scene.texture_objects == 'selected':self._to_texture = [obj for obj in bpy.context.selected_objects if obj.type == 'MESH']# If empty, cancel the operation@@ -521,36 +519,15 @@ class ComfyUIGenerate(bpy.types.Operator):material_id = get_last_material_index(obj)if (material_id > self._material_id):self._material_id = material_id- # Check if there are enough UV map slots- if not context.scene.bake_texture and context.scene.generation_method != 'uv_inpaint':- if not context.scene.overwrite_material or ((context.scene.generation_method == 'refine' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'refine')) and context.scene.refine_preserve):- if 8 - len(obj.data.uv_layers) < uv_slots_needed:- self.report({'ERROR'}, "Not enough UV map slots for all cameras.")- context.scene.generation_status = 'idle'- ComfyUIGenerate._is_running = False- return {'CANCELLED'}- else: # Overwrite material is enabled- uv_maps = set()- mesh = obj.data- uv_maps = [uv_layer.name for uv_layer in mesh.uv_layers]- usable_maps = 0- if self._material_id == -1:- self._material_id = 0- # Count only stablegen UV maps- for uv_map in uv_maps:- for i in range(uv_slots_needed):- if uv_map == f"ProjectionUV_{i}_{self._material_id}":- usable_maps += 1- if 8 - len(obj.data.uv_layers) + usable_maps < uv_slots_needed:- print(f"8 - {len(obj.data.uv_layers)} + {usable_maps} < {uv_slots_needed}")- self.report({'ERROR'}, "Not enough UV map slots for all cameras.")- context.scene.generation_status = 'idle'- ComfyUIGenerate._is_running = False- return {'CANCELLED'}-- else: # Baking- if 8 - len(obj.data.uv_layers) < 1:- self.report({'ERROR'}, "Not enough UV map slots for baking. At least 1 slot is required.")+ # Check if there's room for the projection buffer UV map (only 1 slot needed)+ # Projection UV data is stored as attributes (no slot limit), but we need+ # 1 temporary buffer UV slot for the UV Project modifier+ has_buffer = obj.data.uv_layers.get("_SG_ProjectionBuffer") is not None+ if not has_buffer and len(obj.data.uv_layers) >= 8:+ self.report({'ERROR'}, "Not enough UV map slots. Please remove at least 1 UV map to free a slot for the projection buffer.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}if not context.scene.overwrite_material or self._material_id == -1 or ((context.scene.generation_method == 'refine' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'refine')) and context.scene.refine_preserve):self._material_id += 1diff --git a/stablegen/project.py b/stablegen/project.pyindex efbf1d2..e37be26 100644--- a/stablegen/project.py+++ b/stablegen/project.py@@ -6,6 +6,34 @@ from .utils import get_last_material_index, get_file_path, get_dir_pathfrom .render_tools import prepare_baking, bake_texture, unwrapfrom mathutils import Vector+_SG_BUFFER_UV_NAME = "_SG_ProjectionBuffer"+++def _copy_uv_to_attribute(obj, uv_layer_name, attr_name):+ """Copy UV data from a UV layer to a named FLOAT_VECTOR corner-domain attribute.+ Uses FLOAT_VECTOR (3-component) instead of FLOAT2 so the attribute does NOT+ appear in the UV Maps list (FLOAT2 + CORNER = UV map in Blender 3.5+).+ """+ uv_layer = obj.data.uv_layers.get(uv_layer_name)+ if not uv_layer:+ return+ n = len(obj.data.loops)+ uv_buf = [0.0] * (n * 2)+ uv_layer.data.foreach_get("uv", uv_buf)+ # Convert (u,v) pairs to (u,v,0) triples for FLOAT_VECTOR storage+ vec_buf = [0.0] * (n * 3)+ for i in range(n):+ vec_buf[i * 3] = uv_buf[i * 2]+ vec_buf[i * 3 + 1] = uv_buf[i * 2 + 1]+ # vec_buf[i * 3 + 2] already 0.0+ # Remove existing attribute if present+ existing = obj.data.attributes.get(attr_name)+ if existing:+ obj.data.attributes.remove(existing)+ attr = obj.data.attributes.new(name=attr_name, type='FLOAT_VECTOR', domain='CORNER')+ attr.data.foreach_set("vector", vec_buf)+ obj.data.update()+def create_native_raycast_visibility(nodes, links, camera, geometry, context, i, mat_id, stop_index):"""@@ -758,24 +786,17 @@ def project_image(context, to_project, mat_id, stop_index=1000000):print("Error: Cannot make object data single user. Exiting.")return Exception("Cannot make object data single user. Exiting.")- # Add new UV map if not present (with same name)- # Check if "ProjectionUV" UV map already exists- uv_map = None+ # Create or reuse a buffer UV map for the UV Project modifier+ 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)- if context.scene.overwrite_material and not context.scene.bake_texture:- for uv in obj.data.uv_layers:- if uv.name == f"ProjectionUV_{i}_{mat_id}":- uv_map = uv- break-- # If the objects has no UV map and we are baking textures, create a new one- if not obj.data.uv_layers and context.scene.bake_texture:+ # If the object has no UV map other than the buffer and we are baking, create one+ non_buffer_uvs = [uv for uv in obj.data.uv_layers if uv.name != _SG_BUFFER_UV_NAME]+ if not non_buffer_uvs and context.scene.bake_texture:obj.data.uv_layers.new(name="BakeUV")- if not uv_map:- uv_map = obj.data.uv_layers.new(name=f"ProjectionUV_{i}_{mat_id}")-- # Add the UV Project Modifier if not present+ # Add the UV Project Modifieruv_project_mod = obj.modifiers.new(name="UVProject", type='UV_PROJECT')# Assign the active camera to the UV Project modifier@@ -784,12 +805,8 @@ def project_image(context, to_project, mat_id, stop_index=1000000):uv_project_mod.projectors[0].object = camera- # Set the UV map for the modifier- try:- uv_project_mod.uv_layer = uv_map.name- except:- # Throw custom exception: Not enough UV map slots- raise Exception("Not enough UV map slots. Please remove some UV maps.")+ # Set the buffer UV map for the modifier+ uv_project_mod.uv_layer = buffer_uv.name# Calculate and set the aspect ratiorender = context.scene.render@@ -797,16 +814,21 @@ def project_image(context, to_project, mat_id, stop_index=1000000):uv_project_mod.aspect_x = aspect_ratio if aspect_ratio > 1 else 1uv_project_mod.aspect_y = 1 / aspect_ratio if aspect_ratio < 1 else 1- # Set the new UV map as active so the modifier writes to it+ # Set the buffer UV as active so the modifier writes to it# (Blender 5.0+ ignores uv_layer and writes to the active UV map)- obj.data.uv_layers.active = uv_map+ obj.data.uv_layers.active = buffer_uv# Apply the modifierbpy.ops.object.modifier_apply(modifier=uv_project_mod.name)- # Restore active UV to the original map so subsequent baking- # doesn't accidentally target a ProjectionUV+ # Copy buffer UV data to a named attribute (no UV slot limit)+ attr_name = f"ProjectionUV_{i}_{mat_id}"+ _copy_uv_to_attribute(obj, _SG_BUFFER_UV_NAME, attr_name)++ # Restore active UV to the first non-buffer UV layeroriginal_uv_map = obj.data.uv_layers[0]+ if original_uv_map.name == _SG_BUFFER_UV_NAME and len(obj.data.uv_layers) > 1:+ original_uv_map = obj.data.uv_layers[1]obj.data.uv_layers.active = original_uv_map# If we are running in sequential mode, we already have baked textures for i < stop_index@@ -819,7 +841,16 @@ def project_image(context, to_project, mat_id, stop_index=1000000):obj.select_set(True)if i <= stop_index and (not context.scene.generation_method == 'sequential' or i == stop_index):simple_project_bake(context, i, obj, mat_id)- obj.data.uv_layers.remove(obj.data.uv_layers[-1]) # Remove the last UV map+ # Remove the projection attribute (data is now baked into texture)+ attr = obj.data.attributes.get(f"ProjectionUV_{i}_{mat_id}")+ if attr:+ obj.data.attributes.remove(attr)++ # Clean up buffer UV map from all objects+ for obj in to_project:+ buffer_uv = obj.data.uv_layers.get(_SG_BUFFER_UV_NAME)+ if buffer_uv:+ obj.data.uv_layers.remove(buffer_uv)# Switch to Cycles (needed for Raycast shader node on all versions)context.scene.render.engine = 'CYCLES'@@ -983,12 +1014,15 @@ def project_image(context, to_project, mat_id, stop_index=1000000):tex_image.label = f"{i}-{mat_id}"tex_image_nodes.append(tex_image)- # Add UV map node- uv_map_node = nodes.new("ShaderNodeUVMap")+ # Add UV map / attribute nodeif not context.scene.bake_texture:- uv_map_node.uv_map = f"ProjectionUV_{i}_{mat_id}"+ # Use ShaderNodeAttribute to read from the corner-domain attribute+ uv_map_node = nodes.new("ShaderNodeAttribute")+ uv_map_node.attribute_name = f"ProjectionUV_{i}_{mat_id}"+ uv_map_node.attribute_type = 'GEOMETRY'else:- # Use the original UV map+ # Baked textures use the original UV map+ uv_map_node = nodes.new("ShaderNodeUVMap")uv_map_node.uv_map = original_uv_map.nameuv_map_node.location = (-200, -200 * (i+1))uv_map_nodes.append(uv_map_node)@@ -1184,7 +1218,8 @@ def project_image(context, to_project, mat_id, stop_index=1000000):uv_map_node = uv_map_nodes[i]# Connect UV → Texture (needed for both paths)- links.new(uv_map_node.outputs["UV"], tex_image.inputs["Vector"])+ uv_output = "Vector" if uv_map_node.type == 'ATTRIBUTE' else "UV"+ links.new(uv_map_node.outputs[uv_output], tex_image.inputs["Vector"])if not use_native_raycast:# OSL path: connect subtract, normalize, script inputs, length@@ -1265,9 +1300,10 @@ def simple_project_bake(context, camera_id, obj, mat_id):if image:tex_image.image = image- # Add UV map node- uv_map_node = nodes.new("ShaderNodeUVMap")- uv_map_node.uv_map = f"ProjectionUV_{camera_id}_{mat_id}"+ # Add UV attribute node (reads from corner-domain attribute)+ uv_map_node = nodes.new("ShaderNodeAttribute")+ uv_map_node.attribute_name = f"ProjectionUV_{camera_id}_{mat_id}"+ uv_map_node.attribute_type = 'GEOMETRY'# Add BSDF nodebsdf = nodes.new("ShaderNodeBsdfPrincipled")@@ -1275,7 +1311,7 @@ def simple_project_bake(context, camera_id, obj, mat_id):# Add output nodeoutput = nodes.new("ShaderNodeOutputMaterial")- links.new(uv_map_node.outputs["UV"], tex_image.inputs["Vector"])+ links.new(uv_map_node.outputs["Vector"], tex_image.inputs["Vector"])# Connect the nodesif context.scene.apply_bsdf:links.new(tex_image.outputs["Color"], bsdf.inputs["Base Color"])diff --git a/stablegen/render_tools.py b/stablegen/render_tools.pyindex 89a3c8d..4ce9e1e 100644--- a/stablegen/render_tools.py+++ b/stablegen/render_tools.py@@ -138,7 +138,7 @@ def apply_uv_inpaint_texture(context, obj, baked_image_path):if not uv_layers or len(uv_layers) == 0:return Nonefor uv_layer in uv_layers:- if not uv_layer.name.startswith("ProjectionUV"):+ if not uv_layer.name.startswith("ProjectionUV") and uv_layer.name != "_SG_ProjectionBuffer":return uv_layer.namereturn uv_layers.active.name@@ -325,7 +325,7 @@ def flatten_projection_material_for_refine(context, obj, baked_image_path):# -------------------------------------------------------------------------uv_name = Nonefor uv in obj.data.uv_layers:- if not uv.name.startswith("ProjectionUV"):+ if not uv.name.startswith("ProjectionUV") and uv.name != "_SG_ProjectionBuffer":uv_name = uv.namebreak@@ -1544,8 +1544,8 @@ def unwrap(obj, method, overlap_only):is_new = False- # If all UV maps are ProjectionUV, add new one- if all(["ProjectionUV" in uv.name for uv in obj.data.uv_layers]):+ # If all UV maps are ProjectionUV or buffer, add new one+ if all(["ProjectionUV" in uv.name or uv.name == "_SG_ProjectionBuffer" for uv in obj.data.uv_layers]):# Add a new UV mapobj.data.uv_layers.new(name=f"BakeUV")is_new = True@@ -1553,9 +1553,9 @@ def unwrap(obj, method, overlap_only):# Set it for renderingobj.data.uv_layers.active = obj.data.uv_layers[-1]else:- # Ensure the active UV is a non-ProjectionUV map+ # Ensure the active UV is a non-ProjectionUV/buffer mapfor uv_layer in obj.data.uv_layers:- if "ProjectionUV" not in uv_layer.name:+ if "ProjectionUV" not in uv_layer.name and uv_layer.name != "_SG_ProjectionBuffer":obj.data.uv_layers.active = uv_layerbreak@@ -1664,9 +1664,9 @@ def bake_texture(context, obj, texture_resolution, suffix = "", view_transform =# Set the image node as the active bake targetnodes.active = tex_image- # Ensure the active UV is a non-ProjectionUV map for correct baking+ # Ensure the active UV is a non-ProjectionUV/buffer map for correct bakingfor uv_layer in obj.data.uv_layers:- if "ProjectionUV" not in uv_layer.name:+ if "ProjectionUV" not in uv_layer.name and uv_layer.name != "_SG_ProjectionBuffer":obj.data.uv_layers.active = uv_layerbreak