-
Notifications
You must be signed in to change notification settings - Fork 84
/
physics.py
1719 lines (1422 loc) · 66.5 KB
/
physics.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 math
import os
import mathutils
import bpy
from . import geom, bones, imageutils, meshutils, materials, modifiers, utils, jsonutils, vars
COLLISION_THICKESS = 0.001
HAIR_THICKNESS = 0.001
CLOTH_THICKNESS = 0.004
def apply_cloth_settings(obj, cloth_type, self_collision = False):
props = vars.props()
prefs = vars.prefs()
mod = modifiers.get_cloth_physics_mod(obj)
if mod is None:
return
obj_cache = props.get_object_cache(obj)
obj_cache.cloth_settings = cloth_type
utils.log_info("Setting " + obj.name + " cloth settings to: " + cloth_type)
mod.settings.vertex_group_mass = prefs.physics_group + "_Pin"
mod.settings.time_scale = 1
mod.collision_settings.use_self_collision = self_collision
cloth_area = geom.get_area(obj)
air_dampening_mod = cloth_area / 2.0
utils.log_info(f"Using cloth area: {cloth_area} sqm, air dampening mod: {air_dampening_mod}")
BASE_GSM = 1.0 / 2666
if cloth_type == "HAIR":
mod.settings.quality = 6
mod.settings.pin_stiffness = 0.025
# physical properties
mod.settings.mass = 0.05
mod.settings.air_damping = 1.0
mod.settings.bending_model = 'ANGULAR'
# stiffness
mod.settings.tension_stiffness = 5.0
mod.settings.compression_stiffness = 5.0
mod.settings.shear_stiffness = 5.0
mod.settings.bending_stiffness = 5.0
# dampening
mod.settings.tension_damping = 0.0
mod.settings.compression_damping = 0.0
mod.settings.shear_damping = 0.0
mod.settings.bending_damping = 0.0
# collision
mod.collision_settings.distance_min = HAIR_THICKNESS
mod.collision_settings.collision_quality = 4
mod.collision_settings.self_distance_min = 0.0005 # 0.5mm
mod.collision_settings.self_friction = 1.0
elif cloth_type == "DENIM":
mod.settings.quality = 8
mod.settings.pin_stiffness = 0.5
# physical properties
mod.settings.mass = 400 * BASE_GSM
mod.settings.air_damping = 1.0 + 0.35 * air_dampening_mod
mod.settings.bending_model = 'ANGULAR'
# stiffness
mod.settings.tension_stiffness = 40.0
mod.settings.compression_stiffness = 40.0
mod.settings.shear_stiffness = 40.0
mod.settings.bending_stiffness = 60.0
# dampening
mod.settings.tension_damping = 25.0
mod.settings.compression_damping = 25.0
mod.settings.shear_damping = 25.0
mod.settings.bending_damping = 10.0
# collision
mod.collision_settings.distance_min = CLOTH_THICKNESS
mod.collision_settings.collision_quality = 4
mod.collision_settings.self_distance_min = 0.005 # 5mm
mod.collision_settings.self_friction = 10.0
elif cloth_type == "LEATHER":
mod.settings.quality = 8
mod.settings.pin_stiffness = 0.5
# physical properties
mod.settings.mass = 800 * BASE_GSM
mod.settings.air_damping = 1.0 + 0.25 * air_dampening_mod
mod.settings.bending_model = 'ANGULAR'
# stiffness
mod.settings.tension_stiffness = 80.0
mod.settings.compression_stiffness = 80.0
mod.settings.shear_stiffness = 80.0
mod.settings.bending_stiffness = 80.0
# dampening
mod.settings.tension_damping = 25.0
mod.settings.compression_damping = 25.0
mod.settings.shear_damping = 25.0
mod.settings.bending_damping = 10.0
# collision
mod.collision_settings.distance_min = CLOTH_THICKNESS
mod.collision_settings.collision_quality = 4
mod.collision_settings.self_distance_min = 0.0025 # 5mm
mod.collision_settings.self_friction = 15.0
elif cloth_type == "RUBBER":
mod.settings.quality = 8
mod.settings.pin_stiffness = 0.25
# physical properties
mod.settings.mass = 650 * BASE_GSM
mod.settings.air_damping = 1.0 + 0.25 * air_dampening_mod
mod.settings.bending_model = 'ANGULAR'
# stiffness
mod.settings.tension_stiffness = 15.0
mod.settings.compression_stiffness = 15.0
mod.settings.shear_stiffness = 15.0
mod.settings.bending_stiffness = 40.0
# dampening
mod.settings.tension_damping = 25.0
mod.settings.compression_damping = 25.0
mod.settings.shear_damping = 25.0
mod.settings.bending_damping = 0.0
# collision
mod.collision_settings.distance_min = CLOTH_THICKNESS
mod.collision_settings.collision_quality = 4
mod.collision_settings.self_distance_min = 0.0025 # 2.5mm
mod.collision_settings.self_friction = 20.0
elif cloth_type == "LINEN":
mod.settings.quality = 8
mod.settings.pin_stiffness = 0.1
# physical properties
mod.settings.mass = 160 * BASE_GSM
mod.settings.air_damping = 1.0 + 0.5 * air_dampening_mod
mod.settings.bending_model = 'ANGULAR'
# stiffness
mod.settings.tension_stiffness = 5.0
mod.settings.compression_stiffness = 5.0
mod.settings.shear_stiffness = 5.0
mod.settings.bending_stiffness = 20.0
# dampening
mod.settings.tension_damping = 5.0
mod.settings.compression_damping = 5.0
mod.settings.shear_damping = 5.0
mod.settings.bending_damping = 0.0
# collision
mod.collision_settings.distance_min = CLOTH_THICKNESS
mod.collision_settings.collision_quality = 4
mod.collision_settings.self_distance_min = 0.0025 # 2.5mm
mod.collision_settings.self_friction = 5.0
elif cloth_type == "COTTON":
mod.settings.quality = 8
mod.settings.pin_stiffness = 0.075
# physical properties
mod.settings.mass = 140 * BASE_GSM
mod.settings.air_damping = 1.0 + 0.75 * air_dampening_mod
mod.settings.bending_model = 'ANGULAR'
# stiffness
mod.settings.tension_stiffness = 2.0
mod.settings.compression_stiffness = 2.0
mod.settings.shear_stiffness = 2.0
mod.settings.bending_stiffness = 10.0
# dampening
mod.settings.tension_damping = 2.0
mod.settings.compression_damping = 2.0
mod.settings.shear_damping = 2.0
mod.settings.bending_damping = 0.0
# collision
mod.collision_settings.distance_min = CLOTH_THICKNESS
mod.collision_settings.collision_quality = 4
mod.collision_settings.self_distance_min = 0.0025 # 2.5mm
mod.collision_settings.self_friction = 5.0
elif cloth_type == "SILK":
mod.settings.quality = 8
mod.settings.pin_stiffness = 0.05
# physical properties
mod.settings.mass = 120 * BASE_GSM
mod.settings.air_damping = 1.0 + 1.0 * air_dampening_mod
mod.settings.bending_model = 'ANGULAR'
# stiffness
mod.settings.tension_stiffness = 0.5
mod.settings.compression_stiffness = 0.5
mod.settings.shear_stiffness = 0.5
mod.settings.bending_stiffness = 1.0
# dampening
mod.settings.tension_damping = 0.0
mod.settings.compression_damping = 0.0
mod.settings.shear_damping = 0.0
mod.settings.bending_damping = 0.0
# collision
mod.collision_settings.distance_min = CLOTH_THICKNESS
mod.collision_settings.collision_quality = 4
mod.collision_settings.self_distance_min = 0.0025 # 2.5mm
mod.collision_settings.self_friction = 1.0
def uses_collision_physics(chr_cache, obj):
obj_cache = chr_cache.get_object_cache(obj)
collision_setting = "OFF"
if obj == obj_cache.get_object():
collision_setting = obj_cache.collision_physics
if "rl_collision_physics" in obj:
collision_setting = obj["rl_collision_physics"]
if collision_setting == "ON" or collision_setting == "PROXY":
return True
# Body objects should use collision physics by default
if collision_setting == "DEFAULT" and \
(obj_cache.object_type == "BODY" or obj_cache.object_type == "OCCLUSION"):
return True
return False
def apply_collision_physics(chr_cache, obj, obj_cache):
"""Adds a Collision modifier to the object, depending on the object cache settings.
Does not overwrite or re-create any existing Collision modifier.
"""
if not (chr_cache and obj and obj_cache):
return
# physics seem to apply better if done in rest pose
arm = chr_cache.get_armature()
if arm:
pose_position = arm.data.pose_position
arm.data.pose_position = "REST"
has_cloth = modifiers.get_cloth_physics_mod(obj) is not None
if uses_collision_physics(chr_cache, obj):
if obj_cache.use_collision_proxy and not has_cloth:
proxy = chr_cache.get_collision_proxy(obj)
if not proxy:
proxy = create_collision_proxy(chr_cache, obj_cache, obj)
if proxy:
obj = proxy
else:
remove_collision_proxy(chr_cache, obj)
collision_mod = modifiers.get_collision_physics_mod(obj)
if not collision_mod:
collision_mod = obj.modifiers.new(utils.unique_name("Collision"), type="COLLISION")
collision_mod.settings.thickness_outer = COLLISION_THICKESS
utils.log_info("Collision Modifier: " + collision_mod.name + " applied to " + obj.name)
elif obj_cache.collision_physics == "OFF":
remove_collision_physics(chr_cache, obj)
utils.log_info("Collision Physics disabled for: " + obj.name)
if arm:
arm.data.pose_position = pose_position
def remove_collision_physics(chr_cache, obj):
"""Removes the Collision modifier from the object.
"""
if chr_cache and obj:
proxy = chr_cache.get_collision_proxy(obj)
if proxy:
utils.delete_mesh_object(proxy)
for mod in obj.modifiers:
if mod.type == "COLLISION":
utils.log_info("Removing Collision modifer: " + mod.name + " from: " + obj.name)
obj.modifiers.remove(mod)
def add_cloth_physics(chr_cache, obj, add_weight_maps = False):
"""Adds a Cloth modifier to the object depending on the object cache settings.
Does not overwrite or re-create any existing Cloth modifier.
Sets the cache bake range to the same as any action on the character's armature.
Applies cloth settings based on the object cache settings.
Repopulates the existing weight maps, depending on their cache settings.
"""
prefs = vars.prefs()
props = vars.props()
if not (chr_cache and obj):
return
obj_cache = chr_cache.get_object_cache(obj)
if (obj_cache and
obj_cache.cloth_physics == "ON"):
utils.object_mode_to(obj)
# Add weight maps
if add_weight_maps:
for mat in obj.data.materials:
if mat:
add_material_weight_map(chr_cache, obj, mat, create = False)
if modifiers.has_cloth_weight_map_mods(obj):
attach_cloth_weight_map_remap(obj, prefs.physics_weightmap_curve)
cloth_mod = modifiers.get_cloth_physics_mod(obj)
if not cloth_mod:
# Create the Cloth modifier
cloth_mod : bpy.types.ClothModifier
cloth_mod_id = utils.unique_name("Cloth")
cloth_mod = obj.modifiers.new(cloth_mod_id, type="CLOTH")
utils.log_info("Cloth Modifier: " + cloth_mod.name + " applied to " + obj.name)
# Set cache bake frame range
frame_start, frame_end = utils.get_scene_frame_range()
utils.log_info(f"Setting {obj.name} bake cache frame range to [{str(frame_start)} - {str(frame_end)}]")
cloth_mod.point_cache.frame_start = frame_start
cloth_mod.point_cache.frame_end = frame_end
if not cloth_mod.point_cache.name:
random_id = utils.generate_random_id(10)
cache_id = f"{obj.name}_{random_id}"
cloth_mod.point_cache.name = cache_id
# Apply cloth settings
if obj_cache.cloth_settings != "DEFAULT":
apply_cloth_settings(obj,
obj_cache.cloth_settings,
self_collision = obj_cache.cloth_self_collision)
elif obj_cache.object_type == "HAIR":
apply_cloth_settings(obj, "HAIR")
else:
apply_cloth_settings(obj, "COTTON")
# fix mod order
arrange_physics_modifiers(obj)
elif obj_cache.cloth_physics == "OFF":
utils.log_info("Cloth Physics disabled for: " + obj.name)
def remove_cloth_physics(obj):
"""Removes the Cloth modifier from the object.
Also removes any active weight maps and also removes the weight map vertex group.
"""
if not obj:
return
prefs = vars.prefs()
utils.object_mode_to(obj)
# Remove the Cloth modifier
for mod in obj.modifiers:
if mod.type == "CLOTH":
utils.log_info("Removing Cloth modifer: " + mod.name + " from: " + obj.name)
obj.modifiers.remove(mod)
# Remove any weight maps
for mat in obj.data.materials:
if mat:
remove_material_weight_maps(obj, mat)
weight_group = prefs.physics_group + "_" + utils.strip_name(mat.name)
if weight_group in obj.vertex_groups:
obj.vertex_groups.remove(obj.vertex_groups[weight_group])
remove_cloth_weight_map_remap(obj)
# If there are no weight maps left on the object, remove the vertex group
mods = 0
for mod in obj.modifiers:
if mod.type == "VERTEX_WEIGHT_EDIT" and vars.NODE_PREFIX in mod.name:
mods += 1
pin_group = prefs.physics_group + "_Pin"
if mods == 0 and pin_group in obj.vertex_groups:
utils.log_info("Removing vertex group: " + pin_group + " from: " + obj.name)
obj.vertex_groups.remove(obj.vertex_groups[pin_group])
def remove_all_physics_mods(obj):
"""Removes all physics modifiers from the object.
Used when (re)building the character materials.
"""
utils.log_info("Removing all related physics modifiers from: " + obj.name)
for mod in obj.modifiers:
if mod.type == "VERTEX_WEIGHT_EDIT" and vars.NODE_PREFIX in mod.name:
obj.modifiers.remove(mod)
elif mod.type == "VERTEX_WEIGHT_MIX" and vars.NODE_PREFIX in mod.name:
obj.modifiers.remove(mod)
elif mod.type == "CLOTH":
obj.modifiers.remove(mod)
elif mod.type == "COLLISION":
obj.modifiers.remove(mod)
def enable_collision_physics(chr_cache, obj):
props = vars.props()
if chr_cache and utils.object_exists_is_mesh(obj):
obj, proxy, is_proxy = chr_cache.get_related_physics_objects(obj)
obj_cache = chr_cache.get_object_cache(obj)
if obj_cache:
has_cloth = modifiers.get_cloth_physics_mod(obj) is not None
collision_mode = "PROXY" if (obj_cache.use_collision_proxy and not has_cloth) else "ON"
if obj == obj_cache.get_object():
obj_cache.collision_physics = collision_mode
obj["rl_collision_physics"] = collision_mode
utils.log_info("Enabling Collision physics for: " + obj.name)
apply_collision_physics(chr_cache, obj, obj_cache)
def disable_collision_physics(chr_cache, obj):
if chr_cache and utils.object_exists_is_mesh(obj):
obj, proxy, is_proxy = chr_cache.get_related_physics_objects(obj)
obj_cache = chr_cache.get_object_cache(obj)
if obj_cache:
if obj == obj_cache.get_object():
obj_cache.collision_physics = "OFF"
obj["rl_collision_physics"] = "OFF"
utils.log_info("Disabling Collision physics for: " + obj.name)
remove_collision_physics(chr_cache, obj)
def show_hide_collision_proxies(context, chr_cache, show, select=False, use_local=False):
if chr_cache:
objects = []
proxies = []
# get all character objects with proxies
for obj in chr_cache.get_cache_objects():
obj, proxy, is_proxy = chr_cache.get_related_physics_objects(obj)
if obj and proxy:
objects.append(obj)
proxies.append(proxy)
# show / hide all proxy objects
if show:
if proxies:
for proxy in proxies:
utils.unhide(proxy)
utils.object_mode()
if select or use_local:
utils.try_select_objects(proxies, clear_selection=True)
if use_local and not utils.is_local_view(context):
bpy.ops.view3d.localview()
return True
else:
if proxies:
for proxy in proxies:
utils.hide(proxy)
utils.object_mode()
if select:
utils.try_select_objects(objects, clear_selection=True)
if use_local and utils.is_local_view(context):
bpy.ops.view3d.localview()
return False
def enable_cloth_physics(chr_cache, obj, add_weight_maps = True):
props = vars.props()
if chr_cache and obj:
obj_cache = chr_cache.get_object_cache(obj)
if obj_cache:
obj_cache.cloth_physics = "ON"
utils.log_info("Enabling Cloth physics for: " + obj.name)
add_cloth_physics(chr_cache, obj, add_weight_maps)
def disable_cloth_physics(chr_cache, obj):
props = vars.props()
if chr_cache and obj:
obj_cache = chr_cache.get_object_cache(obj)
if obj_cache:
obj_cache.cloth_physics = "OFF"
utils.log_info("Removing cloth physics for: " + obj.name)
remove_cloth_physics(obj)
def remove_collision_proxy(chr_cache, obj):
proxy = chr_cache.get_collision_proxy(obj)
if proxy:
utils.log_info(f"Removing collision proxy: {proxy.name}")
utils.delete_mesh_object(proxy)
def create_collision_proxy(chr_cache, obj_cache, obj):
utils.log_info(f"Creating collision proxy mesh from: {obj.name}")
# remove old proxy
remove_collision_proxy(chr_cache, obj)
# clone obj to proxy
collision_proxy = utils.duplicate_object(obj)
collision_proxy.name = obj.name + ".Collision_Proxy"
collision_proxy["rl_collision_proxy"] = obj.name
if utils.object_mode_to(collision_proxy) and utils.set_only_active_object(collision_proxy):
# remove shape keys
collision_proxy.shape_key_clear()
# remove eye-lashes
eye_lash_mat = materials.get_material_by_type(chr_cache, collision_proxy, "EYELASH")
if eye_lash_mat:
meshutils.remove_material_verts(collision_proxy, eye_lash_mat)
# remove materials
collision_proxy.data.materials.clear()
# delete loose
utils.edit_mode_to(collision_proxy)
bpy.ops.mesh.select_all(action="SELECT")
bpy.ops.mesh.delete_loose(use_verts=True, use_edges=True, use_faces=True)
utils.object_mode_to(collision_proxy)
if obj_cache.collision_proxy_decimate < 1.0:
# add decimate modifier
mod = modifiers.add_decimate_modifier(collision_proxy, obj_cache.collision_proxy_decimate)
modifiers.move_mod_first(collision_proxy, mod)
# apply decimate modifier
bpy.ops.object.modifier_apply(modifier=mod.name)
utils.log_info(f"Storing collision mesh: {collision_proxy.name}")
obj_cache.use_collision_proxy = True
obj_cache.collision_physics = "PROXY"
utils.hide(collision_proxy)
collision_proxy.hide_render = True
utils.set_only_active_object(obj)
return collision_proxy
def get_weight_map_from_modifiers(obj, mat):
mat_name = "_" + utils.strip_name(mat.name) + "_"
if obj.type == "MESH":
for mod in obj.modifiers:
if mod.type == "VERTEX_WEIGHT_EDIT" and vars.NODE_PREFIX in mod.name and mat_name in mod.name:
if mod.mask_texture is not None and mod.mask_texture.image is not None:
image = mod.mask_texture.image
return image
return None
def get_weight_map_image(chr_cache, obj, mat, create = False):
"""Returns the weight map image for the material.
Fetches the Image for the given materials weight map, if it exists.
If not, the image can be created and packed into the blend file and stored
in the material cache as a temporary weight map image.
"""
props = vars.props()
mat_cache = props.get_material_cache(mat)
weight_map = imageutils.find_material_image(mat, "WEIGHTMAP")
if mat_cache:
if weight_map:
if weight_map.size[0] == 0 or weight_map.size[1] == 0:
weight_map = None
else:
mat_cache.temp_weight_map = weight_map
if weight_map is None and create:
name = utils.strip_name(mat.name) + "_WeightMap"
tex_size = int(props.physics_tex_size)
weight_map = bpy.data.images.new(name, tex_size, tex_size, is_data=False)
# make the image 'dirty' so it converts to a file based image which can be saved:
weight_map.pixels[0] = 0.0
weight_map.file_format = "PNG"
weight_map.filepath_raw = os.path.join(mat_cache.get_tex_dir(chr_cache), name + ".png")
weight_map.save()
# keep track of which weight maps we created:
mat_cache.temp_weight_map = weight_map
utils.log_info("Weight-map image: " + weight_map.name + " created and saved.")
return weight_map
def add_material_weight_map(chr_cache, obj, mat, create = False):
"""Adds a weight map 'Vertex Weight Edit' modifier for the object's material.
Gets or creates (if instructed) the material's weight map then creates
or re-creates the modifier to generate the physics 'Pin' vertex group.
"""
if chr_cache and obj and mat:
if cloth_physics_available(chr_cache, obj, mat):
if create:
weight_map = get_weight_map_image(chr_cache, obj, mat, create)
else:
weight_map = imageutils.find_material_image(mat, "WEIGHTMAP")
remove_material_weight_maps(obj, mat)
if weight_map is not None:
attach_material_weight_map(obj, mat, weight_map)
else:
utils.log_info("Cloth Physics has been disabled for: " + obj.name)
def remove_material_weight_maps(obj, mat):
"""Removes the weight map 'Vertex Weight Edit' modifier for the object's material.
This does not remove or delete the weight map image or temporary packed image,
or the texture based on the weight map image, just the modifier.
"""
if obj and mat:
edit_mod, mix_mod = modifiers.get_material_weight_map_mods(obj, mat)
if edit_mod is not None:
utils.log_info("Removing weight map vertex edit modifer: " + edit_mod.name)
obj.modifiers.remove(edit_mod)
if mix_mod is not None:
utils.log_info("Removing weight map vertex mix modifer: " + mix_mod.name)
obj.modifiers.remove(mix_mod)
def enable_material_weight_map(chr_cache, obj, mat):
"""Enables the weight map for the object's material and (re)creates the Vertex Weight Edit modifier.
"""
prefs = vars.prefs()
props = vars.props()
if chr_cache and obj and mat:
mat_cache = chr_cache.get_material_cache(mat)
if mat_cache:
if mat_cache.cloth_physics == "OFF":
mat_cache.cloth_physics = "ON"
add_material_weight_map(chr_cache, obj, mat, True)
if modifiers.has_cloth_weight_map_mods(obj):
attach_cloth_weight_map_remap(obj, prefs.physics_weightmap_curve)
# fix mod order
arrange_physics_modifiers(obj)
def disable_material_weight_map(chr_cache, obj, mat):
"""Disables the weight map for the object's material and removes the Vertex Weight Edit modifier.
"""
if chr_cache and obj and mat:
mat_cache = chr_cache.get_material_cache(mat)
mat_cache.cloth_physics = "OFF"
remove_material_weight_maps(obj, mat)
def collision_physics_available(chr_cache, obj):
"""Is cloth collisions physics allowed on the character object?"""
if chr_cache and obj:
obj_cache = chr_cache.get_object_cache(obj)
collision_mod = modifiers.get_collision_physics_mod(obj)
if collision_mod is None:
if obj_cache.collision_physics == "OFF":
return False
return True
return False
def cloth_physics_available(chr_cache, obj, mat):
"""Is cloth physics allowed on this character object and material?"""
if chr_cache and obj and mat:
obj_cache = chr_cache.get_object_cache(obj)
mat_cache = chr_cache.get_material_cache(mat)
cloth_mod = modifiers.get_cloth_physics_mod(obj)
if cloth_mod is None:
if obj_cache.cloth_physics == "OFF":
return False
if mat_cache is not None and mat_cache.cloth_physics == "OFF":
return False
else:
# if cloth physics was disabled by the add-on,
# but re-enabled in the physics panel,
# correct the object cache setting:
if obj_cache.cloth_physics == "OFF":
obj_cache.cloth_physics == "ON"
return True
return False
def is_cloth_physics_enabled(mat_cache, mat, obj):
"""Is cloth physics enabled on this character object and material?"""
if mat_cache and obj and mat:
cloth_mod = modifiers.get_cloth_physics_mod(obj)
edit_mods, mix_mods = modifiers.get_material_weight_map_mods(obj, mat)
if cloth_mod and edit_mods and mix_mods:
if mat_cache and mat_cache.cloth_physics != "OFF":
return True
return False
return False
def attach_cloth_weight_map_remap(obj, replace = True, curve_power = 5.0):
"""Attach the final remap vertex weight edit to convert the physx weight
map values to something more blender physics friendly."""
prefs = vars.prefs()
remap_mod : bpy.types.VertexWeightEditModifier
if replace:
modifiers.remove_object_modifiers(obj, "VERTEX_WEIGHT_EDIT", "_WeightEditRemap")
else:
remap_mod = modifiers.get_object_modifier(obj, "VERTEX_WEIGHT_EDIT", "_WeightEditRemap")
if remap_mod:
return
pin_group = prefs.physics_group + "_Pin"
obj_name = utils.safe_export_name(obj.name)
remap_mod = obj.modifiers.new(utils.unique_name(obj_name + "_WeightEditRemap"), "VERTEX_WEIGHT_EDIT")
remap_mod.use_add = False
remap_mod.use_remove = False
remap_mod.vertex_group = pin_group
remap_mod.default_weight = 0.0
remap_mod.falloff_type = 'CURVE'
remap_mod.invert_falloff = False
#remap_mod.map_curve.curves[0].points.new(0.25, pow(0.25, curve_power))
#remap_mod.map_curve.curves[0].points.new(0.5, pow(0.5, curve_power))
remap_mod.map_curve.curves[0].points.new(0.75, pow(0.75, curve_power))
remap_mod.map_curve.update()
def remove_cloth_weight_map_remap(obj):
modifiers.remove_object_modifiers(obj, "VERTEX_WEIGHT_EDIT", "_WeightEditRemap")
def attach_material_weight_map(obj, mat, weight_map):
"""Attaches a weight map to the object's material via a 'Vertex Weight Edit' modifier.
This will attach the supplied weight map or will try to find an existing weight map,
but will not create a new weight map if it doesn't already exist.
"""
prefs = vars.prefs()
if obj and mat and weight_map:
# Make a texture based on the weight map image
# As we are matching names to find existing textures,
# get a name that keeps the duplication suffix
mat_name = utils.safe_export_name(mat.name)
tex_name = mat_name + "_Weight"
tex = None
for t in bpy.data.textures:
if t.name.startswith(vars.NODE_PREFIX + tex_name):
tex = t
if tex is None:
tex = bpy.data.textures.new(utils.unique_name(tex_name), "IMAGE")
utils.log_info("Texture: " + tex.name + " created for weight map transfer")
else:
utils.log_info("Texture: " + tex.name + " already exists for weight map transfer")
tex.image = weight_map
# Create the physics pin vertex group and the material weightmap group if they don't exist:
pin_group = prefs.physics_group + "_Pin"
material_group = prefs.physics_group + "_" + mat_name
if pin_group not in obj.vertex_groups:
pin_vertex_group = obj.vertex_groups.new(name = pin_group)
else:
pin_vertex_group = obj.vertex_groups[pin_group]
if material_group not in obj.vertex_groups:
weight_vertex_group = obj.vertex_groups.new(name = material_group)
else:
weight_vertex_group = obj.vertex_groups[material_group]
# The material weight map group should contain only those vertices affected by the material, default weight to 1.0
meshutils.clear_vertex_group(obj, weight_vertex_group)
mat_vert_indices = meshutils.get_material_vertex_indices(obj, mat)
weight_vertex_group.add(mat_vert_indices, 1.0, 'ADD')
# The pin group should contain all vertices in the mesh default weighted to 1.0
meshutils.set_vertex_group(obj, pin_vertex_group, 1.0)
# set the pin group in the cloth physics modifier
mod_cloth = modifiers.get_cloth_physics_mod(obj)
if mod_cloth is not None:
mod_cloth.settings.vertex_group_mass = pin_group
# re-create create the Vertex Weight Edit modifier and the Vertex Weight Mix modifer
remove_material_weight_maps(obj, mat)
edit_mod : bpy.types.VertexWeightEditModifier
edit_mod = obj.modifiers.new(utils.unique_name(mat_name + "_WeightEdit"), "VERTEX_WEIGHT_EDIT")
mix_mod = obj.modifiers.new(utils.unique_name(mat_name + "_WeightMix"), "VERTEX_WEIGHT_MIX")
# Use the texture as the modifiers vertex weight source
edit_mod.mask_texture = tex
# Setup the modifier to generate the inverse of the weight map in the vertex group
edit_mod.use_add = False
edit_mod.use_remove = False
edit_mod.add_threshold = 0.01
edit_mod.remove_threshold = 0.01
edit_mod.vertex_group = material_group
edit_mod.default_weight = 1
edit_mod.falloff_type = 'LINEAR'
edit_mod.invert_falloff = True
edit_mod.mask_constant = 1
edit_mod.mask_tex_mapping = 'UV'
edit_mod.mask_tex_use_channel = 'INT'
try:
edit_mod.normalize = False
except:
pass
# The Vertex Weight Mix modifier takes the material weight map group and mixes it into the pin weight group:
# (this allows multiple weight maps from different materials and UV layouts to combine in the same mesh)
mix_mod.vertex_group_a = pin_group
mix_mod.vertex_group_b = material_group
mix_mod.invert_mask_vertex_group = True
mix_mod.default_weight_a = 1
mix_mod.default_weight_b = 1
mix_mod.mix_set = 'B' #'ALL'
mix_mod.mix_mode = 'SET'
mix_mod.invert_mask_vertex_group = False
utils.log_info("Weight map: " + weight_map.name + " applied to: " + obj.name + "/" + mat.name)
def get_physx_weight_range(obj):
"""Get the range (min, max) of weights for physics pin group"""
props = vars.props()
prefs = vars.prefs()
weight_min = 1.0
weight_max = 0.0
if obj:
vertex_group_name = prefs.physics_group + "_Pin"
if obj.type == "MESH" and vertex_group_name in obj.vertex_groups:
if utils.set_active_object(obj):
# normalize pin vertex group range
pin_vg = obj.vertex_groups[vertex_group_name]
pin_vg_index = pin_vg.index
# determine range
for vertex in obj.data.vertices:
for vg in vertex.groups:
if vg.group == pin_vg_index:
w = vg.weight
weight_min = min(w, weight_min)
weight_max = max(w, weight_max)
return weight_min, weight_max
def count_weightmaps(objects):
num_maps = 0
num_dirty = 0
for obj in objects:
if obj.type == "MESH":
for mod in obj.modifiers:
if mod.type == "VERTEX_WEIGHT_EDIT" and vars.NODE_PREFIX in mod.name:
if mod.mask_texture is not None and mod.mask_texture.image is not None:
num_maps += 1
image = mod.mask_texture.image
if image.is_dirty:
num_dirty += 1
return num_maps, num_dirty
def get_dirty_weightmaps(objects):
maps = []
for obj in objects:
if obj.type == "MESH":
for mod in obj.modifiers:
if mod.type == "VERTEX_WEIGHT_EDIT" and vars.NODE_PREFIX in mod.name:
if mod.mask_texture is not None and mod.mask_texture.image is not None:
image = mod.mask_texture.image
abs_image_path = bpy.path.abspath(image.filepath)
if image.filepath != "" and (image.is_dirty or not os.path.exists(abs_image_path)):
maps.append(image)
return maps
def physics_paint_strength_update(self, context):
props = vars.props()
if context.mode == "PAINT_TEXTURE":
ups = context.tool_settings.unified_paint_settings
prop_owner = ups if ups.use_unified_color else context.tool_settings.image_paint.brush
s = props.physics_paint_strength
prop_owner.color = (s, s, s)
def weight_strength_update(self, context):
props = vars.props()
strength = props.weight_map_strength
influence = 1 - math.pow(1 - strength, 3)
edit_mod, mix_mod = modifiers.get_material_weight_map_mods(context.object, utils.get_context_material(context))
mix_mod.mask_constant = influence
def browse_weight_map(chr_cache, context):
obj = context.object
mat = utils.get_context_material(context)
if obj and mat:
weight_map = get_weight_map_image(chr_cache, obj, mat)
if weight_map:
path = bpy.path.abspath(weight_map.filepath)
utils.show_system_file_browser(path)
def begin_paint_weight_map(context, chr_cache):
obj = context.object
mat = utils.get_context_material(context)
props = vars.props()
shading = utils.get_view_3d_shading(context)
if obj is not None and mat is not None:
if shading:
props.paint_store_render = shading.type
else:
props.paint_store_render = "MATERIAL"
if context.mode != "PAINT_TEXTURE":
bpy.ops.object.mode_set(mode="TEXTURE_PAINT")
if context.mode == "PAINT_TEXTURE":
physics_paint_strength_update(None, context)
weight_map = get_weight_map_image(chr_cache, obj, mat)
weight_map.update()
props.paint_object = obj
props.paint_material = mat
props.paint_image = weight_map
shading = utils.get_view_3d_shading(context)
if weight_map is not None:
bpy.context.scene.tool_settings.image_paint.mode = 'IMAGE'
bpy.context.scene.tool_settings.image_paint.canvas = weight_map
if shading:
shading.type = 'SOLID'
def resize_weight_map(chr_cache, context, op):
props = vars.props()
if context.mode == "PAINT_TEXTURE":
return
obj = context.object
mat = utils.get_context_material(context)
props = vars.props()
if obj is not None and mat is not None:
weight_map : bpy.types.Image = get_weight_map_image(chr_cache, obj, mat)
size = int(props.physics_tex_size)
if weight_map and (weight_map.size[0] != size or weight_map.size[1] != size):
weight_map.scale(size, size)
# force Blender to update the image by changing a pixel value
# otherwise it doesn't recognise the size change.
value = weight_map.pixels[0]
weight_map.pixels[0] = 0.0
weight_map.pixels[0] = value
weight_map.update()
op.report({'INFO'}, f"Weightmap Resized to: {size} x {size}")
def end_paint_weight_map(op, context, chr_cache):
try:
props = vars.props()
shading = utils.get_view_3d_shading(context)
if context.mode != "OBJECT":
bpy.ops.object.mode_set(mode="OBJECT")
if shading:
shading.type = props.paint_store_render
#props.paint_image.save()
op.report({'INFO'}, f"Weightmap painting done, Save the weightmap to preserve changes.")
except Exception as e:
utils.log_error("Something went wrong restoring object mode from paint mode!", e)
def save_dirty_weight_maps(chr_cache, objects):
"""Saves all altered active weight map images to their respective material folders.
Also saves any missing weight maps.
"""
maps = get_dirty_weightmaps(objects)
for weight_map in maps:
if weight_map.is_dirty:
utils.log_info("Dirty weight map: " + weight_map.name + " : " + weight_map.filepath)
weight_map.save()
utils.log_info("Weight Map: " + weight_map.name + " saved to: " + weight_map.filepath)
if not os.path.exists(weight_map.filepath):
utils.log_info("Missing weight map: " + weight_map.name + " : " + weight_map.filepath)
weight_map.save()
utils.log_info("Weight Map: " + weight_map.name + " saved to: " + weight_map.filepath)