Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
keep projection materials within cycles' svm stack
sakalond2d98c20ca6c5
diff --git a/stablegen/texturing/generator.py b/stablegen/texturing/generator.pyindex 516ab17..2a1bd0e 100644--- a/stablegen/texturing/generator.py+++ b/stablegen/texturing/generator.py@@ -28,7 +28,7 @@ from ..util.workflow_templates import prompt_text, prompt_text_img2img, prompt_tfrom .rendering import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap, export_render, export_viewport, render_edge_feather_mask, apply_uv_inpaint_texture, flatten_projection_material_for_refine, _RenderStateTransaction, _legacy_render_dither, _prepare_compositor_render, _finish_compositor_renderfrom ..cameras.geometry import _SGCameraResolution, _get_camera_resolution, _get_resolution_alignfrom ..cameras.overlays import _sg_restore_square_display, _sg_remove_crop_overlay, _sg_ensure_crop_overlay, _sg_hide_label_overlay, _sg_restore_label_overlay-from .projection import project_image, reinstate_compare_nodes, _bake_visibility_weights, reset_projection_material_nodes, _is_projection_mesh+from .projection import project_image, reinstate_compare_nodes, _bake_visibility_weights, reset_projection_material_nodes, _is_projection_mesh, pop_svm_stack_warningfrom ..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, sg_modal_activefrom ..util.mirror_color import MirrorReproject, _get_viewport_ref_np, _apply_color_match_to_filefrom ..timeout_config import get_timeout@@ -171,6 +171,9 @@ class Regenerate(bpy.types.Operator):context.window_manager.event_timer_remove(self._timer)# Report completionself.report({'INFO'}, "Regeneration complete.")+ svm_warning = pop_svm_stack_warning()+ if svm_warning:+ self.report({'WARNING'}, svm_warning)return {'FINISHED'}return {'PASS_THROUGH'}@@ -349,6 +352,9 @@ class Reproject(bpy.types.Operator):context.window_manager.event_timer_remove(self._timer)# Report completionself.report({'INFO'}, "Reprojection complete.")+ svm_warning = pop_svm_stack_warning()+ if svm_warning:+ self.report({'WARNING'}, svm_warning)return {'FINISHED'}return {'PASS_THROUGH'}@@ -1319,6 +1325,9 @@ class ComfyUIGenerate(_PBRMixin, bpy.types.Operator):return {'CANCELLED'}if not context.scene.generation_mode == 'project_only':self.report({'INFO'}, "Generation complete.")+ svm_warning = pop_svm_stack_warning()+ if svm_warning:+ self.report({'WARNING'}, svm_warning)# If viewport rendering mode is 'Rendered' and mode is 'regenerate_selected', switch to 'Solid' and then back to 'Rendered' to refresh the viewportif context.scene.generation_mode == 'regenerate_selected' and context.area.spaces.active.shading.type == 'RENDERED':diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.pyindex dce27e8..0a74f0c 100644--- a/stablegen/texturing/projection.py+++ b/stablegen/texturing/projection.py@@ -7,9 +7,129 @@ from ..utils import get_last_material_index, get_file_path, get_dir_pathfrom .rendering import prepare_baking, bake_texture, unwrapfrom ..cameras.geometry import _get_camera_resolutionfrom mathutils import Matrix, Vector+from .svm_budget import SVM_STACK_SIZE, estimate_svm_stack_SG_BUFFER_UV_NAME = "_SG_ProjectionBuffer"+# The estimate matches Cycles; warn a little before the hard limit.+_SVM_STACK_WARNING = SVM_STACK_SIZE - 16+++# Cycles compiles an SVM shader in sweeps over the (inlined) nodes, and a node+# reading another socket type waits for a conversion node that Cycles creates+# after all nodes, i.e. for the next sweep. Everything a camera computes before+# such a wait stays on the 255-float SVM stack until the wait is over, for all+# cameras at once. The raycast's direction is such a conversion, so projection+# graphs keep the values that wait for it few, give masks explicit float+# conversions and read the masks' UVs through the camera's raycast result.+# svm_budget.estimate_svm_stack() replays the compiler to check the result.++def _mask_value(nodes, links, texture):+ """Grey mask texture as a float, without an implicit Cycles conversion."""+ value = nodes.new('ShaderNodeRGBToBW')+ value.label = texture.label + ' value'+ value.hide = True+ links.new(texture.outputs['Color'], value.inputs[0])+ return value+++def _absorb_unused_raycast_outputs(nodes, links, raycast, visible):+ """Return ``visible`` with the raycast's unused outputs read but ignored.++ Cycles' Raycast node writes all five outputs to the SVM stack and frees an+ output only after reading it, so unread outputs leak 7 floats per camera.+ Each is read by a node of its exact type (no conversion) and folded in as+ max(visible, min(..., 0)), which equals ``visible`` (>= 0) and ignores NaN.+ """+ position = nodes.new('ShaderNodeTexGradient')+ position.label = 'Read hit position'+ links.new(raycast.outputs['Hit Position'], position.inputs['Vector'])+ normal = nodes.new('ShaderNodeFresnel')+ normal.label = 'Read hit normal'+ links.new(raycast.outputs['Hit Normal'], normal.inputs['Normal'])+ hit = _projection_feather_math(nodes, links, 'MINIMUM', 'Unused raycast outputs',+ raycast.outputs['Self Hit'], position.outputs['Fac'])+ surface = _projection_feather_math(nodes, links, 'MINIMUM', 'Unused raycast outputs',+ hit.outputs[0], normal.outputs['Fac'])+ zero = _projection_feather_math(nodes, links, 'MINIMUM', 'Unused raycast outputs (zero)',+ surface.outputs[0], 0.0)+ absorbed = _projection_feather_math(nodes, links, 'MAXIMUM', 'Visible from camera',+ visible, zero.outputs[0])+ return absorbed, (position, normal, hit, surface, zero)+++def _late_projection_uv(nodes, links, uv_node, visible, camera_index, mat_id):+ """Projection UV that Cycles reads only after the camera's raycast.++ Masks and the generated image only depend on the UV, so Cycles would+ sample them for every camera in the sweep before any raycast and keep all+ those values on the stack. min(uv, max(visible, 1e30)) equals the UV but+ depends on the raycast, so each camera's textures follow its raycast.+ """+ def new(node_type, label):+ node = nodes.new(node_type)+ node.label = f"{label}-{camera_index}-{mat_id}"+ node.hide = True+ node['sg_layout_stage'] = 'Image and UV'+ return node++ bound = new('ShaderNodeMath', 'ProjectionUVAfterRaycastBound')+ bound.operation = 'MAXIMUM'+ bound.inputs[1].default_value = 1e30+ links.new(visible, bound.inputs[0])+ bounds = new('ShaderNodeCombineXYZ', 'ProjectionUVAfterRaycastBounds')+ for axis in range(3):+ links.new(bound.outputs[0], bounds.inputs[axis])+ late = new('ShaderNodeVectorMath', 'ProjectionUVAfterRaycast')+ late.operation = 'MINIMUM'+ links.new(_projection_uv_output(uv_node), late.inputs[0])+ links.new(bounds.outputs[0], late.inputs[1])+ return late+++# Materials whose estimated SVM stack use is near or past Cycles' limit,+# reported by the generation operators once they finish.+_svm_stack_warnings = {}+++def check_projection_svm_stack(material, estimates=None):+ """Estimate the material's Cycles SVM stack use and warn when too big.++ Cycles only logs an SVM stack overflow and renders the material black,+ which also blanks every Qwen context render made from it. ``estimates``+ caches results for materials with the same topology within one build.+ """+ tree = material.node_tree+ key = (len(tree.nodes), len(tree.links))+ if estimates is not None and key in estimates:+ peak, details = estimates[key]+ else:+ peak, details = estimate_svm_stack(material)+ if estimates is not None:+ estimates[key] = (peak, details)+ material['sg_svm_stack_estimate'] = peak+ if peak >= _SVM_STACK_WARNING:+ holders = ', '.join(f'{name} ({size})' for name, size in details.get('holders', ())[:4])+ print(f"[StableGen] WARNING: projection material '{material.name}' needs about "+ f"{peak} of Cycles' {SVM_STACK_SIZE} SVM stack slots and may render black "+ f"in Cycles. Largest live values: {holders}")+ _svm_stack_warnings[material.name] = peak+ else:+ _svm_stack_warnings.pop(material.name, None)+ return peak+++def pop_svm_stack_warning():+ """Return a one-line user warning for oversized materials, then reset."""+ if not _svm_stack_warnings:+ return None+ names = sorted(_svm_stack_warnings)+ peak = max(_svm_stack_warnings.values())+ _svm_stack_warnings.clear()+ shown = ', '.join(names[:3]) + (f' and {len(names) - 3} more' if len(names) > 3 else '')+ return (f"Projection material {shown} is near Cycles' shader size limit "+ f"(~{peak}/{SVM_STACK_SIZE}) and may render black. Use fewer cameras "+ f"or disable some Precise+ features.")def _is_projection_mesh(obj):@@ -219,13 +339,17 @@ def _create_projection_uv_nodes(nodes, links, camera_index, mat_id, location):homogeneous.attribute_name = _projection_uvw_name(camera_index, mat_id)homogeneous.attribute_type = 'GEOMETRY'- separate = new("ShaderNodeSeparateXYZ", "ProjectionW", -600)- links.new(homogeneous.outputs["Vector"], separate.inputs[0])+ # w = dot(uvw, Z). Cycles' Separate XYZ would keep the unused X and Y on+ # the SVM stack for the rest of the shader and reads through a conversion.+ w = new("ShaderNodeVectorMath", "ProjectionW", -600)+ w.operation = 'DOT_PRODUCT'+ w.inputs[1].default_value = (0.0, 0.0, 1.0)+ links.new(homogeneous.outputs["Vector"], w.inputs[0])inverse_w = new("ShaderNodeMath", "PerspectiveDivide", -450)inverse_w.operation = 'DIVIDE'inverse_w.inputs[0].default_value = 1.0- links.new(separate.outputs["Z"], inverse_w.inputs[1])+ links.new(w.outputs["Value"], inverse_w.inputs[1])divided = new("ShaderNodeVectorMath", "PerspectiveUV", -300)divided.operation = 'SCALE'@@ -236,7 +360,7 @@ def _create_projection_uv_nodes(nodes, links, camera_index, mat_id, location):missing.operation = 'COMPARE'missing.inputs[1].default_value = 0.0missing.inputs[2].default_value = 0.0- links.new(separate.outputs["Z"], missing.inputs[0])+ links.new(w.outputs["Value"], missing.inputs[0])# divided + missing * (legacy - divided); plain vector math so graph# walkers never mistake the selector for a colour mix.@@ -704,7 +828,8 @@ def _bake_visibility_weights(obj.data.update()-def create_native_raycast_visibility(nodes, links, camera, geometry, context, i, mat_id, stop_index):+def create_native_raycast_visibility(nodes, links, camera, geometry, context, i, mat_id, stop_index,+ pre_factors=None, extra=None):"""Creates a visibility weight node group using the native Raycast shader node (Blender 5.1+).Replicates the OSL raycast.osl shader logic:@@ -712,7 +837,14 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,2. Occlusion check (Raycast from camera, compare Hit Distance with expected distance)3. Angle check (surface normal vs ray direction)4. Weight = pow(orthogonality, Power)-++ Cycles compiles the raycast one sweep after the camera math (its direction+ is converted to a normal), so the raycast-free terms are multiplied first+ and the occlusion test last: one float per camera waits for the raycast.+ ``pre_factors(weight_socket, parts)`` may multiply further raycast-free+ terms in. ``extra`` (a dict) receives the 'visible' socket and the+ 'view_depth' sockets (camera-axis depth = product of the two).+Returns: (weight_output_node, subtract_node, normalize_node, length_node,camera_loc_node, camera_fov_node, camera_aspect_node, camera_dir_node, camera_up_node)"""@@ -959,6 +1091,8 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,occlusion_ok.location = (x_base + 600, y_base + 50)links.new(raycast.outputs["Is Hit"], occlusion_ok.inputs[0])links.new(dist_check.outputs[0], occlusion_ok.inputs[1])+ visible, raycast_sinks = _absorb_unused_raycast_outputs(+ nodes, links, raycast, occlusion_ok.outputs[0])# ========================================# ANGLE CHECK + WEIGHT@@ -1029,26 +1163,34 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,links.new(facing_dot.outputs[0], power_node.inputs[0])# ========================================- # COMBINE ALL: frustum_ok * occlusion_ok * angle_ok * weight+ # COMBINE ALL: frustum_ok * angle_ok * weight [* pre_factors] * occlusion_ok# ========================================combine1 = nodes.new("ShaderNodeMath")combine1.operation = 'MULTIPLY'combine1.location = (x_base + 800, y_base)links.new(frustum_ok.outputs[0], combine1.inputs[0])- links.new(occlusion_ok.outputs[0], combine1.inputs[1])+ links.new(angle_check.outputs[0], combine1.inputs[1])combine2 = nodes.new("ShaderNodeMath")combine2.operation = 'MULTIPLY'combine2.location = (x_base + 900, y_base)links.new(combine1.outputs[0], combine2.inputs[0])- links.new(angle_check.outputs[0], combine2.inputs[1])+ links.new(power_node.outputs[0], combine2.inputs[1])+ weighted = combine2.outputs[0]+ if pre_factors is not None:+ weighted = pre_factors(weighted, dict(+ normalize=normalize_node, length=length_node, fov=camera_fov_node,+ aspect=camera_aspect_node, direction=camera_dir_node, up=camera_up_node))final_weight = nodes.new("ShaderNodeMath")final_weight.operation = 'MULTIPLY'final_weight.location = (x_base + 1000, y_base)final_weight.label = f"Angle-{i}-{mat_id}"- links.new(combine2.outputs[0], final_weight.inputs[0])- links.new(power_node.outputs[0], final_weight.inputs[1])+ links.new(weighted, final_weight.inputs[0])+ links.new(visible.outputs[0], final_weight.inputs[1])+ if extra is not None:+ extra['visible'] = visible.outputs[0]+ extra['view_depth'] = (neg_cam_z.outputs[0], length_node.outputs["Value"])# Presentation metadata only: keep the native graph's large camera math# readable without changing any operation, input or connection.@@ -1062,7 +1204,7 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,shift_y_amount centered_y abs_x x_in_bounds abs_y y_in_boundsfrustum_xy frustum_ok''','Raycast visibility': '''- raycast threshold_plus hit_dist_plus dist_check occlusion_ok''',+ raycast threshold_plus hit_dist_plus dist_check occlusion_ok visible''','Facing and angle': '''dot_d_normal clamp_dot clamp_dot2 facing_raw facing_dot acos_nodeto_degrees angle_check power_node combine1 combine2 final_weight''',@@ -1081,11 +1223,11 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,'threshold_plus': 'Ray length tolerance','hit_dist_plus': 'Hit distance tolerance','dist_check': 'Target depth matches hit',- 'occlusion_ok': 'Visible from camera',+ 'occlusion_ok': 'Hit is the surface','dot_d_normal': 'View facing angle','facing_raw': 'Apply backface setting',- 'combine1': 'Frustum and occlusion',- 'combine2': 'Apply discard angle',+ 'combine1': 'Frustum and discard angle',+ 'combine2': 'Apply facing weight',}available = locals()for stage, names in stage_names.items():@@ -1094,6 +1236,12 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,node['sg_layout_stage'] = stageif not node.label:node.label = readable_names.get(name, name.replace('_', ' ').capitalize())+ for node in raycast_sinks:+ node['sg_layout_stage'] = 'Raycast visibility'+ if pre_factors is not None:+ # The final weight now follows the frame-edge and density terms; keep+ # it in their frame so the graph still reads left to right.+ final_weight['sg_layout_stage'] = 'Acquisition quality'return (final_weight, subtract, normalize_node, length_node,add_camera_loc, camera_fov_node, camera_aspect_node,@@ -1288,13 +1436,22 @@ def create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_map_range.inputs["To Min"].default_value = 1.0 # Invert: edge=low -> factor=1map_range.inputs["To Max"].default_value = 0.0 # edge=high -> factor=0links.new(edge.outputs[0], map_range.inputs["Value"])+ # Clamp explicitly: Cycles turns the Map Range clamp option into a+ # node created after all others, which delays the frame weight to the+ # raycast's compile sweep and keeps its inputs on the SVM stack.+ map_range.clamp = False+ clamped = nodes.new("ShaderNodeClamp")+ clamped.clamp_type = 'RANGE'+ clamped.inputs["Min"].default_value = 1.0+ clamped.inputs["Max"].default_value = 0.0+ links.new(map_range.outputs[0], clamped.inputs["Value"])# edge_factor = pow(smoothstep_result, gamma)pow_node = nodes.new("ShaderNodeMath")pow_node.operation = 'POWER'pow_node.location = (x_base + 700, y_base - 150)pow_node.inputs[1].default_value = max(0.01, gamma_val)- links.new(map_range.outputs[0], pow_node.inputs[0])+ links.new(clamped.outputs[0], pow_node.inputs[0])# Multiply by cam_z_check (0 if behind camera)final_feather = nodes.new("ShaderNodeMath")@@ -2250,6 +2407,7 @@ def project_image(context.scene.cycles.use_osl = Trueprocessed_materials = set()+ svm_estimates = {}for obj in to_project:@@ -2457,7 +2615,7 @@ def project_image(to_float.inputs[1].default_value = 1.0to_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])+ links.new(_mask_value(nodes, links, mask_tex).outputs[0], to_float.inputs[0])return to_floatdef _create_write_mask_weight(@@ -2498,7 +2656,7 @@ def project_image(to_float.inputs[1].default_value = 1.0to_float.location = (-300, -200 * cam_index - 300)to_float.label = f"{label_prefix}Weight-{cam_index}-{mat_id_inner}"- links.new(mask_tex.outputs[0], to_float.inputs[0])+ links.new(_mask_value(nodes, links, mask_tex).outputs[0], to_float.inputs[0])return to_floatdef _create_projection_guard_weight(cam_index, mat_id_inner):@@ -2528,9 +2686,38 @@ def project_image(guard_weight.operation = 'MULTIPLY'guard_weight.inputs[1].default_value = 1.0guard_weight.label = f"ProjectionGuardWeight-{cam_index}-{mat_id_inner}"- links.new(guard_tex.outputs[0], guard_weight.inputs[0])+ links.new(_mask_value(nodes, links, guard_tex).outputs[0], guard_weight.inputs[0])return guard_weight+ def _acquisition_quality(weight, length_node, camera, cam_index):+ """Multiply a projection weight by the view's projected pixel density."""+ cam_res_x, cam_res_y = _get_camera_resolution(camera, context.scene)+ fov_for_density = camera.data.angle_x+ if cam_res_y > cam_res_x:+ fov_for_density = 2 * atan(+ tan(fov_for_density / 2) * cam_res_x / cam_res_y+ )+ focal_pixels = cam_res_x / max(2.0 * tan(fov_for_density / 2), 1e-7)+ density_numerator = (+ _scene_projection_scale(context) * focal_pixels+ / max(0.5 * min(cam_res_x, cam_res_y), 1.0)+ )+ density = nodes.new("ShaderNodeMath")+ density.operation = 'DIVIDE'+ density.inputs[0].default_value = density_numerator+ density.label = f"ProjectedDensity-{cam_index}-{mat_id}"+ links.new(length_node.outputs["Value"], density.inputs[1])+ clamp_density = nodes.new("ShaderNodeMath")+ clamp_density.operation = 'MINIMUM'+ clamp_density.inputs[1].default_value = 1.0+ links.new(density.outputs[0], clamp_density.inputs[0])+ acquisition = nodes.new("ShaderNodeMath")+ acquisition.operation = 'MULTIPLY'+ acquisition.label = f"AcquisitionQuality-{cam_index}-{mat_id}"+ links.new(weight, acquisition.inputs[0])+ links.new(clamp_density.outputs[0], acquisition.inputs[1])+ return acquisition+# Voronoi mode flag: keep natural weights for non-generated camerasvoronoi_active = (context.scene.model_architecture in ('qwen_image_edit', 'qwen_image_21', 'flux2_klein')and getattr(context.scene, 'qwen_voronoi_mode', False)@@ -2547,6 +2734,7 @@ def project_image(geometry_nodes = []for i, camera in enumerate(cameras):camera_node_start = {node.as_pointer() for node in nodes}+ native_extra = {}# Geometry is evaluated at the current shading point. Keeping an# instance in each view avoids links spanning every camera row.geometry = nodes.new("ShaderNodeNewGeometry")@@ -2634,17 +2822,40 @@ def project_image(elif use_native_raycast:# ── Native Raycast path (Blender 5.1+) ──+ is_local_edit_mode = (context.scene.generation_method == 'local_edit' or (context.scene.model_architecture.startswith('qwen') and context.scene.qwen_generation_method == 'local_edit'))+ native_pre_factors = None+ if (not is_local_edit_mode+ and getattr(context.scene, 'sg_rework_acquisition_quality', False)):+ # Frame-edge and density terms do not depend on the+ # raycast; they are combined before it (see there).+ def native_pre_factors(weight, parts, camera=camera, i=i):+ if (context.scene.generation_method == 'sequential'+ and context.scene.visibility_vignette):+ frame_weight = create_native_feather(+ nodes, links, parts['normalize'], parts['fov'],+ parts['aspect'], parts['direction'], parts['up'],+ camera, context, i, mat_id,+ )+ frame_quality = nodes.new("ShaderNodeMath")+ frame_quality.operation = 'MULTIPLY'+ frame_quality.label = f"FrameEdgeQuality-{i}-{mat_id}"+ links.new(weight, frame_quality.inputs[0])+ links.new(frame_weight.outputs[0], frame_quality.inputs[1])+ weight = frame_quality.outputs[0]+ return _acquisition_quality(weight, parts['length'], camera, i).outputs[0]result = create_native_raycast_visibility(- nodes, links, camera, geometry, context, i, mat_id, stop_index+ nodes, links, camera, geometry, context, i, mat_id, stop_index,+ pre_factors=native_pre_factors, extra=native_extra,)angle_weight = result[0]# Destructure result for create_native_feather_, _, normalize_node, length_node, camera_loc_node, camera_fov_node, camera_aspect_node, camera_dir_node, camera_up_node = result+ uv_map_nodes[i] = _late_projection_uv(+ nodes, links, uv_map_node, native_extra['visible'], i, mat_id)scripts_to_connect = [] # No OSL scripts to connectfinal_weight_node = None- is_local_edit_mode = (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_mode:feather_weight = create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_aspect_node,@@ -2661,20 +2872,6 @@ def project_image(final_weight_node = (angle_weight, feather_weight)else:final_weight_node = angle_weight- if (getattr(context.scene, 'sg_rework_acquisition_quality', False)- and context.scene.generation_method == 'sequential'- and context.scene.visibility_vignette):- frame_weight = create_native_feather(- nodes, links, normalize_node, camera_fov_node,- camera_aspect_node, camera_dir_node, camera_up_node,- camera, context, i, mat_id,- )- frame_quality = nodes.new("ShaderNodeMath")- frame_quality.operation = 'MULTIPLY'- frame_quality.label = f"FrameEdgeQuality-{i}-{mat_id}"- links.new(angle_weight.outputs[0], frame_quality.inputs[0])- links.new(frame_weight.outputs[0], frame_quality.inputs[1])- final_weight_node = frame_qualityscript_nodes.append(scripts_to_connect)@@ -2878,38 +3075,16 @@ def project_image(length.location = (-400, 200 * (i+1))length_nodes.append(length)- # Add projected pixel density to live native/OSL paths. Baked- # acquisition attributes already contain this term.+ # Add projected pixel density to live OSL paths (the native path+ # adds it before its raycast). Baked acquisition attributes+ # already contain this term.if (getattr(context.scene, 'sg_rework_acquisition_quality', False)- and not use_baked_weights and script_nodes_outputs+ and not use_baked_weights and not use_native_raycast+ and script_nodes_outputsand not isinstance(script_nodes_outputs[-1], tuple)and length_nodes[-1] is not None):- cam_res_x, cam_res_y = _get_camera_resolution(camera, context.scene)- fov_for_density = camera.data.angle_x- if cam_res_y > cam_res_x:- fov_for_density = 2 * atan(- tan(fov_for_density / 2) * cam_res_x / cam_res_y- )- focal_pixels = cam_res_x / max(2.0 * tan(fov_for_density / 2), 1e-7)- density_numerator = (- _scene_projection_scale(context) * focal_pixels- / max(0.5 * min(cam_res_x, cam_res_y), 1.0)- )- density = nodes.new("ShaderNodeMath")- density.operation = 'DIVIDE'- density.inputs[0].default_value = density_numerator- density.label = f"ProjectedDensity-{i}-{mat_id}"- links.new(length_nodes[-1].outputs[0], density.inputs[1])- clamp_density = nodes.new("ShaderNodeMath")- clamp_density.operation = 'MINIMUM'- clamp_density.inputs[1].default_value = 1.0- links.new(density.outputs[0], clamp_density.inputs[0])- acquisition = nodes.new("ShaderNodeMath")- acquisition.operation = 'MULTIPLY'- acquisition.label = f"AcquisitionQuality-{i}-{mat_id}"- links.new(script_nodes_outputs[-1].outputs[0], acquisition.inputs[0])- links.new(clamp_density.outputs[0], acquisition.inputs[1])- script_nodes_outputs[-1] = acquisition+ script_nodes_outputs[-1] = _acquisition_quality(+ script_nodes_outputs[-1].outputs[0], length_nodes[-1], camera, i)use_qwen_write_mask = (i > 0@@ -3000,15 +3175,20 @@ def project_image(feather_tex.image = feather_imagefeather_tex.extension = 'CLIP'feather_tex.interpolation = 'Linear'- feather_tex.label = f"ProjectionGuardFeather-{i}-{mat_id}"+ feather_tex.label = f"ProjectionGuardFeatherMask-{i}-{mat_id}"+ feather_tex['sg_layout_stage'] = 'Guard feather'uv = uv_map_nodes[i]links.new(_projection_uv_output(uv),feather_tex.inputs['Vector'])+ # The float value carries the feather label that+ # graph controls and diagnostics look up.+ feather_value = _mask_value(nodes, links, feather_tex)+ feather_value.label = f"ProjectionGuardFeather-{i}-{mat_id}"feathered = nodes.new("ShaderNodeMath")feathered.operation = 'MULTIPLY'feathered.label = f"DepthPartFeathered-{i}-{mat_id}"links.new(guarded.outputs[0], feathered.inputs[0])- links.new(feather_tex.outputs[0], feathered.inputs[1])+ links.new(feather_value.outputs[0], feathered.inputs[1])script_nodes_outputs[-1] = featheredocclusion_path = os.path.join(os.path.dirname(feather_path),f"projection_occlusion_geometry{i}.png")@@ -3036,6 +3216,15 @@ def project_image(receiver.attribute_name = f'_SG_ProjectionDepth_{i}_{mat_id}'depth_socket = receiver.outputs['Fac']divisor = distance_scale+ elif 'view_depth' in native_extra:+ # (view direction . forward) * distance+ # is the camera-axis depth; scalars+ # keep the SVM stack small.+ depth_socket = _projection_feather_math(+ nodes, links, 'MULTIPLY',+ f'OcclusionReceiverCameraDepth-{i}',+ *native_extra['view_depth']).outputs[0]+ divisor = distance_scaleelse:coordinates = nodes.new('ShaderNodeTexCoord')coordinates.object = camera@@ -3067,13 +3256,15 @@ def project_image(influence_path, force_reload=context.scene.overwrite_material)influence_image.colorspace_settings.name = 'Non-Color'influence_tex = nodes.new("ShaderNodeTexImage")- influence_tex.name = f"SGFeatherInfluence-{i}-{mat_id}"+ influence_tex.name = f"SGFeatherInfluenceMask-{i}-{mat_id}"influence_tex.label = f"ProjectionGuardInfluence-{i}-{mat_id}"influence_tex.image = influence_imageinfluence_tex.extension = 'CLIP'influence_tex.interpolation = 'Linear'links.new(feather_tex.inputs['Vector'].links[0].from_socket,influence_tex.inputs['Vector'])+ _mask_value(nodes, links, influence_tex).name = (+ f"SGFeatherInfluence-{i}-{mat_id}")# Confidence is deliberately independent from colour ownership.# Preserve the unnormalised source-camera quality before the mix@@ -3239,6 +3430,7 @@ def project_image(layout_camera_nodes, cameras, stop_index, local_edit=is_local_edit,feather_method=getattr(context.scene, 'sg_guard_feather_method', 'ORIGINAL'),)+ check_projection_svm_stack(mat, svm_estimates)return Truediff --git a/stablegen/texturing/svm_budget.py b/stablegen/texturing/svm_budget.pynew file mode 100644index 0000000..ed4fd81--- /dev/null+++ b/stablegen/texturing/svm_budget.py@@ -0,0 +1,635 @@+"""Estimate Cycles SVM stack use of a material before Cycles renders it black.++Cycles syncs Blender's inlined copy of the tree (depth-first from the output)+and compiles an SVM shader by sweeping those nodes in order; a node compiles+in the first sweep in which all its inputs are ready. A value occupies the+255-float stack until its last consumer has compiled. When the stack+overflows, Cycles only logs "out of SVM stack space" and the material renders+black, so StableGen checks its own projection graphs.++The model mirrors the parts of Cycles that decide the stack use: implicit+socket conversions and expanded clamps (created after all nodes, so their+consumers wait for the next sweep), constant folding, deduplication, the+allocation order inside nodes, and nodes such as Raycast whose compile()+assigns every output even when it is unused. It reproduces the peak usage+Cycles 5.1 logs exactly for StableGen's projection materials.+"""++import bpy+++SVM_STACK_SIZE = 255++_SIZE = {'FLOAT': 1, 'INT': 1, 'COLOR': 3, 'VECTOR': 3, 'POINT': 3, 'NORMAL': 3,+ 'CLOSURE': 0}+_BLENDER_TYPES = {'VALUE': 'FLOAT', 'INT': 'INT', 'BOOLEAN': 'INT', 'RGBA': 'COLOR',+ 'VECTOR': 'VECTOR', 'SHADER': 'CLOSURE'}++# Cycles socket types that differ from the Blender socket type.+_INPUT_TYPES = {+ 'ShaderNodeTexImage': {'Vector': 'POINT'},+ 'ShaderNodeTexGradient': {'Vector': 'POINT'},+ 'ShaderNodeTexNoise': {'Vector': 'POINT'},+ 'ShaderNodeTexVoronoi': {'Vector': 'POINT'},+ 'ShaderNodeRaycast': {'Position': 'POINT', 'Direction': 'NORMAL'},+ 'ShaderNodeSeparateXYZ': {'Vector': 'COLOR'},+ 'ShaderNodeFresnel': {'Normal': 'NORMAL'},+ 'ShaderNodeLayerWeight': {'Normal': 'NORMAL'},+ 'ShaderNodeNormal': {'Normal': 'NORMAL'},+ 'ShaderNodeBump': {'Normal': 'NORMAL'},+ 'ShaderNodeMapping': {'Vector': 'POINT', 'Location': 'POINT',+ 'Rotation': 'POINT', 'Scale': 'POINT'},+}+_OUTPUT_TYPES = {+ 'ShaderNodeNewGeometry': {'Position': 'POINT', 'Normal': 'NORMAL', 'Tangent': 'NORMAL',+ 'True Normal': 'NORMAL', 'Parametric': 'POINT'},+ 'ShaderNodeTexCoord': {'Generated': 'POINT', 'Normal': 'NORMAL', 'UV': 'POINT',+ 'Object': 'POINT', 'Camera': 'POINT', 'Window': 'POINT',+ 'Reflection': 'NORMAL'},+ 'ShaderNodeUVMap': {'UV': 'POINT'},+ 'ShaderNodeRaycast': {'Hit Position': 'POINT', 'Hit Normal': 'NORMAL'},+ 'ShaderNodeMapping': {'Vector': 'POINT'},+ 'ShaderNodeNormal': {'Normal': 'NORMAL'},+ 'ShaderNodeBump': {'Normal': 'NORMAL'},+ 'ShaderNodeNormalMap': {'Normal': 'NORMAL'},+}+# compile() assigns every output, linked or not; unused ones are never freed.+_ALL_OUTPUTS_ASSIGNED = {'ShaderNodeRaycast', 'ShaderNodeSeparateXYZ',+ 'ShaderNodeSeparateColor', 'ShaderNodeNormal'}+# Inputs compile() reads only when linked (no temporary constant slot).+_LINKED_ONLY_INPUTS = {+ 'ShaderNodeMapRange': {'From Min', 'From Max', 'To Min', 'To Max'},+ 'ShaderNodeEmission': {'Strength'},+ 'ShaderNodeFresnel': {'Normal'},+}+_ALWAYS_PRESENT_INPUTS = {+ 'ShaderNodeMath': {'Value', 'Value_001', 'Value_002'},+ 'ShaderNodeVectorMath': {'Vector', 'Vector_001', 'Vector_002', 'Scale'},+ 'ShaderNodeMapRange': {'Value', 'From Min', 'From Max', 'To Min', 'To Max', 'Steps'},+}+_FOLDABLE = {'ShaderNodeMath', 'ShaderNodeVectorMath', 'ShaderNodeCombineXYZ',+ 'ShaderNodeSeparateXYZ', 'ShaderNodeMapRange', 'ShaderNodeMixRGB',+ 'ShaderNodeMix', 'ShaderNodeSeparateColor', 'ShaderNodeCombineColor',+ 'ShaderNodeRGBToBW', 'ShaderNodeClamp', 'CONVERT', 'ShaderNodeValToRGB'}+_IGNORED_PROPS = {'rna_type', 'name', 'label', 'location', 'location_absolute', 'width',+ 'height', 'dimensions', 'select', 'hide', 'show_options', 'show_preview',+ 'show_texture', 'color', 'use_custom_color', 'parent', 'internal_links',+ 'inputs', 'outputs', 'mute', 'warning_propagation', 'color_tag', 'type'}+++class _Node:+ __slots__ = ('id', 'kind', 'op', 'label', 'key', 'inputs', 'outputs', 'const', 'proxy')++ def __init__(self, ident, kind, op='', label='', key=()):+ self.id = ident+ self.kind = kind+ self.op = op+ self.label = label+ self.key = key+ self.inputs = [] # [name, type, link (node, output index) | None, value]+ self.outputs = [] # [name, type]+ self.const = None+ self.proxy = False++ def clamped(self):+ return ('use_clamp', True) in self.key+++def _prop_key(node):+ """Unlinkable settings; Cycles only merges nodes whose settings match."""+ values = []+ for prop in node.bl_rna.properties:+ name = prop.identifier+ if name in _IGNORED_PROPS or name.startswith('bl_'):+ continue+ try:+ value = getattr(node, name)+ except AttributeError:+ continue+ if isinstance(value, bpy.types.ID):+ value = value.as_pointer()+ elif not isinstance(value, (str, int, float, bool, type(None))):+ continue+ values.append((name, value))+ ramp = getattr(node, 'color_ramp', None)+ if ramp is not None:+ values.append(('ramp', tuple((e.position, tuple(e.color)) for e in ramp.elements)))+ return tuple(values)+++def _socket_value(socket):+ value = getattr(socket, 'default_value', None)+ if value is None:+ return None+ try:+ return float(value)+ except TypeError:+ try:+ return tuple(round(v, 7) for v in value)+ except TypeError:+ return None+++def _evaluate(node):+ """Folded output values; unknown operations get a value equal to nothing."""+ values = [entry[3] for entry in node.inputs]+ result = {}+ try:+ if node.kind == 'ShaderNodeMath':+ result['Value'] = _math(node.op, *values[:3])+ elif node.kind == 'ShaderNodeCombineXYZ':+ result['Vector'] = tuple(values[:3])+ elif node.kind == 'ShaderNodeSeparateXYZ':+ result.update(zip(('X', 'Y', 'Z'), values[0]))+ elif node.kind == 'ShaderNodeVectorMath':+ result.update(_vector_math(node.op, *values[:4]))+ elif node.kind == 'CONVERT':+ value = values[0]+ if isinstance(value, tuple) and _SIZE[node.op[1]] == 1:+ weights = ((0.2126, 0.7152, 0.0722) if node.op[0] == 'COLOR'+ else (1 / 3, 1 / 3, 1 / 3))+ value = sum(w * v for w, v in zip(weights, value))+ elif not isinstance(value, tuple) and _SIZE[node.op[1]] == 3:+ value = (value, value, value)+ result['Out'] = value+ except (TypeError, ValueError, ZeroDivisionError, OverflowError, IndexError):+ result = {}+ return [result.get(name, ('folded', node.id, name)) for name, _type in node.outputs]+++def _math(op, a, b, c):+ import math+ operations = {+ 'ADD': lambda: a + b, 'SUBTRACT': lambda: a - b, 'MULTIPLY': lambda: a * b,+ 'DIVIDE': lambda: a / b if b != 0.0 else 0.0, 'POWER': lambda: a ** b,+ 'MINIMUM': lambda: min(a, b), 'MAXIMUM': lambda: max(a, b),+ 'LESS_THAN': lambda: float(a < b), 'GREATER_THAN': lambda: float(a > b),+ 'ABSOLUTE': lambda: abs(a), 'TANGENT': lambda: math.tan(a),+ 'ARCCOSINE': lambda: math.acos(max(-1.0, min(1.0, a))),+ 'COMPARE': lambda: float(abs(a - b) <= max(c, 1e-5)),+ 'MULTIPLY_ADD': lambda: a * b + c, 'SQRT': lambda: math.sqrt(a) if a > 0 else 0.0,+ }+ return float(operations[op]())+++def _vector_math(op, a, b, c, scale):+ import math++ def length(v):+ return math.sqrt(sum(x * x for x in v))++ if op == 'NORMALIZE':+ n = length(a)+ return {'Vector': tuple(x / n for x in a) if n else (0.0, 0.0, 0.0)}+ if op == 'LENGTH':+ return {'Value': length(a)}+ if op == 'DOT_PRODUCT':+ return {'Value': sum(x * y for x, y in zip(a, b))}+ if op == 'SCALE':+ return {'Vector': tuple(x * scale for x in a)}+ if op == 'CROSS_PRODUCT':+ return {'Vector': (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2],+ a[0] * b[1] - a[1] * b[0])}+ if op in {'ADD', 'SUBTRACT', 'MULTIPLY'}:+ function = {'ADD': lambda x, y: x + y, 'SUBTRACT': lambda x, y: x - y,+ 'MULTIPLY': lambda x, y: x * y}[op]+ return {'Vector': tuple(function(x, y) for x, y in zip(a, b))}+ return {}+++class _Graph:+ def __init__(self):+ self.nodes = []+ self.output = None+ self.clamped = []+ self.deduplicated = 0++ def expand(self):+ """MathNode/MapRangeNode::expand append a Clamp after every node."""+ for node in self.clamped:+ if node.const is not None:+ continue+ clamp = self.add('CLAMP', '', node.label + ' clamp')+ clamp.inputs = [['Value', 'FLOAT', None, None], ['Min', 'FLOAT', None, 0.0],+ ['Max', 'FLOAT', None, 1.0]]+ clamp.outputs.append(['Result', 'FLOAT'])+ self._relink(node, (clamp, 0))+ clamp.inputs[0][2] = (node, 0)++ def add(self, kind, op='', label='', key=()):+ node = _Node(len(self.nodes), kind, op, label, key)+ self.nodes.append(node)+ return node++ def connect(self, source, target):+ """ShaderGraph::connect: a type mismatch adds a conversion node."""+ node, index = source+ from_type = node.outputs[index][1]+ to_type = target[1]+ if from_type != to_type and 'CLOSURE' not in (from_type, to_type):+ convert = self.add('CONVERT', (from_type, to_type), 'convert ' + node.label,+ (from_type, to_type))+ convert.inputs.append(['In', from_type, source, None])+ convert.outputs.append(['Out', to_type])+ source = (convert, 0)+ target[2] = source++ def _proxy(self, ctype, value=None):+ proxy = self.add('PROXY')+ proxy.proxy = True+ proxy.inputs.append(['In', ctype, None, value])+ proxy.outputs.append(['Out', ctype])+ return proxy++ def add_tree(self, tree, input_proxies=None, output_proxies=None):+ """blender/shader.cpp add_nodes(): all nodes first, then all links."""+ outputs = {}+ inputs = {}+ for b_node in tree.nodes:+ kind = b_node.bl_idname+ if kind == 'NodeFrame':+ continue+ if b_node.mute or kind == 'NodeReroute':+ for link in b_node.internal_links:+ ctype = _BLENDER_TYPES.get(link.to_socket.type)+ if ctype is None:+ continue+ proxy = self._proxy(ctype, _socket_value(link.from_socket))+ inputs.setdefault(link.from_socket.as_pointer(), []).append(proxy.inputs[0])+ outputs[link.to_socket.as_pointer()] = (proxy, 0)+ continue+ if kind == 'ShaderNodeGroup':+ group_inputs, group_outputs = {}, {}+ for socket in b_node.inputs:+ ctype = _BLENDER_TYPES.get(socket.type)+ if ctype is not None:+ proxy = self._proxy(ctype, _socket_value(socket))+ group_inputs[socket.identifier] = proxy+ inputs.setdefault(socket.as_pointer(), []).append(proxy.inputs[0])+ for socket in b_node.outputs:+ ctype = _BLENDER_TYPES.get(socket.type)+ if ctype is not None:+ proxy = self._proxy(ctype)+ group_outputs[socket.identifier] = proxy+ outputs[socket.as_pointer()] = (proxy, 0)+ if b_node.node_tree is not None:+ self.add_tree(b_node.node_tree, group_inputs, group_outputs)+ continue+ if kind == 'NodeGroupInput':+ for socket in b_node.outputs:+ proxy = (input_proxies or {}).get(socket.identifier)+ if proxy is not None:+ outputs[socket.as_pointer()] = (proxy, 0)+ continue+ if kind == 'NodeGroupOutput':+ if b_node.is_active_output:+ for socket in b_node.inputs:+ proxy = (output_proxies or {}).get(socket.identifier)+ if proxy is not None:+ inputs.setdefault(socket.as_pointer(), []).append(proxy.inputs[0])+ continue+ if kind == 'ShaderNodeOutputMaterial' and (+ input_proxies is not None or self.output is not None+ or not b_node.is_active_output or b_node.target == 'EEVEE'):+ continue+ if kind == 'ShaderNodeValue':+ node = self.add(kind, '', b_node.label or b_node.name)+ node.const = [b_node.outputs[0].default_value]+ node.outputs.append(['Value', 'FLOAT'])+ outputs[b_node.outputs[0].as_pointer()] = (node, 0)+ continue+ op = getattr(b_node, 'operation', '') or getattr(b_node, 'blend_type', '')+ node = self.add(kind, op, b_node.label or b_node.name, _prop_key(b_node))+ if kind == 'ShaderNodeOutputMaterial':+ self.output = node+ if getattr(b_node, 'use_clamp', False) and kind == 'ShaderNodeMath' \+ or kind == 'ShaderNodeMapRange' and b_node.clamp:+ self.clamped.append(node)+ in_types = _INPUT_TYPES.get(kind, {})+ out_types = _OUTPUT_TYPES.get(kind, {})+ always = (_ALWAYS_PRESENT_INPUTS.get(kind, ())+ if getattr(b_node, 'data_type', 'FLOAT') == 'FLOAT' else ())+ for socket in b_node.inputs:+ # Cycles keeps inputs that Blender hides for some operations.+ if not socket.enabled and socket.identifier not in always:+ continue+ ctype = in_types.get(socket.name) or _BLENDER_TYPES.get(socket.type)+ if ctype is None:+ continue+ entry = [socket.name, ctype, None, _socket_value(socket)]+ node.inputs.append(entry)+ if socket.enabled:+ inputs.setdefault(socket.as_pointer(), []).append(entry)+ for socket in b_node.outputs:+ if not socket.enabled:+ continue+ ctype = out_types.get(socket.name) or _BLENDER_TYPES.get(socket.type)+ if ctype is not None:+ node.outputs.append([socket.name, ctype])+ outputs[socket.as_pointer()] = (node, len(node.outputs) - 1)+ for link in tree.links:+ # Cycles ignores invalid and muted links and unavailable sockets.+ if (not link.is_valid or link.is_muted+ or not link.from_socket.enabled or not link.to_socket.enabled):+ continue+ source = outputs.get(link.from_socket.as_pointer())+ if source is None:+ continue+ for target in inputs.get(link.to_socket.as_pointer(), ()):+ if target[2] is None:+ self.connect(source, target)++ def _relink(self, node, replacement):+ for other in self.nodes:+ for entry in other.inputs:+ if entry[2] is not None and entry[2][0] is node:+ entry[2] = replacement++ def remove_proxies(self):+ for node in self.nodes:+ if not node.proxy:+ continue+ source = node.inputs[0][2]+ for other in self.nodes:+ for entry in other.inputs:+ if entry[2] is not None and entry[2][0] is node:+ entry[2] = source+ if source is None:+ entry[3] = node.inputs[0][3]+ node.const = 'removed'++ def fold(self):+ """ShaderGraph::constant_fold for the node types projection graphs use."""+ changed = True+ while changed:+ changed = False+ for node in self.nodes:+ if node.const is not None:+ continue+ for entry in node.inputs:+ source = entry[2]+ if source is not None and isinstance(source[0].const, list):+ entry[2] = None+ entry[3] = source[0].const[source[1]]+ changed = True+ if node.kind in _FOLDABLE and node.inputs \+ and all(entry[2] is None for entry in node.inputs):+ node.const = _evaluate(node)+ changed = True+ continue+ target = self._fold_identity(node)+ if target == 'zero':+ node.const = [0.0]+ elif target == 'one':+ node.const = [1.0]+ elif target is not None:+ self._relink(node, target)+ node.const = 'removed'+ if target is not None:+ changed = True++ @staticmethod+ def _fold_identity(node):+ def zero(entry):+ return entry[2] is None and entry[3] in (0.0, (0.0, 0.0, 0.0))++ def one(entry):+ return entry[2] is None and entry[3] in (1.0, (1.0, 1.0, 1.0))++ def through(entry):+ if entry[2] is None:+ return None+ source, index = entry[2]+ return entry[2] if source.outputs[index][1] == node.outputs[0][1] else None++ if node.kind == 'ShaderNodeMath' and len(node.inputs) >= 2 and not node.clamped():+ a, b = node.inputs[0], node.inputs[1]+ if node.op == 'ADD':+ return through(b) if zero(a) else through(a) if zero(b) else None+ if node.op == 'SUBTRACT':+ return through(a) if zero(b) else None+ if node.op == 'MULTIPLY':+ if one(a):+ return through(b)+ if one(b):+ return through(a)+ return 'zero' if zero(a) or zero(b) else None+ if node.op == 'DIVIDE':+ return through(a) if one(b) else 'zero' if zero(a) else None+ if node.op == 'POWER':+ if one(a) or zero(b):+ return 'one'+ return through(a) if one(b) else None+ if node.kind == 'CONVERT':+ source = node.inputs[0][2]+ if source is not None and source[0].kind == 'CONVERT' \+ and source[0].op == (node.op[1], node.op[0]) \+ and _SIZE[node.op[0]] == 3 and source[0].inputs[0][2] is not None:+ return source[0].inputs[0][2]+ return None++ def reachable(self):+ seen = set()+ pending = [self.output] if self.output is not None else []+ while pending:+ node = pending.pop()+ if node.id in seen:+ continue+ seen.add(node.id)+ pending.extend(entry[2][0] for entry in node.inputs if entry[2] is not None)+ return seen++ def deduplicate(self, alive):+ """ShaderGraph::deduplicate_nodes: merge equal settings and inputs."""+ changed = True+ while changed:+ changed = False+ seen = {}+ for node in self.nodes:+ if node.id not in alive or node is self.output:+ continue+ signature = (node.kind, node.op, node.key, tuple(+ (entry[0], (entry[2][0].id, entry[2][1]) if entry[2] is not None+ else ('constant', entry[3])) for entry in node.inputs))+ keep = seen.setdefault(signature, node)+ if keep is node:+ continue+ for other in self.nodes:+ for entry in other.inputs:+ if entry[2] is not None and entry[2][0] is node:+ entry[2] = (keep, entry[2][1])+ alive.discard(node.id)+ self.deduplicated += 1+ changed = True+++def _temporary_inputs(node):+ """Indices of unlinked inputs that compile() loads into temporary slots."""+ linked_only = _LINKED_ONLY_INPUTS.get(node.kind, ())+ temps = []+ for index, entry in enumerate(node.inputs):+ if entry[2] is not None or entry[0] in linked_only:+ continue+ if node.kind == 'ShaderNodeVectorMath' and index == 2 \+ and node.op not in {'WRAP', 'FACEFORWARD', 'MULTIPLY_ADD'}:+ continue+ if node.kind == 'ShaderNodeMapRange' and entry[0] not in {'Value', 'Steps'}:+ continue+ if _SIZE.get(entry[1], 0):+ temps.append(index)+ return temps+++# compile() functions that allocate several sockets as arguments of a single+# call. MSVC and GCC evaluate those arguments right to left, which decides+# where each value lands on the stack and therefore its fragmentation.+_ALLOCATION_ORDER = {+ 'ShaderNodeRaycast': ('out:Hit Normal', 'out:Hit Position', 'out:Hit Distance',+ 'out:Self Hit', 'out:Is Hit', 'in:Length', 'in:Direction',+ 'in:Position'),+ 'ShaderNodeMixRGB': ('in:Color2', 'in:Color1', 'in:Fac', 'out:Color'),+ 'ShaderNodeTexImage': ('in:Vector', 'out:Alpha', 'out:Color'),+ 'ShaderNodeTexGradient': ('in:Vector', 'out:Color', 'out:Fac'),+ 'ShaderNodeFresnel': ('out:Fac', 'in:Normal', 'in:IOR'),+ 'ShaderNodeCombineXYZ': ('out:Vector', 'in:X', 'in:Y', 'in:Z'),+ 'ShaderNodeSeparateXYZ': ('out:X', 'in:Vector', 'out:Y', 'out:Z'),+}+++def _allocation_steps(node):+ """Ordered ('in', index) temporaries and ('out', index) outputs."""+ temps = _temporary_inputs(node)+ order = _ALLOCATION_ORDER.get(node.kind)+ if order is None:+ return ([('in', index) for index in temps]+ + [('out', index) for index in range(len(node.outputs))])+ steps = []+ for item in order:+ side, name = item.split(':', 1)+ if side == 'in':+ steps += [('in', index) for index in temps if node.inputs[index][0] == name]+ else:+ steps += [('out', index) for index, output in enumerate(node.outputs)+ if output[0] == name]+ return steps+++def _simulate(graph, alive, limit):+ """Replay SVMCompiler::generate_svm_nodes with its stack allocator."""+ order = [node for node in graph.nodes if node.id in alive and node is not graph.output]+ users = {}+ for node in order + [graph.output]:+ for entry in node.inputs:+ if entry[2] is not None:+ users.setdefault((entry[2][0].id, entry[2][1]), set()).add(node.id)+ stack = [0] * limit+ state = {'peak': 0, 'overflow': False, 'peak_live': ()}+ offsets = {}+ done = set()++ def allocate(size):+ run = 0+ for index in range(limit):+ run = 0 if stack[index] else run + 1+ if run == size:+ offset = index + 1 - size+ for slot in range(offset, index + 1):+ stack[slot] = 1+ if index + 1 > state['peak']:+ state['peak'] = index + 1+ state['peak_live'] = tuple(offsets.values())+ return offset+ state['overflow'] = True+ return None++ def release(offset, size):+ for slot in range(offset, offset + size):+ stack[slot] -= 1++ remaining = order+ passes = 0+ while remaining and not state['overflow']:+ passes += 1+ deferred = []+ for node in remaining:+ if any(entry[2] is not None and entry[2][0].id not in done+ for entry in node.inputs):+ deferred.append(node)+ continue+ temporaries = []+ if node.kind == 'CONVERT' and _SIZE[node.op[0]] == 3 == _SIZE[node.op[1]]:+ # float3 -> float3 conversions alias their input (stack_link).+ source = node.inputs[0][2]+ offset, size, _owner = offsets[(source[0].id, source[1])]+ for slot in range(offset, offset + size):+ stack[slot] += 1+ offsets[(node.id, 0)] = (offset, size, node)+ else:+ for side, index in _allocation_steps(node):+ if side == 'in':+ size = _SIZE[node.inputs[index][1]]+ temporaries.append((allocate(size), size))+ continue+ size = _SIZE.get(node.outputs[index][1], 0)+ if not size:+ continue+ if (node.id, index) in users:+ offset = allocate(size)+ if offset is not None:+ offsets[(node.id, index)] = (offset, size, node)+ elif node.kind in _ALL_OUTPUTS_ASSIGNED:+ allocate(size) # Cycles never releases it+ done.add(node.id)+ for entry in node.inputs:+ if entry[2] is None:+ continue+ key = (entry[2][0].id, entry[2][1])+ if key in offsets and users[key] <= done:+ offset, size, _owner = offsets.pop(key)+ release(offset, size)+ for offset, size in temporaries:+ if offset is not None:+ release(offset, size)+ if state['overflow']:+ break+ if len(deferred) == len(remaining):+ break # dependency cycle; Cycles breaks it before compiling+ remaining = deferred+ return state, passes+++def estimate_svm_stack(material, limit=SVM_STACK_SIZE):+ """Return (peak stack floats, details) for the material's Cycles surface.++ A peak of SVM_STACK_SIZE means Cycles cannot compile the shader and the+ material renders black. ``details`` contains the number of compile+ sweeps and the node labels that hold the most stack at the peak. A larger+ ``limit`` measures how far an oversized graph exceeds the stack.+ """+ if material is None or not material.use_nodes or material.node_tree is None:+ return 0, {}+ graph = _Graph()+ # Blender 5.1+ Cycles compiles an inlined copy of the tree: groups are+ # flattened, constants folded and nodes copied in depth-first order from+ # the output. That order, not creation order, is the SVM compile order.+ inlined = (material.inline_shader_nodes()+ if hasattr(material, 'inline_shader_nodes') else None)+ graph.add_tree(inlined.node_tree if inlined is not None else material.node_tree)+ if graph.output is None:+ return 0, {}+ graph.remove_proxies()+ graph.expand()+ graph.fold()+ alive = graph.reachable()+ graph.deduplicate(alive)+ alive = graph.reachable()+ state, passes = _simulate(graph, alive, max(limit, SVM_STACK_SIZE))+ holders = {}+ for _offset, size, owner in state['peak_live']:+ label = owner.label.split('-', 1)[0] if owner.label else owner.kind+ holders[label] = holders.get(label, 0) + size+ top = sorted(holders.items(), key=lambda item: -item[1])[:8]+ peak = max(limit, SVM_STACK_SIZE) if state['overflow'] else state['peak']+ return peak, {'passes': passes, 'holders': top, 'overflow': state['overflow'],+ 'deduplicated': graph.deduplicated,+ 'live': [(owner.label, size) for _offset, size, owner in state['peak_live']]}