-
Notifications
You must be signed in to change notification settings - Fork 82
/
utils.py
2434 lines (1941 loc) · 70.9 KB
/
utils.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
# Copyright (C) 2021 Victor Soupday
# This file is part of CC/iC Blender Tools <https://github.com/soupday/cc_blender_tools>
#
# CC/iC Blender Tools is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CC/iC Blender Tools is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with CC/iC Blender Tools. If not, see <https://www.gnu.org/licenses/>.
import os
import platform
import subprocess
import time
import difflib
import random
import re
import traceback
from mathutils import Vector, Quaternion, Matrix, Euler, Color
from hashlib import md5
import bpy
from . import vars
timer = 0
LOG_INDENT = 0
def log_indent():
global LOG_INDENT
LOG_INDENT += 3
def log_recess():
global LOG_INDENT
LOG_INDENT -= 3
def log_spacing():
return " " * LOG_INDENT
def log_detail(msg):
prefs = vars.prefs()
"""Log an info message to console."""
if prefs.log_level == "DETAILS":
print((" " * LOG_INDENT) + msg)
def log_info(msg):
prefs = vars.prefs()
"""Log an info message to console."""
if prefs.log_level == "ALL" or prefs.log_level == "DETAILS":
print((" " * LOG_INDENT) + msg)
def log_always(msg):
prefs = vars.prefs()
"""Log an info message to console."""
print((" " * LOG_INDENT) + msg)
def log_warn(msg):
prefs = vars.prefs()
"""Log a warning message to console."""
if prefs.log_level == "ALL" or prefs.log_level == "DETAILS" or prefs.log_level == "WARN":
print((" " * LOG_INDENT) + "Warning: " + msg)
def log_error(msg, e: Exception = None):
"""Log an error message to console and raise an exception."""
indent = LOG_INDENT
if indent > 1: indent -= 1
print("*" + (" " * indent) + "Error: " + msg)
if e is not None:
print(" -> " + getattr(e, 'message', repr(e)))
print("Stack Trace: ")
traceback.print_exc()
def start_timer():
global timer
timer = time.perf_counter()
def log_timer(msg, unit = "s"):
prefs = vars.prefs()
global timer
if prefs.log_level == "ALL":
duration = time.perf_counter() - timer
if unit == "ms":
duration *= 1000
elif unit == "us":
duration *= 1000000
elif unit == "ns":
duration *= 1000000000
print(msg + ": " + str(duration) + " " + unit)
def message_box(message = "", title = "Info", icon = 'INFO'):
def draw(self, context):
self.layout.label(text = message)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
def update_ui(context = None, area_type="VIEW_3D", region_type="UI", all=False):
for screen in bpy.data.screens:
for area in screen.areas:
if area.type == area_type or all:
for region in area.regions:
if region.type == region_type or all:
region.tag_redraw()
def report_multi(op, icon = 'INFO', messages = None):
if messages:
text = ""
for msg in messages:
text += msg + " \n"
if text:
op.report({icon}, text)
def message_box_multi(title = "Info", icon = 'INFO', messages = None):
def draw(self, context):
if messages:
for message in messages:
self.layout.label(text = message)
bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)
def unique_name(name, no_version = False):
"""Generate a unique name for the node or property to quickly
identify texture nodes or nodes with parameters."""
props = vars.props()
if no_version:
name = name + "_" + vars.NODE_PREFIX + str(props.node_id)
else:
name = vars.NODE_PREFIX + name + "_" + vars.VERSION_STRING + "_" + str(props.node_id)
props.node_id = props.node_id + 1
return name
def set_ccic_id(obj: bpy.types.Object):
props = vars.props()
obj["ccic_id"] = vars.VERSION_STRING + "_" + str(props.node_id)
props.node_id = props.node_id + 1
def has_ccic_id(obj: bpy.types.Object):
if "ccic_id" in obj:
return True
if vars.NODE_PREFIX in obj.name:
return True
return False
def obj_is_linked(obj):
try:
if obj.library is not None:
return True
except: ...
return False
def obj_is_override(obj):
try:
if obj.override_library is not None:
return True
except: ...
return False
def unique_material_name(name, mat=None, start_index=1):
name = strip_name(name)
index = start_index
if name in bpy.data.materials and bpy.data.materials[name] != mat:
while name + "_" + str(index).zfill(2) in bpy.data.materials:
index += 1
return name + "_" + str(index).zfill(2)
return name
def unique_image_name(name, image=None, start_index=1):
name = strip_name(name)
index = start_index
if name in bpy.data.images and bpy.data.images[name] != image:
while name + "_" + str(index).zfill(2) in bpy.data.images:
index += 1
return name + "_" + str(index).zfill(2)
return name
def unique_object_name(name, obj=None, capitalize=False, start_index=1):
name = strip_name(name)
if capitalize:
name = name.capitalize()
if name in bpy.data.objects and bpy.data.objects[name] != obj:
index = start_index
while name + "_" + str(index).zfill(2) in bpy.data.objects:
index += 1
return name + "_" + str(index).zfill(2)
return name
def un_suffix_name(name):
"""Removes any combination of numerical suffixes from the end of a string"""
base_name = re.sub("([._+|/\,]\d+)*$", "", name)
return base_name
def is_same_path(pa, pb):
try:
if pa and pb:
return os.path.normpath(os.path.realpath(pa)) == os.path.normpath(os.path.realpath(pb))
else:
return False
except:
return False
def is_in_path(a, b):
"""Is path a in path b"""
try:
if a and b:
return os.path.normpath(os.path.realpath(a)) in os.path.normpath(os.path.realpath(b))
else:
return False
except:
return False
def path_is_parent(parent_path, child_path):
try:
parent_path = os.path.abspath(parent_path)
child_path = os.path.abspath(child_path)
return os.path.commonpath([parent_path]) == os.path.commonpath([parent_path, child_path])
except:
return False
def local_repath(path, original_start):
"""Takes the path relative to the original_start and makes
it relative to the blend file location instead.
Returns the full path."""
rel_path = relpath(path, original_start)
return os.path.normpath(bpy.path.abspath(f"//{rel_path}"))
def local_path(path = ""):
"""Get the full path of <path> relative to the blend file. Returns empty if no blend file path."""
if bpy.path.abspath("//"):
abs_path = bpy.path.abspath(f"//{path}")
return os.path.normpath(abs_path)
else:
return ""
def blend_file_name():
file_path = bpy.data.filepath
name = ""
if file_path:
folder, file = os.path.split(file_path)
name, ext = os.path.splitext(file)
return name
def relpath(path, start):
try:
return os.path.relpath(path, start)
except ValueError:
return os.path.abspath(path)
def search_up_path(path, folder):
path = os.path.normpath(path)
dir : str = os.path.dirname(path)
if dir == path or dir == "" or dir is None:
return ""
elif dir.lower().endswith(os.path.sep + folder.lower()):
return dir
return search_up_path(dir, folder)
def object_has_material(obj, name):
name = name.lower()
if obj.type == "MESH":
for mat in obj.data.materials:
if mat and name in mat.name.lower():
return True
return False
def object_exists_is_empty(obj):
"""Test if Object: obj still exists as an object in the scene, and is an empty."""
if obj is None:
return False
try:
name = obj.name
return len(obj.users_scene) > 0 and obj.type == "EMPTY"
except:
return False
def object_exists_is_mesh(obj):
"""Test if Object: obj still exists as an object in the scene, and is a mesh."""
if obj is None:
return False
try:
name = obj.name
return len(obj.users_scene) > 0 and obj.type == "MESH"
except:
return False
def object_exists_is_armature(obj):
"""Test if Object: obj still exists as an object in the scene, and is an armature."""
if obj is None:
return False
try:
name = obj.name
return len(obj.users_scene) > 0 and obj.type == "ARMATURE"
except:
return False
def object_exists_is_light(obj):
"""Test if Object: obj still exists as an object in the scene, and is a light."""
if obj is None:
return False
try:
name = obj.name
return len(obj.users_scene) > 0 and obj.type == "LIGHT"
except:
return False
def object_exists(obj: bpy.types.Object):
"""Test if Object: obj still exists as an object in the scene."""
if obj is None:
return False
try:
name = obj.name
return len(obj.users_scene) > 0
except:
return False
def material_exists(mat: bpy.types.Material):
"""Test if material still exists."""
if mat is None:
return False
try:
name = mat.name
return True
except:
return False
def image_exists(img: bpy.types.Image):
"""Test if material still exists."""
if img is None:
return False
try:
name = img.name
return True
except:
return False
def purge_image(img: bpy.types.Image):
if image_exists(img):
users = img.users - (1 if img.use_extra_user else 0)
if users <= 0:
bpy.data.images.remove(img)
def get_selected_mesh():
if object_exists_is_mesh(get_active_object()):
return get_active_object()
elif bpy.context.selected_objects:
for obj in bpy.context.selected_objects:
if object_exists_is_mesh(obj):
return obj
return None
def get_selected_meshes(context = None):
"""Gets selected meshes and includes any current context mesh"""
objects = [ obj for obj in bpy.context.selected_objects if object_exists_is_mesh(obj) ]
if context and context.object:
if object_exists_is_mesh(context.object):
if context.object not in objects:
objects.append(context.object)
return objects
def get_selected_armatures(context = None):
"""Gets selected armatures and includes any current context armature"""
objects = [ obj for obj in bpy.context.selected_objects if object_exists_is_armature(obj) ]
if context and context.object:
if object_exists_is_armature(context.object):
if context.object not in objects:
objects.append(context.object)
return objects
def safe_remove(item, force = False):
if object_exists(item):
if type(item) == bpy.types.Armature:
if (item.use_fake_user and item.users == 1) or item.users == 0 or force:
log_info("Removing Armature: " + item.name)
bpy.data.armatures.remove(item)
else:
log_info("Armature: " + item.name + " still in use!")
elif type(item) == bpy.types.Mesh:
if (item.use_fake_user and item.users == 1) or item.users == 0 or force:
log_info("Removing Mesh: " + item.name)
bpy.data.meshes.remove(item)
else:
log_info("Mesh: " + item.name + " still in use!")
elif type(item) == bpy.types.Object:
if (item.use_fake_user and item.users == 1) or item.users == 0 or force:
log_info("Removing Object: " + item.name)
bpy.data.objects.remove(item)
else:
log_info("Object: " + item.name + " still in use!")
elif type(item) == bpy.types.Material:
if (item.use_fake_user and item.users == 1) or item.users == 0 or force:
log_info("Removing Material: " + item.name)
bpy.data.materials.remove(item)
else:
log_info("Material: " + item.name + " still in use!")
elif type(item) == bpy.types.Image:
if (item.use_fake_user and item.users == 1) or item.users == 0 or force:
log_info("Removing Image: " + item.name)
bpy.data.images.remove(item)
else:
log_info("Image: " + item.name + " still in use!")
elif type(item) == bpy.types.Texture:
if (item.use_fake_user and item.users == 1) or item.users == 0 or force:
log_info("Removing Texture: " + item.name)
bpy.data.textures.remove(item)
else:
log_info("Texture: " + item.name + " still in use!")
elif type(item) == bpy.types.Action:
if (item.use_fake_user and item.users == 1) or item.users == 0 or force:
log_info("Removing Action: " + item.name)
bpy.data.textures.remove(item)
else:
log_info("Action: " + item.name + " still in use!")
def clean_collection(collection, include_fake = False):
cleaned = False
for item in collection:
if (include_fake and item.use_fake_user and item.users == 1) or item.users == 0:
log_detail(f"Clean Collection Removing: {item}")
collection.remove(item)
cleaned = True
return cleaned
def clean_up_unused():
clean_collection(bpy.data.images)
clean_collection(bpy.data.materials)
clean_collection(bpy.data.textures)
clean_collection(bpy.data.meshes)
clean_collection(bpy.data.armatures)
# as some node_groups are nested...
while clean_collection(bpy.data.node_groups):
clean_collection(bpy.data.node_groups)
def clamp(x, min = 0.0, max = 1.0):
if x < min:
x = min
if x > max:
x = max
return x
def smoothstep(edge0, edge1, x):
x = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0)
return x * x * (3 - 2 * x)
def map_smoothstep(edge0, edge1, value0, value1, x):
if edge1 == edge0:
return value1
x = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0)
t = x * x * (3 - 2 * x)
return value0 + (value1 - value0) * t
def saturate(x):
if x < 0.0:
x = 0.0
if x > 1.0:
x = 1.0
return x
def remap(edge0, edge1, min, max, x):
return min + ((x - edge0) * (max - min) / (edge1 - edge0))
def lerp(v0, v1, t):
t = max(0, min(1, t))
l = v0 + (v1 - v0) * t
return l
def inverse_lerp(vmin, vmax, value):
return min(1.0, max(0.0, (value - vmin) / (vmax - vmin)))
def lerp_color(c0, c1, t):
r = (lerp(c0[0], c1[0], t),
lerp(c0[1], c1[1], t),
lerp(c0[2], c1[2], t),
lerp(c0[3], c1[3], t))
return r
def inverse_lerp_color(min, max, value):
return (inverse_lerp(min[0], max[0], value[0]),
inverse_lerp(min[1], max[1], value[1]),
inverse_lerp(min[2], max[2], value[2]),
inverse_lerp(min[3], max[3], value[3]))
def linear_to_srgbx(x):
if x < 0.0:
return 0.0
elif x < 0.0031308:
return x * 12.92
elif x < 1.0:
return 1.055 * pow(x, 1.0 / 2.4) - 0.055
else:
return pow(x, 5.0 / 11.0)
def linear_to_srgb(color):
return (linear_to_srgbx(color[0]),
linear_to_srgbx(color[1]),
linear_to_srgbx(color[2]),
color[3])
def srgb_to_linearx(x):
if x <= 0.04045:
return x / 12.95
elif x < 1.0:
return pow((x + 0.055) / 1.055, 2.4)
else:
return pow(x, 2.2)
def srgb_to_linear(color):
return (srgb_to_linearx(color[0]),
srgb_to_linearx(color[1]),
srgb_to_linearx(color[2]),
color[3])
def count_maps(*maps):
count = 0
for map in maps:
if map is not None:
count += 1
return count
def key_count(obj: bpy.types.Object):
if obj.data.shape_keys and obj.data.shape_keys.key_blocks:
return len(obj.data.shape_keys.key_blocks)
return 0
def dimensions(x):
try:
l = len(x)
return l
except:
return 1
return 1
def match_dimensions(socket, value):
socket_dimensions = dimensions(socket)
value_dimensions = dimensions(value)
if socket_dimensions == 3 and value_dimensions == 1:
return (value, value, value)
elif socket_dimensions == 2 and value_dimensions == 1:
return (value, value)
else:
return value
def find_pose_bone(chr_cache, *name):
props = vars.props()
arm = chr_cache.get_armature()
for n in name:
if n in arm.pose.bones:
return arm.pose.bones[n]
return None
def find_pose_bone_in_armature(arm, *name):
if (arm.type == "ARMATURE"):
for n in name:
if n in arm.pose.bones:
return arm.pose.bones[n]
return None
def find_edit_bone_in_armature(arm, *name):
if (arm.type == "ARMATURE"):
for n in name:
if n in arm.data.edit_bones:
return arm.data.edit_bones[n]
return None
def get_active_object():
"""Return the actual active object and not the context reference."""
try:
if bpy.context.active_object:
return bpy.data.objects[bpy.context.active_object.name]
except:
pass
return None
def get_active_view_layer_object():
return bpy.context.view_layer.objects.active
def set_active_object(obj, deselect_all = False):
try:
if deselect_all:
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
return (bpy.context.active_object == obj)
except:
return False
def set_only_active_object(obj):
return set_active_object(obj, True)
def set_mode(mode):
try:
if bpy.context.object == None:
if mode != "OBJECT":
log_error("No context object, unable to set any mode but OBJECT!")
return False
return True
else:
if bpy.context.object.mode != mode:
bpy.ops.object.mode_set(mode=mode)
if bpy.context.object.mode != mode:
log_error("Unable to set " + mode + " on object: " + bpy.context.object.name)
return False
return True
except:
return False
def get_mode():
try:
return bpy.context.object.mode
except:
return "OBJECT"
def is_selected_and_active(obj):
return get_active_object() == obj and obj in bpy.context.selected_objects
def is_only_selected_and_active(obj):
return (get_active_object() == obj and
obj in bpy.context.selected_objects and
len(bpy.context.selected_objects) == 1)
def edit_mode_to(obj, only_this = False):
if object_exists(obj):
if only_this and not is_only_selected_and_active(obj):
set_only_active_object(obj)
if is_selected_and_active(obj) and get_mode() == "EDIT":
return True
else:
if set_mode("OBJECT") and set_active_object(obj) and set_mode("EDIT"):
return True
return False
def object_mode():
return set_mode("OBJECT")
def object_mode_to(obj):
if object_exists(obj):
if get_mode() == "OBJECT" and get_active_object() == obj:
return True
if set_mode("OBJECT"):
if try_select_object(obj):
if set_active_object(obj):
return True
return False
def pose_mode_to(arm):
if object_exists_is_armature(arm):
if get_mode() == "POSE" and get_active_object() == arm:
return True
if object_mode_to(arm):
if set_mode("POSE"):
return True
return False
def duplicate_object(obj) -> bpy.types.Object:
if set_mode("OBJECT"):
if try_select_object(obj, True) and set_active_object(obj):
bpy.ops.object.duplicate()
return get_active_object()
return None
def remove_all_shape_keys(obj):
if obj and obj.data.shape_keys and obj.data.shape_keys.key_blocks:
keys = [key for key in obj.data.shape_keys.key_blocks]
keys.reverse() # make sure basis is last to be removed...
for key in keys:
obj.shape_key_remove(key)
def force_object_name(obj, name):
if name in bpy.data.objects:
existing = bpy.data.objects[name]
if existing != obj:
old_name = obj.name
rnd_id = generate_random_id(10)
existing.name = existing.name + "_" + rnd_id
obj.name = name
existing.name = old_name
else:
obj.name = name
def force_mesh_name(mesh, name):
if name in bpy.data.meshes:
existing = bpy.data.meshes[name]
if existing != mesh:
old_name = mesh.name
rnd_id = generate_random_id(10)
existing.name = existing.name + "_" + rnd_id
mesh.name = name
existing.name = old_name
else:
mesh.name = name
def force_armature_name(arm, name):
if name in bpy.data.armatures:
existing = bpy.data.armatures[name]
if existing != arm:
old_name = arm.name
rnd_id = generate_random_id(10)
existing.name = existing.name + "_" + rnd_id
arm.name = name
existing.name = old_name
else:
arm.name = name
def force_material_name(mat, name):
if name in bpy.data.materials:
existing = bpy.data.materials[name]
if existing != mat:
old_name = mat.name
rnd_id = generate_random_id(10)
existing.name = existing.name + "_" + rnd_id
mat.name = name
existing.name = old_name
else:
mat.name = name
def s2lin(x):
a = 0.055
if x <= 0.04045:
y = x * (1.0/12.92)
else:
y = pow((x + a)*(1.0/(1 + a)), 2.4)
return y
def lin2s(x):
a = 0.055
if x <= 0.0031308:
y = x * 12.92
else:
y = (1 + a)*pow(x, 1/2.4) - a
return y
# remove any .001 from the material name
def strip_name(name: str):
if len(name) >= 4:
if name[-3:].isdigit() and name[-4] == ".":
name = name[:-4]
return name
def get_auto_index_suffix(name):
auto_index = 0
try:
if type(name) is not str:
name = name.name
if name[-4] == "|" and name[-3:].isdigit():
auto_index = int(name[-3:])
elif name[-5] == "|" and name[-4:].isdigit():
auto_index = int(name[-4:])
except:
pass
return auto_index
def is_blender_duplicate(name):
if len(name) >= 4:
if (name[-1:].isdigit() and
name[-2:].isdigit() and
name[-3:].isdigit() and
name[-4] == "."):
return True
return False
def get_duplication_suffix(name):
if len(name) >= 4:
if (name[-1:].isdigit() and
name[-2:].isdigit() and
name[-3:].isdigit() and
name[-4] == "."):
return int(name[-3:])
return 0
def make_unique_name_in(name, keys):
""""""
if name in keys:
i = 1
while name + "_" + str(i) in keys:
i += 1
return name + "_" + str(i)
return name
def partial_match(text, search, start = 0):
"""Action names can be truncated so sometimes we have to fall back on partial name matches."""
if text and search:
ls = len(search)
lt = len(text)
if start > -1 and lt > start:
if text[start:] == search:
return True
j = 0
for i in range(start, min(start + ls, lt)):
if text[i] != search[j]:
return False
j += 1
return True
return False
def get_longest_alpha_match(a : str, b : str):
match = difflib.SequenceMatcher(lambda x: x in " 0123456789", a, b).find_longest_match()
if match[2] == 0:
return ""
else:
return a[match[0]:(match[0] + match[2])]
def get_common_name(names):
common_name = names[0]
for i in range(1, len(names)):
common_name = get_longest_alpha_match(common_name, names[i])
while common_name[-1] in "_0123456789":
common_name = common_name[:-1]
return common_name
def get_dot_file_ext(ext):
try:
if ext[0] == ".":
return ext.lower()
else:
return f".{ext}".lower()
except:
return ""
def get_file_ext(ext):
try:
if ext[0] == ".":
return ext[1:].lower()
else:
return ext.lower()
except:
return ""
def is_file_ext(test, ext):
try:
if ext[0] == ".":
ext = ext[1:]
if test[0] == ".":
test = test[1:]
return test.lower() == ext.lower()
except:
return False
def get_set(collection) -> set:
return set(collection)
def get_set_new(collection, old: set) -> list:
current = get_set(collection)
return list(current - old)
def tag_objects():
for obj in bpy.data.objects:
obj.tag = True
def untagged_objects():
untagged = []
for obj in bpy.data.objects:
if obj.tag == False:
untagged.append(obj)
obj.tag = False
return untagged
def tag_materials():
for mat in bpy.data.materials:
if mat:
mat.tag = True
def untagged_materials():
untagged = []
for mat in bpy.data.materials:
if mat and mat.tag == False:
untagged.append(mat)
mat.tag = False
return untagged
def tag_images():
for img in bpy.data.images:
img.tag = True
def untagged_images():
untagged = []
for img in bpy.data.images:
if img.tag == False:
untagged.append(img)
img.tag = False
return untagged
def tag_actions():
for action in bpy.data.actions:
action.tag = True