-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
common.py
6707 lines (5124 loc) · 212 KB
/
common.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, os, sys, re, numpy, math, pathlib
import bpy_extras.image_utils
from mathutils import *
from bpy.app.handlers import persistent
BLENDER_28_GROUP_INPUT_HACK = False
MAX_VERTEX_DATA = 8
LAYERGROUP_PREFIX = '~yP Layer '
MASKGROUP_PREFIX = '~yP Mask '
INFO_PREFIX = '__yp_info_'
TREE_START = 'Group Input'
TREE_END = 'Group Output'
ONE_VALUE = 'One Value'
ZERO_VALUE = 'Zero Value'
BAKED_PARALLAX = 'Baked Parallax'
BAKED_PARALLAX_FILTER = 'Baked Parallax Filter'
TEXCOORD = 'Texture Coordinate'
GEOMETRY = 'Geometry'
PARALLAX_PREP_SUFFIX = ' Parallax Preparation'
PARALLAX = 'Parallax'
MOD_TREE_START = '__mod_start'
MOD_TREE_END = '__mod_end'
HEIGHT_MAP = 'Height Map'
START_UV = ' Start UV'
DELTA_UV = ' Delta UV'
CURRENT_UV = ' Current UV'
LAYER_VIEWER = '_Layer Viewer'
LAYER_ALPHA_VIEWER = '_Layer Alpha Viewer'
EMISSION_VIEWER = 'Emission Viewer'
ITERATE_GROUP = '~yP Iterate Parallax Group'
PARALLAX_DIVIDER = 4
FLOW_VCOL = '__flow_'
COLOR_ID_VCOL_NAME = '__yp_color_id'
BUMP_MULTIPLY_TWEAK = 5
blend_type_items = (
("MIX", "Mix", ""),
("ADD", "Add", ""),
("SUBTRACT", "Subtract", ""),
("MULTIPLY", "Multiply", ""),
("SCREEN", "Screen", ""),
("OVERLAY", "Overlay", ""),
("DIFFERENCE", "Difference", ""),
("DIVIDE", "Divide", ""),
("DARKEN", "Darken", ""),
("LIGHTEN", "Lighten", ""),
("HUE", "Hue", ""),
("SATURATION", "Saturation", ""),
("VALUE", "Value", ""),
("COLOR", "Color", ""),
("SOFT_LIGHT", "Soft Light", ""),
("LINEAR_LIGHT", "Linear Light", ""),
("DODGE", "Dodge", ""),
("BURN", "Burn", "")
)
mask_blend_type_items = (
("MIX", "Replace", ""),
("ADD", "Add", ""),
("SUBTRACT", "Subtract", ""),
("MULTIPLY", "Multiply", ""),
("SCREEN", "Screen", ""),
("OVERLAY", "Overlay", ""),
("DIFFERENCE", "Difference", ""),
("DIVIDE", "Divide", ""),
("DARKEN", "Darken", ""),
("LIGHTEN", "Lighten", ""),
("HUE", "Hue", ""),
("SATURATION", "Saturation", ""),
("VALUE", "Value", ""),
("COLOR", "Color", ""),
("SOFT_LIGHT", "Soft Light", ""),
("LINEAR_LIGHT", "Linear Light", ""),
("DODGE", "Dodge", ""),
("BURN", "Burn", "")
)
voronoi_feature_items = (
("F1", "F1", "Compute and return the distance to the closest feature point as well as its position and color"),
("F2", "F2", "Compute and return the distance to the second closest feature point as well as its position and color."),
("SMOOTH_F1", "Smooth F1", "Compute and return a smooth version of F1."),
("DISTANCE_TO_EDGE", "Distance to Edge", "Compute and return the distance to the edges of the Voronoi cells."),
("N_SPHERE_RADIUS", "N-Sphere Radius", "Compute and return the radius of the n-sphere inscribed in the Voronoi cells. In other words, it is half the distance between the closest feature point and the feature point closest to it.")
)
def entity_input_items(self, context):
yp = self.id_data.yp
entity = self
m = re.match(r'yp\.layers\[(\d+)\]\.channels\[(\d+)\]', entity.path_from_id())
if m: entity = yp.layers[int(m.group(1))]
items = []
if entity.type not in layer_type_labels:
items.append(('RGB', 'RGB', ''))
items.append(('ALPHA', 'Alpha', ''))
else:
label = layer_type_labels[entity.type]
if is_bl_newer_than(2, 81) and entity.type == 'VORONOI':
items.append(('RGB', label + ' Color', ''))
items.append(('ALPHA', label + ' Distance', ''))
elif entity.type == 'GABOR':
items.append(('RGB', label + ' Value', ''))
items.append(('ALPHA', label + ' Phase', ''))
elif entity.type == 'VCOL':
items.append(('RGB', label, ''))
items.append(('ALPHA', label + ' Alpha', ''))
elif entity.type == 'IMAGE':
items.append(('RGB', label + ' Color', ''))
items.append(('ALPHA', label + ' Alpha', ''))
else:
items.append(('RGB', label + ' Color', ''))
items.append(('ALPHA', label + ' Factor', ''))
return items
COLORID_TOLERANCE = 0.003906 # 1/256
TEMP_UV = '~TL Temp Paint UV'
TANGENT_SIGN_PREFIX = '__tsign_'
neighbor_directions = ['n', 's', 'e', 'w']
normal_blend_items = (
('MIX', 'Mix', ''),
('OVERLAY', 'Add', ''),
('COMPARE', 'Compare Height', '')
)
height_blend_items = (
('REPLACE', 'Replace', ''),
('COMPARE', 'Compare', ''),
('ADD', 'Add', ''),
)
layer_type_items = (
('IMAGE', 'Image', ''),
('BRICK', 'Brick', ''),
('CHECKER', 'Checker', ''),
('GRADIENT', 'Gradient', ''),
('MAGIC', 'Magic', ''),
('MUSGRAVE', 'Musgrave', ''),
('NOISE', 'Noise', ''),
('VORONOI', 'Voronoi', ''),
('WAVE', 'Wave', ''),
('VCOL', 'Vertex Color', ''),
('BACKGROUND', 'Background', ''),
('COLOR', 'Solid Color', ''),
('GROUP', 'Group', ''),
('HEMI', 'Fake Lighting', ''),
('GABOR', 'Gabor', ''),
)
mask_type_items = (
('IMAGE', 'Image', ''),
('BRICK', 'Brick', ''),
('CHECKER', 'Checker', ''),
('GRADIENT', 'Gradient', ''),
('MAGIC', 'Magic', ''),
('MUSGRAVE', 'Musgrave', ''),
('NOISE', 'Noise', ''),
('VORONOI', 'Voronoi', ''),
('WAVE', 'Wave', ''),
('VCOL', 'Vertex Color', ''),
('HEMI', 'Fake Lighting', ''),
('OBJECT_INDEX', 'Object Index', ''),
('COLOR_ID', 'Color ID', ''),
('BACKFACE', 'Backface', ''),
('EDGE_DETECT', 'Edge Detect', ''),
('MODIFIER', 'Modifier', ''),
('GABOR', 'Gabor', ''),
)
channel_override_type_items = (
('DEFAULT', 'Default', ''),
('IMAGE', 'Image', ''),
('BRICK', 'Brick', ''),
('CHECKER', 'Checker', ''),
('GRADIENT', 'Gradient', ''),
('MAGIC', 'Magic', ''),
('MUSGRAVE', 'Musgrave', ''),
('NOISE', 'Noise', ''),
('VORONOI', 'Voronoi', ''),
('WAVE', 'Wave', ''),
('VCOL', 'Vertex Color', ''),
('GABOR', 'Gabor', ''),
)
# Override 1 will only use default value or image for now
channel_override_1_type_items = (
('DEFAULT', 'Default', ''),
('IMAGE', 'Image', ''),
)
hemi_space_items = (
('WORLD', 'World Space', ''),
('OBJECT', 'Object Space', ''),
('CAMERA', 'Camera Space', ''),
)
layer_type_labels = {
'IMAGE' : 'Image',
'BRICK' : 'Brick',
'CHECKER' : 'Checker',
'GRADIENT' : 'Gradient',
'MAGIC' : 'Magic',
'MUSGRAVE' : 'Musgrave',
'NOISE' : 'Noise',
'VORONOI' : 'Voronoi',
'WAVE' : 'Wave',
'VCOL' : 'Vertex Color',
'BACKGROUND' : 'Background',
'COLOR' : 'Solid Color',
'GROUP' : 'Layer Group',
'HEMI' : 'Fake Lighting',
'GABOR' : 'Gabor',
}
bake_type_items = (
('AO', 'Ambient Occlusion', ''),
('POINTINESS', 'Pointiness', ''),
('CAVITY', 'Cavity', ''),
('DUST', 'Dust', ''),
('PAINT_BASE', 'Paint Base', ''),
('BEVEL_NORMAL', 'Bevel Normal', ''),
('BEVEL_MASK', 'Bevel Grayscale', ''),
('MULTIRES_NORMAL', 'Multires Normal', ''),
('MULTIRES_DISPLACEMENT', 'Multires Displacement', ''),
('OTHER_OBJECT_NORMAL', 'Other Objects Normal', ''),
('OTHER_OBJECT_EMISSION', 'Other Objects Emission', ''),
('OTHER_OBJECT_CHANNELS', 'Other Objects Ucupaint Channels', ''),
('SELECTED_VERTICES', 'Selected Vertices/Edges/Faces', ''),
('FLOW', 'Flow Map based on straight UVMap', ''),
)
image_resolution_items = (
('512', "512", 'Create a 512x512 texture image'),
('1024', "1024", 'Create a 1024x1024 texture image'),
('2048', "2048", 'Create a 2048x2048 texture image'),
('4096', "4096", 'Create a 4096x4096 texture image'),
)
channel_override_labels = {
'DEFAULT' : 'Default',
'IMAGE' : 'Image',
'BRICK' : 'Brick',
'CHECKER' : 'Checker',
'GRADIENT' : 'Gradient',
'MAGIC' : 'Magic',
'MUSGRAVE' : 'Musgrave',
'NOISE' : 'Noise',
'VORONOI' : 'Voronoi',
'WAVE' : 'Wave',
'VCOL' : 'Vertex Color',
'HEMI' : 'Fake Lighting',
'GABOR' : 'Gabor',
}
bake_type_labels = {
'AO' : 'Ambient Occlusion',
'POINTINESS': 'Pointiness',
'CAVITY': 'Cavity',
'DUST': 'Dust',
'PAINT_BASE': 'Paint Base',
'BEVEL_NORMAL': 'Bevel Normal',
'BEVEL_MASK': 'Bevel Grayscale',
'MULTIRES_NORMAL': 'Multires Normal',
'MULTIRES_DISPLACEMENT': 'Multires Displacement',
'OTHER_OBJECT_NORMAL': 'Other Objects Normal',
'OTHER_OBJECT_EMISSION': 'Other Objects Emission',
'OTHER_OBJECT_CHANNELS': 'Other Objects Ucupaint Channels',
'SELECTED_VERTICES': 'Selected Vertices',
'FLOW': 'Flow'
}
bake_type_suffixes = {
'AO' : 'AO',
'POINTINESS': 'Pointiness',
'CAVITY': 'Cavity',
'DUST': 'Dust',
'PAINT_BASE': 'Paint Base',
'BEVEL_NORMAL': 'Bevel Normal',
'BEVEL_MASK': 'Bevel Grayscale',
'MULTIRES_NORMAL': 'Normal Multires',
'MULTIRES_DISPLACEMENT': 'Displacement Multires',
'OTHER_OBJECT_NORMAL': 'OO Normal',
'OTHER_OBJECT_EMISSION': 'OO Emission',
'OTHER_OBJECT_CHANNELS': 'OO Channel',
'SELECTED_VERTICES': 'Selected Vertices',
'FLOW': 'Flow'
}
texcoord_lists = [
'Generated',
'Normal',
#'UV',
'Object',
'Camera',
'Window',
'Reflection',
]
texcoord_type_items = (
('Generated', 'Generated', ''),
('Normal', 'Normal', ''),
('UV', 'UV', ''),
('Object', 'Object', ''),
('Camera', 'Camera', ''),
('Window', 'Window', ''),
('Reflection', 'Reflection', ''),
('Decal', 'Decal', ''),
)
mask_texcoord_type_items = (
('Generated', 'Generated', ''),
('Normal', 'Normal', ''),
('UV', 'UV', ''),
('Object', 'Object', ''),
('Camera', 'Camera', ''),
('Window', 'Window', ''),
('Reflection', 'Reflection', ''),
('Decal', 'Decal', ''),
('Layer', 'Use Layer Vector', ''),
)
interpolation_type_items = (
('Linear', 'Linear', 'Linear interpolation.'),
('Closest', 'Closest', 'No interpolation (sample closest texel).'),
('Cubic', 'Cubic', 'Cubic interpolation.'),
)
channel_socket_input_bl_idnames = {
'RGB': 'NodeSocketColor',
'VALUE': 'NodeSocketFloatFactor',
'NORMAL': 'NodeSocketVector',
}
channel_socket_output_bl_idnames = {
'RGB': 'NodeSocketColor',
'VALUE': 'NodeSocketFloat',
'NORMAL': 'NodeSocketVector',
}
possible_object_types = {
'MESH',
'META',
'CURVE',
'CURVES',
'SURFACE',
'FONT'
}
texture_node_types = {
'TEX_IMAGE',
'TEX_BRICK',
'TEX_ENVIRONMENT',
'TEX_CHECKER',
'TEX_GRADIENT',
'TEX_MAGIC',
'TEX_MUSGRAVE',
'TEX_NOISE',
'TEX_POINTDENSITY',
'TEX_SKY',
'TEX_VORONOI',
'TEX_WAVE',
}
layer_node_bl_idnames = {
'IMAGE' : 'ShaderNodeTexImage',
'ENVIRONMENT' : 'ShaderNodeTexEnvironment',
'BRICK' : 'ShaderNodeTexBrick',
'CHECKER' : 'ShaderNodeTexChecker',
'GRADIENT' : 'ShaderNodeTexGradient',
'MAGIC' : 'ShaderNodeTexMagic',
'MUSGRAVE' : 'ShaderNodeTexMusgrave',
'NOISE' : 'ShaderNodeTexNoise',
'POINT_DENSITY' : 'ShaderNodeTexPointDensity',
'SKY' : 'ShaderNodeTexSky',
'VORONOI' : 'ShaderNodeTexVoronoi',
'WAVE' : 'ShaderNodeTexWave',
'VCOL' : 'ShaderNodeAttribute',
'BACKGROUND' : 'NodeGroupInput',
'COLOR' : 'ShaderNodeRGB',
'GROUP' : 'NodeGroupInput',
'HEMI' : 'ShaderNodeGroup',
'OBJECT_INDEX' : 'ShaderNodeGroup',
'COLOR_ID' : 'ShaderNodeGroup',
'BACKFACE' : 'ShaderNodeNewGeometry',
'EDGE_DETECT' : 'ShaderNodeGroup',
'GABOR' : 'ShaderNodeTexGabor',
}
io_suffix = {
'GROUP' : ' Group',
'BACKGROUND' : ' Background',
'ALPHA' : ' Alpha',
'DISPLACEMENT' : ' Displacement',
'HEIGHT' : ' Height',
'MAX_HEIGHT' : ' Max Height',
'VDISP' : ' Vector Displacement',
'HEIGHT_ONS' : ' Height ONS',
'HEIGHT_EW' : ' Height EW',
'UV' : ' UV',
'TANGENT' : ' Tangent',
'BITANGENT' : ' Bitangent',
'HEIGHT_N' : ' Height N',
'HEIGHT_S' : ' Height S',
'HEIGHT_E' : ' Height E',
'HEIGHT_W' : ' Height W',
}
io_names = {
'Generated' : 'Texcoord Generated',
'Object' : 'Texcoord Object',
'Normal' : 'Texcoord Normal',
'Camera' : 'Texcoord Camera',
'Window' : 'Texcoord Window',
'Reflection' : 'Texcoord Reflection',
'Decal' : 'Texcoord Object',
}
math_method_items = (
("ADD", "Add", ""),
("SUBTRACT", "Subtract", ""),
("MULTIPLY", "Multiply", ""),
("DIVIDE", "Divide", ""),
("POWER", "Power", ""),
("LOGARITHM", "Logarithm", ""),
)
vcol_domain_items = (
('POINT', 'Vertex', ''),
('CORNER', 'Face Corner', ''),
)
vcol_data_type_items = (
('FLOAT_COLOR', 'Color', ''),
('BYTE_COLOR', 'Byte Color', ''),
)
limited_mask_blend_types = {
'ADD',
'DIVIDE',
'SCREEN',
'MIX',
'DIFFERENCE',
'LIGHTEN',
'VALUE',
'LINEAR_LIGHT',
}
eraser_names = {
'TEXTURE_PAINT' : 'Eraser Tex',
'VERTEX_PAINT' : 'Eraser Vcol',
'SCULPT' : 'Eraser Paint',
}
rgba_letters = ['r', 'g', 'b', 'a']
nsew_letters = ['n', 's', 'e', 'w']
TEXCOORD_IO_PREFIX = 'Texcoord '
PARALLAX_MIX_PREFIX = 'Parallax Mix '
PARALLAX_DELTA_PREFIX = 'Parallax Delta '
PARALLAX_CURRENT_PREFIX = 'Parallax Current '
PARALLAX_CURRENT_MIX_PREFIX = 'Parallax Current Mix '
CACHE_TANGENT_IMAGE_SUFFIX = '_YP_CACHE_TANGENT'
CACHE_BITANGENT_IMAGE_SUFFIX = '_YP_CACHE_BITANGENT'
GAMMA = 2.2
valid_image_extensions = [".jpg",".gif",".png",".tga", ".jpeg", ".mp4", ".webp"]
def version_tuple(version_string):
return tuple(map(int, version_string.split('.'))) if version_string != '' else (0, 0, 0)
def get_manifest():
import tomllib
# Load manifest file
with open(get_addon_filepath() + 'blender_manifest.toml', 'rb') as f:
manifest = tomllib.load(f)
return manifest
def get_addon_name():
return os.path.basename(os.path.dirname(bpy.path.abspath(__file__)))
def get_addon_title():
if not is_bl_newer_than(4, 2):
bl_info = sys.modules[get_addon_name()].bl_info
return bl_info['name']
manifest = get_manifest()
return manifest['name']
def get_addon_warning():
if not is_bl_newer_than(4, 2):
bl_info = sys.modules[get_addon_name()].bl_info
return bl_info['warning']
return ''
def get_alpha_suffix():
if not is_bl_newer_than(4, 2):
bl_info = sys.modules[get_addon_name()].bl_info
if 'Alpha' in bl_info['warning']:
return ' Alpha'
elif 'Beta' in bl_info['warning']:
return ' Beta'
return ''
def get_current_version_str():
if not is_bl_newer_than(4, 2):
bl_info = sys.modules[get_addon_name()].bl_info
return str(bl_info['version']).replace(', ', '.').replace('(','').replace(')','')
manifest = get_manifest()
return manifest['version']
def get_current_blender_version_str():
return str(bpy.app.version).replace(', ', '.').replace('(','').replace(')','')
def get_current_version():
if not is_bl_newer_than(4, 2):
bl_info = sys.modules[get_addon_name()].bl_info
return bl_info['version']
manifest = get_manifest()
return tuple(map(int, manifest['version'].split('.')))
def is_online():
return not is_bl_newer_than(4, 2) or bpy.app.online_access
def is_bl_newer_than(major, minor=0, patch=0):
return bpy.app.version >= (major, minor, patch)
def is_bl_equal(major, minor=None, patch=None):
if minor == None and patch == None:
return bpy.app.version[0] == major
elif patch == None:
return bpy.app.version[:2] == (major, minor)
else:
return bpy.app.version == (major, minor, patch)
def is_created_before(major, minor=0, patch=0):
return bpy.data.version < (major, minor, patch)
def get_bpytypes():
if not is_bl_newer_than(2, 77):
import bpy_types
return bpy_types.bpy_types
return bpy.types
def get_srgb_name():
names = bpy.types.Image.bl_rna.properties['colorspace_settings'].fixed_type.properties['name'].enum_items.keys()
if 'sRGB' not in names:
# Try 'srgb' prefix
for name in names:
if name.lower().startswith('srgb'):
return name
# Check srgb name by creating new 8-bit image
ypprops = bpy.context.window_manager.ypprops
if ypprops.custom_srgb_name == '':
temp_image = bpy.data.images.new('temmmmp', width=1, height=1, alpha=False, float_buffer=False)
ypprops.custom_srgb_name = temp_image.colorspace_settings.name
remove_datablock(bpy.data.images, temp_image)
return ypprops.custom_srgb_name
return 'sRGB'
def get_noncolor_name():
names = bpy.types.Image.bl_rna.properties['colorspace_settings'].fixed_type.properties['name'].enum_items.keys()
if 'Non-Color' not in names:
# Try 'raw' name
for name in names:
if name.lower() == 'raw':
return name
# Check non-color name by creating new float image
ypprops = bpy.context.window_manager.ypprops
if ypprops.custom_noncolor_name == '':
temp_image = bpy.data.images.new('temmmmp', width=1, height=1, alpha=False, float_buffer=True)
ypprops.custom_noncolor_name = temp_image.colorspace_settings.name
remove_datablock(bpy.data.images, temp_image)
return ypprops.custom_noncolor_name
return 'Non-Color'
def remove_datablock(blocks, block, user=None, user_prop=''):
if is_bl_newer_than(2, 79):
blocks.remove(block)
elif is_bl_newer_than(2, 78):
blocks.remove(block, do_unlink=True)
else:
if user and user_prop != '':
setattr(user, user_prop, None)
if blocks == bpy.data.objects:
# Need to remove object from scene first
objs = get_scene_objects()
if block.name in objs:
objs.unlink(block)
block.user_clear()
blocks.remove(block)
def set_active_object(obj):
if is_bl_newer_than(2, 80):
try: bpy.context.view_layer.objects.active = obj
except: print('EXCEPTIION: Cannot set active object!')
else: bpy.context.scene.objects.active = obj
def link_object(scene, obj, custom_collection=None):
if is_bl_newer_than(2, 80):
if custom_collection:
custom_collection.objects.link(obj)
else: scene.collection.objects.link(obj)
else: scene.objects.link(obj)
def get_object_select(obj):
if is_bl_newer_than(2, 80):
try: return obj.select_get()
except: return False
else: return obj.select
def set_object_select(obj, val):
if is_bl_newer_than(2, 80):
obj.select_set(val)
else: obj.select = val
def set_object_hide(obj, val):
if is_bl_newer_than(2, 80):
obj.hide_set(val)
else: obj.hide = val
def get_scene_objects():
if is_bl_newer_than(2, 80):
return bpy.context.view_layer.objects
else: return bpy.context.scene.objects
def remove_mesh_obj(obj):
data = obj.data
remove_datablock(bpy.data.objects, obj)
remove_datablock(bpy.data.meshes, data)
def get_viewport_shade():
if is_bl_newer_than(2, 80):
return bpy.context.area.spaces[0].shading.type
else: return bpy.context.area.spaces[0].viewport_shade
def get_user_preferences():
if is_bl_newer_than(2, 80):
return bpy.context.preferences.addons[__package__].preferences
return bpy.context.user_preferences.addons[__package__].preferences
def get_operator_description(operator):
if hasattr(operator, 'bl_description'):
description = operator.bl_description
elif hasattr(operator, 'bl_label'):
description = operator.bl_label
else:
return ''
return description + ". Hold Shift for options" if get_user_preferences().skip_property_popups else ""
def get_all_layer_collections(arr, col):
if col not in arr:
arr.append(col)
for c in col.children:
arr = get_all_layer_collections(arr, c)
return arr
def get_object_parent_layer_collections(arr, col, obj):
for o in col.collection.objects:
if o == obj:
if col not in arr: arr.append(col)
if not arr:
for c in col.children:
get_object_parent_layer_collections(arr, c, obj)
if arr: break
if arr:
if col not in arr: arr.append(col)
return arr
def get_node_input_index(node, inp):
index = -1
try: index = [i for i, s in enumerate(node.inputs) if s == inp][0]
except Exception as e: print(e)
return index
def get_active_material(obj=None):
scene = bpy.context.scene
engine = scene.render.engine
if not obj:
if hasattr(bpy.context, 'object'):
obj = bpy.context.object
elif is_bl_newer_than(2, 80):
obj = bpy.context.view_layer.objects.active
if not obj: return None
mat = obj.active_material
if engine in {'BLENDER_RENDER', 'BLENDER_GAME'}:
return None
return mat
def get_material_output(mat):
if mat != None and mat.node_tree:
output = [n for n in mat.node_tree.nodes if n.type == 'OUTPUT_MATERIAL' and n.is_active_output]
if output: return output[0]
return None
def get_list_of_ypaint_nodes(mat):
if not mat.node_tree: return []
yp_nodes = []
for node in mat.node_tree.nodes:
if node.type == 'GROUP' and node.node_tree.yp.is_ypaint_node:
yp_nodes.append(node)
return yp_nodes
def in_active_279_layer(obj):
scene = bpy.context.scene
space = bpy.context.space_data
if space.type == 'VIEW_3D' and space.local_view:
return any([layer for layer in obj.layers_local_view if layer])
else:
return any([layer for i, layer in enumerate(obj.layers) if layer and scene.layers[i]])
def in_renderable_layer_collection(obj):
if is_bl_newer_than(2, 80):
layer_cols = get_object_parent_layer_collections([], bpy.context.view_layer.layer_collection, obj)
if any([lc for lc in layer_cols if lc.collection.hide_render]): return False
return True
else:
return in_active_279_layer(obj)
def is_layer_collection_hidden(obj):
layer_cols = get_object_parent_layer_collections([], bpy.context.view_layer.layer_collection, obj)
if any([lc for lc in layer_cols if lc.collection.hide_viewport]): return True
if any([lc for lc in layer_cols if lc.hide_viewport]): return True
return False
def get_addon_filepath():
return os.path.dirname(bpy.path.abspath(__file__)) + os.sep
def srgb_to_linear_per_element(e):
if e <= 0.03928:
return e / 12.92
else:
return pow((e + 0.055) / 1.055, 2.4)
def linear_to_srgb_per_element(e):
if e > 0.0031308:
return 1.055 * (pow(e, (1.0 / 2.4))) - 0.055
else:
return 12.92 * e
def srgb_to_linear(inp):
if type(inp) == float:
return srgb_to_linear_per_element(inp)
elif type(inp) == Color:
c = inp.copy()
for i in range(3):
c[i] = srgb_to_linear_per_element(c[i])
return c
def linear_to_srgb(inp):
if type(inp) == float:
return linear_to_srgb_per_element(inp)
elif type(inp) == Color:
c = inp.copy()
for i in range(3):
c[i] = linear_to_srgb_per_element(c[i])
return c
def divide_round_i(a, b):
return (2 * a + b) / (2 * b)
def blend_color_mix_byte(src1, src2, intensity1=1.0, intensity2=1.0):
dst = [0.0, 0.0, 0.0, 0.0]
c1 = list(src1)
c2 = list(src2)
c1[3] *= intensity1
c2[3] *= intensity2
if c2[3] != 0.0:
# Multiply first by 255
for i in range(4):
c1[i] *= 255
c2[i] *= 255
# Straight over operation
t = c2[3]
mt = 255 - t
tmp = [0.0, 0.0, 0.0, 0.0]
tmp[0] = (mt * c1[3] * c1[0]) + (t * 255 * c2[0])
tmp[1] = (mt * c1[3] * c1[1]) + (t * 255 * c2[1])
tmp[2] = (mt * c1[3] * c1[2]) + (t * 255 * c2[2])
tmp[3] = (mt * c1[3]) + (t * 255)
dst[0] = divide_round_i(tmp[0], tmp[3])
dst[1] = divide_round_i(tmp[1], tmp[3])
dst[2] = divide_round_i(tmp[2], tmp[3])
dst[3] = divide_round_i(tmp[3], 255)
# Divide it back
for i in range(4):
dst[i] /= 255
else :
# No op
dst[0] = c1[0]
dst[1] = c1[1]
dst[2] = c1[2]
dst[3] = c1[3]
return dst
def copy_id_props(source, dest, extras=[], reverse=False):
bpytypes = get_bpytypes()
props = dir(source)
filters = ['bl_rna', 'rna_type']
filters.extend(extras)
if reverse: props.reverse()
for prop in props:
if prop.startswith('__'): continue
if prop in filters: continue
#if hasattr(prop, 'is_readonly'): continue
try: val = getattr(source, prop)
except:
print('Error prop:', prop)
continue
attr_type = type(val)
if 'bpy_prop_collection_idprop' in str(attr_type):
dest_val = getattr(dest, prop)
for subval in val:
dest_subval = dest_val.add()
copy_id_props(subval, dest_subval, reverse=reverse)
elif hasattr(bpytypes, 'bpy_prop_collection') and attr_type == bpytypes.bpy_prop_collection:
dest_val = getattr(dest, prop)
for i, subval in enumerate(val):
dest_subval = None
if hasattr(dest_val, 'new'):
dest_subval = dest_val.new()
if not dest_subval:
try: dest_subval = dest_val[i]
except: print('Error bpy_prop_collection get by index:', prop)
if dest_subval:
copy_id_props(subval, dest_subval, reverse=reverse)
elif hasattr(bpytypes, 'bpy_prop_array') and attr_type == bpytypes.bpy_prop_array:
dest_val = getattr(dest, prop)
for i, subval in enumerate(val):
dest_val[i] = subval
else:
if getattr(dest, prop) != val:
try: setattr(dest, prop, val)
except: print('Error set prop:', prop)
def copy_node_props_(source, dest, extras=[]):
bpytypes = get_bpytypes()
props = dir(source)
filters = ['rna_type', 'name', 'location', 'parent']
filters.extend(extras)
for prop in props:
if prop.startswith('__'): continue
if prop.startswith('bl_'): continue
if prop in filters: continue
val = getattr(source, prop)
attr_type = type(val)
if 'bpy_func' in str(attr_type): continue
#if 'bpy_prop' in attr_type: continue
#print(prop, str(type(getattr(source, prop))))
# Copy stuff here
#if 'bpy_prop_collection_idprop' in str(attr_type):
# dest_val = getattr(dest, prop)
# for subval in val:
# dest_subval = dest_val.add()
# copy_id_props(subval, dest_subval)
if hasattr(bpytypes, 'bpy_prop_array') and attr_type == bpytypes.bpy_prop_array:
dest_val = getattr(dest, prop)
for i, subval in enumerate(val):
try:
dest_val[i] = subval
except:
pass
else:
if getattr(dest, prop) != val:
try: setattr(dest, prop, val)
except: pass
def copy_node_props(source, dest, extras=[]):
if source.type != dest.type: return
# Copy node props
copy_node_props_(source, dest, extras)
if source.type == 'CURVE_RGB':
# Copy mapping props
copy_node_props_(source.mapping, dest.mapping)
# Copy curve props
for i, curve in enumerate(source.mapping.curves):
curve_copy = dest.mapping.curves[i]
copy_node_props_(curve, curve_copy)
# Copy point props
for j, point in enumerate(curve.points):
if j >= len(curve_copy.points):
point_copy = curve_copy.points.new(point.location[0], point.location[1])
else:
point_copy = curve_copy.points[j]
point_copy.location = (point.location[0], point.location[1])
copy_node_props_(point, point_copy)
# Copy selection
for j, point in enumerate(curve.points):
point_copy = curve_copy.points[j]
point_copy.select = point.select
# Update curve
dest.mapping.update()