-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Root.py
4250 lines (3383 loc) · 150 KB
/
Root.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import bpy, time, re
from bpy.props import *
from bpy.app.handlers import persistent
from .common import *
from .subtree import *
from .node_arrangements import *
from .node_connections import *
from . import lib, Modifier, Layer, Mask, transition, Bake, BakeTarget
from .input_outputs import *
YP_GROUP_SUFFIX = ' ' + get_addon_title()
YP_GROUP_PREFIX = get_addon_title() + ' '
channel_socket_types = {
'RGB' : 'RGBA',
'VALUE' : 'VALUE',
'NORMAL' : 'VECTOR',
}
channel_socket_custom_icon_names = {
'RGB' : 'rgb_channel',
'VALUE' : 'value_channel',
'NORMAL' : 'vector_channel',
}
colorspace_items = (
('LINEAR', 'Non-Color Data', ''),
('SRGB', 'Color Data', '')
)
AO_MULTIPLY = 'yP AO Multiply'
def set_input_default_value(group_node, channel, custom_value=None):
#channel = group_node.node_tree.yp.channels[index]
if custom_value:
if channel.type == 'RGB' and len(custom_value) == 3:
custom_value = (custom_value[0], custom_value[1], custom_value[2], 1)
#group_node.inputs[channel.io_index].default_value = custom_value
group_node.inputs[channel.name].default_value = custom_value
return
# Set default value
if channel.type == 'RGB':
#group_node.inputs[channel.io_index].default_value = (1,1,1,1)
group_node.inputs[channel.name].default_value = (1, 1, 1, 1)
if channel.type == 'VALUE':
#group_node.inputs[channel.io_index].default_value = 0.0
group_node.inputs[channel.name].default_value = 0.0
if channel.type == 'NORMAL':
# Use 999 as normal z value so it will fallback to use geometry normal at checking process
#group_node.inputs[channel.io_index].default_value = (999,999,999)
group_node.inputs[channel.name].default_value = (999, 999, 999)
# Update height default value
io_name = channel.name + io_suffix['HEIGHT']
inp = get_tree_input_by_name(group_node.node_tree, io_name)
if inp: group_node.inputs[io_name].default_value = inp.default_value
# Update max height default value
io_name = channel.name + io_suffix['MAX_HEIGHT']
inp = get_tree_input_by_name(group_node.node_tree, io_name)
if inp: group_node.inputs[io_name].default_value = inp.default_value
if channel.enable_alpha:
#group_node.inputs[channel.io_index+1].default_value = 1.0
group_node.inputs[channel.name + io_suffix['ALPHA']].default_value = 1.0
def check_yp_channel_nodes(yp, reconnect=False):
# Link between layers
for layer in yp.layers:
layer_tree = get_tree(layer)
num_difference = len(yp.channels) - len(layer.channels)
if num_difference > 0:
for i in range(num_difference):
# Add new channel
c = layer.channels.add()
elif num_difference < 0:
for i in range(abs(num_difference)):
last_idx = len(layer.channels)-1
# Remove layer channel
layer.channels.remove(channel_idx)
for mask in layer.masks:
num_difference = len(yp.channels) - len(mask.channels)
if num_difference > 0:
for i in range(num_difference):
# Add new channel to mask
mc = mask.channels.add()
elif num_difference < 0:
for i in range(abs(num_difference)):
last_idx = len(mask.channels)-1
# Remove mask channel
mask.channels.remove(channel_idx)
# Check and set mask intensity nodes
transition.check_transition_bump_influences_to_other_channels(layer, layer_tree) #, target_ch=c)
# Set mask multiply nodes
check_mask_mix_nodes(layer, layer_tree)
# Add new nodes
Layer.check_all_layer_channel_io_and_nodes(layer, layer_tree) #, specific_ch=c)
# Check uv maps
check_uv_nodes(yp)
if reconnect:
for layer in yp.layers:
reconnect_layer_nodes(layer)
rearrange_layer_nodes(layer)
reconnect_yp_nodes(yp.id_data)
rearrange_yp_nodes(yp.id_data)
def create_new_group_tree(mat):
#ypup = bpy.context.user_preferences.addons[__name__].preferences
# Group name is based from the material
#group_name = mat.name + YP_GROUP_SUFFIX
group_name = YP_GROUP_PREFIX + mat.name
# Create new group tree
group_tree = bpy.data.node_groups.new(group_name, 'ShaderNodeTree')
group_tree.yp.is_ypaint_node = True
group_tree.yp.version = get_current_version_str()
group_tree.yp.blender_version = get_current_blender_version_str()
group_tree.yp.enable_baked_outside = get_user_preferences().enable_baked_outside_by_default
# Create IO nodes
create_essential_nodes(group_tree, True, True, True)
# Create info nodes
create_info_nodes(group_tree)
return group_tree
def create_new_yp_channel(group_tree, name, channel_type, non_color=True, enable=False):
yp = group_tree.yp
yp.halt_reconnect = True
# Add new channel
channel = yp.channels.add()
channel.name = name
channel.bake_to_vcol_name = 'Baked ' + name
channel.type = channel_type
# Get last index
last_index = len(yp.channels) - 1
# Link new channel
check_yp_channel_nodes(yp)
for layer in yp.layers:
# New channel is disabled in layer by default
layer.channels[last_index].enable = enable
if channel_type in {'RGB', 'VALUE'}:
if non_color:
channel.colorspace = 'LINEAR'
else: channel.colorspace = 'SRGB'
else:
# NOTE: Smooth bump is no longer enabled by default in Blender 2.80+
if is_bl_newer_than(2, 80): channel.enable_smooth_bump = False
yp.halt_reconnect = False
return channel
class YSelectMaterialPolygons(bpy.types.Operator):
bl_idname = "material.y_select_all_material_polygons"
bl_label = "Select All Material Polygons"
bl_description = "Select all polygons using this material"
bl_options = {'REGISTER', 'UNDO'}
new_uv : BoolProperty(
name = 'Create New UV',
description = 'Create new UV rather than using available one',
default = False
)
new_uv_name : StringProperty(
name = 'New UV Name',
description = 'Name of the new UV',
default = 'UVMap'
)
uv_map : StringProperty(
name = 'Active UV Map',
description = "It will create one if other objects don't have it.\nIf empty, it will use the current active uv map for each object",
default = ''
)
set_canvas_to_empty : BoolProperty(
name = 'Set Image Editor to empty',
description = "Set image editor & canvas image to empty, so it's easier to see",
default = True
)
uv_map_coll : CollectionProperty(type=bpy.types.PropertyGroup)
@classmethod
def poll(cls, context):
return context.object
@classmethod
def description(self, context, properties):
return get_operator_description(self)
def invoke(self, context, event):
if not is_bl_newer_than(2, 80):
self.execute(context)
obj = context.object
# Always set new uv to false to avoid unwanted new uv
self.new_uv = False
self.new_uv_name = get_unique_name('UVMap', get_uv_layers(obj))
node = get_active_ypaint_node()
if node: yp = node.node_tree.yp
else: yp = None
# UV Map collections update
self.uv_map = get_default_uv_name(obj, yp)
self.uv_map_coll.clear()
for uv in get_uv_layers(obj):
if not uv.name.startswith(TEMP_UV):
self.uv_map_coll.add().name = uv.name
if get_user_preferences().skip_property_popups and not event.shift:
return self.execute(context)
return context.window_manager.invoke_props_dialog(self, width=400)
def check(self, context):
return True
def draw(self, context):
self.layout.prop(self, "new_uv")
if self.new_uv:
self.layout.prop(self, "new_uv_name")
else:
self.layout.prop_search(self, "uv_map", self, "uv_map_coll", icon='GROUP_UVS')
self.layout.prop(self, "set_canvas_to_empty")
def execute(self, context):
if not is_bl_newer_than(2, 80):
self.report({'ERROR'}, "This feature only works in Blender 2.8+")
return {'CANCELLED'}
if (self.new_uv and self.new_uv_name == '') or (not self.new_uv and self.uv_map == ''):
self.report({'ERROR'}, "UV name cannot be empty!")
return {'CANCELLED'}
obj = context.object
mat = obj.active_material
objs = []
for o in get_scene_objects():
if o.type != 'MESH': continue
if is_layer_collection_hidden(o): continue
if mat.name in o.data.materials:
o.select_set(True)
objs.append(o)
else: o.select_set(False)
bpy.ops.object.mode_set(mode='EDIT')
bpy.context.tool_settings.mesh_select_mode = (False, False, True)
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
uv_name = self.uv_map if not self.new_uv else get_unique_name(self.new_uv_name, get_uv_layers(obj))
for o in objs:
#if uv_name != '':
# Get uv layer
uv_layers = get_uv_layers(o)
uvl = uv_layers.get(uv_name)
# Create one if it didn't exist
if not uvl:
uvl = uv_layers.new(name=uv_name)
uv_layers.active = uvl
active_mat_id = [i for i, m in enumerate(o.data.materials) if m == mat][0]
# Select polygons
for p in o.data.polygons:
if p.material_index == active_mat_id:
p.select = True
else: p.select = False
bpy.ops.object.mode_set(mode='EDIT')
if self.set_canvas_to_empty:
update_image_editor_image(context, None)
set_image_paint_canvas(None)
return {'FINISHED'}
class YRenameUVMaterial(bpy.types.Operator):
bl_idname = "material.y_rename_uv_using_the_same_material"
bl_label = "Rename UV that using same Material"
bl_description = "Rename UV on objects that used the same material"
bl_options = {'REGISTER', 'UNDO'}
uv_map : StringProperty(
name = 'Target UV Map',
description = "Target UV Map that will be renamed",
default = ''
)
uv_map_coll : CollectionProperty(type=bpy.types.PropertyGroup)
new_uv_name : StringProperty(
name = 'New UV Name',
description = 'New name for the UV',
default = 'UVMap'
)
@classmethod
def poll(cls, context):
return context.object
def invoke(self, context, event):
obj = context.object
# Always set new uv to false to avoid unwanted new uv
self.new_uv_name = get_unique_name(self.new_uv_name, get_uv_layers(obj))
node = get_active_ypaint_node()
if node: yp = node.node_tree.yp
else: yp = None
# UV Map collections update
self.uv_map = get_default_uv_name(obj, yp)
self.uv_map_coll.clear()
for uv in get_uv_layers(obj):
if not uv.name.startswith(TEMP_UV):
self.uv_map_coll.add().name = uv.name
return context.window_manager.invoke_props_dialog(self, width=400)
def check(self, context):
return True
def draw(self, context):
self.layout.prop_search(self, "uv_map", self, "uv_map_coll", icon='GROUP_UVS')
self.layout.prop(self, "new_uv_name")
def execute(self, context):
if self.new_uv_name == '' or self.uv_map == '':
self.report({'ERROR'}, "Name cannot be empty!")
return {'CANCELLED'}
obj = context.object
mat = get_active_material()
# Check all uv names available on all objects
#uvls = []
#for obj in bpy.data.objects:
# if obj.type == 'MESH' and any([m for m in obj.data.materials if mat == m]):
# for uvl in get_uv_layers(obj):
# if uvl not in uvls:
# uvls.append(uvl)
#new_uv_name = get_unique_name(self.new_uv_name, uvls)
new_uv_name = self.new_uv_name
for obj in bpy.data.objects:
if obj.type == 'MESH' and any([m for m in obj.data.materials if mat == m]):
uv_layers = get_uv_layers(obj)
new_uvl = uv_layers.get(new_uv_name)
if not new_uvl:
uvl = uv_layers.get(self.uv_map)
if not uvl:
uvl = uv_layers.new(name=new_uv_name)
else:
uvl.name = new_uv_name
# Dealing with yp
node = get_active_ypaint_node()
if node: yp = node.node_tree.yp
else: yp = None
if yp:
# Check baked images uv
if yp.baked_uv_name == self.uv_map:
yp.baked_uv_name = new_uv_name
# Check baked normal channel
for ch in yp.channels:
baked_normal = node.node_tree.nodes.get(ch.baked_normal)
if baked_normal and baked_normal.uv_map == self.uv_map:
baked_normal.uv_map = new_uv_name
# Check layer and masks uv
for layer in yp.layers:
if layer.uv_name == self.uv_map:
layer.uv_name = new_uv_name
for mask in layer.masks:
if mask.uv_name == self.uv_map:
mask.uv_name = new_uv_name
# Check height channel uv
height_ch = get_root_height_channel(yp)
if height_ch and height_ch.main_uv == self.uv_map:
height_ch.main_uv = new_uv_name
return {'FINISHED'}
class YQuickYPaintNodeSetup(bpy.types.Operator):
bl_idname = "node.y_quick_ypaint_node_setup"
bl_label = "Quick " + get_addon_title() + " Node Setup"
bl_description = "Quick " + get_addon_title() + " Node Setup"
bl_options = {'REGISTER', 'UNDO'}
type : EnumProperty(
name = 'Type',
items = (
('BSDF_PRINCIPLED', 'Principled', ''),
('BSDF_DIFFUSE', 'Diffuse', ''),
('EMISSION', 'Emission', ''),
),
default = 'BSDF_PRINCIPLED'
)
color : BoolProperty(name='Color', default=True)
ao : BoolProperty(name='Ambient Occlusion', default=False)
metallic : BoolProperty(name='Metallic', default=True)
roughness : BoolProperty(name='Roughness', default=True)
normal : BoolProperty(name='Normal', default=True)
mute_texture_paint_overlay : BoolProperty(
name = 'Mute Stencil Mask Opacity',
description = 'Set Stencil Mask Opacity found in the 3D Viewport\'s Overlays menu to 0',
default = True
)
use_linear_blending : BoolProperty(
name = 'Use Linear Color Blending',
description = 'Use more accurate linear color blending (it will behave differently than Photoshop)',
default = True
)
switch_to_material_view : BoolProperty(
name = 'Switch to Material View',
description = 'Switch to material view so the node setup is automatically visible',
default = True
)
target_bsdf_name : StringProperty(default='')
not_muted_paint_opacity : BoolProperty(default=False)
not_on_material_view : BoolProperty(default=True)
@classmethod
def poll(cls, context):
return context.object
@classmethod
def description(self, context, properties):
return get_operator_description(self)
def invoke(self, context, event):
space = context.space_data
obj = context.object
mat = get_active_material()
valid_bsdf_types = ['BSDF_PRINCIPLED', 'BSDF_DIFFUSE', 'EMISSION']
# Get target bsdf
self.target_bsdf_name = ''
output = get_material_output(mat)
if output:
bsdf_node = get_closest_bsdf_backward(output, valid_bsdf_types)
if bsdf_node:
self.type = bsdf_node.type
self.target_bsdf_name = bsdf_node.name
# Normal channel does not works to non mesh object
if obj.type != 'MESH':
self.normal = False
self.not_muted_paint_opacity = False
if is_bl_newer_than(2, 80):
for area in context.screen.areas:
if area.type == 'VIEW_3D':
self.not_muted_paint_opacity = area.spaces[0].overlay.texture_paint_mode_opacity > 0.0
break
self.not_on_material_view = space.type == 'VIEW_3D' and ((not is_bl_newer_than(2, 80) and space.viewport_shade not in {'MATERIAL', 'RENDERED'}) or (is_bl_newer_than(2, 80) and space.shading.type not in {'MATERIAL', 'RENDERED'}))
if get_user_preferences().skip_property_popups and not event.shift:
return self.execute(context)
return context.window_manager.invoke_props_dialog(self)
def check(self, context):
return True
def draw(self, context):
row = split_layout(self.layout, 0.35)
col = row.column()
col.label(text='Type:')
if self.type != 'EMISSION':
ccol = col.column(align=True)
ccol.label(text='Channels:')
ccol.label(text='')
if self.type == 'BSDF_PRINCIPLED':
ccol.label(text='')
ccol.label(text='')
ccol.label(text='')
col = row.column()
col.prop(self, 'type', text='')
if self.type != 'EMISSION':
ccol = col.column(align=True)
ccol.prop(self, 'color', toggle=True)
ccol.prop(self, 'ao', toggle=True)
if self.type == 'BSDF_PRINCIPLED':
ccol.prop(self, 'metallic', toggle=True)
ccol.prop(self, 'roughness', toggle=True)
ccol.prop(self, 'normal', toggle=True)
col.prop(self, 'use_linear_blending')
if is_bl_newer_than(2, 80) and self.not_muted_paint_opacity:
col.prop(self, 'mute_texture_paint_overlay')
if self.not_on_material_view:
col.prop(self, 'switch_to_material_view')
def execute(self, context):
obj = context.object
if not obj.data or not hasattr(obj.data, 'materials'):
self.report({'ERROR'}, "Cannot use " + get_addon_title() + " with object '" + obj.name + "'!")
return {'CANCELLED'}
mat = get_active_material()
if not mat:
mat = bpy.data.materials.new(obj.name)
mat.use_nodes = True
if len(obj.material_slots) > 0:
matslot = obj.material_slots[obj.active_material_index]
matslot.material = mat
else:
obj.data.materials.append(mat)
# Remove default nodes
for n in mat.node_tree.nodes:
mat.node_tree.nodes.remove(n)
if not mat.node_tree:
mat.use_nodes = True
# Remove default nodes
for n in mat.node_tree.nodes:
mat.node_tree.nodes.remove(n)
nodes = mat.node_tree.nodes
links = mat.node_tree.links
ao_needed = self.ao and self.type != 'EMISSION'
main_bsdf = None
outsoc = None
ao_mul = None
# If target bsdf is used as main bsdf
target_bsdf = nodes.get(self.target_bsdf_name)
if target_bsdf and target_bsdf.type == self.type:
main_bsdf = target_bsdf
for l in main_bsdf.outputs[0].links:
outsoc = l.to_socket
# Get active material output
output = get_material_output(mat)
loc = Vector((0, 0))
# Create new group node
group_tree = create_new_group_tree(mat)
node = nodes.new(type='ShaderNodeGroup')
node.node_tree = group_tree
node.select = True
nodes.active = node
mat.yp.active_ypaint_node = node.name
# BSDF node
if not main_bsdf:
if self.type == 'BSDF_PRINCIPLED':
if not is_bl_newer_than(2, 79):
main_bsdf = nodes.new('ShaderNodeGroup')
main_bsdf.node_tree = get_node_tree_lib(lib.BL278_BSDF)
else:
main_bsdf = nodes.new('ShaderNodeBsdfPrincipled')
if 'Subsurface Radius' in main_bsdf.inputs:
main_bsdf.inputs['Subsurface Radius'].default_value = (1.0, 0.2, 0.1) # Use eevee default value
if 'Subsurface Color' in main_bsdf.inputs:
main_bsdf.inputs['Subsurface Color'].default_value = (0.8, 0.8, 0.8, 1.0) # Use eevee default value
elif self.type == 'BSDF_DIFFUSE':
main_bsdf = nodes.new('ShaderNodeBsdfDiffuse')
elif self.type == 'EMISSION':
main_bsdf = nodes.new('ShaderNodeEmission')
if output:
loc = output.location.copy()
loc.x += 200
node.location = loc.copy()
loc.x += 200
else:
loc = main_bsdf.location.copy()
# Move away already existing nodes
for n in mat.node_tree.nodes:
# Skip nodes with parents
if n.parent: continue
if n.location.x < loc.x:
if ao_needed: n.location.x -= 400
else: n.location.x -= 200
if ao_needed: loc.x -= 200
loc.x -= 200
node.location = loc.copy()
loc.x += 200
if ao_needed:
ao_mul = simple_new_mix_node(mat.node_tree)
ao_mixcol0, ao_mixcol1, ao_mixout = get_mix_color_indices(ao_mul)
ao_mul.inputs[0].default_value = 1.0
ao_mul.blend_type = 'MULTIPLY'
ao_mul.label = get_addon_title() + ' AO Multiply'
ao_mul.name = AO_MULTIPLY
ao_mul.inputs[0].default_value = 1.0
ao_mul.inputs[ao_mixcol0].default_value = (1.0, 1.0, 1.0, 1.0)
ao_mul.inputs[ao_mixcol1].default_value = (1.0, 1.0, 1.0, 1.0)
ao_mul.location = loc.copy()
loc.x += 200
main_bsdf.location = loc.copy()
if main_bsdf.type == 'BSDF_PRINCIPLED' and is_bl_newer_than(2, 80):
loc.x += 270
else: loc.x += 200
if not outsoc:
# Blender 3.1 has bug which prevent material output changes
if output and bpy.data.version >= (3, 1, 0) and bpy.data.version < (3, 2, 0):
outsoc = output.inputs[0]
output.location = loc.copy()
loc.x += 200
else:
mat_out = nodes.new(type='ShaderNodeOutputMaterial')
mat_out.is_active_output = True
outsoc = mat_out.inputs[0]
mat_out.location = loc.copy()
loc.x += 200
if output:
output.is_active_output = False
links.new(main_bsdf.outputs[0], outsoc)
# Add new channels
ch_color = None
ch_ao = None
ch_metallic = None
ch_roughness = None
ch_normal = None
if self.color:
ch_color = create_new_yp_channel(group_tree, 'Color', 'RGB', non_color=False)
if self.type != 'EMISSION':
if self.ao:
ch_ao = create_new_yp_channel(group_tree, 'Ambient Occlusion', 'RGB', non_color=True)
if self.type == 'BSDF_PRINCIPLED' and self.metallic:
ch_metallic = create_new_yp_channel(group_tree, 'Metallic', 'VALUE', non_color=True)
if self.roughness:
ch_roughness = create_new_yp_channel(group_tree, 'Roughness', 'VALUE', non_color=True)
if self.normal:
ch_normal = create_new_yp_channel(group_tree, 'Normal', 'NORMAL')
# Update io
check_all_channel_ios(group_tree.yp, yp_node=node)
# Update linear blending
if self.use_linear_blending:
group_tree.yp.use_linear_blending = self.use_linear_blending
# HACK: Remap channel pointers, because sometimes pointers are lost at this time
ch_color = group_tree.yp.channels.get('Color')
ch_ao = group_tree.yp.channels.get('Ambient Occlusion')
ch_metallic = group_tree.yp.channels.get('Metallic')
ch_roughness = group_tree.yp.channels.get('Roughness')
ch_normal = group_tree.yp.channels.get('Normal')
if ch_color:
inp = main_bsdf.inputs[0]
# Check original link
for l in inp.links:
links.new(l.from_socket, node.inputs[ch_color.name])
set_input_default_value(node, ch_color, inp.default_value)
if ch_ao and ao_mul:
links.new(node.outputs[ch_color.name], ao_mul.inputs[ao_mixcol0])
links.new(node.outputs[ch_ao.name], ao_mul.inputs[ao_mixcol1])
links.new(ao_mul.outputs[ao_mixout], inp)
else:
links.new(node.outputs[ch_color.name], inp)
if ch_ao:
set_input_default_value(node, ch_ao, (1, 1, 1))
if ch_metallic:
inp = main_bsdf.inputs['Metallic']
# Check original link
for l in inp.links:
links.new(l.from_socket, node.inputs[ch_metallic.name])
set_input_default_value(node, ch_metallic, inp.default_value)
#links.new(node.outputs[ch_metallic.io_index], inp)
links.new(node.outputs[ch_metallic.name], inp)
if ch_roughness:
inp = main_bsdf.inputs['Roughness']
# Check original link
for l in inp.links:
links.new(l.from_socket, node.inputs[ch_roughness.name])
set_input_default_value(node, ch_roughness, inp.default_value)
#links.new(node.outputs[ch_roughness.io_index], inp)
links.new(node.outputs[ch_roughness.name], inp)
if ch_normal:
inp = main_bsdf.inputs['Normal']
# Check original link
for l in inp.links:
links.new(l.from_socket, node.inputs[ch_normal.name])
set_input_default_value(node, ch_normal)
#links.new(node.outputs[ch_normal.io_index], inp)
links.new(node.outputs[ch_normal.name], inp)
# Disable overlay in Blender 2.8
for area in context.screen.areas:
if area.type == 'VIEW_3D':
if is_bl_newer_than(2, 80) and self.not_muted_paint_opacity and self.mute_texture_paint_overlay:
area.spaces[0].overlay.texture_paint_mode_opacity = 0.0
area.spaces[0].overlay.vertex_paint_mode_opacity = 0.0
if self.not_on_material_view and self.switch_to_material_view:
if not is_bl_newer_than(2, 80):
area.spaces[0].viewport_shade = 'MATERIAL'
else: area.spaces[0].shading.type = 'MATERIAL'
# Expand channels now is enabled by default if it's the only yp node
if len([ng for ng in bpy.data.node_groups if hasattr(ng, 'yp') and ng.yp.is_ypaint_node]) == 1:
context.window_manager.ypui.expand_channels = True
# Update UI
context.window_manager.ypui.need_update = True
return {'FINISHED'}
class YNewYPaintNode(bpy.types.Operator):
bl_idname = "node.y_add_new_ypaint_node"
bl_label = "Add new " + get_addon_title() + " Node"
bl_description = "Add new " + get_addon_title() + " node"
bl_options = {'REGISTER', 'UNDO'}
@staticmethod
def store_mouse_cursor(context, event):
space = context.space_data
tree = space.edit_tree
# convert mouse position to the View2D for later node placement
if context.region.type == 'WINDOW':
# convert mouse position to the View2D for later node placement
space.cursor_location_from_region(event.mouse_region_x, event.mouse_region_y)
else:
space.cursor_location = tree.view_center
@classmethod
def poll(cls, context):
space = context.space_data
# needs active node editor and a tree to add nodes to
return (
space.type == 'NODE_EDITOR' and
space.edit_tree and
not space.edit_tree.library
)
def execute(self, context):
space = context.space_data
tree = space.edit_tree
mat = space.id
ypui = context.window_manager.ypui
# select only the new node
for n in tree.nodes:
n.select = False
# Create new group tree
group_tree = create_new_group_tree(mat)
yp = group_tree.yp
# Add new channel
channel = create_new_yp_channel(group_tree, 'Color', 'RGB', non_color=False)
# Check channel io
check_all_channel_ios(yp)
# Create new group node
node = tree.nodes.new(type='ShaderNodeGroup')
node.node_tree = group_tree
# Select new node
node.select = True
tree.nodes.active = node
# Set default input value
set_input_default_value(node, channel)
# Linear blending is on by default
yp.use_linear_blending = True
# Set the location of new node
node.location = space.cursor_location
# Expand channels now is enabled by default if it's the only yp node
if len([ng for ng in bpy.data.node_groups if hasattr(ng, 'yp') and ng.yp.is_ypaint_node]) == 1:
context.window_manager.ypui.expand_channels = True
# Update UI
context.window_manager.ypui.need_update = True
return {'FINISHED'}
# Default invoke stores the mouse position to place the node correctly
# and optionally invokes the transform operator
def invoke(self, context, event):
self.store_mouse_cursor(context, event)
result = self.execute(context)
if 'FINISHED' in result:
# Removes the node again if transform is canceled
bpy.ops.node.translate_attach_remove_on_cancel('INVOKE_DEFAULT')
return result
def new_channel_items(self, context):
items = [
('VALUE', 'Value', '', lib.get_icon(lib.channel_custom_icon_dict['VALUE']), 0),
('RGB', 'RGB', '', lib.get_icon(lib.channel_custom_icon_dict['RGB']), 1),
('NORMAL', 'Normal', '', lib.get_icon(lib.channel_custom_icon_dict['NORMAL']), 2)
]
return items
class YPaintNodeInputCollItem(bpy.types.PropertyGroup):
name : StringProperty(default='')
node_name : StringProperty(default='')
input_name : StringProperty(default='')
input_index : IntProperty(default=0)
def update_connect_to(self, context):
yp = get_active_ypaint_node().node_tree.yp
item = self.input_coll.get(self.connect_to)
if item:
self.name = get_unique_name(item.input_name, yp.channels)
# Emission will not use clamp by default
if 'Emission' in self.name:
self.use_clamp = False
else: self.use_clamp = True
def refresh_input_coll(self, context, ch_type):
# Refresh input names
self.input_coll.clear()
mat = get_active_material()
nodes = mat.node_tree.nodes
yp_node = get_active_ypaint_node()
for node in nodes:
if node == yp_node: continue
for i, inp in enumerate(node.inputs):
if ch_type == 'VALUE' and inp.type != 'VALUE': continue
elif ch_type == 'RGB' and inp.type not in {'RGBA', 'VECTOR'}: continue
elif ch_type == 'NORMAL' and 'Normal' not in inp.name: continue
if len(inp.links) > 0 : continue
label = inp.name + ' (' + node.name +')'
item = self.input_coll.add()
item.name = label
item.node_name = node.name
item.input_name = inp.name
item.input_index = i
def do_alpha_setup(mat, node, channel):
tree = mat.node_tree
yp = node.node_tree.yp
input_index = channel.io_index
alpha_input = node.inputs[input_index+1]
output_index = get_output_index(channel)
output = node.outputs[output_index]
alpha_output = node.outputs[output_index+1]
# Main channel output need to be already connected
if len(output.links) == 0:
return
alpha_input_connected = len(alpha_input.links) > 0
new_nodes_created = False
for i, l in enumerate(output.links):
if is_valid_bsdf_node(l.to_node) or l.to_node.type == 'OUTPUT_MATERIAL':
target_node = l.to_node
else: target_node = get_closest_bsdf_forward(l.to_node)
if not target_node: continue
target_socket = None
# Connect to alpha input if target node has one
if 'Alpha' in target_node.inputs:
target_socket = target_node.inputs['Alpha']
# Search for transparent and mix bsdf
if not target_socket and len(target_node.outputs) > 0:
# Check if target node is mix and has transparent bsdf connected to it
if target_node.type == 'MIX_SHADER':
if len(target_node.inputs[1].links) > 0 and target_node.inputs[1].links[0].from_node.type == 'BSDF_TRANSPARENT':
target_socket = target_node.inputs[0]
if not target_socket:
# Check if node following target node is mix and has transparent bsdf connected to it
for l in target_node.outputs[0].links:
if l.to_node.type == 'MIX_SHADER':
for n in l.to_node.inputs[1].links:
if n.from_node.type == 'BSDF_TRANSPARENT':
target_socket = l.to_node.inputs[0]
# Create new transparent and mix bsdf if target node is BSDF
if not target_socket and not new_nodes_created and any([o for o in target_node.outputs if o.type == 'SHADER']):
# Shift some nodes to the right
for n in tree.nodes:
if n.location.x > target_node.location.x and n.location.x < target_node.location.x + 350:
n.location.x += 200
mix_bsdf = tree.nodes.new('ShaderNodeMixShader')
mix_bsdf.location = (target_node.location.x + 200, target_node.location.y)
mix_bsdf.inputs[0].default_value = 1.0
transp_bsdf = tree.nodes.new('ShaderNodeBsdfTransparent')
transp_bsdf.location = (target_node.location.x, target_node.location.y + 100)
final_sockets = []
if len(target_node.outputs) > 0:
final_sockets = [l.to_socket for l in target_node.outputs[0].links]
tree.links.new(target_node.outputs[0], mix_bsdf.inputs[2])
tree.links.new(transp_bsdf.outputs[0], mix_bsdf.inputs[1])
target_socket = mix_bsdf.inputs[0]
if final_sockets:
tree.links.new(mix_bsdf.outputs[0], final_sockets[0])
new_nodes_created = True