Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
expose shader controls and organize projection node graphs
sakalondb85977284588
diff --git a/stablegen/texturing/graph_controls.py b/stablegen/texturing/graph_controls.pynew file mode 100644index 0000000..5d8ee70--- /dev/null+++ b/stablegen/texturing/graph_controls.py@@ -0,0 +1,250 @@+"""Editable shader inputs for settings that can change without rebuilding masks.++Only link controls to a feature that is actually present in the material.+Camera geometry, depth thresholds, margins, guard resolution and feather width+are baked into attributes or PNGs and deliberately do not get inert controls.+"""+++_PREFIX = 'SG Control | '+++def _control(nodes, key, label, initial):+ name = _PREFIX + key+ node = nodes.get(name)+ if node is None:+ node = nodes.new('ShaderNodeValue')+ node.name = name+ node.label = label+ node.outputs[0].default_value = float(initial)+ node['sg_layout_stage'] = 'Graph controls'+ node.use_custom_color = True+ node.color = (0.19, 0.29, 0.24)+ node.width = 220+ return node.outputs[0]+++def _math(nodes, links, operation, label, a, b, *, stage='Graph control wiring',+ camera_nodes=None, camera_index=None):+ node = nodes.new('ShaderNodeMath')+ node.operation = operation+ node.label = label+ node.hide = True+ node['sg_layout_stage'] = stage+ if camera_nodes is not None and camera_index is not None:+ camera_nodes[node.as_pointer()] = camera_index+ for index, value in enumerate((a, b)):+ if isinstance(value, (int, float)):+ node.inputs[index].default_value = value+ else:+ links.new(value, node.inputs[index])+ return node.outputs[0]+++def _controlled_rejection(nodes, links, source, amount, label, *, stage='Graph control wiring',+ camera_nodes=None, camera_index=None):+ """Replace uses of source by 1 - amount * (1 - source)."""+ targets = [link.to_socket for link in list(source.links)]+ if not targets:+ return None+ placement = dict(stage=stage, camera_nodes=camera_nodes, camera_index=camera_index)+ missing = _math(nodes, links, 'SUBTRACT', label + ' missing', 1.0, source, **placement)+ scaled = _math(nodes, links, 'MULTIPLY', label + ' amount', amount, missing, **placement)+ effective = _math(nodes, links, 'SUBTRACT', label, 1.0, scaled, **placement)+ for target in targets:+ links.new(effective, target)+ return effective+++def _indexed(nodes, prefix):+ result = {}+ for node in nodes:+ if not node.label.startswith(prefix):+ continue+ index = node.label[len(prefix):].split('-', 1)[0]+ if index.isdigit():+ result[int(index)] = node+ return result+++def install_projection_controls(material, scene, new_nodes, camera_nodes=None):+ """Expose live settings on a newly built projection pass.++ Existing controls are reused by appended local-edit passes. The caller+ passes only the nodes built in this pass so old mask switches are never+ wrapped a second time.+ """+ nodes, links = material.node_tree.nodes, material.node_tree.links+ if camera_nodes is None:+ camera_nodes = {}+ new = [node for node in new_nodes if node.type != 'FRAME']+ if not new:+ return++ angle = [node for node in new if node.label.startswith('AngleThreshold-')+ and node.type == 'MATH']+ scripts = [node for node in new if node.type == 'SCRIPT']+ if angle or any('AngleThreshold' in node.inputs for node in scripts):+ setting = _control(nodes, 'discard_angle', 'Discard Angle (degrees)',+ scene.discard_factor)+ for node in angle:+ links.new(setting, node.inputs[1])+ for node in scripts:+ if 'AngleThreshold' in node.inputs:+ links.new(setting, node.inputs['AngleThreshold'])++ sharp = [node for node in new if node.type == 'MATH'+ and node.operation == 'POWER' and node.label.startswith('SharpW-')]+ base_power = [node for node in new if node.type == 'MATH'+ and node.operation == 'POWER' and node.label == 'power_weight']+ script_power = [node for node in scripts if 'Power' in node.inputs]+ if sharp or base_power or script_power:+ setting = _control(nodes, 'exponent', 'Weight Exponent', scene.weight_exponent)+ for node in sharp:+ links.new(setting, node.inputs[1])+ if not sharp:+ for node in base_power:+ links.new(setting, node.inputs[1])+ for node in script_power:+ links.new(setting, node.inputs['Power'])++ guards = [node for node in new if node.label.startswith('ProjectionGuardWeight-')]+ if guards:+ enabled = _control(nodes, 'dppg_enabled', 'DPPG Enabled (0 / 1)', 1.0)+ enabled = _math(nodes, links, 'GREATER_THAN', 'DPPG switch', enabled, 0.5)+ for node in guards:+ _controlled_rejection(nodes, links, node.outputs[0], enabled,+ 'ProjectionGuardWeightSwitch-' + node.label.split('-', 1)[1],+ stage='Depth and part guard', camera_nodes=camera_nodes,+ camera_index=camera_nodes.get(node.as_pointer()))++ feathers = [node for node in new if node.label.startswith('ProjectionGuardFeather-')]+ occlusion = [node for node in new if node.name.startswith('SGOcclusionFeather-')]+ influences = [node for node in new if node.name.startswith(+ ('SGFeatherInfluence-', 'SGOcclusionInfluence-'))]+ if feathers or occlusion or influences:+ feather = _control(nodes, 'feather_amount', 'DPPG Feather Amount (0..1)', 1.0)+ feather = _math(nodes, links, 'MINIMUM', 'Feather amount upper bound', feather, 1.0)+ feather = _math(nodes, links, 'MAXIMUM', 'Feather amount lower bound', feather, 0.0)+ amount = _math(nodes, links, 'MULTIPLY', 'Effective DPPG feather', enabled, feather)+ for node in feathers:+ _controlled_rejection(nodes, links, node.outputs[0], amount,+ 'ProjectionGuardFeatherSwitch-' + node.label.split('-', 1)[1],+ stage='Guard feather', camera_nodes=camera_nodes,+ camera_index=camera_nodes.get(node.as_pointer()))+ for node in occlusion:+ _controlled_rejection(nodes, links, node.outputs[0], amount,+ 'Occlusion feather switch ' + node.name,+ stage='Occlusion fade', camera_nodes=camera_nodes,+ camera_index=camera_nodes.get(node.as_pointer()))+ for node in influences:+ targets = [link.to_socket for link in list(node.outputs[0].links)]+ if targets:+ gated = _math(nodes, links, 'MULTIPLY',+ 'Feather influence switch ' + node.name,+ node.outputs[0], amount,+ stage=('Occlusion fade' if node.name.startswith('SGOcclusion')+ else 'Guard feather'), camera_nodes=camera_nodes,+ camera_index=camera_nodes.get(node.as_pointer()))+ for target in targets:+ links.new(gated, target)++ thresholds = [node for node in new if node.label == 'GuardRescueThreshold']+ actives = [node for node in new if node.label == 'GuardRescueActive']+ if thresholds or actives:+ rescue = _control(nodes, 'coverage_rescue', 'Coverage Rescue (0..1)',+ scene.sg_guard_coverage_rescue)+ rescue = _math(nodes, links, 'MINIMUM', 'Rescue upper bound', rescue, 1.0,+ stage='Guard coverage rescue')+ rescue = _math(nodes, links, 'MAXIMUM', 'Rescue lower bound', rescue, 0.0,+ stage='Guard coverage rescue')+ for node in thresholds:+ links.new(rescue, node.inputs[1])+ for node in actives:+ links.new(rescue, node.inputs[0])++ signed_dots = _indexed(new, 'FacingSignedDot-')+ facing_weights = _indexed(new, 'FacingWeight-')+ if (signed_dots and facing_weights) or any('AllowBackface' in node.inputs for node in scripts):+ backface = _control(nodes, 'allow_backface', 'Allow Backface (0 / 1)',+ scene.sg_allow_backface_projection)+ backface = _math(nodes, links, 'GREATER_THAN', 'Backface switch', backface, 0.5)+ for node in scripts:+ if 'AllowBackface' in node.inputs:+ links.new(backface, node.inputs['AllowBackface'])+ for index, signed in signed_dots.items():+ current = facing_weights.get(index)+ if current is None:+ continue+ placement = dict(stage='Facing and angle', camera_nodes=camera_nodes,+ camera_index=camera_nodes.get(current.as_pointer()))+ targets = [link.to_socket for link in list(current.outputs[0].links)]+ if scene.sg_allow_backface_projection:+ back = current.outputs[0]+ front = _math(nodes, links, 'MULTIPLY', f'Front facing {index}',+ signed.outputs[0], -1.0, **placement)+ front = _math(nodes, links, 'MAXIMUM', f'Front clamp {index}', front, 0.0,+ **placement)+ else:+ front = current.outputs[0]+ back = _math(nodes, links, 'ABSOLUTE', f'Back facing {index}',+ signed.outputs[0], 0.0, **placement)+ difference = _math(nodes, links, 'SUBTRACT', f'Backface difference {index}',+ back, front, **placement)+ selected = _math(nodes, links, 'MULTIPLY', f'Backface selection {index}',+ backface, difference, **placement)+ selected = _math(nodes, links, 'ADD', f'Facing switch {index}', front, selected,+ **placement)+ for target in targets:+ links.new(selected, target)++ camera_mixes = [node for node in new if node.label.startswith('CameraMix-')]+ if camera_mixes:+ priority = _control(nodes, 'priority_enabled', 'Prioritize Initial Views (0 / 1)',+ scene.early_priority)+ priority = _math(nodes, links, 'GREATER_THAN', 'Priority switch', priority, 0.5,+ stage='Early view priority')+ strength = _control(nodes, 'priority_strength', 'Initial View Priority Strength',+ scene.early_priority_strength)+ for mix in camera_mixes:+ factor = mix.inputs['Fac']+ if not factor.links:+ continue+ source = factor.links[0].from_socket+ if source.node.type == 'MAP_RANGE':+ mapping = source.node+ unprioritized = mapping.inputs[0].links[0].from_socket+ else:+ unprioritized = source+ mapping = nodes.new('ShaderNodeMapRange')+ mapping.label = 'EarlyPriorityMap-' + mix.label.split('-', 1)[1]+ mapping['sg_layout_stage'] = 'Early view priority'+ mapping.hide = True+ links.new(unprioritized, mapping.inputs[0])+ links.new(strength, mapping.inputs[1])+ placement = dict(stage='Early view priority')+ difference = _math(nodes, links, 'SUBTRACT', 'Priority difference',+ mapping.outputs[0], unprioritized, **placement)+ added = _math(nodes, links, 'MULTIPLY', 'Priority adjustment', priority,+ difference, **placement)+ selected = _math(nodes, links, 'ADD', 'Priority result', unprioritized, added,+ **placement)+ links.new(selected, factor)++ acquisition = [node for node in new if node.label.startswith('AcquisitionQuality-')+ and node.type == 'MATH' and node.inputs[1].links]+ if acquisition:+ amount = _control(nodes, 'acquisition_quality', 'Acquisition Quality Amount (0..1)', 1.0)+ amount = _math(nodes, links, 'MINIMUM', 'Acquisition upper bound', amount, 1.0)+ amount = _math(nodes, links, 'MAXIMUM', 'Acquisition lower bound', amount, 0.0)+ for node in acquisition:+ placement = dict(stage='Acquisition quality', camera_nodes=camera_nodes,+ camera_index=camera_nodes.get(node.as_pointer()))+ density = node.inputs[1].links[0].from_socket+ missing = _math(nodes, links, 'SUBTRACT', 'Acquisition missing', 1.0, density,+ **placement)+ adjustment = _math(nodes, links, 'MULTIPLY', 'Acquisition adjustment', amount,+ missing, **placement)+ effective = _math(nodes, links, 'SUBTRACT', 'Acquisition factor', 1.0,+ adjustment, **placement)+ links.new(effective, node.inputs[1])diff --git a/stablegen/texturing/node_layout.py b/stablegen/texturing/node_layout.pynew file mode 100644index 0000000..ac06962--- /dev/null+++ b/stablegen/texturing/node_layout.py@@ -0,0 +1,386 @@+"""Presentation-only layout for StableGen projection shader graphs.++This module never creates or removes shader nodes or links. Frames, node labels,+widths and positions are the only things it changes. Projection keeps its own+construction order, including incremental sequential and appended edit passes.+"""++from collections import defaultdict+++_VIEW_STAGES = (+ 'Surface geometry',+ 'Visibility and angle',+ 'Camera basis and frustum',+ 'Raycast visibility',+ 'Facing and angle',+ 'Frame edge and vignette',+ 'Acquisition quality',+ 'Image and UV',+ 'Sequential write mask',+ 'Generated alpha',+ 'Depth and part guard',+ 'Guard feather',+ 'Occlusion fade',+ 'Local edit edge mask',+ 'Source confidence',+)++_BLEND_STAGES = (+ 'Surface blend',+ 'Guard coverage rescue',+ 'Occlusion handoff',+ 'Normalize and sharpen',+ 'Boundary crossfade',+ 'Local unsharpen',+ 'Guard feathering',+ 'Local edit ramps',+ 'Early view priority',+ 'Combine view colors',+ 'Source confidence output',+)+++def _frame_color(title):+ """Keep view, guard, blend, and output regions distinct at a glance."""+ if title.startswith('Projection pass'):+ return (0.10, 0.12, 0.17)+ if title.startswith('View '):+ return (0.10, 0.17, 0.19)+ if title == 'Graph controls':+ return (0.11, 0.23, 0.17)+ if title == 'Graph control wiring':+ return (0.12, 0.17, 0.14)+ if title.startswith('Handoff level') or title == 'Boundary crossfade':+ return (0.20, 0.14, 0.22)+ if 'guard' in title.lower() or 'feather' in title.lower() or 'occlusion' in title.lower():+ return (0.19, 0.16, 0.11)+ if title == 'Material output':+ return (0.12, 0.20, 0.14)+ if title in {'Combine view colors', 'Normalize and sharpen', 'Surface blend'}:+ return (0.12, 0.15, 0.22)+ return (0.13, 0.16, 0.18)+++def _view_stage(node):+ if node.get('sg_layout_stage') in _VIEW_STAGES:+ return node['sg_layout_stage']+ if node.type == 'NEW_GEOMETRY':+ return 'Surface geometry'+ label = node.label+ if (node.type == 'TEX_IMAGE' and label.split('-')[0].isdigit()+ or node.type == 'ATTRIBUTE' and node.attribute_name.startswith('ProjectionUV_')):+ return 'Image and UV'+ if label.startswith(('Confidence',)):+ return 'Source confidence'+ if label.startswith(('EdgeFeather-', 'EF_Weight-')):+ return 'Local edit edge mask'+ if label.startswith(('ProjectionOcclusion', 'Occlusion', 'SGOcclusion')):+ return 'Occlusion fade'+ if label.startswith(('ProjectionGuardFeather-', 'DepthPartFeathered-',+ 'ProjectionGuardInfluence-')):+ return 'Guard feather'+ if label.startswith(('ProjectionGuard-', 'ProjectionGuardWeight-',+ 'ProjectionGuardFloor-', 'DepthPartGuarded-')):+ return 'Depth and part guard'+ if label.startswith(('Qwen21GeneratedAlpha-', 'SDXLFeatherAlpha-')):+ return 'Generated alpha'+ if label.startswith(('SequentialWrite', 'QwenWriteMasked-')):+ return 'Sequential write mask'+ if label.startswith(('AcquisitionQuality-', 'ProjectedDensity-')):+ return 'Acquisition quality'+ if label.startswith(('FrameEdgeQuality-', 'Feather-')):+ return 'Frame edge and vignette'+ return 'Visibility and angle'+++def _blend_stage(node, feather_method):+ if node.get('sg_layout_stage') in _BLEND_STAGES:+ return node['sg_layout_stage']+ label = node.label+ if label.startswith('SurfaceBlend'):+ return 'Surface blend'+ if label.startswith(('GuardRescue', 'GuardCoverage')):+ return 'Guard coverage rescue'+ if label.startswith(('OcclusionHandoff', 'GuardOcclusion')):+ return 'Occlusion handoff'+ if label.startswith('SharpW-Feather-'):+ return 'Boundary crossfade'+ if label.startswith(('WeightMax', 'SafeMax', 'NormW-', 'SharpW-')):+ return 'Normalize and sharpen'+ if label.startswith('Crossfade'):+ return 'Boundary crossfade'+ if label.startswith('PostExponentFeather-'):+ return {'BOUNDARY_CROSSFADE': 'Boundary crossfade',+ 'LOCAL_UNSHARPEN': 'Local unsharpen'}.get(+ feather_method, 'Guard feathering')+ if label.startswith(('FeatherPreference-', 'FeatherVisible-', 'FeatherActive-',+ 'FeatherInfluence', 'FeatherSharp', 'FeatherSoft',+ 'ProjectionFeatherFloor-')):+ return 'Local unsharpen'+ if node.type == 'VALTORGB':+ return 'Local edit ramps'+ if node.type == 'MAP_RANGE':+ return 'Early view priority'+ if label.startswith('SGBestSourceQuality'):+ return 'Source confidence output'+ return 'Combine view colors'+++def _label_unlabeled(node, stage):+ if node.label:+ return+ if node.type == 'MATH':+ operation = node.operation.replace('_', ' ').title()+ if stage == 'Combine view colors':+ node.label = {+ 'ADD': 'Sum view weights',+ 'DIVIDE': 'Mix factor from weights',+ 'MULTIPLY': 'Combine visibility factors',+ }.get(node.operation, operation)+ else:+ node.label = operation+ elif node.type == 'VECT_MATH':+ node.label = node.operation.replace('_', ' ').title()+ elif node.type == 'MIX_RGB':+ node.label = 'Mix projected images'+ elif node.type == 'VALTORGB':+ node.label = 'Local edit visibility ramp'+ elif node.type == 'TEX_IMAGE':+ node.label = 'Feature mask'+ elif node.type == 'ATTRIBUTE':+ node.label = node.attribute_name or 'Mesh attribute'+ elif node.type == 'OUTPUT_MATERIAL':+ node.label = 'Projected material output'+ elif node.type == 'NEW_GEOMETRY':+ node.label = 'Surface position and normal'+ elif node.type == 'MAP_RANGE':+ node.label = 'Prioritize earlier view'+ else:+ node.label = node.bl_label+++def _create_frame(nodes, title, parent, x, y, width, height):+ frame = nodes.new('NodeFrame')+ frame.name = 'SG Layout | ' + title+ frame.label = title+ frame.label_size = 26 if parent is None else 21+ frame.use_custom_color = True+ frame.color = _frame_color(title)+ frame.shrink = False+ frame.width = width+ frame.height = height+ if parent is not None:+ frame.parent = parent+ frame.location = (x, y)+ return frame+++def _estimated_height(node):+ if node.hide:+ return 60+ if node.type == 'TEX_IMAGE':+ return 300+ if node.type in {'VALTORGB', 'SCRIPT'}:+ return 220+ return max(125, min(240, 65 + 25 * len(node.inputs)))+++def _arrange_group(nodes, links, items, title, parent, x, y):+ """Place a feature's nodes in dependency columns inside a labeled frame."""+ members = {node.as_pointer(): node for node in items}+ parents = defaultdict(list)+ children = defaultdict(list)+ for link in links:+ source, target = link.from_node.as_pointer(), link.to_node.as_pointer()+ if source in members and target in members and source != target:+ parents[target].append(source)+ children[source].append(target)++ depth = {pointer: 0 for pointer in members}+ indegree = {pointer: len(set(parents[pointer])) for pointer in members}+ ready = [pointer for pointer, count in indegree.items() if count == 0]+ while ready:+ pointer = ready.pop()+ for target in set(children[pointer]):+ depth[target] = max(depth[target], depth[pointer] + 1)+ indegree[target] -= 1+ if indegree[target] == 0:+ ready.append(target)++ columns = defaultdict(list)+ for node in items:+ columns[depth[node.as_pointer()]].append(node)+ column_heights = {+ index: sum(_estimated_height(node) + 35 for node in column)+ for index, column in columns.items()+ }+ width = max(380, 60 + (max(columns) + 1) * 250)+ height = max(270, 105 + max(column_heights.values()))+ frame = _create_frame(nodes, title, parent, x, y, width, height)+ for index, column in columns.items():+ top = -65+ for node in column:+ stage = title.split(' | ', 1)[-1]+ _label_unlabeled(node, stage)+ node.parent = frame+ node.width = (240 if node.type == 'VALUE' else+ 205 if node.type in {'TEX_IMAGE', 'SCRIPT', 'VALTORGB'} else 180)+ node.location = (35 + 250 * index, top)+ top -= _estimated_height(node) + 35+ return width, height+++def _arrange_crossfade(nodes, links, items, parent, x, y):+ """Separate the six threshold levels of the exact crossfade graph."""+ levels = defaultdict(list)+ final = []+ for node in items:+ label = node.label+ if label.startswith('PostExponentFeather-'):+ final.append(node)+ else:+ parts = label.split('-')+ index = 2 if label.startswith('SharpW-Feather-') else 1+ if len(parts) > index and parts[index].isdigit():+ levels[int(parts[index])].append(node)+ else:+ final.append(node)+ sections = [(f'Handoff level {index + 1:02d}', levels[index])+ for index in sorted(levels)]+ if final:+ sections.append(('Final view weights', final))+ frame = _create_frame(nodes, 'Boundary crossfade', parent, x, y, 500, 400)+ top, width = -70, 0+ for offset in range(0, len(sections), 2):+ left_title, left_items = sections[offset]+ left_width, left_height = _arrange_group(+ nodes, links, left_items, left_title, frame, 35, top)+ row_width, row_height = left_width, left_height+ if offset + 1 < len(sections):+ right_title, right_items = sections[offset + 1]+ right_width, right_height = _arrange_group(+ nodes, links, right_items, right_title,+ frame, 35 + left_width + 55, top)+ row_width += 55 + right_width+ row_height = max(row_height, right_height)+ width = max(width, row_width)+ top -= row_height + 60+ frame.width = width + 70+ frame.height = -top + 30+ return frame.width, frame.height+++def organize_projection_material(material, new_nodes, camera_nodes, cameras, stop_index,+ local_edit=False, feather_method='ORIGINAL'):+ """Arrange only nodes made by this build, preserving earlier edit passes."""+ items = [node for node in new_nodes if node.type != 'FRAME']+ if not items:+ return+ tree = material.node_tree+ nodes, links = tree.nodes, tree.links+ view_items = defaultdict(list)+ global_items = []+ for node in items:+ view = camera_nodes.get(node.as_pointer())+ if view is None:+ global_items.append(node)+ else:+ view_items[view].append(node)++ old_frames = [node for node in nodes if node.type == 'FRAME'+ and node.name.startswith('SG Layout | Projection pass')]+ if old_frames:+ origin_x = max(frame.location_absolute.x + frame.width for frame in old_frames) + 320+ else:+ origin_x = 0+ pass_number = len(old_frames) + 1+ pass_title = (f'Projection pass {pass_number:02d} | Local edit'+ if local_edit else f'Projection pass {pass_number:02d} | Base projection')+ pass_frame = _create_frame(nodes, pass_title, None, origin_x, 0, 600, 400)++ controls = [node for node in global_items+ if node.get('sg_layout_stage') == 'Graph controls']+ control_wiring = [node for node in global_items+ if node.get('sg_layout_stage') == 'Graph control wiring']+ shared = [node for node in global_items if node.label == 'SGMaterialIndex']+ output = [node for node in global_items if node.type == 'OUTPUT_MATERIAL']+ blend_items = [node for node in global_items+ if node not in controls and node not in control_wiring+ and node not in shared and node not in output]++ controls_width = controls_height = 0+ if controls:+ controls_width, controls_height = _arrange_group(+ nodes, links, controls, 'Graph controls', pass_frame, 35, -70)+ wiring_width = wiring_height = 0+ if control_wiring:+ wiring_width, wiring_height = _arrange_group(+ nodes, links, control_wiring, 'Graph control wiring', pass_frame,+ 35 + controls_width + (55 if controls else 0), -70)+ shared_width = shared_height = 0+ if shared:+ shared_width, shared_height = _arrange_group(+ nodes, links, shared, 'Material index', pass_frame,+ 35 + controls_width + wiring_width+ + (55 if controls else 0)+ + (55 if control_wiring else 0), -70)+ view_origin_x = 35 + controls_width + (55 if controls else 0)+ if control_wiring:+ view_origin_x += wiring_width + 55+ if shared:+ view_origin_x += shared_width + 70+ view_right = view_origin_x+ view_top = -70+ for index, camera in enumerate(cameras):+ current = view_items.get(index)+ if not current:+ continue+ stages = defaultdict(list)+ for node in current:+ stages[_view_stage(node)].append(node)+ camera_title = f'View {index + 1:02d} | {camera.name}'+ if index > stop_index:+ camera_title += ' | pending'+ view_frame = _create_frame(nodes, camera_title, pass_frame,+ view_origin_x, view_top, 400, 300)+ section_x, section_height = 35, 0+ for stage in _VIEW_STAGES:+ members = stages.get(stage)+ if not members:+ continue+ width, height = _arrange_group(nodes, links, members, stage,+ view_frame, section_x, -70)+ section_x += width + 45+ section_height = max(section_height, height)+ view_frame.width = section_x + 10+ view_frame.height = section_height + 155+ view_right = max(view_right, view_origin_x + view_frame.width)+ view_top -= view_frame.height + 90++ stage_items = defaultdict(list)+ for node in blend_items:+ stage_items[_blend_stage(node, feather_method)].append(node)+ blend_x = view_right + 120+ blend_height = 0+ for stage in _BLEND_STAGES:+ members = stage_items.get(stage)+ if not members:+ continue+ if stage == 'Boundary crossfade':+ width, height = _arrange_crossfade(+ nodes, links, members, pass_frame, blend_x, -70)+ else:+ width, height = _arrange_group(+ nodes, links, members, stage, pass_frame, blend_x, -70)+ blend_x += width + 60+ blend_height = max(blend_height, height)+ if output:+ width, height = _arrange_group(nodes, links, output, 'Material output',+ pass_frame, blend_x, -70)+ blend_x += width + 40+ blend_height = max(blend_height, height)+ pass_frame.width = max(blend_x + 35, view_right + 60)+ pass_frame.height = max(-view_top + 30, blend_height + 155,+ controls_height + 155, wiring_height + 155,+ shared_height + 155)diff --git a/stablegen/texturing/projection.py b/stablegen/texturing/projection.pyindex 3288fa7..a1ac75a 100644--- a/stablegen/texturing/projection.py+++ b/stablegen/texturing/projection.py@@ -764,12 +764,14 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,clamp_dot2 = nodes.new("ShaderNodeMath")clamp_dot2.operation = 'MINIMUM'+ clamp_dot2.label = f'FacingSignedDot-{i}-{mat_id}'clamp_dot2.location = (x_base + 500, y_base - 150)clamp_dot2.inputs[1].default_value = 1.0links.new(clamp_dot.outputs[0], clamp_dot2.inputs[0])facing_dot = nodes.new("ShaderNodeMath")facing_dot.location = (x_base + 600, y_base - 150)+ facing_raw = facing_dotif getattr(context.scene, 'sg_allow_backface_projection', False):facing_dot.operation = 'ABSOLUTE'links.new(clamp_dot2.outputs[0], facing_dot.inputs[0])@@ -786,6 +788,8 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,links.new(facing_dot.outputs[0], facing_clamp.inputs[0])facing_dot = facing_clamp+ facing_dot.label = f'FacingWeight-{i}-{mat_id}'+acos_node = nodes.new("ShaderNodeMath")acos_node.operation = 'ARCCOSINE'acos_node.location = (x_base + 700, y_base - 150)@@ -833,6 +837,51 @@ def create_native_raycast_visibility(nodes, links, camera, geometry, context, i,links.new(combine2.outputs[0], final_weight.inputs[0])links.new(power_node.outputs[0], final_weight.inputs[1])+ # Presentation metadata only: keep the native graph's large camera math+ # readable without changing any operation, input or connection.+ stage_names = {+ 'Camera basis and frustum': '''+ add_camera_loc subtract normalize_node length_node camera_fov_node+ camera_aspect_node camera_dir_node camera_up_node norm_forward+ cross_fwd_up norm_right cross_right_fwd norm_up_vec neg_forward+ dot_d_right dot_d_up dot_d_neg_fwd cam_z_check fov_half filmw+ filmh neg_cam_z x_proj y_proj shift_x_amount centered_x+ shift_y_amount centered_y abs_x x_in_bounds abs_y y_in_bounds+ frustum_xy frustum_ok''',+ 'Raycast visibility': '''+ raycast threshold_plus hit_dist_plus dist_check occlusion_ok''',+ 'Facing and angle': '''+ dot_d_normal clamp_dot clamp_dot2 facing_raw facing_dot acos_node+ to_degrees angle_check power_node combine1 combine2 final_weight''',+ }+ readable_names = {+ 'add_camera_loc': 'Camera position',+ 'subtract': 'Camera to surface',+ 'normalize_node': 'View direction',+ 'length_node': 'Camera distance',+ 'camera_fov_node': 'Camera field of view',+ 'camera_aspect_node': 'Camera aspect',+ 'camera_dir_node': 'Camera forward',+ 'camera_up_node': 'Camera up',+ 'frustum_ok': 'Inside camera frame',+ 'raycast': 'Raycast to surface',+ 'threshold_plus': 'Ray length tolerance',+ 'hit_dist_plus': 'Hit distance tolerance',+ 'dist_check': 'Target depth matches hit',+ 'occlusion_ok': 'Visible from camera',+ 'dot_d_normal': 'View facing angle',+ 'facing_raw': 'Apply backface setting',+ 'combine1': 'Frustum and occlusion',+ 'combine2': 'Apply discard angle',+ }+ available = locals()+ for stage, names in stage_names.items():+ for name in names.split():+ node = available[name]+ node['sg_layout_stage'] = stage+ if not node.label:+ node.label = readable_names.get(name, name.replace('_', ' ').capitalize())+return (final_weight, subtract, normalize_node, length_node,add_camera_loc, camera_fov_node, camera_aspect_node,camera_dir_node, camera_up_node)@@ -846,6 +895,7 @@ def create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_Returns the feather output node (ShaderNodeMath)."""+ before = {node.as_pointer() for node in nodes}x_base = -400y_base = (-800) * i - 400 # Offset below the raycast nodes@@ -1045,6 +1095,14 @@ def create_native_feather(nodes, links, normalize_node, camera_fov_node, camera_final_feather = cam_z_checkfinal_feather.label = f"Feather-{i}-{mat_id}"+ for node in nodes:+ if node.as_pointer() not in before:+ node['sg_layout_stage'] = 'Frame edge and vignette'+ if not node.label:+ node.label = 'Frame edge ' + (+ node.operation.replace('_', ' ').lower()+ if hasattr(node, 'operation') else node.bl_label.lower())+return final_feather@@ -1784,12 +1842,14 @@ def project_image(if legacy_priority:map_range_node = nodes_collection.new("ShaderNodeMapRange")+ map_range_node.label = f'EarlyPriorityMap-{level}-{i}'map_range_node.location = (x_offset - 400, y_offset + vert_offset)map_range_node.inputs[1].default_value = context.scene.early_priority_strengthlinks.new(div_node.outputs[0], map_range_node.inputs[0])# Create a MixRGB node for color blending of the two inputsmix_node = nodes_collection.new("ShaderNodeMixRGB")+ mix_node.label = f'CameraMix-{level}-{i}'mix_node.location = (x_offset - 200, y_offset + vert_offset)mix_node.use_clamp = True# Connect first color to Color1 and second color to Color2@@ -2016,6 +2076,9 @@ def project_image(mat.use_nodes = Truenodes = mat.node_tree.nodeslinks = mat.node_tree.links+ layout_existing = ({node.as_pointer() for node in nodes}+ if is_local_edit else set())+ layout_camera_nodes = {}previous_node = Noneoutput = None@@ -2125,9 +2188,6 @@ def project_image(output = nodes.new("ShaderNodeOutputMaterial")output.location = (3000, 0)- geometry = nodes.new("ShaderNodeNewGeometry")- geometry.location = (-600, 0)-use_native_raycast = bpy.app.version >= (5, 1, 0)tex_image_nodes = []@@ -2268,7 +2328,13 @@ def project_image(in {'REPLACE_STYLE', 'ADDITIONAL'})+ geometry_nodes = []for i, camera in enumerate(cameras):+ camera_node_start = {node.as_pointer() for node in nodes}+ # Geometry is evaluated at the current shading point. Keeping an+ # instance in each view avoids links spanning every camera row.+ geometry = nodes.new("ShaderNodeNewGeometry")+ geometry_nodes.append(geometry)# Add image texture nodetex_image = nodes.new("ShaderNodeTexImage")if i <= stop_index:@@ -2848,6 +2914,13 @@ def project_image(confidence_quality = accepted_qualityconfidence_quality_nodes.append(confidence_quality)+ # Record ownership only for layout. A local edit can append another+ # complete view pass without touching the older material graph.+ for camera_node in nodes:+ pointer = camera_node.as_pointer()+ if pointer not in camera_node_start:+ layout_camera_nodes[pointer] = i+# Expose a confidence-only max chain for context rendering. This# node does not mix RGB. Continuous weighted blending retains a separate# best-source trust signal to Qwen.@@ -2886,6 +2959,7 @@ def project_image(for i, camera in enumerate(cameras):tex_image = tex_image_nodes[i]uv_map_node = uv_map_nodes[i]+ geometry = geometry_nodes[i]# Connect UV → Texture (needed for both paths)uv_output = "Vector" if uv_map_node.type == 'ATTRIBUTE' else "UV"@@ -2935,6 +3009,24 @@ def project_image(subtract_node.inputs[0].default_value = mat_idsubtract_node.label = 'SGMaterialIndex'subtract_node.location = (-1000, 0)+ from .graph_controls import install_projection_controls+ install_projection_controls(+ mat, context.scene,+ [node for node in nodes if node.as_pointer() not in layout_existing],+ layout_camera_nodes,+ )+ from .node_layout import organize_projection_material+ layout_nodes = [node for node in nodes+ if node.as_pointer() not in layout_existing]+ if is_local_edit and output not in layout_nodes:+ # The output is reused by appended edit passes. Move its frame to+ # the latest pass so the visible graph still ends at the output.+ layout_nodes.append(output)+ organize_projection_material(+ mat, layout_nodes,+ layout_camera_nodes, cameras, stop_index, local_edit=is_local_edit,+ feather_method=getattr(context.scene, 'sg_guard_feather_method', 'ORIGINAL'),+ )return True@@ -3048,6 +3140,10 @@ def reset_projection_material_nodes(material, angle_threshold, exponent):from .surface_blend import updateupdate(material, angle_threshold, exponent)nodes = material.node_tree.nodes+ for key, value in (('discard_angle', angle_threshold), ('exponent', exponent)):+ control = nodes.get('SG Control | ' + key)+ if control is not None and control.type == 'VALUE':+ control.outputs[0].default_value = valuehas_sharp = any(node.type == 'MATH' and node.operation == 'POWER'and node.label.startswith('SharpW-') for node in nodes