-
Notifications
You must be signed in to change notification settings - Fork 75
/
weight_tools.py
2620 lines (2275 loc) · 94.1 KB
/
weight_tools.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
# SPDX-FileCopyrightText: 2022-2023 Blender Foundation
#
# SPDX-License-Identifier: GPL-2.0-or-later
import bpy, bmesh, os
import numpy as np
import math, timeit, time
from math import pi
from statistics import mean, stdev
from mathutils import Vector
from mathutils.kdtree import KDTree
from numpy import *
try: import numexpr as ne
except: pass
from bpy.types import (
Operator,
Panel,
PropertyGroup,
)
from bpy.props import (
BoolProperty,
EnumProperty,
FloatProperty,
IntProperty,
StringProperty,
FloatVectorProperty,
IntVectorProperty,
PointerProperty
)
from .utils import *
class formula_prop(PropertyGroup):
name : StringProperty()
formula : StringProperty()
float_var : FloatVectorProperty(name="", description="", default=(0, 0, 0, 0, 0), size=5)
int_var : IntVectorProperty(name="", description="", default=(0, 0, 0, 0, 0), size=5)
from numpy import *
def compute_formula(ob=None, formula="rx", float_var=(0,0,0,0,0), int_var=(0,0,0,0,0)):
verts = ob.data.vertices
n_verts = len(verts)
f1,f2,f3,f4,f5 = float_var
i1,i2,i3,i4,i5 = int_var
do_groups = "w[" in formula
do_local = "lx" in formula or "ly" in formula or "lz" in formula
do_global = "gx" in formula or "gy" in formula or "gz" in formula
do_relative = "rx" in formula or "ry" in formula or "rz" in formula
do_normal = "nx" in formula or "ny" in formula or "nz" in formula
mat = ob.matrix_world
for i in range(1000):
if "w["+str(i)+"]" in formula and i > len(ob.vertex_groups)-1:
return "w["+str(i)+"] not found"
w = []
for i in range(len(ob.vertex_groups)):
w.append([])
if "w["+str(i)+"]" in formula:
vg = ob.vertex_groups[i]
for v in verts:
try:
w[i].append(vg.weight(v.index))
except:
w[i].append(0)
w[i] = array(w[i])
start_time = timeit.default_timer()
# compute vertex coordinates
if do_local or do_relative or do_global:
co = [0]*n_verts*3
verts.foreach_get('co', co)
np_co = array(co).reshape((n_verts, 3))
lx, ly, lz = array(np_co).transpose()
if do_relative:
rx = np.interp(lx, (lx.min(), lx.max()), (0, +1))
ry = np.interp(ly, (ly.min(), ly.max()), (0, +1))
rz = np.interp(lz, (lz.min(), lz.max()), (0, +1))
if do_global:
co = [v.co for v in verts]
global_co = []
for v in co:
global_co.append(mat @ v)
global_co = array(global_co).reshape((n_verts, 3))
gx, gy, gz = array(global_co).transpose()
# compute vertex normals
if do_normal:
normal = [0]*n_verts*3
verts.foreach_get('normal', normal)
normal = array(normal).reshape((n_verts, 3))
nx, ny, nz = array(normal).transpose()
try:
weight = eval(formula)
return weight
except:
return "There is something wrong"
print("Weight Formula: " + str(timeit.default_timer() - start_time))
class weight_formula_wiki(Operator):
bl_idname = "scene.weight_formula_wiki"
bl_label = "Online Documentation"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
bpy.ops.wm.url_open(url="https://github.com/alessandro-zomparelli/tissue/wiki/Weight-Tools#weight-formula")
return {'FINISHED'}
class weight_formula(Operator):
bl_idname = "object.weight_formula"
bl_label = "Weight Formula"
bl_description = "Generate a Vertex Group according to a mathematical formula"
bl_options = {'REGISTER', 'UNDO'}
ex_items = [
('cos(arctan(nx/ny)*i1*2 + sin(rz*i3))/i2 + cos(arctan(nx/ny)*i1*2 - sin(rz*i3))/i2 + 0.5','Vertical Spots'),
('cos(arctan(nx/ny)*i1*2 + sin(rz*i2))/2 + cos(arctan(nx/ny)*i1*2 - sin(rz*i2))/2','Vertical Spots'),
('(sin(arctan(nx/ny)*i1*2)*sin(nz*i1*2)+1)/2','Grid Spots'),
('cos(arctan(nx/ny)*f1)','Vertical Stripes'),
('cos(arctan(lx/ly)*f1 + sin(rz*f2)*f3)','Curly Stripes'),
('sin(rz*pi*i1+arctan2(nx,ny))/2+0.5', 'Vertical Spiral'),
('sin(nx*15)<sin(ny*15)','Chess'),
('cos(ny*rz**2*i1)','Hyperbolic'),
('sin(rx*30) > 0','Step Stripes'),
('sin(nz*i1)','Normal Stripes'),
('w[0]**2','Vertex Group square'),
('abs(0.5-rz)*2','Double vertical gradient'),
('rz', 'Vertical Gradient')
]
_ex_items = list((str(i),'{} ( {} )'.format(s[0],s[1]),s[1]) for i,s in enumerate(ex_items))
_ex_items.append(('CUSTOM', "User Formula", ""))
examples : EnumProperty(
items = _ex_items, default='CUSTOM', name="Examples")
old_ex = ""
formula : StringProperty(
name="Formula", default="", description="Formula to Evaluate")
slider_f01 : FloatProperty(
name="f1", default=1, description="Slider Float 1")
slider_f02 : FloatProperty(
name="f2", default=1, description="Slider Float 2")
slider_f03 : FloatProperty(
name="f3", default=1, description="Slider Float 3")
slider_f04 : FloatProperty(
name="f4", default=1, description="Slider Float 4")
slider_f05 : FloatProperty(
name="f5", default=1, description="Slider Float 5")
slider_i01 : IntProperty(
name="i1", default=1, description="Slider Integer 1")
slider_i02 : IntProperty(
name="i2", default=1, description="Slider Integer 2")
slider_i03 : IntProperty(
name="i3", default=1, description="Slider Integer 3")
slider_i04 : IntProperty(
name="i4", default=1, description="Slider Integer 4")
slider_i05 : IntProperty(
name="i5", default=1, description="Slider Integer 5")
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self, width=350)
def draw(self, context):
layout = self.layout
#layout.label(text="Examples")
layout.prop(self, "examples", text="Examples")
#if self.examples == 'CUSTOM':
layout.label(text="Formula")
layout.prop(self, "formula", text="")
#try: self.examples = self.formula
#except: pass
if self.examples != 'CUSTOM':
example = self.ex_items[int(self.examples)][0]
if example != self.old_ex:
self.formula = example
self.old_ex = example
elif self.formula != example:
self.examples = 'CUSTOM'
formula = self.formula
layout.separator()
if "f1" in formula: layout.prop(self, "slider_f01")
if "f2" in formula: layout.prop(self, "slider_f02")
if "f3" in formula: layout.prop(self, "slider_f03")
if "f4" in formula: layout.prop(self, "slider_f04")
if "f5" in formula: layout.prop(self, "slider_f05")
if "i1" in formula: layout.prop(self, "slider_i01")
if "i2" in formula: layout.prop(self, "slider_i02")
if "i3" in formula: layout.prop(self, "slider_i03")
if "i4" in formula: layout.prop(self, "slider_i04")
if "i5" in formula: layout.prop(self, "slider_i05")
layout.label(text="Variables (for each vertex):")
layout.label(text="lx, ly, lz: Local Coordinates", icon='ORIENTATION_LOCAL')
layout.label(text="gx, gy, gz: Global Coordinates", icon='WORLD')
layout.label(text="rx, ry, rz: Local Coordinates (0 to 1)", icon='NORMALIZE_FCURVES')
layout.label(text="nx, ny, nz: Normal Coordinates", icon='SNAP_NORMAL')
layout.label(text="w[0], w[1], w[2], ... : Vertex Groups", icon="GROUP_VERTEX")
layout.separator()
layout.label(text="f1, f2, f3, f4, f5: Float Sliders", icon='MOD_HUE_SATURATION')#PROPERTIES
layout.label(text="i1, i2, i3, i4, i5: Integer Sliders", icon='MOD_HUE_SATURATION')
layout.separator()
#layout.label(text="All mathematical functions are based on Numpy", icon='INFO')
#layout.label(text="https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.math.html", icon='INFO')
layout.operator("scene.weight_formula_wiki", icon="HELP")
#layout.label(text="(where 'i' is the index of the Vertex Group)")
def execute(self, context):
ob = context.active_object
n_verts = len(ob.data.vertices)
#if self.examples == 'CUSTOM':
# formula = self.formula
#else:
#self.formula = self.examples
# formula = self.examples
#f1, f2, f3, f4, f5 = self.slider_f01, self.slider_f02, self.slider_f03, self.slider_f04, self.slider_f05
#i1, i2, i3, i4, i5 = self.slider_i01, self.slider_i02, self.slider_i03, self.slider_i04, self.slider_i05
f_sliders = self.slider_f01, self.slider_f02, self.slider_f03, self.slider_f04, self.slider_f05
i_sliders = self.slider_i01, self.slider_i02, self.slider_i03, self.slider_i04, self.slider_i05
if self.examples != 'CUSTOM':
example = self.ex_items[int(self.examples)][0]
if example != self.old_ex:
self.formula = example
self.old_ex = example
elif self.formula != example:
self.examples = 'CUSTOM'
formula = self.formula
if formula == "": return {'FINISHED'}
# replace numeric sliders value
for i, slider in enumerate(f_sliders):
formula = formula.replace('f'+str(i+1),"{0:.2f}".format(slider))
for i, slider in enumerate(i_sliders):
formula =formula.replace('i'+str(i+1),str(slider))
vertex_group_name = "" + formula
ob.vertex_groups.new(name=vertex_group_name)
weight = compute_formula(ob, formula=formula, float_var=f_sliders, int_var=i_sliders)
if type(weight) == str:
self.report({'ERROR'}, weight)
return {'CANCELLED'}
#start_time = timeit.default_timer()
weight = nan_to_num(weight)
vg = ob.vertex_groups[-1]
if type(weight) == int or type(weight) == float:
for i in range(n_verts):
vg.add([i], weight, 'REPLACE')
elif type(weight) == ndarray:
for i in range(n_verts):
vg.add([i], weight[i], 'REPLACE')
ob.data.update()
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
# Store formula settings
new_formula = ob.formula_settings.add()
new_formula.name = ob.vertex_groups[-1].name
new_formula.formula = formula
new_formula.int_var = i_sliders
new_formula.float_var = f_sliders
#for f in ob.formula_settings:
# print(f.name, f.formula, f.int_var, f.float_var)
return {'FINISHED'}
class update_weight_formula(Operator):
bl_idname = "object.update_weight_formula"
bl_label = "Update Weight Formula"
bl_description = "Update an existing Vertex Group. Make sure that the name\nof the active Vertex Group is a valid formula"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return len(context.object.vertex_groups) > 0
def execute(self, context):
ob = context.active_object
n_verts = len(ob.data.vertices)
vg = ob.vertex_groups.active
formula = vg.name
weight = compute_formula(ob, formula=formula)
if type(weight) == str:
self.report({'ERROR'}, "The name of the active Vertex Group\nis not a valid Formula")
return {'CANCELLED'}
#start_time = timeit.default_timer()
weight = nan_to_num(weight)
if type(weight) == int or type(weight) == float:
for i in range(n_verts):
vg.add([i], weight, 'REPLACE')
elif type(weight) == ndarray:
for i in range(n_verts):
vg.add([i], weight[i], 'REPLACE')
ob.data.update()
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
return {'FINISHED'}
class _weight_laplacian(Operator):
bl_idname = "object._weight_laplacian"
bl_label = "Weight Laplacian"
bl_description = ("Compute the Vertex Group Laplacian")
bl_options = {'REGISTER', 'UNDO'}
bounds : EnumProperty(
items=(('MANUAL', "Manual Bounds", ""),
('POSITIVE', "Positive Only", ""),
('NEGATIVE', "Negative Only", ""),
('AUTOMATIC', "Automatic Bounds", "")),
default='AUTOMATIC', name="Bounds")
mode : EnumProperty(
items=(('LENGTH', "Length Weight", ""),
('SIMPLE', "Simple", "")),
default='SIMPLE', name="Evaluation Mode")
min_def : FloatProperty(
name="Min", default=0, soft_min=-1, soft_max=0,
description="Laplacian value with 0 weight")
max_def : FloatProperty(
name="Max", default=0.5, soft_min=0, soft_max=5,
description="Laplacian value with 1 weight")
bounds_string = ""
frame = None
@classmethod
def poll(cls, context):
return len(context.object.vertex_groups) > 0
def draw(self, context):
layout = self.layout
col = layout.column(align=True)
col.label(text="Evaluation Mode")
col.prop(self, "mode", text="")
col.label(text="Bounds")
col.prop(self, "bounds", text="")
if self.bounds == 'MANUAL':
col.label(text="Strain Rate \u03B5:")
col.prop(self, "min_def")
col.prop(self, "max_def")
col.label(text="\u03B5" + ": from " + self.bounds_string)
def execute(self, context):
try: ob = context.object
except:
self.report({'ERROR'}, "Please select an Object")
return {'CANCELLED'}
group_id = ob.vertex_groups.active_index
input_group = ob.vertex_groups[group_id].name
group_name = "Laplacian"
ob.vertex_groups.new(name=group_name)
me = ob.data
bm = bmesh.new()
bm.from_mesh(me)
bm.edges.ensure_lookup_table()
# store weight values
weight = []
for v in me.vertices:
try:
weight.append(ob.vertex_groups[input_group].weight(v.index))
except:
weight.append(0)
n_verts = len(bm.verts)
lap = [0]*n_verts
for e in bm.edges:
if self.mode == 'LENGTH':
length = e.calc_length()
if length == 0: continue
id0 = e.verts[0].index
id1 = e.verts[1].index
lap[id0] += weight[id1]/length - weight[id0]/length
lap[id1] += weight[id0]/length - weight[id1]/length
else:
id0 = e.verts[0].index
id1 = e.verts[1].index
lap[id0] += weight[id1] - weight[id0]
lap[id1] += weight[id0] - weight[id1]
mean_lap = mean(lap)
stdev_lap = stdev(lap)
filter_lap = [i for i in lap if mean_lap-2*stdev_lap < i < mean_lap+2*stdev_lap]
if self.bounds == 'MANUAL':
min_def = self.min_def
max_def = self.max_def
elif self.bounds == 'AUTOMATIC':
min_def = min(filter_lap)
max_def = max(filter_lap)
self.min_def = min_def
self.max_def = max_def
elif self.bounds == 'NEGATIVE':
min_def = 0
max_def = min(filter_lap)
self.min_def = min_def
self.max_def = max_def
elif self.bounds == 'POSITIVE':
min_def = 0
max_def = max(filter_lap)
self.min_def = min_def
self.max_def = max_def
delta_def = max_def - min_def
# check undeformed errors
if delta_def == 0: delta_def = 0.0001
for i in range(len(lap)):
val = (lap[i]-min_def)/delta_def
#if val > 0.7: print(str(val) + " " + str(lap[i]))
#val = weight[i] + 0.2*lap[i]
ob.vertex_groups[-1].add([i], val, 'REPLACE')
self.bounds_string = str(round(min_def,2)) + " to " + str(round(max_def,2))
ob.vertex_groups[-1].name = group_name + " " + self.bounds_string
ob.vertex_groups.update()
ob.data.update()
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
bm.free()
return {'FINISHED'}
class ok_weight_laplacian(Operator):
bl_idname = "object.weight_laplacian"
bl_label = "Weight Laplacian"
bl_description = ("Compute the Vertex Group Laplacian")
bl_options = {'REGISTER', 'UNDO'}
bounds_string = ""
frame = None
@classmethod
def poll(cls, context):
return len(context.object.vertex_groups) > 0
def execute(self, context):
try: ob = context.object
except:
self.report({'ERROR'}, "Please select an Object")
return {'CANCELLED'}
me = ob.data
bm = bmesh.new()
bm.from_mesh(me)
bm.edges.ensure_lookup_table()
group_id = ob.vertex_groups.active_index
input_group = ob.vertex_groups[group_id].name
group_name = "Laplacian"
ob.vertex_groups.new(name=group_name)
# store weight values
a = []
for v in me.vertices:
try:
a.append(ob.vertex_groups[input_group].weight(v.index))
except:
a.append(0)
a = array(a)
# initialize
n_verts = len(bm.verts)
# find max number of edges for vertex
max_edges = 0
n_neighbors = []
id_neighbors = []
for v in bm.verts:
n_edges = len(v.link_edges)
max_edges = max(max_edges, n_edges)
n_neighbors.append(n_edges)
neighbors = []
for e in v.link_edges:
for v1 in e.verts:
if v != v1: neighbors.append(v1.index)
id_neighbors.append(neighbors)
n_neighbors = array(n_neighbors)
lap_map = [[] for i in range(n_verts)]
#lap_map = []
'''
for e in bm.edges:
id0 = e.verts[0].index
id1 = e.verts[1].index
lap_map[id0].append(id1)
lap_map[id1].append(id0)
'''
lap = zeros((n_verts))#[0]*n_verts
n_records = zeros((n_verts))
for e in bm.edges:
id0 = e.verts[0].index
id1 = e.verts[1].index
length = e.calc_length()
if length == 0: continue
#lap[id0] += abs(a[id1] - a[id0])/length
#lap[id1] += abs(a[id0] - a[id1])/length
lap[id0] += (a[id1] - a[id0])/length
lap[id1] += (a[id0] - a[id1])/length
n_records[id0]+=1
n_records[id1]+=1
lap /= n_records
lap /= max(lap)
for i in range(n_verts):
ob.vertex_groups['Laplacian'].add([i], lap[i], 'REPLACE')
ob.vertex_groups.update()
ob.data.update()
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
bm.free()
return {'FINISHED'}
class weight_laplacian(Operator):
bl_idname = "object.weight_laplacian"
bl_label = "Weight Laplacian"
bl_description = ("Compute the Vertex Group Laplacian")
bl_options = {'REGISTER', 'UNDO'}
bounds_string = ""
frame = None
@classmethod
def poll(cls, context):
return len(context.object.vertex_groups) > 0
def execute(self, context):
try: ob = context.object
except:
self.report({'ERROR'}, "Please select an Object")
return {'CANCELLED'}
me = ob.data
bm = bmesh.new()
bm.from_mesh(me)
bm.edges.ensure_lookup_table()
n_verts = len(me.vertices)
group_id = ob.vertex_groups.active_index
input_group = ob.vertex_groups[group_id].name
group_name = "Laplacian"
vg = ob.vertex_groups.new(name=group_name)
# store weight values
dvert_lay = bm.verts.layers.deform.active
weight = bmesh_get_weight_numpy(group_id, dvert_lay, bm.verts)
#verts, normals = get_vertices_and_normals_numpy(me)
#lap = zeros((n_verts))#[0]*n_verts
lap = [Vector((0,0,0)) for i in range(n_verts)]
n_records = zeros((n_verts))
for e in bm.edges:
vert0 = e.verts[0]
vert1 = e.verts[1]
id0 = vert0.index
id1 = vert1.index
v0 = vert0.co
v1 = vert1.co
v01 = v1-v0
v10 = -v01
v01 -= v01.project(vert0.normal)
v10 -= v10.project(vert1.normal)
length = e.calc_length()
if length == 0: continue
dw = (weight[id1] - weight[id0])/length
lap[id0] += v01.normalized() * dw
lap[id1] -= v10.normalized() * dw
n_records[id0]+=1
n_records[id1]+=1
#lap /= n_records[:,np.newaxis]
lap = [l.length/r for r,l in zip(n_records,lap)]
lap = np.array(lap)
lap /= np.max(lap)
lap = list(lap)
for i in range(n_verts):
vg.add([i], lap[i], 'REPLACE')
ob.vertex_groups.update()
ob.data.update()
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
bm.free()
return {'FINISHED'}
class edges_deformation(Operator):
bl_idname = "object.edges_deformation"
bl_label = "Edges Deformation"
bl_description = ("Compute Weight based on the deformation of edges"+
"according to visible modifiers.")
bl_options = {'REGISTER', 'UNDO'}
bounds : EnumProperty(
items=(('MANUAL', "Manual Bounds", ""),
('COMPRESSION', "Compressed Only", ""),
('TENSION', "Extended Only", ""),
('AUTOMATIC', "Automatic Bounds", "")),
default='AUTOMATIC', name="Bounds")
mode : EnumProperty(
items=(('MAX', "Max Deformation", ""),
('MEAN', "Average Deformation", "")),
default='MEAN', name="Evaluation Mode")
min_def : FloatProperty(
name="Min", default=0, soft_min=-1, soft_max=0,
description="Deformations with 0 weight")
max_def : FloatProperty(
name="Max", default=0.5, soft_min=0, soft_max=5,
description="Deformations with 1 weight")
bounds_string = ""
frame = None
@classmethod
def poll(cls, context):
return len(context.object.modifiers) > 0
def draw(self, context):
layout = self.layout
col = layout.column(align=True)
col.label(text="Evaluation Mode")
col.prop(self, "mode", text="")
col.label(text="Bounds")
col.prop(self, "bounds", text="")
if self.bounds == 'MANUAL':
col.label(text="Strain Rate \u03B5:")
col.prop(self, "min_def")
col.prop(self, "max_def")
col.label(text="\u03B5" + ": from " + self.bounds_string)
def execute(self, context):
try: ob = context.object
except:
self.report({'ERROR'}, "Please select an Object")
return {'CANCELLED'}
# check if the object is Cloth or Softbody
physics = False
for m in ob.modifiers:
if m.type == 'CLOTH' or m.type == 'SOFT_BODY':
physics = True
if context.scene.frame_current == 1 and self.frame != None:
context.scene.frame_current = self.frame
break
if not physics: self.frame = None
if self.mode == 'MEAN': group_name = "Average Deformation"
elif self.mode == 'MAX': group_name = "Max Deformation"
ob.vertex_groups.new(name=group_name)
me0 = ob.data
me = simple_to_mesh(ob) #ob.to_mesh(preserve_all_data_layers=True, depsgraph=bpy.context.evaluated_depsgraph_get()).copy()
if len(me.vertices) != len(me0.vertices) or len(me.edges) != len(me0.edges):
self.report({'ERROR'}, "The topology of the object should be" +
"unaltered")
return {'CANCELLED'}
bm0 = bmesh.new()
bm0.from_mesh(me0)
bm = bmesh.new()
bm.from_mesh(me)
deformations = []
for e0, e in zip(bm0.edges, bm.edges):
try:
l0 = e0.calc_length()
l1 = e.calc_length()
epsilon = (l1 - l0)/l0
deformations.append(epsilon)
except: deformations.append(1)
v_deformations = []
for v in bm.verts:
vdef = []
for e in v.link_edges:
vdef.append(deformations[e.index])
if self.mode == 'MEAN': v_deformations.append(mean(vdef))
elif self.mode == 'MAX': v_deformations.append(max(vdef, key=abs))
#elif self.mode == 'MIN': v_deformations.append(min(vdef, key=abs))
if self.bounds == 'MANUAL':
min_def = self.min_def
max_def = self.max_def
elif self.bounds == 'AUTOMATIC':
min_def = min(v_deformations)
max_def = max(v_deformations)
self.min_def = min_def
self.max_def = max_def
elif self.bounds == 'COMPRESSION':
min_def = 0
max_def = min(v_deformations)
self.min_def = min_def
self.max_def = max_def
elif self.bounds == 'TENSION':
min_def = 0
max_def = max(v_deformations)
self.min_def = min_def
self.max_def = max_def
delta_def = max_def - min_def
# check undeformed errors
if delta_def == 0:
if self.bounds == 'MANUAL':
delta_def = 0.0001
else:
message = "The object doesn't have deformations."
if physics:
message = message + ("\nIf you are using Physics try to " +
"save it in the cache before.")
self.report({'ERROR'}, message)
return {'CANCELLED'}
else:
if physics:
self.frame = context.scene.frame_current
for i in range(len(v_deformations)):
weight = (v_deformations[i] - min_def)/delta_def
ob.vertex_groups[-1].add([i], weight, 'REPLACE')
self.bounds_string = str(round(min_def,2)) + " to " + str(round(max_def,2))
ob.vertex_groups[-1].name = group_name + " " + self.bounds_string
ob.vertex_groups.update()
ob.data.update()
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
bpy.data.meshes.remove(me)
bm.free()
bm0.free()
return {'FINISHED'}
class edges_bending(Operator):
bl_idname = "object.edges_bending"
bl_label = "Edges Bending"
bl_description = ("Compute Weight based on the bending of edges"+
"according to visible modifiers.")
bl_options = {'REGISTER', 'UNDO'}
bounds : EnumProperty(
items=(('MANUAL', "Manual Bounds", ""),
('POSITIVE', "Positive Only", ""),
('NEGATIVE', "Negative Only", ""),
('UNSIGNED', "Absolute Bending", ""),
('AUTOMATIC', "Signed Bending", "")),
default='AUTOMATIC', name="Bounds")
min_def : FloatProperty(
name="Min", default=-10, soft_min=-45, soft_max=45,
description="Deformations with 0 weight")
max_def : FloatProperty(
name="Max", default=10, soft_min=-45, soft_max=45,
description="Deformations with 1 weight")
bounds_string = ""
frame = None
@classmethod
def poll(cls, context):
return len(context.object.modifiers) > 0
def draw(self, context):
layout = self.layout
layout.label(text="Bounds")
layout.prop(self, "bounds", text="")
if self.bounds == 'MANUAL':
layout.prop(self, "min_def")
layout.prop(self, "max_def")
def execute(self, context):
try: ob = context.object
except:
self.report({'ERROR'}, "Please select an Object")
return {'CANCELLED'}
group_name = "Edges Bending"
ob.vertex_groups.new(name=group_name)
# check if the object is Cloth or Softbody
physics = False
for m in ob.modifiers:
if m.type == 'CLOTH' or m.type == 'SOFT_BODY':
physics = True
if context.scene.frame_current == 1 and self.frame != None:
context.scene.frame_current = self.frame
break
if not physics: self.frame = None
#ob.data.update()
#context.scene.update()
me0 = ob.data
me = simple_to_mesh(ob) #ob.to_mesh(preserve_all_data_layers=True, depsgraph=bpy.context.evaluated_depsgraph_get()).copy()
if len(me.vertices) != len(me0.vertices) or len(me.edges) != len(me0.edges):
self.report({'ERROR'}, "The topology of the object should be" +
"unaltered")
bm0 = bmesh.new()
bm0.from_mesh(me0)
bm = bmesh.new()
bm.from_mesh(me)
deformations = []
for e0, e in zip(bm0.edges, bm.edges):
try:
ang = e.calc_face_angle_signed()
ang0 = e0.calc_face_angle_signed()
if self.bounds == 'UNSIGNED':
deformations.append(abs(ang-ang0))
else:
deformations.append(ang-ang0)
except: deformations.append(0)
v_deformations = []
for v in bm.verts:
vdef = []
for e in v.link_edges:
vdef.append(deformations[e.index])
v_deformations.append(mean(vdef))
if self.bounds == 'MANUAL':
min_def = radians(self.min_def)
max_def = radians(self.max_def)
elif self.bounds == 'AUTOMATIC':
min_def = min(v_deformations)
max_def = max(v_deformations)
elif self.bounds == 'POSITIVE':
min_def = 0
max_def = min(v_deformations)
elif self.bounds == 'NEGATIVE':
min_def = 0
max_def = max(v_deformations)
elif self.bounds == 'UNSIGNED':
min_def = 0
max_def = max(v_deformations)
delta_def = max_def - min_def
# check undeformed errors
if delta_def == 0:
if self.bounds == 'MANUAL':
delta_def = 0.0001
else:
message = "The object doesn't have deformations."
if physics:
message = message + ("\nIf you are using Physics try to " +
"save it in the cache before.")
self.report({'ERROR'}, message)
return {'CANCELLED'}
else:
if physics:
self.frame = context.scene.frame_current
for i in range(len(v_deformations)):
weight = (v_deformations[i] - min_def)/delta_def
ob.vertex_groups[-1].add([i], weight, 'REPLACE')
self.bounds_string = str(round(min_def,2)) + " to " + str(round(max_def,2))
ob.vertex_groups[-1].name = group_name + " " + self.bounds_string
ob.vertex_groups.update()
ob.data.update()
bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
bpy.data.meshes.remove(me)
bm0.free()
bm.free()
return {'FINISHED'}
class weight_contour_displace(Operator):
bl_idname = "object.weight_contour_displace"
bl_label = "Contour Displace"
bl_description = ("")
bl_options = {'REGISTER', 'UNDO'}
use_modifiers : BoolProperty(
name="Use Modifiers", default=True,
description="Apply all the modifiers")
min_iso : FloatProperty(
name="Min Iso Value", default=0.49, min=0, max=1,
description="Threshold value")
max_iso : FloatProperty(
name="Max Iso Value", default=0.51, min=0, max=1,
description="Threshold value")
n_cuts : IntProperty(
name="Cuts", default=2, min=1, soft_max=10,
description="Number of cuts in the selected range of values")
bool_displace : BoolProperty(
name="Add Displace", default=True, description="Add Displace Modifier")
bool_flip : BoolProperty(
name="Flip", default=False, description="Flip Output Weight")
weight_mode : EnumProperty(
items=[('Remapped', 'Remapped', 'Remap values'),
('Alternate', 'Alternate', 'Alternate 0 and 1'),
('Original', 'Original', 'Keep original Vertex Group')],
name="Weight", description="Choose how to convert vertex group",
default="Remapped", options={'LIBRARY_EDITABLE'})
@classmethod
def poll(cls, context):
return len(context.object.vertex_groups) > 0
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self, width=350)
def execute(self, context):
start_time = timeit.default_timer()
try:
check = context.object.vertex_groups[0]
except:
self.report({'ERROR'}, "The object doesn't have Vertex Groups")
return {'CANCELLED'}
ob0 = context.object
group_id = ob0.vertex_groups.active_index
vertex_group_name = ob0.vertex_groups[group_id].name
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
if self.use_modifiers:
#me0 = ob0.to_mesh(preserve_all_data_layers=True, depsgraph=bpy.context.evaluated_depsgraph_get()).copy()
me0 = simple_to_mesh(ob0)
else:
me0 = ob0.data.copy()
# generate new bmesh
bm = bmesh.new()
bm.from_mesh(me0)
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
# store weight values
weight = []
ob = bpy.data.objects.new("temp", me0)
for g in ob0.vertex_groups:
ob.vertex_groups.new(name=g.name)
for v in me0.vertices:
try:
weight.append(ob.vertex_groups[vertex_group_name].weight(v.index))
except:
weight.append(0)
# define iso values
iso_values = []
for i_cut in range(self.n_cuts):
delta_iso = abs(self.max_iso - self.min_iso)
min_iso = min(self.min_iso, self.max_iso)
max_iso = max(self.min_iso, self.max_iso)
if delta_iso == 0: iso_val = min_iso
elif self.n_cuts > 1: iso_val = i_cut/(self.n_cuts-1)*delta_iso + min_iso
else: iso_val = (self.max_iso + self.min_iso)/2
iso_values.append(iso_val)
# Start Cuts Iterations
filtered_edges = bm.edges
for iso_val in iso_values:
delete_edges = []
faces_mask = []
for f in bm.faces:
w_min = 2
w_max = 2
for v in f.verts:
w = weight[v.index]
if w_min == 2:
w_max = w_min = w
if w > w_max: w_max = w
if w < w_min: w_min = w
if w_min < iso_val and w_max > iso_val:
faces_mask.append(f)
break
#link_faces = [[f for f in e.link_faces] for e in bm.edges]
#faces_todo = [f.select for f in bm.faces]
#faces_todo = [True for f in bm.faces]
verts = []
edges = []
edges_id = {}
_filtered_edges = []
n_verts = len(bm.verts)
count = n_verts
for e in filtered_edges:
#id0 = e.vertices[0]
#id1 = e.vertices[1]
id0 = e.verts[0].index
id1 = e.verts[1].index