-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathhair.py
2090 lines (1633 loc) · 75 KB
/
hair.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 bpy, bmesh
import os, math, random
from mathutils import Vector
from . import physics, rigidbody, springbones, modifiers, geom, utils, jsonutils, bones, meshutils, vars
STROKE_JOIN_THRESHOLD = 1.0 / 100.0 # 1cm
BONE_SMOOTH_LEVEL_CUSTOM_PROP = "rl_generated_smoothing_level"
def begin_hair_sculpt(chr_cache):
return
def end_hair_sculpt(chr_cache):
return
def find_obj_cache(chr_cache, obj):
if chr_cache and obj and obj.type == "MESH":
# try to find directly
obj_cache = chr_cache.get_object_cache(obj)
if obj_cache:
return obj_cache
# obj might be part of a split or a copy from original character object
# so will have the same name but with duplication suffixes
possible = []
source_name = utils.strip_name(obj.name)
for obj_cache in chr_cache.object_cache:
if obj_cache.is_mesh() and obj_cache.source_name == source_name:
possible.append(obj_cache)
# if only one possibility return that
if possible and len(possible) == 1:
return possible[0]
# try to find the correct object cache by matching the materials
# try matching all the materials first
for obj_cache in possible:
o = obj_cache.get_object()
if o:
found = True
for mat in obj.data.materials:
if mat not in o.data.materials:
found = False
if found:
return obj_cache
# then try just matching any
for obj_cache in possible:
o = obj_cache.get_object()
if o:
found = True
for mat in obj.data.materials:
if mat in o.data.materials:
return obj_cache
return None
def clear_particle_systems(obj):
if utils.object_mode() and utils.set_only_active_object(obj):
for i in range(0, len(obj.particle_systems)):
bpy.ops.object.particle_system_remove()
return True
return False
def convert_hair_group_to_particle_systems(obj, curves):
if clear_particle_systems(obj):
for c in curves:
if utils.set_only_active_object(c):
bpy.ops.curves.convert_to_particle_system()
def export_blender_hair(op, chr_cache, objects, base_path):
props = vars.props()
prefs = vars.prefs()
utils.expand_with_child_objects(objects)
folder, name = os.path.split(base_path)
file, ext = os.path.splitext(name)
parents = []
for obj in objects:
if obj.type == "CURVES":
if obj.parent:
if obj.parent not in parents:
parents.append(obj.parent)
else:
op.report({'ERROR'}, f"Curve: {obj.data.name} has no parent!")
json_data = { "Hair": { "Objects": { } } }
export_id = 0
for parent in parents:
groups = {}
obj_cache = find_obj_cache(chr_cache, parent)
if obj_cache:
parent_name = utils.determine_object_export_name(chr_cache, parent, obj_cache)
json_data["Hair"]["Objects"][parent_name] = { "Groups": {} }
if props.hair_export_group_by == "CURVE":
for obj in objects:
if obj.type == "CURVES" and obj.parent == parent:
group = [obj]
name = obj.data.name
groups[name] = group
utils.log_info(f"Group: {name}, Object: {obj.data.name}")
elif props.hair_export_group_by == "NAME":
for obj in objects:
if obj.type == "CURVES" and obj.parent == parent:
name = utils.strip_name(obj.data.name)
if name not in groups.keys():
groups[name] = []
groups[name].append(obj)
utils.log_info(f"Group: {name}, Object: {obj.data.name}")
else: #props.hair_export_group_by == "NONE":
if "Hair" not in groups.keys():
groups["Hair"] = []
for obj in objects:
if obj.type == "CURVES" and obj.parent == parent:
groups["Hair"].append(obj)
utils.log_info(f"Group: Hair, Object: {obj.data.name}")
for group_name in groups.keys():
file_name = f"{file}_{export_id}.abc"
file_path = os.path.join(folder, file_name)
export_id += 1
convert_hair_group_to_particle_systems(parent, groups[group_name])
utils.try_select_objects(groups[group_name], True)
utils.set_active_object(parent)
json_data["Hair"]["Objects"][parent_name]["Groups"][group_name] = { "File": file_name }
bpy.ops.wm.alembic_export(
filepath=file_path,
check_existing=False,
global_scale=100.0,
start=1, end=1,
use_instancing = False,
selected=True,
visible_objects_only=True,
evaluation_mode = "RENDER",
packuv=False,
export_hair=True,
export_particles=True)
clear_particle_systems(parent)
else:
op.report({'ERROR'}, f"Unable to find source mesh object in character for: {parent.name}!")
new_json_path = os.path.join(folder, file + ".json")
jsonutils.write_json(json_data, new_json_path)
utils.try_select_objects(objects, True)
def create_curve():
curve = bpy.data.curves.new("Hair Curve", type="CURVE")
curve.dimensions = "3D"
obj = bpy.data.objects.new("Hair Curve", curve)
bpy.context.collection.objects.link(obj)
return curve
def create_hair_curves():
curves = bpy.data.hair_curves.new("Hair Curves")
obj = bpy.data.objects.new("Hair Curves", curves)
bpy.context.collection.objects.link(obj)
return curves
def add_poly_spline(points, curve):
"""Create a poly curve from a list of Vectors
"""
spline : bpy.types.Spline = curve.splines.new("POLY")
spline.points.add(len(points) - 1)
for i in range(0, len(points)):
co = points[i]
spline.points[i].co = (co.x, co.y, co.z, 1.0)
def card_dir_from_uv_map(card_dirs, uv_map):
# analyse uv bounds
uv_min, uv_max = geom.get_uv_bounds(uv_map)
uv_extent = uv_max - uv_min
uv_aspect = uv_extent.x / uv_extent.y
# only deal with vertical or horizontal cards
# squarish cards are patches of hair that shouldn't be weighted
if uv_aspect >= 2.0:
uv_orient = "HORIZONTAL"
elif uv_aspect <= 0.5:
uv_orient = "VERTICAL"
else:
uv_orient = "SQUARE"
return card_dirs[uv_orient]
def parse_loop(bm, edge_index, edges_left, loop, edge_map):
"""Returns a set of vertex indices in the edge loop
"""
if edge_index in edges_left:
edges_left.remove(edge_index)
edge = bm.edges[edge_index]
loop.add(edge.verts[0].index)
loop.add(edge.verts[1].index)
if edge.index in edge_map:
for ce in edge_map[edge.index]:
parse_loop(bm, ce, edges_left, loop, edge_map)
def sort_func_u(vert_uv_pair):
return vert_uv_pair[-1].x
def sort_func_v(vert_uv_pair):
return vert_uv_pair[-1].y
def sort_verts_by_uv(obj, bm, loop, uv_map, dir):
sorted = []
for vert in loop:
uv = uv_map[vert]
sorted.append([vert, uv])
if dir.x > 0:
sorted.sort(reverse=False, key=sort_func_u)
elif dir.x < 0:
sorted.sort(reverse=True, key=sort_func_u)
elif dir.y > 0:
sorted.sort(reverse=False, key=sort_func_v)
else:
sorted.sort(reverse=True, key=sort_func_v)
return [ obj.matrix_world @ bm.verts[v].co for v, uv in sorted]
def get_ordered_coordinate_loops(obj, bm, edges, dir, uv_map, edge_map):
edges_left = set(edges)
loops = []
# separate edges into vertex loops
while len(edges_left) > 0:
loop = set()
edge_index = list(edges_left)[0]
parse_loop(bm, edge_index, edges_left, loop, edge_map)
sorted = sort_verts_by_uv(obj, bm, loop, uv_map, dir)
loops.append(sorted)
return loops
def get_vert_loops(obj, bm, edges, edge_map):
edges_left = set(edges)
vert_loops = []
# separate edges into vertex loops
while len(edges_left) > 0:
loop = set()
edge_index = list(edges_left)[0]
parse_loop(bm, edge_index, edges_left, loop, edge_map)
verts = [ index for index in loop]
vert_loops.append(verts)
return vert_loops
def merge_length_coordinate_loops(loops):
size = len(loops[0])
for merged in loops:
if len(merged) != size:
return None
num = len(loops)
merged = []
for i in range(0, size):
co = Vector((0,0,0))
for l in range(0, num):
co += loops[l][i]
co /= num
merged.append(co)
return merged
def sort_lateral_card(obj, bm, loops, uv_map, dir):
sorted = []
card = {}
for loop in loops:
co = Vector((0,0,0))
uv = Vector((0,0))
count = 0
for vert_index in loop:
co += obj.matrix_world @ bm.verts[vert_index].co
uv += uv_map[vert_index]
count += 1
co /= count
uv /= count
sorted.append([co, loop, uv])
if dir.x > 0:
sorted.sort(reverse=False, key=sort_func_u)
elif dir.x < 0:
sorted.sort(reverse=True, key=sort_func_u)
elif dir.y > 0:
sorted.sort(reverse=False, key=sort_func_v)
else:
sorted.sort(reverse=True, key=sort_func_v)
card["median"] = [ co for co, loop, uv in sorted ]
card["loops"] = [ loop for co, loop, uv in sorted ]
return card
def grid_to_loops(obj, bm, island, card_dirs, one_loop_per_card):
props = vars.props()
# each island has a unique UV map
uv_map = geom.get_uv_island_map(bm, 0, island)
card_dir = card_dir_from_uv_map(card_dirs, uv_map)
# get all edges aligned with the card dir in the island
edges = geom.get_uv_aligned_edges(bm, island, card_dir, uv_map, dir_threshold=props.hair_card_dir_threshold)
utils.log_info(f"{len(edges)} aligned edges.")
# map connected edges
edge_map = geom.get_linked_edge_map(bm, edges)
# separate into ordered vertex loops
loops = get_ordered_coordinate_loops(obj, bm, edges, card_dir, uv_map, edge_map)
utils.log_info(f"{len(loops)} ordered loops.")
# (merge and) generate poly curves
if one_loop_per_card:
loop = merge_length_coordinate_loops(loops)
if loop:
return [loop]
else:
utils.log_info("Loops have differing lengths, grid extraction failed.")
return None
else:
return loops
return True
def get_vert_loop_to(obj, bm, from_index, to_index, edges, reverse = False):
verts = []
co_loop = []
following = False
for edge_index in edges:
if edge_index == from_index:
following = True
if edge_index == to_index:
following = False
if following:
edge = bm.edges[edge_index]
for vert in edge.verts:
if vert.index not in verts:
verts.append(vert.index)
if reverse:
co_loop.insert(0, obj.matrix_world @ vert.co)
else:
co_loop.append(obj.matrix_world @ vert.co)
return verts, co_loop
def sort_boundary_edges(bm, edges : set, start_index):
edge = bm.edges[start_index]
vert = edge.verts[1]
edge_loop = [start_index]
edges.remove(start_index)
following = True
while following:
following = False
for next_edge in vert.link_edges:
if next_edge != edge and next_edge.index in edges:
edge_loop.append(next_edge.index)
edges.remove(next_edge.index)
for next_vert in next_edge.verts:
if next_vert.index != vert.index:
edge = next_edge
vert = next_vert
following = True
break
if following:
break
return edge_loop
def split_boundary_loops(obj, bm, boundary_edges, card_dir, uv_map):
edge : bmesh.types.BMEdge
min_proj = math.inf
max_proj = -math.inf
list_edges = list(boundary_edges)
min_edge_index = list_edges[0]
max_edge_index = list_edges[-1]
for edge_index in boundary_edges:
edge = bm.edges[edge_index]
vert = edge.verts[0]
uv = uv_map[vert.index]
proj = -card_dir.dot(uv)
if proj < min_proj:
min_proj = proj
min_edge_index = edge.index
if proj > max_proj:
max_proj = proj
max_edge_index = edge.index
# sort the boundary edges in order, starting from max_edge (the top most UV edge)
num_edges = len(boundary_edges)
edge_loop = sort_boundary_edges(bm, boundary_edges, max_edge_index)
# return nothing if the sorted boundary edge does not contain all the edges
# (i.e. there are breaks in the edges)
if len(edge_loop) != num_edges:
utils.log_info(f"Unable to sort boundary edges: {len(edge_loop)} != {num_edges}")
return None, None
# extract the left and right coordinate loops
left_verts, left_coords = get_vert_loop_to(obj, bm, max_edge_index, min_edge_index, edge_loop)
right_verts, right_coords = get_vert_loop_to(obj, bm, min_edge_index, max_edge_index, edge_loop, reverse=True)
# need to reverse the order of one of these... but which one
return left_coords, right_coords
def get_projection_on_loop(loop, co):
p0 = loop[0]
min_distance = math.inf
projected_point = p0
projected_length = 0.0
length = 0.0
for i in range(1, len(loop)):
p1 = loop[i]
segment_length = (p1 - p0).length
dist, fac = distance_from_line(co, p0, p1)
if dist < min_distance:
min_distance = dist
projected_point = p0 * (1.0 - fac) + p1 * fac
projected_length = length + segment_length * fac
length += segment_length
p0 = p1
return projected_point, projected_length
def proj_loop_sort_func(co_len_pair):
return co_len_pair[1]
def project_boundary_loop(src_loop, dst_loop):
"""Projects the source loop onto the destination loop."""
sort_points = []
# add the original points & lengths
for i in range(0, len(dst_loop)):
sort_points.append([dst_loop[i], loop_length(dst_loop, i)])
# add the projected points & lengths
for co in src_loop:
projected_point, projected_length = get_projection_on_loop(dst_loop, co)
sort_points.append([projected_point, projected_length])
# sort by length
sort_points.sort(key=proj_loop_sort_func)
# return the coordinate loop
loop = [ pair[0] for pair in sort_points ]
return loop
def mesh_to_loops(obj, bm, island, card_dirs):
props = vars.props()
# each island has a unique UV map
uv_map = geom.get_uv_island_map(bm, 0, island)
card_dir = card_dir_from_uv_map(card_dirs, uv_map)
# find the boundary edges
boundary_edges = geom.get_boundary_edges(bm, island)
# check for minimum bound edges
if len(boundary_edges) < 4:
return None
# the top most UV in the boundary edge is the start of the left hand side
# the bottom most UV in the boundary edge is the end of the right hand side
# split the boundary edge into two loops left and right
left_loop, right_loop = split_boundary_loops(obj, bm, boundary_edges, card_dir, uv_map)
if left_loop and right_loop:
# project each vertex in loop_left into loop_right, order by projected length
projected_right_loop = project_boundary_loop(left_loop, right_loop)
# project each vertex in loop_right into loop_left, order by projected length
projected_left_loop = project_boundary_loop(right_loop, left_loop)
# the two loops should now be the same length and each index in the loops represents
# a point in one loop and/or it's projection in the other
# now average the loops into one loop representing the mesh hair card
loop = merge_length_coordinate_loops([projected_left_loop, projected_right_loop])
if loop:
return [loop]
utils.log_info("Loops have differing lengths or breaks, mesh extraction failed.")
return None
def selected_cards_to_length_loops(chr_cache, obj, card_dirs, one_loop_per_card = True, card_selection_mode = "SELECTED"):
prefs = vars.prefs()
props = vars.props()
# select linked and set to edge mode
utils.edit_mode_to(obj, only_this=True)
if card_selection_mode == "ALL":
bpy.ops.mesh.select_all(action='SELECT')
else:
bpy.ops.mesh.select_linked(delimit={'UV'})
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='FACE')
# object mode to save edit changes
utils.object_mode_to(obj)
deselect_invalid_materials(chr_cache, obj)
# get the bmesh
mesh = obj.data
bm = geom.get_bmesh(mesh)
# get lists of the faces in each selected island
islands = geom.get_uv_islands(bm, 0, use_selected=True)
utils.log_info(f"{len(islands)} islands selected.")
all_loops = []
cards = []
for island in islands:
utils.log_info(f"Processing island, faces: {len(island)}")
utils.log_indent()
is_grid = geom.is_island_grid(bm, island)
loops = None
if is_grid:
loops = grid_to_loops(obj, bm, island, card_dirs, one_loop_per_card)
if not loops:
is_grid = False
loops = mesh_to_loops(obj, bm, island, card_dirs)
if is_grid:
utils.log_info("Grid")
else:
utils.log_info("Polymesh")
face : bmesh.types.BMFace
verts = set()
for face_index in island:
face = bm.faces[face_index]
for vert in face.verts:
verts.add(vert.index)
card = { "verts": verts, "loops": loops }
cards.append(card)
utils.log_recess()
return cards, bm
def debug_loop(loop):
curve = create_curve()
add_poly_spline(loop, curve)
def selected_cards_to_curves(chr_cache, obj, card_dirs, one_loop_per_card = True):
curve = create_curve()
cards, bm = selected_cards_to_length_loops(chr_cache, obj, card_dirs, one_loop_per_card)
for card in cards:
loops = card["loops"]
for loop in loops:
add_poly_spline(loop, curve)
# TODO
# Put the curve object to the same scale as the body mesh
# With roots above the scalp plant the root of the curves into the scalp? (within tolerance)
# or add an new root point on the scalp...
# With roots below the scalp, crop the loop
# convert to curves
# set curve render subdivision to at least 2
# snap curves to surface
def loop_length(loop, index = -1):
if index == -1:
index = len(loop) - 1
p0 = loop[0]
d = 0
for i in range(1, index + 1):
p1 = loop[i]
d += (p1 - p0).length
p0 = p1
return d
def eval_loop_at(loop, length, fac):
p0 = loop[0]
f0 = 0
for i in range(1, len(loop)):
p1 = loop[i]
v = p1 - p0
fl = v.length / length
f1 = f0 + fl
if fl > 0 and fac <= f1 and fac >= f0:
df = fac - f0
return p0 + v * (df / fl)
f0 = f1
p0 = p1
f1 += fl
return p0
def is_on_loop(co, loop, threshold = 0.001):
"""Is the coordinate on the loop.
(All coordintes should be in world space)"""
p0 = loop[0]
min_distance = threshold + 1.0
for i in range(1, len(loop)):
p1 = loop[i]
dist, fac = distance_from_line(co, p0, p1)
if dist < min_distance:
min_distance = dist
if min_distance < threshold:
return True
p0 = p1
return min_distance < threshold
def clear_hair_bone_weights(chr_cache, arm, objects, card_mode, bone_mode, parent_mode):
utils.object_mode_to(arm)
bone_chain_defs = get_bone_chain_defs(chr_cache, arm, bone_mode, parent_mode)
hair_bones = []
for bone_chain in bone_chain_defs:
for bone_def in bone_chain:
hair_bones.append(bone_def["name"])
if not objects:
objects = meshutils.get_child_objects_with_vertex_groups(arm, hair_bones)
for obj in objects:
remove_hair_bone_weights(obj, hair_bones, card_mode)
arm.data.pose_position = "POSE"
utils.pose_mode_to(arm)
def remove_hair_bones(chr_cache, arm, bone_mode, parent_mode):
utils.object_mode_to(arm)
hair_bones = []
bone_chain_defs = get_bone_chain_defs(chr_cache, arm, bone_mode, parent_mode)
for bone_chain in bone_chain_defs:
for bone_def in bone_chain:
hair_bones.append(bone_def["name"])
# remove the bones in edit mode
if hair_bones and utils.edit_mode_to(arm, True):
for bone_name in hair_bones:
arm.data.edit_bones.remove(arm.data.edit_bones[bone_name])
# remove the spring rig if there are no child bones left
if utils.edit_mode_to(arm):
spring_rig = springbones.get_spring_rig(chr_cache, arm, parent_mode, mode = "EDIT")
if spring_rig and not spring_rig.children:
arm.data.edit_bones.remove(spring_rig)
#use all mesh objects in the character with matching vertex groups
objects = meshutils.get_child_objects_with_vertex_groups(arm, hair_bones)
#remove the weights from the character meshes
for obj in objects:
remove_hair_bone_weights(obj, hair_bones, "ALL")
utils.object_mode_to(arm)
def rename_hair_bones(chr_cache, arm, base_name, parent_mode):
utils.object_mode_to(arm)
bone_remap = {}
bone_chain_defs = None
hair_bones = []
bone_chain_defs = get_bone_chain_defs(chr_cache, arm, "SELECTED", parent_mode)
for bone_chain in bone_chain_defs:
for bone_def in bone_chain:
hair_bones.append(bone_def["name"])
utils.edit_mode_to(arm)
loop_index = 1
for bone_chain in bone_chain_defs:
loop_index = find_unused_hair_bone_index(arm, loop_index, base_name)
chain_index = 0
for bone_def in bone_chain:
old_name = bone_def["name"]
new_name = f"{base_name}_{loop_index}_{chain_index}"
edit_bone : bpy.types.EditBone
edit_bone = arm.data.edit_bones[old_name]
edit_bone.name = new_name
edit_bone.select = True
bone_remap[old_name] = edit_bone.name
chain_index += 1
utils.object_mode_to(arm)
#if no objects selected, use all mesh objects in the character with matching vertex groups
objects = meshutils.get_child_objects_with_vertex_groups(arm, hair_bones)
# now rename the vertex groups in all the objects...
for obj in objects:
for vg in obj.vertex_groups:
if vg.name in bone_remap:
vg.name = bone_remap[vg.name]
def contains_hair_bone_chain(arm, loop_index, prefix):
"""Edit mode"""
for bone in arm.data.edit_bones:
if bone.name.startswith(f"{prefix}_{loop_index}_"):
return True
return False
def find_unused_hair_bone_index(arm, loop_index, prefix):
"""Edit mode"""
while contains_hair_bone_chain(arm, loop_index, prefix):
loop_index += 1
return loop_index
def is_nearby_bone(arm, world_pos):
"""Edit mode"""
for edit_bone in arm.data.edit_bones:
length = (world_pos - arm.matrix_world @ edit_bone.head).length
if length < 0.01:
return True
return False
def custom_bone(chr_cache, arm, parent_mode, loop_index, bone_length, new_bones):
"""Must be in edit mode on the armature."""
props = vars.props()
hair_rig = springbones.get_spring_rig(chr_cache, arm, parent_mode, create_if_missing=True, mode = "EDIT")
hair_bone_prefix = props.hair_rig_group_name
if hair_rig:
parent_bone = hair_rig
bone_name = f"{hair_bone_prefix}_{loop_index}_0"
bone : bpy.types.EditBone = bones.new_edit_bone(arm, bone_name, parent_bone.name)
new_bones.append(bone_name)
bone.select = True
bone.select_head = True
bone.select_tail = True
world_origin = arm.matrix_world @ hair_rig.head
world_pos = world_origin + Vector((0, 0.05, 0.15))
while is_nearby_bone(arm, world_pos):
world_pos += Vector((0, 0.0175, 0))
world_head = world_pos
world_tail = world_pos + Vector((0, 0, bone_length))
bone.head = arm.matrix_world.inverted() @ world_head
bone.tail = arm.matrix_world.inverted() @ world_tail
bone_z = (((world_head + world_tail) * 0.5) - world_origin).normalized()
bone.align_roll(bone_z)
# set bone layer to 25, so we can show only the added hair bones 'in front'
bones.set_bone_collection(arm, bone, "Spring (Edit)", None, vars.SPRING_EDIT_LAYER)
# don't directly connect first bone in a chain
bone.use_connect = False
return True
return False
def get_linked_bones(edit_bone, bone_list):
if edit_bone.name not in bone_list:
bone_list.append(edit_bone.name)
for child_bone in edit_bone.children:
get_linked_bones(child_bone, bone_list)
return bone_list
def bone_chains_match(arm, bone_list_a, bone_list_b, tolerance = 0.001):
tolerance /= ((arm.scale[0] + arm.scale[1] + arm.scale[2]) / 3.0)
for bone_name_a in bone_list_a:
edit_bone_a = arm.data.edit_bones[bone_name_a]
has_match = False
for bone_name_b in bone_list_b:
edit_bone_b = arm.data.edit_bones[bone_name_b]
delta = (edit_bone_a.head - edit_bone_b.head).length + (edit_bone_a.tail - edit_bone_b.tail).length
if (delta < tolerance):
has_match = True
if not has_match:
return False
return True
def bone_chain_matches_loop(arm, bone_list, loop, threshold = 0.001):
for bone_name in bone_list:
if bone_name in arm.data.edit_bones:
edit_bone = arm.data.edit_bones[bone_name]
if not is_on_loop(arm.matrix_world @ edit_bone.head, loop, threshold):
return False
if not is_on_loop(arm.matrix_world @ edit_bone.tail, loop, threshold):
return False
else:
return False
return True
def remove_existing_loop_bones(chr_cache, arm, smoothed_loops):
"""Removes any bone chains in the hair rig that align with the loops"""
props = vars.props()
bone_selection_mode = props.hair_rig_bind_bone_mode
if bone_selection_mode == "SELECTED":
# select all linked bones
utils.edit_mode_to(arm)
bpy.ops.armature.select_linked()
utils.object_mode_to(arm)
utils.edit_mode_to(arm)
hair_rigs = springbones.get_spring_rigs(chr_cache, arm, ["HEAD", "JAW"], mode="EDIT")
remove_bone_list = []
remove_loop_set_list = []
removed_roots = []
for parent_mode in hair_rigs:
hair_rig = hair_rigs[parent_mode]["bone"]
if hair_rig:
for chain_root in hair_rig.children:
chain_root : bpy.types.EditBone
if chain_root not in removed_roots:
chain_bones = get_linked_bones(chain_root, [])
for smoothed_loop_set in smoothed_loops:
bone_smooth_level = 0
if BONE_SMOOTH_LEVEL_CUSTOM_PROP in chain_root:
bone_smooth_level = chain_root[BONE_SMOOTH_LEVEL_CUSTOM_PROP]
bone_smooth_loop = smoothed_loop_set[bone_smooth_level]
# compare the bone chain with the loop at it's generated smoothing level
if bone_chain_matches_loop(arm, chain_bones, bone_smooth_loop, 0.001):
remove_bones = False
remove_loop = False
if bone_selection_mode == "SELECTED":
if chain_root.select:
# if the chain is selected, then it is to be replaced, so remove it.
remove_bones = True
else:
# otherwise remove the loop, so it won't generate new bones over the existing bones.
remove_loop = True
else:
remove_bones = True
if remove_bones:
utils.log_info(f"Existing bone chain starting: {chain_root.name} is to be re-generated.")
remove_bone_list.extend(chain_bones)
removed_roots.append(chain_root)
if remove_loop:
utils.log_info(f"Existing bone chain starting: {chain_root.name} will not be replaced.")
remove_loop_set_list.append(smoothed_loop_set)
if remove_bone_list:
for bone_name in remove_bone_list:
if bone_name in arm.data.edit_bones:
utils.log_info(f"Removing bone on generating loop: {bone_name}")
arm.data.edit_bones.remove(arm.data.edit_bones[bone_name])
else:
utils.log_info(f"Already deleted: {bone_name} ?")
if remove_loop_set_list:
for smoothed_loop_set in remove_loop_set_list:
if smoothed_loop_set in smoothed_loops:
smoothed_loops.remove(smoothed_loop_set)
utils.log_info(f"Removing loop from generation list")
return
def remove_duplicate_bones(chr_cache, arm):
"""Remove any duplicate bone chains"""
remove_list = []
removed_roots = []
utils.edit_mode_to(arm)
hair_rigs = springbones.get_spring_rigs(chr_cache, arm, ["HEAD", "JAW"], mode = "EDIT")
for parent_mode in hair_rigs:
hair_rig = hair_rigs[parent_mode]["bone"]
if hair_rig:
for chain_root in hair_rig.children:
if chain_root not in removed_roots:
chain_bones = get_linked_bones(chain_root, [])
for i in range(len(hair_rig.children)-1, 0, -1):
test_chain_root = hair_rig.children[i]
if test_chain_root not in removed_roots:
test_chain_bones = get_linked_bones(test_chain_root, [])
if chain_root == test_chain_root:
break
if bone_chains_match(arm, test_chain_bones, chain_bones, 0.001):
remove_list.extend(test_chain_bones)
removed_roots.append(test_chain_root)
if remove_list:
for bone_name in remove_list:
if bone_name in arm.data.edit_bones:
utils.log_info(f"Removing duplicate bone: {bone_name}")
arm.data.edit_bones.remove(arm.data.edit_bones[bone_name])
else:
utils.log_info(f"Already deleted: {bone_name} ?")
# object mode to save changes to edit bones
utils.object_mode_to(arm)
return
def loop_to_bones(chr_cache, arm, parent_mode, loop, loop_index, bone_length,
skip_length, trunc_length, smooth_level, new_bones):
"""Generate hair rig bones from vertex loops. Must be in edit mode on armature."""
props = vars.props()
if len(loop) < 2:
return False
length = loop_length(loop)
# maximum skip length of half the length
skip_length = min(skip_length, length / 2.0)
# maximum trunc length of half the remaining length
trunc_length = min(trunc_length, (length - skip_length) / 2.0)
# skip zero length loops
if length < 0.001:
return False
segments = max(1, round((length - skip_length - trunc_length) / bone_length))
fac = skip_length / length
max_fac = (length - trunc_length) / length
df = (max_fac - fac) / segments
chain = []
first = True
hair_rig = springbones.get_spring_rig(chr_cache, arm, parent_mode, create_if_missing=True, mode = "EDIT")
hair_bone_prefix = props.hair_rig_group_name