forked from animate1978/MB-Lab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithms.py
1457 lines (1098 loc) · 43.4 KB
/
algorithms.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
# MB-Lab
# MB-Lab fork website : https://github.com/animate1978/MB-Lab
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import logging
import itertools
import random
import time
import os
import json
import array
import mathutils
import bpy
from .utils import get_object_parent
logger = logging.getLogger(__name__)
DEBUG_LEVEL = 3
def print_log_report(level, text_to_write):
import warnings
warnings.warn("print_log_report deprecated, use python logging", DeprecationWarning)
l = 0
levels = {"INFO": 0, "DEBUG": 1, "WARNING": 2, "ERROR": 3, "CRITICAL": 4, }
if level in levels:
l = levels[level]
if l >= DEBUG_LEVEL:
print(level + ": " + text_to_write)
def is_writeable(filepath):
try:
with open(filepath, 'w'):
return True
except IOError:
logger.warning("Writing permission denied for %s", filepath)
return False
def get_data_path():
addon_directory = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.join(addon_directory, "data")
logger.info("Looking for the retarget data in the folder %s...", simple_path(data_dir))
if not os.path.isdir(data_dir):
logger.critical("Tools data not found. Please check your Blender addons directory.")
return None
return data_dir
def get_configuration():
data_path = get_data_path()
if data_path:
configuration_path = os.path.join(data_path, "characters_config.json")
if os.path.isfile(configuration_path):
return load_json_data(configuration_path, "Characters definition")
logger.critical("Configuration database not found. Please check your Blender addons directory.")
return None
def get_blendlibrary_path():
data_path = get_data_path()
if data_path:
return os.path.join(data_path, "humanoid_library.blend")
logger.critical("Models library not found. Please check your Blender addons directory.")
return None
def simple_path(input_path, use_basename=True, max_len=50):
"""
Return the last part of long paths
"""
if use_basename:
return os.path.basename(input_path)
if len(input_path) > max_len:
return f"[Trunked]..{input_path[len(input_path)-max_len:]}"
return input_path
def json_booleans_to_python(value):
return value == 0
def quick_dist(p_1, p_2):
return ((p_1[0]-p_2[0])**2) + ((p_1[1]-p_2[1])**2) + ((p_1[2]-p_2[2])**2)
def full_dist(vert1, vert2, axis="ALL"):
v1 = mathutils.Vector(vert1)
v2 = mathutils.Vector(vert2)
if axis not in {"X", "Y", "Z"}:
v3 = v1 - v2
return v3.length
if axis == "X":
return abs(v1[0]-v2[0])
if axis == "Y":
return abs(v1[1]-v2[1])
# if axis == "Z":
return abs(v1[2]-v2[2])
def exists_database(lib_path):
result = False
if simple_path(lib_path) != "":
if os.path.isdir(lib_path):
if os.listdir(lib_path):
for database_file in os.listdir(lib_path):
_, extension = os.path.splitext(database_file)
if "json" in extension or "bvh" in extension:
result = True
else:
logger.warning("Unknow file extension in %s", simple_path(lib_path))
else:
logger.warning("data path %s not found", simple_path(lib_path))
return result
# TODO: This may be the data input we are looking for?
def length_of_strip(vertices_coords, indices, axis="ALL"):
strip_length = 0
for x in range(len(indices)-1):
v1 = vertices_coords[indices[x]]
v2 = vertices_coords[indices[x+1]]
strip_length += full_dist(v1, v2, axis)
return strip_length
def function_modifier_a(val_x):
return 2 * val_x - 1 if val_x > 0.5 else 0.0
def function_modifier_b(val_x):
return 1-2 * val_x if val_x < 0.5 else 0.0
def bounding_box(verts_coo, indices, roundness=4):
val_x, val_y, val_z = [], [], []
for idx in indices:
if len(verts_coo) > idx:
val_x.append(verts_coo[idx][0])
val_y.append(verts_coo[idx][1])
val_z.append(verts_coo[idx][2])
else:
logger.warning("Error in calculating bounding box: index %s not in verts_coo (len(verts_coo) = %s)",
idx, len(verts_coo))
return None
box_x = round(max(val_x)-min(val_x), roundness)
box_y = round(max(val_y)-min(val_y), roundness)
box_z = round(max(val_z)-min(val_z), roundness)
return (box_x, box_y, box_z)
def get_bounding_box(v_coords):
if v_coords:
val_x, val_y, val_z = [], [], []
for coord in v_coords:
val_x.append(coord[0])
val_y.append(coord[1])
val_z.append(coord[2])
box_x = max(val_x)-min(val_x)
box_y = max(val_y)-min(val_y)
box_z = max(val_z)-min(val_z)
return (box_x, box_y, box_z)
return None
def load_bbox_data(filepath):
bboxes = []
database_file = open(filepath, "r")
for line in database_file:
bboxes.append(line.split())
database_file.close()
bbox_data_dict = {}
for x_data in bboxes:
bbox_data_dict[x_data[0]] = [
int(x_data[1]),
int(x_data[2]),
int(x_data[3]),
int(x_data[4]),
int(x_data[5]),
int(x_data[6]),
]
return bbox_data_dict
def smart_combo(prefix, morph_values):
tags = []
names = []
weights = []
max_morph_values = []
# Compute the combinations and get the max values
for v_data in morph_values:
tags.append(["max", "min"])
max_morph_values.append(max(v_data))
for n_data in itertools.product(*tags):
names.append(prefix+"_"+'-'.join(n_data))
# Compute the weight of each combination
for n_data in itertools.product(*morph_values):
weights.append(sum(n_data))
factor = max(max_morph_values)
best_val = max(weights)
toll = 1.5
# Filter on bestval and calculate the normalize factor
summ = 0.0
for i, weight in enumerate(weights):
new = max(0, weight - best_val / toll)
summ += new
weights[i] = new
# Normalize using summ
# FIXME: this is bad idea as
# >>> (1.0/3) * 3 == 0.0
# False
if summ != 0:
for i in range(len(weights)):
weights[i] = factor*(weights[i]/summ)
return (names, weights)
def is_excluded(property_name, excluded_properties):
for excluded_property in excluded_properties:
if excluded_property in property_name:
return True
return False
def generate_parameter(val, random_value, preserve_phenotype=False):
if preserve_phenotype:
if val > 0.5:
if val > 0.8:
new_value = 0.8 + 0.2*random.random()
else:
new_value = 0.5+random.random()*random_value
else:
if val < 0.2:
new_value = 0.2*random.random()
else:
new_value = 0.5-random.random()*random_value
else:
if random.random() > 0.5:
new_value = min(1.0, 0.5+random.random()*random_value)
else:
new_value = max(0.0, 0.5-random.random()*random_value)
return new_value
def polygon_forma(list_of_verts):
form_factors = []
for idx in range(len(list_of_verts)):
index_a = idx
index_b = idx-1
index_c = idx+1
if index_c > len(list_of_verts)-1:
index_c = 0
p_a = list_of_verts[index_a]
p_b = list_of_verts[index_b]
p_c = list_of_verts[index_c]
v_1 = p_b-p_a
v_2 = p_c-p_a
v_1.normalize()
v_2.normalize()
factor = v_1.dot(v_2)
form_factors.append(factor)
return form_factors
def average_center(verts_coords):
n_verts = len(verts_coords)
bcenter = mathutils.Vector((0.0, 0.0, 0.0))
if n_verts != 0:
for v_coord in verts_coords:
bcenter += v_coord
bcenter = bcenter/n_verts
return bcenter
def linear_interpolation_y(xa, xb, ya, yb, y):
return (((xa-xb)*y)+(xb*ya)-(xa*yb))/(ya-yb)
def correct_morph(base_form, current_form, morph_deltas, bboxes):
time1 = time.time()
new_morph_deltas = []
for d_data in morph_deltas:
idx = d_data[0]
if str(idx) in bboxes:
indices = bboxes[str(idx)]
current_bounding_box = bounding_box(current_form, indices)
if current_bounding_box:
base_bounding_box = bounding_box(base_form, indices)
if base_bounding_box:
if base_bounding_box[0] != 0:
scale_x = current_bounding_box[0]/base_bounding_box[0]
else:
scale_x = 1
if base_bounding_box[1] != 0:
scale_y = current_bounding_box[1]/base_bounding_box[1]
else:
scale_y = 1
if base_bounding_box[2] != 0:
scale_z = current_bounding_box[2]/base_bounding_box[2]
else:
scale_z = 1
delta_x = d_data[1][0] * scale_x
delta_y = d_data[1][1] * scale_y
delta_z = d_data[1][2] * scale_z
newd = mathutils.Vector((delta_x, delta_y, delta_z))
new_morph_deltas.append([idx, newd])
else:
new_morph_deltas.append(d_data)
logger.warning("Index %s not in bounding box database", idx)
logger.info("Morphing corrected in %s secs", time.time()-time1)
return new_morph_deltas
def check_version(m_vers, min_version=(1, 5, 0)):
# m_vers can be a list, tuple, IDfloatarray or str
# so it must be converted in a list.
if not isinstance(m_vers, str):
m_vers = list(m_vers)
mesh_version = str(m_vers)
mesh_version = mesh_version.replace(' ', '')
mesh_version = mesh_version.strip("[]()")
if len(mesh_version) < 5:
logger.warning("The current humanoid has wrong format for version")
return False
mesh_version = (float(mesh_version[0]), float(mesh_version[2]), float(mesh_version[4]))
return mesh_version > min_version
def looking_for_humanoid_obj():
"""
Looking for a mesh that is OK for the lab
"""
logger.info("Looking for an humanoid object...")
if bpy.app.version < (2, 78, 0):
msg = "Sorry, the lab requires official Blender 2.78 or 2.79."
logger.warning(msg)
return("ERROR", msg)
# if bpy.app.version >= (2,80,0):
# msg = "Sorry, this version of lab does no work with Blender 2.8"
# logger.warning(sg)
# return("ERROR",msg)
# if bpy.app.version > (2,79,0):
# msg = "The lab is not designed to work with unstable Blender build {0}".format(str(bpy.app.version))
# logger.warning(sg)
# return("ERROR",msg)
human_obj = None
name = ""
for obj in bpy.data.objects:
if obj.type == "MESH":
if "manuellab_vers" in get_object_keys(obj):
if check_version(obj["manuellab_vers"]):
human_obj = obj
name = human_obj.name
break
if not human_obj:
msg = "No lab humanoids in the scene"
logger.info(msg)
return "NO_OBJ", msg
return "FOUND", name
def is_string_in_string(b_string, b_name):
return b_string and b_name and b_string.lower() in b_name.lower()
def is_too_much_similar(string1, string2, val=2):
s1, s2 = set(string1), set(string2)
threshold = len(s1) - val if len(s1) > len(s2) else len(s2) - val
return len(s1.intersection(s2)) > threshold
def is_in_list(list1, list2, position="ANY"):
for element1 in list1:
for element2 in list2:
if position == "ANY" and element1.lower() in element2.lower():
return True
if position == "START" and element1.lower() in element2[:len(element1)].lower():
return True
if position == "END" and element1.lower() in element2[len(element1):].lower():
return True
return False
#TODO: Calls from morphengine.py loads JSON file
def load_json_data(json_path, description=None):
try:
time1 = time.time()
with open(json_path, "r") as j_file:
j_database = json.load(j_file)
if not description:
logger.info("Json database %s loaded in %s secs",
simple_path(json_path), time.time()-time1)
else:
logger.info("%s loaded from %s in %s secs",
description, simple_path(json_path), time.time()-time1)
return j_database
except IOError:
if simple_path(json_path) != "":
logger.warning("File not found: %s", simple_path(json_path))
except json.JSONDecodeError:
logger.warning("Errors in json file: %s", simple_path(json_path))
return None
def less_boundary_verts(obj, verts_idx, iterations=1):
polygons = obj.data.polygons
while iterations != 0:
verts_to_remove = set()
for poly in polygons:
poly_verts_idx = poly.vertices
for v_idx in poly_verts_idx:
if v_idx not in verts_idx:
for _v_idx in poly_verts_idx:
verts_to_remove.add(_v_idx)
break
verts_idx.difference_update(verts_to_remove)
iterations -= 1
def kdtree_from_mesh_polygons(mesh):
polygons = mesh.polygons
research_tree = mathutils.kdtree.KDTree(len(polygons))
for polyg in polygons:
research_tree.insert(polyg.center, polyg.index)
research_tree.balance()
return research_tree
def kdtree_from_obj_polygons(obj, indices_of_polygons_subset=None):
polygons = []
if indices_of_polygons_subset is not None:
for idx in indices_of_polygons_subset:
polygons.append(obj.data.polygons[idx])
else:
polygons = obj.data.polygons
research_tree = mathutils.kdtree.KDTree(len(polygons))
for polyg in polygons:
research_tree.insert(polyg.center, polyg.index)
research_tree.balance()
return research_tree
def kdtree_from_mesh_vertices(mesh):
vertices = mesh.vertices
research_tree = mathutils.kdtree.KDTree(len(vertices))
for idx, vert in enumerate(vertices):
research_tree.insert(vert.co, idx)
research_tree.balance()
return research_tree
def import_mesh_from_lib(lib_filepath, name):
existing_mesh_names = collect_existing_meshes()
append_mesh_from_library(lib_filepath, [name])
new_mesh = get_newest_mesh(existing_mesh_names)
return new_mesh
def get_scene_modifiers_status():
scene_viewport_status = {}
for obj in bpy.data.objects:
obj_name = obj.name
scene_viewport_status[obj_name] = get_object_modifiers_visibility(obj)
return scene_viewport_status
def get_polygon_vertices_coords(obj_data, index):
if is_object(obj_data):
polygon = obj_data.data.polygons[index]
elif is_mesh(obj_data):
polygon = obj_data.polygons[index]
polygon_vindex = polygon.vertices
verts_coords = []
for i in polygon_vindex:
if is_object(obj_data):
v = obj_data.data.vertices[i]
elif is_mesh(obj_data):
v = obj_data.vertices[i]
verts_coords.append(v.co)
return verts_coords
def remove_mesh(mesh, remove_materials=False):
if remove_materials:
for material in mesh.materials:
if material:
bpy.data.materials.remove(material, do_unlink=True)
bpy.data.meshes.remove(mesh, do_unlink=True)
def remove_object(obj, delete_mesh=False, delete_materials=False):
if obj:
mesh_to_remove = None
if obj.type == 'MESH':
mesh_to_remove = obj.data
bpy.data.objects.remove(obj, do_unlink=True)
if delete_mesh:
if mesh_to_remove is not None:
remove_mesh(mesh_to_remove, delete_materials)
def set_object_layer(obj, n):
if obj:
if hasattr(obj, 'layers'):
n_layer = len(obj.layers)
for i in range(n_layer):
obj.layers[i] = False
if n in range(n_layer):
obj.layers[n] = True
def normal_from_points(points):
return mathutils.geometry.normal(*points[:4]) if len(points) == 4 else mathutils.geometry.normal(*points[:3])
def apply_object_matrix(obj):
negative_matrix = False
for val in obj.scale:
if val < 0:
negative_matrix = True
m = obj.matrix_world
obj.data.transform(m)
if negative_matrix and obj.type == 'MESH':
obj.data.flip_normals()
obj.matrix_world = mathutils.Matrix()
def set_scene_modifiers_status_by_type(modfr_type, visib):
for obj in bpy.data.objects:
for modfr in obj.modifiers:
if modfr.type == modfr_type:
set_modifier_viewport(modfr, visib)
def set_scene_modifiers_status(visib, status_data=None):
if not status_data:
for obj in bpy.data.objects:
for modfr in obj.modifiers:
set_modifier_viewport(modfr, visib)
else:
for obj in bpy.data.objects:
obj_name = obj.name
if obj_name in status_data:
modifier_status = status_data[obj_name]
set_object_modifiers_visibility(obj, modifier_status)
def disable_object_modifiers(obj, types_to_disable=[]):
for modfr in obj.modifiers:
modifier_type = modfr.type
if modifier_type in types_to_disable:
set_modifier_viewport(modfr, False)
logger.info("Modifier %s of %s can create unpredictable fitting results. The lab disabled it",
modifier_type, obj.name)
elif types_to_disable == []:
set_modifier_viewport(modfr, False)
logger.info("Modifier %s of %s can create unpredictable fitting results. The lab disabled it",
modifier_type, obj.name)
def get_object_modifiers_visibility(obj):
# Store the viewport visibility for all modifiers of the obj
obj_modifiers_status = {}
for modfr in obj.modifiers:
modfr_name = get_modifier_name(modfr)
modfr_status = get_modifier_viewport(modfr)
if modfr_name:
obj_modifiers_status[modfr_name] = modfr_status
return obj_modifiers_status
def set_object_modifiers_visibility(obj, modifier_status):
# Store the viewport visibility for all modifiers of the obj
for modfr in obj.modifiers:
modfr_name = get_modifier_name(modfr)
if modfr_name in modifier_status:
set_modifier_viewport(modfr, modifier_status[modfr_name])
def get_modifier(obj, modifier_name):
return obj.modifiers.get(modifier_name)
def get_modifier_name(modfr):
return getattr(modfr, 'name')
def apply_modifier(obj, modifier):
modifier_name = get_modifier_name(modifier)
if modifier_name in obj.modifiers:
set_active_object(obj)
try:
bpy.ops.object.modifier_apply(apply_as='DATA', modifier=modifier_name)
except AttributeError:
logger.warning("Problems in applying %s. Is the modifier disabled?", modifier_name)
def move_up_modifier(obj, modifier):
modifier_name = get_modifier_name(modifier)
set_active_object(obj)
for n in range(len(obj.modifiers)):
bpy.ops.object.modifier_move_up(modifier=modifier_name)
def move_down_modifier(obj, modifier):
modifier_name = get_modifier_name(modifier)
set_active_object(obj)
for n in range(len(obj.modifiers)):
bpy.ops.object.modifier_move_down(modifier=modifier_name)
def remove_modifier(obj, modifier_name):
print("Removing ", modifier_name)
if modifier_name in obj.modifiers:
obj.modifiers.remove(obj.modifiers[modifier_name])
def disable_modifier(modfr):
logger.info("Disable %s", modfr.name)
for mdf in ('show_viewport', 'show_render', 'show_in_editmode', 'show_on_cage'):
if hasattr(modfr, mdf):
setattr(modfr, mdf, False)
def get_modifier_viewport(modfr):
return getattr(modfr, 'show_viewport', None)
def set_modifier_viewport(modfr, value):
if hasattr(modfr, 'show_viewport'):
modfr.show_viewport = value
def new_modifier(obj, name, modifier_type, parameters):
if name in obj.modifiers:
logger.info("Modifier %s already present in %s", modifier_type, obj.name)
return obj.modifiers[name]
_new_modifier = obj.modifiers.new(name, modifier_type)
for parameter, value in parameters.items():
if hasattr(_new_modifier, parameter):
try:
setattr(_new_modifier, parameter, value)
except AttributeError:
logger.info("Setattr failed for attribute '%s' of modifier %s", parameter, name)
return _new_modifier
def set_modifier_parameter(modifier, parameter, value):
if hasattr(modifier, parameter):
try:
setattr(modifier, parameter, value)
except AttributeError:
logger.info("Setattr failed for attribute '%s' of modifier %s", parameter, modifier)
def get_object_materials(obj):
if obj.data.materials:
return obj.data.materials
return []
def select_and_change_mode(obj, obj_mode):
deselect_all_objects()
if obj:
obj.select_set(True)
set_active_object(obj)
set_object_visible(obj)
try:
bpy.ops.object.mode_set(mode=obj_mode)
logger.debug("Select and change mode of %s = %s", obj.name, obj_mode)
except AttributeError:
logger.warning("Can't change the mode of %s to %s", obj.name, obj_mode)
def get_selected_objs_names():
return [obj.name for obj in bpy.context.selected_objects]
def select_object_by_name(name):
obj = get_object_by_name(name)
if obj:
obj.select_set(True)
def set_selected_objs_by_name(names):
for name in names:
if name in bpy.data.objects:
bpy.data.objects[name].select_set(True)
def get_active_object():
return bpy.context.view_layer.objects.active
def deselect_all_objects():
for obj in bpy.data.objects:
obj.select_set(False)
def set_active_object(obj):
if obj:
bpy.context.view_layer.objects.active = obj
def get_object_by_name(name):
return bpy.data.objects.get(name)
def is_object(obj):
return isinstance(obj, bpy.types.Object)
def is_mesh(obj):
return isinstance(obj, bpy.types.Mesh)
def get_objects_selected_names():
selected_objects = []
for obj in bpy.context.selected_objects:
if hasattr(obj, 'name'):
selected_objects.append(obj.name)
return selected_objects
def apply_object_transformation(obj):
if obj:
selected_objs = get_selected_objs_names()
active_obj = get_active_object()
if active_obj:
active_mode = active_obj.mode
obj_mode = obj.mode
select_and_change_mode(obj, 'OBJECT')
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
select_and_change_mode(obj, obj_mode)
deselect_all_objects()
set_selected_objs_by_name(selected_objs)
if active_obj:
set_active_object(active_obj)
bpy.ops.object.mode_set(mode=active_mode)
def collect_existing_objects():
existing_obj_names = []
for obj in bpy.data.objects:
name = obj.name
if name:
existing_obj_names.append(name)
return existing_obj_names
def get_newest_object(existing_obj_names):
for obj in bpy.data.objects:
name = obj.name
if name not in existing_obj_names:
return get_object_by_name(name)
return None
def get_selected_gender():
obj = get_active_body()
template = get_template_model(obj)
if template:
if "_female" in template:
return "FEMALE"
if "_male" in template:
return "MALE"
return "NONE"
def identify_template(obj):
if obj:
if obj.type == 'MESH':
verts = obj.data.vertices
polygons = obj.data.polygons
config_data = get_configuration()
# TODO error messages
if verts and polygons:
for template in config_data["templates_list"]:
n_verts2 = config_data[template]["vertices"]
n_polygons2 = config_data[template]["faces"]
if n_verts2 == len(verts) and n_polygons2 == len(polygons):
return template
return None
def get_template_model(obj):
template = identify_template(obj)
config_data = get_configuration()
if template:
return config_data[template]["template_model"]
return None
def get_template_polygons(obj):
template = identify_template(obj)
config_data = get_configuration()
if template:
return config_data[template]["template_polygons"]
return None
def is_a_lab_character(obj):
return get_template_model(obj) is not None
def get_active_body():
obj = get_active_object()
if obj:
if obj.type == 'MESH':
return obj
if obj.type == 'ARMATURE' and obj.children:
for c_obj in obj.children:
obj_id = get_template_model(c_obj)
if obj_id:
return c_obj
return None
def get_linked_armature(obj):
if obj.type == 'MESH':
for modfr in obj.modifiers:
if modfr.type == 'ARMATURE':
return modfr.object
return None
def raw_mesh_from_object(obj, apply_modifiers=False):
if obj.type == 'MESH':
return obj.to_mesh(bpy.context.scene, apply_modifiers, 'PREVIEW')
return None
def get_all_bones_z_axis(armature):
armature_z_axis = {}
select_and_change_mode(armature, 'EDIT')
source_edit_bones = get_edit_bones(armature)
if source_edit_bones:
for e_bone in source_edit_bones:
armature_z_axis[e_bone.name] = e_bone.z_axis.copy()
select_and_change_mode(armature, 'OBJECT')
return armature_z_axis
def reset_bone_rot(p_bone):
# TODO: check pose mode
if p_bone.rotation_mode == 'QUATERNION':
p_bone.rotation_quaternion = [1.0, 0.0, 0.0, 0.0]
elif p_bone.rotation_mode == 'AXIS_ANGLE':
p_bone.rotation_axis_angle = [0.0, 0.0, 1.0, 0.0]
else:
p_bone.rotation_euler = [0.0, 0.0, 0.0]
def collect_existing_meshes():
existing_mesh_names = []
for mesh in bpy.data.meshes:
existing_mesh_names.append(mesh.name)
return existing_mesh_names
def get_mesh(name):
return bpy.data.meshes.get(name, None)
def get_newest_mesh(existing_mesh_names):
for mesh in bpy.data.meshes:
if mesh.name not in existing_mesh_names:
return get_mesh(mesh.name)
return None
def new_shapekey(obj, shapekey_name, slider_min=0, slider_max=1.0, value=1.0):
# TODO a new shapekey should overwrite the existing one
if shapekey_name in get_shapekeys_names(obj):
shapekey = get_shapekey(obj, shapekey_name)
else:
shapekey = obj.shape_key_add(name=shapekey_name, from_mix=False)
shapekey.slider_min = slider_min
shapekey.slider_max = slider_max
shapekey.value = value
obj.use_shape_key_edit_mode = True
return shapekey
def new_shapekey_from_current_vertices(obj, shapekey_name):
shapekey = new_shapekey(obj, shapekey_name)
for i in range(len(obj.data.vertices)):
shapekey.data[i].co = obj.data.vertices[i].co
return shapekey
def reset_shapekeys(obj):
if has_shapekeys(obj):
for sk in obj.data.shape_keys.key_blocks:
sk.value = 0.0
def get_object_keys(obj):
if obj:
return obj.keys()
return None
def get_vertgroup_verts(obj, vgroup_name):
g = get_vertgroup_by_name(obj, vgroup_name)
verts_idxs = []
if g is not None:
for i in range(len(obj.data.vertices)):
try:
if g.weight(i) > 0:
verts_idxs.append(i)
except AttributeError:
pass
# Blender return an error if the vert is not in group
return verts_idxs
def set_object_visible(obj):
if obj: