Newer
Older
bl_description = "Merge Selected Nodes"
bl_options = {'REGISTER', 'UNDO'}
mode = EnumProperty(
name="mode",
description="All possible blend types and math operations",
items=blend_types + [op for op in operations if op not in blend_types],
)
merge_type = EnumProperty(
name="merge type",
description="Type of Merge to be used",
items=(
('AUTO', 'Auto', 'Automatic Output Type Detection'),
('SHADER', 'Shader', 'Merge using ADD or MIX Shader'),
('MIX', 'Mix Node', 'Merge using Mix Nodes'),
('MATH', 'Math Node', 'Merge using Math Nodes'),
('ZCOMBINE', 'Z-Combine Node', 'Merge using Z-Combine Nodes'),
('ALPHAOVER', 'Alpha Over Node', 'Merge using Alpha Over Nodes'),
def execute(self, context):
settings = context.user_preferences.addons[__name__].preferences
merge_hide = settings.merge_hide
merge_position = settings.merge_position # 'center' or 'bottom'
do_hide = False
do_hide_shader = False
if merge_hide == 'ALWAYS':
do_hide = True
do_hide_shader = True
elif merge_hide == 'NON_SHADER':
do_hide = True
tree_type = context.space_data.node_tree.type
if tree_type == 'COMPOSITING':
node_type = 'CompositorNode'
elif tree_type == 'SHADER':
node_type = 'ShaderNode'
elif tree_type == 'TEXTURE':
node_type = 'TextureNode'
nodes, links = get_nodes_links(context)
mode = self.mode
merge_type = self.merge_type
# Prevent trying to add Z-Combine in not 'COMPOSITING' node tree.
# 'ZCOMBINE' works only if mode == 'MIX'
# Setting mode to None prevents trying to add 'ZCOMBINE' node.
if (merge_type == 'ZCOMBINE' or merge_type == 'ALPHAOVER') and tree_type != 'COMPOSITING':
merge_type = 'MIX'
mode = 'MIX'
selected_mix = [] # entry = [index, loc]
selected_shader = [] # entry = [index, loc]
selected_math = [] # entry = [index, loc]
selected_z = [] # entry = [index, loc]
selected_alphaover = [] # entry = [index, loc]
for i, node in enumerate(nodes):
if node.select and node.outputs:
if merge_type == 'AUTO':
for (type, types_list, dst) in (
('SHADER', ('MIX', 'ADD'), selected_shader),
('RGBA', [t[0] for t in blend_types], selected_mix),
('VALUE', [t[0] for t in operations], selected_math),
output_type = node.outputs[0].type
valid_mode = mode in types_list
# When mode is 'MIX' use mix node for both 'RGBA' and 'VALUE' output types.
# Cheat that output type is 'RGBA',
# and that 'MIX' exists in math operations list.
# This way when selected_mix list is analyzed:
# Node data will be appended even though it doesn't meet requirements.
if output_type != 'SHADER' and mode == 'MIX':
output_type = 'RGBA'
valid_mode = True
if output_type == type and valid_mode:
dst.append([i, node.location.x, node.location.y, node.dimensions.x, node.hide])
else:
for (type, types_list, dst) in (
('SHADER', ('MIX', 'ADD'), selected_shader),
('MIX', [t[0] for t in blend_types], selected_mix),
('MATH', [t[0] for t in operations], selected_math),
('ZCOMBINE', ('MIX', ), selected_z),
('ALPHAOVER', ('MIX', ), selected_alphaover),
if merge_type == type and mode in types_list:
dst.append([i, node.location.x, node.location.y, node.dimensions.x, node.hide])
# When nodes with output kinds 'RGBA' and 'VALUE' are selected at the same time
# use only 'Mix' nodes for merging.
# For that we add selected_math list to selected_mix list and clear selected_math.
if selected_mix and selected_math and merge_type == 'AUTO':
selected_mix += selected_math
selected_math = []
for nodes_list in [selected_mix, selected_shader, selected_math, selected_z, selected_alphaover]:
if nodes_list:
count_before = len(nodes)
# sort list by loc_x - reversed
nodes_list.sort(key=lambda k: k[1], reverse=True)
# get maximum loc_x
loc_x = nodes_list[0][1] + nodes_list[0][3] + 70
nodes_list.sort(key=lambda k: k[2], reverse=True)
if merge_position == 'CENTER':
loc_y = ((nodes_list[len(nodes_list) - 1][2]) + (nodes_list[len(nodes_list) - 2][2])) / 2 # average yloc of last two nodes (lowest two)
if nodes_list[len(nodes_list) - 1][-1] == True: # if last node is hidden, mix should be shifted up a bit
if do_hide:
loc_y += 40
else:
loc_y += 80
else:
loc_y = nodes_list[len(nodes_list) - 1][2]
offset_y = 100
if not do_hide:
offset_y = 200
if nodes_list == selected_shader and not do_hide_shader:
offset_y = 150.0
the_range = len(nodes_list) - 1
if len(nodes_list) == 1:
the_range = 1
for i in range(the_range):
if nodes_list == selected_mix:
add_type = node_type + 'MixRGB'
add = nodes.new(add_type)
add.blend_type = mode
if mode != 'MIX':
add.inputs[0].default_value = 1.0
add.show_preview = False
add.hide = do_hide
if do_hide:
loc_y = loc_y - 50
first = 1
second = 2
add.width_hidden = 100.0
elif nodes_list == selected_math:
add_type = node_type + 'Math'
add = nodes.new(add_type)
add.operation = mode
add.hide = do_hide
if do_hide:
loc_y = loc_y - 50
first = 0
second = 1
add.width_hidden = 100.0
elif nodes_list == selected_shader:
if mode == 'MIX':
add_type = node_type + 'MixShader'
add = nodes.new(add_type)
add.hide = do_hide_shader
if do_hide_shader:
loc_y = loc_y - 50
first = 1
second = 2
add.width_hidden = 100.0
elif mode == 'ADD':
add_type = node_type + 'AddShader'
add = nodes.new(add_type)
add.hide = do_hide_shader
if do_hide_shader:
loc_y = loc_y - 50
first = 0
second = 1
add.width_hidden = 100.0
elif nodes_list == selected_z:
add = nodes.new('CompositorNodeZcombine')
add.show_preview = False
add.hide = do_hide
if do_hide:
loc_y = loc_y - 50
first = 0
second = 2
add.width_hidden = 100.0
elif nodes_list == selected_alphaover:
add = nodes.new('CompositorNodeAlphaOver')
add.show_preview = False
add.hide = do_hide
if do_hide:
loc_y = loc_y - 50
first = 1
second = 2
add.width_hidden = 100.0
add.location = loc_x, loc_y
loc_y += offset_y
add.select = True
count_adds = i + 1
count_after = len(nodes)
index = count_after - 1
Bartek Skorupa
committed
first_selected = nodes[nodes_list[0][0]]
# "last" node has been added as first, so its index is count_before.
last_add = nodes[count_before]
# Special case:
# Two nodes were selected and first selected has no output links, second selected has output links.
# Then add links from last add to all links 'to_socket' of out links of second selected.
if len(nodes_list) == 2:
if not first_selected.outputs[0].links:
second_selected = nodes[nodes_list[1][0]]
for ss_link in second_selected.outputs[0].links:
# Prevent cyclic dependencies when nodes to be marged are linked to one another.
# Create list of invalid indexes.
invalid_i = [n[0] for n in (selected_mix + selected_math + selected_shader + selected_z)]
# Link only if "to_node" index not in invalid indexes list.
if ss_link.to_node not in [nodes[i] for i in invalid_i]:
links.new(last_add.outputs[0], ss_link.to_socket)
Bartek Skorupa
committed
# add links from last_add to all links 'to_socket' of out links of first selected.
for fs_link in first_selected.outputs[0].links:
Bartek Skorupa
committed
# Prevent cyclic dependencies when nodes to be marged are linked to one another.
# Create list of invalid indexes.
invalid_i = [n[0] for n in (selected_mix + selected_math + selected_shader + selected_z)]
Bartek Skorupa
committed
# Link only if "to_node" index not in invalid indexes list.
if fs_link.to_node not in [nodes[i] for i in invalid_i]:
links.new(last_add.outputs[0], fs_link.to_socket)
# add link from "first" selected and "first" add node
node_to = nodes[count_after - 1]
links.new(first_selected.outputs[0], node_to.inputs[first])
if node_to.type == 'ZCOMBINE':
for fs_out in first_selected.outputs:
if fs_out != first_selected.outputs[0] and fs_out.name in ('Z', 'Depth'):
links.new(fs_out, node_to.inputs[1])
break
# add links between added ADD nodes and between selected and ADD nodes
for i in range(count_adds):
if i < count_adds - 1:
node_from = nodes[index]
node_to = nodes[index - 1]
node_to_input_i = first
node_to_z_i = 1 # if z combine - link z to first z input
links.new(node_from.outputs[0], node_to.inputs[node_to_input_i])
if node_to.type == 'ZCOMBINE':
for from_out in node_from.outputs:
if from_out != node_from.outputs[0] and from_out.name in ('Z', 'Depth'):
links.new(from_out, node_to.inputs[node_to_z_i])
node_from = nodes[nodes_list[i + 1][0]]
node_to = nodes[index]
node_to_input_i = second
node_to_z_i = 3 # if z combine - link z to second z input
links.new(node_from.outputs[0], node_to.inputs[node_to_input_i])
if node_to.type == 'ZCOMBINE':
for from_out in node_from.outputs:
if from_out != node_from.outputs[0] and from_out.name in ('Z', 'Depth'):
links.new(from_out, node_to.inputs[node_to_z_i])
index -= 1
# set "last" of added nodes as active
Bartek Skorupa
committed
nodes.active = last_add
nodes[i].select = False
return {'FINISHED'}
class NWBatchChangeNodes(Operator, NWBase):
bl_idname = "node.nw_batch_change"
bl_label = "Batch Change"
bl_description = "Batch Change Blend Type and Math Operation"
bl_options = {'REGISTER', 'UNDO'}
blend_type = EnumProperty(
name="Blend Type",
items=blend_types + navs,
)
name="Operation",
items=operations + navs,
)
def execute(self, context):
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
nodes, links = get_nodes_links(context)
blend_type = self.blend_type
operation = self.operation
for node in context.selected_nodes:
if node.type == 'MIX_RGB':
if not blend_type in [nav[0] for nav in navs]:
node.blend_type = blend_type
else:
if blend_type == 'NEXT':
index = [i for i, entry in enumerate(blend_types) if node.blend_type in entry][0]
#index = blend_types.index(node.blend_type)
if index == len(blend_types) - 1:
node.blend_type = blend_types[0][0]
else:
node.blend_type = blend_types[index + 1][0]
if blend_type == 'PREV':
index = [i for i, entry in enumerate(blend_types) if node.blend_type in entry][0]
if index == 0:
node.blend_type = blend_types[len(blend_types) - 1][0]
else:
node.blend_type = blend_types[index - 1][0]
if node.type == 'MATH':
if not operation in [nav[0] for nav in navs]:
node.operation = operation
else:
if operation == 'NEXT':
index = [i for i, entry in enumerate(operations) if node.operation in entry][0]
#index = operations.index(node.operation)
if index == len(operations) - 1:
node.operation = operations[0][0]
else:
node.operation = operations[index + 1][0]
if operation == 'PREV':
index = [i for i, entry in enumerate(operations) if node.operation in entry][0]
#index = operations.index(node.operation)
if index == 0:
node.operation = operations[len(operations) - 1][0]
else:
node.operation = operations[index - 1][0]
return {'FINISHED'}
class NWChangeMixFactor(Operator, NWBase):
bl_idname = "node.nw_factor"
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
bl_label = "Change Factor"
bl_description = "Change Factors of Mix Nodes and Mix Shader Nodes"
bl_options = {'REGISTER', 'UNDO'}
# option: Change factor.
# If option is 1.0 or 0.0 - set to 1.0 or 0.0
# Else - change factor by option value.
option = FloatProperty()
def execute(self, context):
nodes, links = get_nodes_links(context)
option = self.option
selected = [] # entry = index
for si, node in enumerate(nodes):
if node.select:
if node.type in {'MIX_RGB', 'MIX_SHADER'}:
selected.append(si)
for si in selected:
fac = nodes[si].inputs[0]
nodes[si].hide = False
if option in {0.0, 1.0}:
fac.default_value = option
else:
fac.default_value += option
return {'FINISHED'}
class NWCopySettings(Operator, NWBase):
bl_idname = "node.nw_copy_settings"
bl_label = "Copy Settings"
bl_description = "Copy Settings of Active Node to Selected Nodes"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
valid = False
if nw_check(context):
if context.active_node is not None and context.active_node.type is not 'FRAME':
valid = True
return valid
def execute(self, context):
node_active = context.active_node
node_selected = context.selected_nodes
# Error handling
if not (len(node_selected) > 1):
self.report({'ERROR'}, "2 nodes must be selected at least")
return {'CANCELLED'}
# Check if active node is in the selection
selected_node_names = [n.name for n in node_selected]
if node_active.name not in selected_node_names:
self.report({'ERROR'}, "No active node")
return {'CANCELLED'}
# Get nodes in selection by type
valid_nodes = [n for n in node_selected if n.type == node_active.type]
if not (len(valid_nodes) > 1) and node_active:
self.report({'ERROR'}, "Selected nodes are not of the same type as {}".format(node_active.name))
return {'CANCELLED'}
if len(valid_nodes) != len(node_selected):
# Report nodes that are not valid
valid_node_names = [n.name for n in valid_nodes]
not_valid_names = list(set(selected_node_names) - set(valid_node_names))
self.report({'INFO'}, "Ignored {} (not of the same type as {})".format(", ".join(not_valid_names), node_active.name))
orig = node_active
#node_selected_names = [n.name for n in node_selected]
# Output list
success_names = []
# Deselect all nodes
for i in node_selected:
i.select = False
# Code by zeffii from http://blender.stackexchange.com/a/42338/3710
# Run through all other nodes
for node in valid_nodes[1:]:
# Check for frame node
parent = node.parent if node.parent else None
node_loc = [node.location.x, node.location.y]
# Select original to duplicate
orig.select = True
# Duplicate selected node
bpy.ops.node.duplicate()
new_node = context.selected_nodes[0]
# Properties to copy
node_tree = node.id_data
props_to_copy = 'bl_idname name location height width'.split(' ')
# Input and outputs
reconnections = []
mappings = chain.from_iterable([node.inputs, node.outputs])
for i in (i for i in mappings if i.is_linked):
for L in i.links:
reconnections.append([L.from_socket.path_from_id(), L.to_socket.path_from_id()])
# Properties
props = {j: getattr(node, j) for j in props_to_copy}
props_to_copy.pop(0)
for prop in props_to_copy:
setattr(new_node, prop, props[prop])
# Get the node tree to remove the old node
nodes = node_tree.nodes
nodes.remove(node)
new_node.name = props['name']
if parent:
new_node.parent = parent
new_node.location = node_loc
for str_from, str_to in reconnections:
node_tree.links.new(eval(str_from), eval(str_to))
success_names.append(new_node.name)
orig.select = True
node_tree.nodes.active = orig
self.report({'INFO'}, "Successfully copied attributes from {} to: {}".format(orig.name, ", ".join(success_names)))
return {'FINISHED'}
class NWCopyLabel(Operator, NWBase):
bl_idname = "node.nw_copy_label"
bl_label = "Copy Label"
bl_options = {'REGISTER', 'UNDO'}
option = EnumProperty(
name="option",
description="Source of name of label",
items=(
('FROM_ACTIVE', 'from active', 'from active node',),
('FROM_NODE', 'from node', 'from node linked to selected node'),
('FROM_SOCKET', 'from socket', 'from socket linked to selected node'),
)
)
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
def execute(self, context):
nodes, links = get_nodes_links(context)
option = self.option
active = nodes.active
if option == 'FROM_ACTIVE':
if active:
src_label = active.label
for node in [n for n in nodes if n.select and nodes.active != n]:
node.label = src_label
elif option == 'FROM_NODE':
selected = [n for n in nodes if n.select]
for node in selected:
for input in node.inputs:
if input.links:
src = input.links[0].from_node
node.label = src.label
break
elif option == 'FROM_SOCKET':
selected = [n for n in nodes if n.select]
for node in selected:
for input in node.inputs:
if input.links:
src = input.links[0].from_socket
node.label = src.name
break
return {'FINISHED'}
class NWClearLabel(Operator, NWBase):
bl_idname = "node.nw_clear_label"
bl_label = "Clear Label"
bl_options = {'REGISTER', 'UNDO'}
option = BoolProperty()
def execute(self, context):
nodes, links = get_nodes_links(context)
for node in [n for n in nodes if n.select]:
node.label = ''
return {'FINISHED'}
def invoke(self, context, event):
if self.option:
return self.execute(context)
else:
return context.window_manager.invoke_confirm(self, event)
class NWModifyLabels(Operator, NWBase):
"""Modify Labels of all selected nodes"""
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
bl_idname = "node.nw_modify_labels"
bl_label = "Modify Labels"
bl_options = {'REGISTER', 'UNDO'}
prepend = StringProperty(
name="Add to Beginning"
)
append = StringProperty(
name="Add to End"
)
replace_from = StringProperty(
name="Text to Replace"
)
replace_to = StringProperty(
name="Replace with"
)
def execute(self, context):
nodes, links = get_nodes_links(context)
for node in [n for n in nodes if n.select]:
node.label = self.prepend + node.label.replace(self.replace_from, self.replace_to) + self.append
return {'FINISHED'}
def invoke(self, context, event):
self.prepend = ""
self.append = ""
self.remove = ""
return context.window_manager.invoke_props_dialog(self)
class NWAddTextureSetup(Operator, NWBase):
bl_idname = "node.nw_add_texture"
bl_label = "Texture Setup"
bl_description = "Add Texture Node Setup to Selected Shaders"
bl_options = {'REGISTER', 'UNDO'}
add_mapping = BoolProperty(name="Add Mapping Nodes", description="Create coordinate and mapping nodes for the texture (ignored for selected texture nodes)", default=True)
@classmethod
def poll(cls, context):
valid = False
if nw_check(context):
space = context.space_data
if space.tree_type == 'ShaderNodeTree' and context.scene.render.engine == 'CYCLES':
valid = True
return valid
def execute(self, context):
nodes, links = get_nodes_links(context)
shader_types = [x[1] for x in shaders_shader_nodes_props if x[1] not in {'MIX_SHADER', 'ADD_SHADER'}]
texture_types = [x[1] for x in shaders_texture_nodes_props]
selected_nodes = [n for n in nodes if n.select]
for t_node in selected_nodes:
valid = False
input_index = 0
if t_node.inputs:
for index, i in enumerate(t_node.inputs):
if not i.is_linked:
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
input_index = index
break
if valid:
locx = t_node.location.x
locy = t_node.location.y - t_node.dimensions.y/2
xoffset = [500, 700]
is_texture = False
if t_node.type in texture_types + ['MAPPING']:
xoffset = [290, 500]
is_texture = True
coordout = 2
image_type = 'ShaderNodeTexImage'
if (t_node.type in texture_types and t_node.type != 'TEX_IMAGE') or (t_node.type == 'BACKGROUND'):
coordout = 0 # image texture uses UVs, procedural textures and Background shader use Generated
if t_node.type == 'BACKGROUND':
image_type = 'ShaderNodeTexEnvironment'
if not is_texture:
tex = nodes.new(image_type)
tex.location = [locx - 200, locy + 112]
nodes.active = tex
links.new(tex.outputs[0], t_node.inputs[input_index])
t_node.select = False
if self.add_mapping or is_texture:
if t_node.type != 'MAPPING':
m = nodes.new('ShaderNodeMapping')
m.location = [locx - xoffset[0], locy + 141]
m.width = 240
else:
m = t_node
coord = nodes.new('ShaderNodeTexCoord')
coord.location = [locx - (200 if t_node.type == 'MAPPING' else xoffset[1]), locy + 124]
if not is_texture:
links.new(m.outputs[0], tex.inputs[0])
links.new(coord.outputs[coordout], m.inputs[0])
else:
nodes.active = m
links.new(m.outputs[0], t_node.inputs[input_index])
links.new(coord.outputs[coordout], m.inputs[0])
self.report({'WARNING'}, "No free inputs for node: "+t_node.name)
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
class NWAddPrincipledSetup(Operator, NWBase, ImportHelper):
bl_idname = "node.nw_add_textures_for_principled"
bl_label = "Principled Texture Setup"
bl_description = "Add Texture Node Setup for Principled BSDF"
bl_options = {'REGISTER', 'UNDO'}
directory = StringProperty(
name='Directory',
subtype='DIR_PATH',
default='',
description='Folder to search in for image files')
files = CollectionProperty(
type=bpy.types.OperatorFileListElement,
options={'HIDDEN', 'SKIP_SAVE'})
order = [
"filepath",
"files",
]
@classmethod
def poll(cls, context):
valid = False
if nw_check(context):
space = context.space_data
if space.tree_type == 'ShaderNodeTree' and context.scene.render.engine == 'CYCLES':
valid = True
return valid
def execute(self, context):
# Check if everything is ok
if not self.directory:
self.report({'INFO'}, 'No Folder Selected')
return {'CANCELLED'}
if not self.files[:]:
self.report({'INFO'}, 'No Files Selected')
return {'CANCELLED'}
nodes, links = get_nodes_links(context)
active_node = nodes.active
if not active_node.bl_idname == 'ShaderNodeBsdfPrincipled':
self.report({'INFO'}, 'Select Principled BSDF')
return {'CANCELLED'}
# Helper_functions
def split_into__components(fname):
# Split filename into components
# 'WallTexture_diff_2k.002.jpg' -> ['Wall', 'Texture', 'diff', 'k']
# Remove extension
fname = path.splitext(fname)[0]
# Remove digits
fname = ''.join(i for i in fname if not i.isdigit())
# Seperate CamelCase by space
fname = re.sub("([a-z])([A-Z])","\g<1> \g<2>",fname)
# Replace common separators with SPACE
seperators = ['_', '.', '-', '__', '--', '#']
for sep in seperators:
fname = fname.replace(sep, ' ')
components = fname.split(' ')
components = [c.lower() for c in components]
return components
# Filter textures names for texturetypes in filenames
# [Socket Name, [abbreviations and keyword list], Filename placeholder]
tags = context.user_preferences.addons[__name__].preferences.principled_tags
normal_abbr = tags.normal.split(' ')
bump_abbr = tags.bump.split(' ')
gloss_abbr = tags.gloss.split(' ')
rough_abbr = tags.rough.split(' ')
['Displacement', tags.displacement.split(' '), None],
['Base Color', tags.base_color.split(' '), None],
['Subsurface Color', tags.sss_color.split(' '), None],
['Metallic', tags.metallic.split(' '), None],
['Specular', tags.specular.split(' '), None],
['Roughness', rough_abbr + gloss_abbr, None],
['Normal', normal_abbr + bump_abbr, None],
]
# Look through texture_types and set value as filename of first matched file
def match_files_to_socket_names():
for sname in socketnames:
for file in self.files:
fname = file.name
filenamecomponents = split_into__components(fname)
matches = set(sname[1]).intersection(set(filenamecomponents))
# TODO: ignore basename (if texture is named "fancy_metal_nor", it will be detected as metallic map, not normal map)
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
if matches:
sname[2] = fname
break
match_files_to_socket_names()
# Remove socketnames without found files
socketnames = [s for s in socketnames if s[2]
and path.exists(self.directory+s[2])]
if not socketnames:
self.report({'INFO'}, 'No matching images found')
print('No matching images found')
return {'CANCELLED'}
# Add found images
print('\nMatched Textures:')
texture_nodes = []
disp_texture = None
normal_node = None
roughness_node = None
for i, sname in enumerate(socketnames):
print(i, sname[0], sname[2])
# DISPLACEMENT NODES
if sname[0] == 'Displacement':
disp_texture = nodes.new(type='ShaderNodeTexImage')
img = bpy.data.images.load(self.directory+sname[2])
disp_texture.image = img
disp_texture.label = 'Displacement'
disp_texture.color_space = 'NONE'
# Add displacement offset nodes
math_sub = nodes.new(type='ShaderNodeMath')
math_sub.operation = 'SUBTRACT'
math_sub.label = 'Offset'
math_sub.location = active_node.location + Vector((0, -560))
math_mul = nodes.new(type='ShaderNodeMath')
math_mul.operation = 'MULTIPLY'
math_mul.label = 'Strength'
math_mul.location = math_sub.location + Vector((200, 0))
link = links.new(math_mul.inputs[0], math_sub.outputs[0])
link = links.new(math_sub.inputs[0], disp_texture.outputs[0])
# Turn on true displacement in the material
# Too complicated for now
'''
# Frame. Does not update immediatly
# Seems to need an editor redraw
frame = nodes.new(type='NodeFrame')
frame.label = 'Displacement'
math_sub.parent = frame
math_mul.parent = frame
frame.update()
'''
#find ouput node
output_node = [n for n in nodes if n.bl_idname == 'ShaderNodeOutputMaterial']
if output_node:
if not output_node[0].inputs[2].is_linked:
link = links.new(output_node[0].inputs[2], math_mul.outputs[0])
continue
if not active_node.inputs[sname[0]].is_linked:
# No texture node connected -> add texture node with new image
texture_node = nodes.new(type='ShaderNodeTexImage')
img = bpy.data.images.load(self.directory+sname[2])
texture_node.image = img
# NORMAL NODES
if sname[0] == 'Normal':
# Test if new texture node is normal or bump map
fname_components = split_into__components(sname[2])
match_normal = set(normal_abbr).intersection(set(fname_components))
match_bump = set(bump_abbr).intersection(set(fname_components))
if match_normal:
# If Normal add normal node in between
normal_node = nodes.new(type='ShaderNodeNormalMap')
link = links.new(normal_node.inputs[1], texture_node.outputs[0])
elif match_bump:
# If Bump add bump node in between
normal_node = nodes.new(type='ShaderNodeBump')
link = links.new(normal_node.inputs[2], texture_node.outputs[0])
link = links.new(active_node.inputs[sname[0]], normal_node.outputs[0])
normal_node_texture = texture_node
elif sname[0] == 'Roughness':
# Test if glossy or roughness map
fname_components = split_into__components(sname[2])
match_rough = set(rough_abbr).intersection(set(fname_components))
match_gloss = set(gloss_abbr).intersection(set(fname_components))
if match_rough:
# If Roughness nothing to to
link = links.new(active_node.inputs[sname[0]], texture_node.outputs[0])
elif match_gloss:
# If Gloss Map add invert node
invert_node = nodes.new(type='ShaderNodeInvert')
link = links.new(invert_node.inputs[1], texture_node.outputs[0])
link = links.new(active_node.inputs[sname[0]], invert_node.outputs[0])
roughness_node = texture_node
else:
# This is a simple connection Texture --> Input slot
link = links.new(active_node.inputs[sname[0]], texture_node.outputs[0])
# Use non-color for all but 'Base Color' Textures
if not sname[0] in ['Base Color']:
texture_node.color_space = 'NONE'
else:
# If already texture connected. add to node list for alignment
texture_node = active_node.inputs[sname[0]].links[0].from_node
# This are all connected texture nodes
texture_nodes.append(texture_node)
texture_node.label = sname[0]
if disp_texture:
texture_nodes.append(disp_texture)
# Alignment
for i, texture_node in enumerate(texture_nodes):
offset = Vector((-400, (i * -260) + 200))
texture_node.location = active_node.location + offset
if normal_node:
# Extra alignment if normal node was added
normal_node.location = normal_node_texture.location + Vector((200, 0))
if roughness_node:
# Alignment of invert node if glossy map
invert_node.location = roughness_node.location + Vector((200, 0))
# Add texture input + mapping
mapping = nodes.new(type='ShaderNodeMapping')
mapping.location = active_node.location + Vector((-900, 0))
if len(texture_nodes) > 1:
# If more than one texture add reroute node in between
reroute = nodes.new(type='NodeReroute')
tex_coords = Vector((texture_nodes[0].location.x, sum(n.location.y for n in texture_nodes)/len(texture_nodes)))
reroute.location = tex_coords + Vector((-50, -120))
for texture_node in texture_nodes:
link = links.new(texture_node.inputs[0], reroute.outputs[0])
link = links.new(reroute.inputs[0], mapping.outputs[0])
else:
link = links.new(texture_nodes[0].inputs[0], mapping.outputs[0])
# Connect texture_coordiantes to mapping node
texture_input = nodes.new(type='ShaderNodeTexCoord')
texture_input.location = mapping.location + Vector((-200, 0))
link = links.new(mapping.inputs[0], texture_input.outputs[2])
# Just to be sure
active_node.select = False
nodes.update()
links.update()
force_update(context)
return {'FINISHED'}
class NWAddReroutes(Operator, NWBase):
"""Add Reroute Nodes and link them to outputs of selected nodes"""
bl_idname = "node.nw_add_reroutes"
bl_label = "Add Reroutes"
bl_description = "Add Reroutes to Outputs"
bl_options = {'REGISTER', 'UNDO'}
option = EnumProperty(
name="option",
items=[
('ALL', 'to all', 'Add to all outputs'),
('LOOSE', 'to loose', 'Add only to loose outputs'),
('LINKED', 'to linked', 'Add only to linked outputs'),
]
)
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
def execute(self, context):
tree_type = context.space_data.node_tree.type
option = self.option
nodes, links = get_nodes_links(context)
# output valid when option is 'all' or when 'loose' output has no links
valid = False
post_select = [] # nodes to be selected after execution
# create reroutes and recreate links
for node in [n for n in nodes if n.select]:
if node.outputs:
x = node.location.x
y = node.location.y
width = node.width
# unhide 'REROUTE' nodes to avoid issues with location.y
if node.type == 'REROUTE':
node.hide = False
# When node is hidden - width_hidden not usable.
# Hack needed to calculate real width
if node.hide:
bpy.ops.node.select_all(action='DESELECT')
helper = nodes.new('NodeReroute')
helper.select = True
node.select = True
# resize node and helper to zero. Then check locations to calculate width
bpy.ops.transform.resize(value=(0.0, 0.0, 0.0))
width = 2.0 * (helper.location.x - node.location.x)
# restore node location
node.location = x, y
# delete helper
node.select = False
# only helper is selected now
bpy.ops.node.delete()
x = node.location.x + width + 20.0
if node.type != 'REROUTE':
y -= 35.0
y_offset = -22.0
loc = x, y
reroutes_count = 0 # will be used when aligning reroutes added to hidden nodes
for out_i, output in enumerate(node.outputs):
pass_used = False # initial value to be analyzed if 'R_LAYERS'
# if node is not 'R_LAYERS' - "pass_used" not needed, so set it to True
if node.type != 'R_LAYERS':
pass_used = True
else: # if 'R_LAYERS' check if output represent used render pass
node_scene = node.scene
node_layer = node.layer
# If output - "Alpha" is analyzed - assume it's used. Not represented in passes.
if output.name == 'Alpha':
pass_used = True
else:
# check entries in global 'rl_outputs' variable
#for render_pass, output_name, exr_name, in_internal, in_cycles in rl_outputs:
for rlo in rl_outputs:
if output.name == rlo.output_name or output.name == rlo.exr_output_name:
pass_used = getattr(node_scene.render.layers[node_layer], rlo.render_pass)
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
break
if pass_used:
valid = ((option == 'ALL') or
(option == 'LOOSE' and not output.links) or
(option == 'LINKED' and output.links))
# Add reroutes only if valid, but offset location in all cases.
if valid:
n = nodes.new('NodeReroute')
nodes.active = n
for link in output.links:
links.new(n.outputs[0], link.to_socket)
links.new(output, n.inputs[0])
n.location = loc
post_select.append(n)
reroutes_count += 1
y += y_offset
loc = x, y
# disselect the node so that after execution of script only newly created nodes are selected
node.select = False
# nicer reroutes distribution along y when node.hide
if node.hide:
y_translate = reroutes_count * y_offset / 2.0 - y_offset - 35.0
for reroute in [r for r in nodes if r.select]:
reroute.location.y -= y_translate
for node in post_select:
node.select = True
return {'FINISHED'}
class NWLinkActiveToSelected(Operator, NWBase):
"""Link active node to selected nodes basing on various criteria"""
bl_idname = "node.nw_link_active_to_selected"
bl_label = "Link Active Node to Selected"
bl_options = {'REGISTER', 'UNDO'}
replace = BoolProperty()
use_node_name = BoolProperty()
use_outputs_names = BoolProperty()
@classmethod
def poll(cls, context):
valid = False
if nw_check(context):
if context.active_node is not None:
if context.active_node.select:
valid = True
return valid
def execute(self, context):