-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathModelingCloth
941 lines (758 loc) · 36.2 KB
/
ModelingCloth
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
# You are at the top. If you attempt to go any higher
# you will go beyond the known limits of the code
# universe where there are most certainly monsters
# to do:
# add sewing springs
# set up better indexing so that edges only get calculated once
# self colisions
# object collisions
# add bending springs
# add curl by shortening bending springs on one axis or diagonal
# independantly scale bending springs and structural to create buckling
# run on frame update as an option?
# option to cache animation?
'''??? Would it make sense to do self collisions with virtual edges ???'''
bl_info = {
"name": "Modeling Cloth",
"author": "Rich Colburn, email: [email protected]",
"version": (1, 0),
"blender": (2, 78, 0),
"location": "View3D > Extended Tools > Modeling Cloth",
"description": "Maintains the surface area of an object so it behaves like cloth",
"warning": "There might be an angry rhinoceros behind you",
"wiki_url": "",
"category": '3D View'}
import bpy
import bmesh
import numpy as np
from numpy import newaxis as nax
from bpy_extras import view3d_utils
you_have_a_sense_of_humor = False
#you_have_a_sense_of_humor = True
if you_have_a_sense_of_humor:
import antigravity
def create_vertex_groups(groups=['common', 'not_used'], weights=[0.0, 0.0], ob=None):
'''Creates vertex groups and sets weights. "groups" is a list of strings
for the names of the groups. "weights" is a list of weights corresponding
to the strings. Each vertex is assigned a weight for each vertex group to
avoid calling vertex weights that are not assigned. If the groups are
already present, the previous weights will be preserved. To reset weights
delete the created groups'''
if ob is None:
ob = bpy.context.object
vg = ob.vertex_groups
for g in range(0, len(groups)):
if groups[g] not in vg.keys(): # Don't create groups if there are already there
vg.new(groups[g])
vg[groups[g]].add(range(0,len(ob.data.vertices)), weights[g], 'REPLACE')
else:
vg[groups[g]].add(range(0,len(ob.data.vertices)), 0, 'ADD') # This way we avoid resetting the weights for existing groups.
def tile_eidx():
'''currently not used'''
obm = get_bmesh()
obm.verts.ensure_lookup_table()
unique = []
tile = []
flip = []
return unique, tile, flip
def get_bmesh(ob=None):
ob = get_last_object()[1]
obm = bmesh.new()
if ob.mode == 'OBJECT':
obm.from_mesh(ob.data)
elif ob.mode == 'EDIT':
obm = bmesh.from_edit_mesh(ob.data)
return obm
def connected_by_polygons():
obm = get_bmesh()
obm.verts.ensure_lookup_table()
virtual_edges = []
for v in obm.verts:
lv = np.hstack([[fv.index for fv in f.verts if fv != v] for f in v.link_faces])
for i in np.unique(lv):
virtual_edges.append([v.index, i])
return np.array(virtual_edges) # note there are many duplicates: [0,72], [72,0]
def get_last_object():
"""Finds cloth objects for keeping settings active
while selecting other objects like pins"""
cloths = [i for i in bpy.data.objects if i.modeling_cloth] # so we can select an empty and keep the settings menu up
if bpy.context.object.modeling_cloth:
return cloths, bpy.context.object
if len(cloths) > 0: #
ob = extra_data['last_object']
return cloths, ob
return None
def generate_guide_mesh():
"""Makes the icosphere that appears when creating pins"""
verts = [[0.0, 0.0, 0.0], [-0.01, -0.01, 0.1], [-0.01, 0.01, 0.1], [0.01, -0.01, 0.1], [0.01, 0.01, 0.1], [-0.03, -0.03, 0.1], [-0.03, 0.03, 0.1], [0.03, 0.03, 0.1], [0.03, -0.03, 0.1], [-0.01, -0.01, 0.2], [-0.01, 0.01, 0.2], [0.01, -0.01, 0.2], [0.01, 0.01, 0.2]]
edges = [[0, 5], [5, 6], [6, 7], [7, 8], [8, 5], [1, 2], [2, 4], [4, 3], [3, 1], [5, 1], [2, 6], [4, 7], [3, 8], [9, 10], [10, 12], [12, 11], [11, 9], [3, 11], [9, 1], [2, 10], [12, 4], [6, 0], [7, 0], [8, 0]]
faces = [[0, 5, 6], [0, 6, 7], [0, 7, 8], [0, 8, 5], [1, 3, 11, 9], [1, 2, 6, 5], [2, 4, 7, 6], [4, 3, 8, 7], [3, 1, 5, 8], [12, 10, 9, 11], [4, 2, 10, 12], [3, 4, 12, 11], [2, 1, 9, 10]]
name = 'ModelingClothPinGuide'
if 'ModelingClothPinGuide' in bpy.data.objects:
mesh_ob = bpy.data.objects['ModelingClothPinGuide']
else:
mesh = bpy.data.meshes.new('ModelingClothPinGuide')
mesh.from_pydata(verts, edges, faces)
mesh.update()
mesh_ob = bpy.data.objects.new(name, mesh)
bpy.context.scene.objects.link(mesh_ob)
mesh_ob.show_x_ray = True
return mesh_ob
def create_giude():
"""Spawns the guide"""
if 'ModelingClothPinGuide' in bpy.data.objects:
mesh_ob = bpy.data.objects['ModelingClothPinGuide']
return mesh_ob
mesh_ob = generate_guide_mesh()
bpy.context.scene.objects.active = mesh_ob
bpy.ops.object.material_slot_add()
if 'ModelingClothPinGuide' in bpy.data.materials:
mat = bpy.data.materials['ModelingClothPinGuide']
else:
mat = bpy.data.materials.new(name='ModelingClothPinGuide')
mat.use_transparency = True
mat.alpha = 0.35
mat.emit = 2
mat.game_settings.alpha_blend = 'ALPHA_ANTIALIASING'
mat.diffuse_color = (1, 1, 0)
mesh_ob.material_slots[0].material = mat
return mesh_ob
def delete_giude():
"""Deletes the icosphere"""
if 'ModelingClothPinGuide' in bpy.data.objects:
bpy.data.objects.remove(bpy.data.objects['ModelingClothPinGuide'])
if 'ModelingClothPinGuide' in bpy.data.meshes:
bpy.data.meshes.remove(bpy.data.meshes['ModelingClothPinGuide'])
def scale_source(multiplier):
"""grow or shrink the source shape"""
ob = get_last_object()[1]
if ob is not None:
if ob.modeling_cloth:
count = len(ob.data.vertices)
co = np.zeros(count*3)
ob.data.shape_keys.key_blocks['cloth source key'].data.foreach_get('co', co)
co.shape = (count, 3)
mean = np.mean(co, axis=0)
co -= mean
co *= multiplier
co += mean
ob.data.shape_keys.key_blocks['cloth source key'].data.foreach_set('co', co.ravel())
def reset_shapes():
"""Sets the cloth key to match the source key.
Will regenerate shape keys if they are missing"""
if bpy.context.object.modeling_cloth:
ob = bpy.context.object
else:
ob = extra_data['last_object']
if ob.data.shape_keys == None:
ob.shape_key_add('Basis')
if 'cloth source key' not in ob.data.shape_keys.key_blocks:
ob.shape_key_add('cloth source key')
if 'cloth key' not in ob.data.shape_keys.key_blocks:
ob.shape_key_add('cloth key')
ob.data.shape_keys.key_blocks['cloth key'].value=1
keys = ob.data.shape_keys.key_blocks
count = len(ob.data.vertices)
co = np.zeros(count * 3)
keys['cloth source key'].data.foreach_get('co', co)
keys['cloth key'].data.foreach_set('co', co)
data[ob.name].vel *= 0
ob.data.shape_keys.key_blocks['cloth key'].mute = True
ob.data.shape_keys.key_blocks['cloth key'].mute = False
def update_pin_group():
"""Updates the cloth data after changing mesh or vertex weight pins"""
create_instance(new=False)
def refresh_noise(self, context):
if self.name in data:
data[self.name].noise = ((np.random.random(data[self.name].count) + -0.5) * self.modeling_cloth_noise * 0.1)[:, nax]
class Cloth(object):
pass
def create_instance(new=True):
if new:
cloth = Cloth()
cloth.ob = bpy.context.object
else:
ob = get_last_object()[1]
cloth = data[ob.name]
cloth.ob = ob
bpy.context.scene.objects.active = cloth.ob
mode = cloth.ob.mode
if mode == 'EDIT':
bpy.ops.object.mode_set(mode='OBJECT')
cloth.name = cloth.ob.name
if cloth.ob.data.shape_keys == None:
cloth.ob.shape_key_add('Basis')
if 'cloth source key' not in cloth.ob.data.shape_keys.key_blocks:
cloth.ob.shape_key_add('cloth source key')
if 'cloth key' not in cloth.ob.data.shape_keys.key_blocks:
cloth.ob.shape_key_add('cloth key')
cloth.ob.data.shape_keys.key_blocks['cloth key'].value=1
cloth.count = len(cloth.ob.data.vertices)
if 'modeling_cloth_pin' not in cloth.ob.vertex_groups:
cloth.pin_group = create_vertex_groups(groups=['modeling_cloth_pin'], weights=[0.0], ob=None)
for i in range(cloth.count):
try:
cloth.ob.vertex_groups['modeling_cloth_pin'].weight(i)
except RuntimeError:
# assign a weight of zero
cloth.ob.vertex_groups['modeling_cloth_pin'].add(range(0,len(cloth.ob.data.vertices)), 0.0, 'REPLACE')
cloth.pin_bool = -np.array([cloth.ob.vertex_groups['modeling_cloth_pin'].weight(i) for i in range(cloth.count)], dtype=np.bool)
cloth.eidx = connected_by_polygons()
eidx1 = connected_by_polygons()
pindexer = np.arange(cloth.count)[cloth.pin_bool]
unpinned = np.in1d(eidx1[:, 0], pindexer)
cloth.eidx = eidx1[unpinned]
cloth.pcount = pindexer.shape[0]
cloth.pindexer = pindexer
cloth.sco = np.zeros(cloth.count * 3)
cloth.ob.data.shape_keys.key_blocks['cloth source key'].data.foreach_get('co', cloth.sco)
cloth.sco.shape = (cloth.count, 3)
cloth.co = np.zeros(cloth.count * 3)
cloth.ob.data.shape_keys.key_blocks['cloth key'].data.foreach_get('co', cloth.co)
cloth.co.shape = (cloth.count, 3)
cloth.vel = np.zeros(cloth.count * 3)
cloth.vel_start = np.zeros(cloth.count * 3)
cloth.vel_start.shape = (cloth.count, 3)
cloth.vel.shape = (cloth.count, 3)
cloth.noise = ((np.random.random(cloth.count) + -0.5) * cloth.ob.modeling_cloth_noise * 0.1)[:, nax]
cloth.waiting = False
cloth.clicked = False # for the grab tool
cloth.l = np.unique(cloth.eidx[:, 0], return_inverse=True, return_counts=True)
cloth.mix = (1/cloth.l[2][cloth.l[1]])[:, nax] # force gets divided by number of springs
cloth.l_eidx = cloth.eidx[:, 0]
if new:
cloth.pin_list = []
cloth.hook_list = []
bpy.ops.object.mode_set(mode=mode)
return cloth
def run_handler(cloth):
if not cloth.ob.modeling_cloth_pause:
if cloth.ob.mode == 'EDIT':
cloth.waiting = True
if cloth.waiting:
if cloth.ob.mode == 'OBJECT':
update_pin_group()
eidx = cloth.eidx
l_eidx = cloth.l_eidx
# can get a speedup here by indexing the edges and flipping instead of doing
# calculations on the tiled edges. (tile after doing math)
cloth.ob.data.shape_keys.key_blocks['cloth source key'].data.foreach_get('co', cloth.sco.ravel())
sco = cloth.sco
sco.shape = (cloth.count, 3)
cloth.ob.data.shape_keys.key_blocks['cloth key'].data.foreach_get('co', cloth.co.ravel())
co = cloth.co
co.shape = (cloth.count, 3)
svecs = sco[eidx[:, 1]] - sco[eidx[:, 0]]
sdots = np.einsum('ij,ij->i', svecs, svecs)
co[cloth.pindexer] += cloth.noise[cloth.pindexer]
cloth.noise *= cloth.ob.modeling_cloth_noise_decay
#co[cloth.pindexer] -= cloth.vel[cloth.pindexer]
cloth.vel_start[:] = co
force = cloth.ob.modeling_cloth_spring_force
mix = cloth.mix * force
for x in range(cloth.ob.modeling_cloth_iterations):
if force < 0.17:
force += .01
vecs = co[eidx[:, 1]] - co[eidx[:, 0]]
dots = np.einsum('ij,ij->i', vecs, vecs)
div = sdots / dots
swap = vecs * np.sqrt(div)[:, nax]
move = vecs - swap
#---
move *= mix # for stability: force multiplied by 1/number of springs
#---
np.add.at(cloth.co, l_eidx, move)
if len(cloth.pin_list) > 0:
hook_co = np.array([cloth.ob.matrix_world.inverted() * i.matrix_world.to_translation() for i in cloth.hook_list])
cloth.co[cloth.pin_list] = hook_co
vel_dif = cloth.vel_start - cloth.co
cloth.vel += vel_dif
cloth.vel[:,2][cloth.pindexer] -= cloth.ob.modeling_cloth_gravity * .01
# floor ---
if cloth.ob.modeling_cloth_floor:
floored = cloth.co[:,2] < 0
cloth.vel[:,2][floored] *= -1
cloth.vel[floored] *= .1
cloth.co[:, 2][floored] = 0
# floor ---
cloth.vel *= cloth.ob.modeling_cloth_velocity
co[cloth.pindexer] -= cloth.vel[cloth.pindexer]
if cloth.clicked: # for the grab tool
for v in range(len(extra_data['vidx'])):
vert = cloth.ob.data.shape_keys.key_blocks['cloth key'].data
loc = extra_data['stored_vidx'][v] + extra_data['move']
cloth.co[extra_data['vidx'][v]] = loc
cloth.vel[extra_data['vidx'][v]] *= 0
cloth.ob.data.shape_keys.key_blocks['cloth key'].data.foreach_set('co', cloth.co.ravel())
cloth.ob.data.shape_keys.key_blocks['cloth key'].mute = True
cloth.ob.data.shape_keys.key_blocks['cloth key'].mute = False
def modeling_cloth_handler(scene):
items = data.items()
if len(items) == 0:
for i in bpy.data.objects:
i.modeling_cloth = False
for i in bpy.app.handlers.scene_update_post:
if i.__name__ == 'modeling_cloth_handler':
bpy.app.handlers.scene_update_post.remove(i)
for i, cloth in items:
run_handler(cloth)
def pause_update(self, context):
update_pin_group()
def init_cloth(self, context):
global data, extra_data
data = bpy.context.scene.modeling_cloth_data_set
extra_data = bpy.context.scene.modeling_cloth_data_set_extra
extra_data['alert'] = False
extra_data['drag_alert'] = False
extra_data['last_object'] = self
extra_data['clicked'] = False
# iterate through dict: for i, j in d.items()
print('new cloth object data generated from object:', bpy.context.object.name)
if self.modeling_cloth:
cloth = create_instance() # generate an instance of the class
data[cloth.name] = cloth # store class in dictionary using the object name as a key
cull = [] # can't delete dict items while iterating
for i, value in data.items():
if not value.ob.modeling_cloth:
cull.append(i) # store keys to delete
for i in cull:
del data[i]
# could keep the handler unless there are no modeling cloth objects active
if modeling_cloth_handler in bpy.app.handlers.scene_update_post:
bpy.app.handlers.scene_update_post.remove(modeling_cloth_handler)
if len(data) > 0:
bpy.app.handlers.scene_update_post.append(modeling_cloth_handler)
def main(context, event):
"""Raycaster for placing pins"""
scene = context.scene
region = context.region
rv3d = context.region_data
coord = event.mouse_region_x, event.mouse_region_y
guide = create_giude()
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
ray_target = ray_origin + view_vector
def visible_objects_and_duplis():
"""Loop over (object, matrix) pairs (mesh only)"""
for obj in context.visible_objects:
if obj.type == 'MESH':
if obj.modeling_cloth:
yield (obj, obj.matrix_world.copy())
def obj_ray_cast(obj, matrix):
"""Wrapper for ray casting that moves the ray into object space"""
# get the ray relative to the object
matrix_inv = matrix.inverted()
ray_origin_obj = matrix_inv * ray_origin
ray_target_obj = matrix_inv * ray_target
ray_direction_obj = ray_target_obj - ray_origin_obj
# cast the ray
success, location, normal, face_index = obj.ray_cast(ray_origin_obj, ray_direction_obj)
if success:
return location, normal, face_index
else:
return None, None, None
# cast rays and find the closest object
best_length_squared = -1.0
best_obj = None
for obj, matrix in visible_objects_and_duplis():
hit, normal, face_index = obj_ray_cast(obj, matrix)
if hit is not None:
hit_world = matrix * hit
vidx = [v for v in obj.data.polygons[face_index].vertices]
verts = np.array([matrix * obj.data.shape_keys.key_blocks['cloth key'].data[v].co for v in obj.data.polygons[face_index].vertices])
vecs = verts - np.array(hit_world)
closest = vidx[np.argmin(np.einsum('ij,ij->i', vecs, vecs))]
length_squared = (hit_world - ray_origin).length_squared
if best_obj is None or length_squared < best_length_squared:
best_length_squared = length_squared
best_obj = obj
guide.location = matrix * obj.data.shape_keys.key_blocks['cloth key'].data[closest].co
extra_data['latest_hit'] = matrix * obj.data.shape_keys.key_blocks['cloth key'].data[closest].co
extra_data['name'] = obj.name
extra_data['obj'] = obj
extra_data['closest'] = closest
if extra_data['just_clicked']:
extra_data['just_clicked'] = False
best_length_squared = length_squared
best_obj = obj
name = obj.name
class ModelingClothPin(bpy.types.Operator):
"""Modal ray cast for placing pins"""
bl_idname = "view3d.modeling_cloth_pin"
bl_label = "Modeling Cloth Pin"
def __init__(self):
bpy.ops.object.select_all(action='DESELECT')
extra_data['just_clicked'] = False
def modal(self, context, event):
bpy.context.window.cursor_set("CROSSHAIR")
if event.type in {'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}:
# allow navigation
return {'PASS_THROUGH'}
elif event.type == 'MOUSEMOVE':
main(context, event)
return {'RUNNING_MODAL'}
elif event.type == 'LEFTMOUSE' and event.value == 'PRESS':
if extra_data['latest_hit'] is not None:
if extra_data['name'] is not None:
closest = extra_data['closest']
name = extra_data['name']
e = bpy.data.objects.new('modeling_cloth_pin', None)
bpy.context.scene.objects.link(e)
e.location = extra_data['latest_hit']
e.show_x_ray = True
e.select = True
e.empty_draw_size = .1
data[name].pin_list.append(closest)
data[name].hook_list.append(e)
extra_data['latest_hit'] = None
extra_data['name'] = None
elif event.type in {'RIGHTMOUSE', 'ESC'}:
delete_giude()
cloths = [i for i in bpy.data.objects if i.modeling_cloth] # so we can select an empty and keep the settings menu up
extra_data['alert'] = False
if len(cloths) > 0: #
ob = extra_data['last_object'] #
bpy.context.scene.objects.active = ob
bpy.context.window.cursor_set("DEFAULT")
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
cloth_objects = False
cloths = [i for i in bpy.data.objects if i.modeling_cloth] # so we can select an empty and keep the settings menu up
if len(cloths) > 0:
cloth_objects = True
extra_data['alert'] = True
if context.space_data.type == 'VIEW_3D' and cloth_objects:
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "Active space must be a View3d")
extra_data['alert'] = False
bpy.context.window.cursor_set("DEFAULT")
return {'CANCELLED'}
# drag===================================
# drag===================================
#[‘DEFAULT’, ‘NONE’, ‘WAIT’, ‘CROSSHAIR’, ‘MOVE_X’, ‘MOVE_Y’, ‘KNIFE’, ‘TEXT’, ‘PAINT_BRUSH’, ‘HAND’, ‘SCROLL_X’, ‘SCROLL_Y’, ‘SCROLL_XY’, ‘EYEDROPPER’]
def main_drag(context, event):
"""Raycaster for dragging"""
scene = context.scene
region = context.region
rv3d = context.region_data
coord = event.mouse_region_x, event.mouse_region_y
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
ray_target = ray_origin + view_vector
def visible_objects_and_duplis():
"""Loop over (object, matrix) pairs (mesh only)"""
for obj in context.visible_objects:
if obj.type == 'MESH':
if obj.modeling_cloth:
yield (obj, obj.matrix_world.copy())
def obj_ray_cast(obj, matrix):
"""Wrapper for ray casting that moves the ray into object space"""
# get the ray relative to the object
matrix_inv = matrix.inverted()
ray_origin_obj = matrix_inv * ray_origin
ray_target_obj = matrix_inv * ray_target
ray_direction_obj = ray_target_obj - ray_origin_obj
# cast the ray
success, location, normal, face_index = obj.ray_cast(ray_origin_obj, ray_direction_obj)
if success:
return location, normal, face_index, ray_target
else:
return None, None, None, ray_target
# cast rays and find the closest object
best_length_squared = -1.0
best_obj = None
for obj, matrix in visible_objects_and_duplis():
hit, normal, face_index, target = obj_ray_cast(obj, matrix)
extra_data['target'] = target
if hit is not None:
hit_world = matrix * hit
length_squared = (hit_world - ray_origin).length_squared
if best_obj is None or length_squared < best_length_squared:
best_length_squared = length_squared
best_obj = obj
vidx = [v for v in obj.data.polygons[face_index].vertices]
verts = np.array([matrix * obj.data.shape_keys.key_blocks['cloth key'].data[v].co for v in obj.data.polygons[face_index].vertices])
vert = obj.data.shape_keys.key_blocks['cloth key'].data
if best_obj is not None:
if extra_data['clicked']:
#extra_data['move'] = np.array([0.0, 0.0, 0.0])
extra_data['matrix'] = matrix.inverted()
data[best_obj.name].clicked = True
extra_data['stored_mouse'] = np.copy(target)
extra_data['vidx'] = vidx
extra_data['stored_vidx'] = np.array([vert[v].co for v in extra_data['vidx']])
extra_data['clicked'] = False
if extra_data['stored_mouse'] is not None:
move = np.array(extra_data['target'] * extra_data['matrix']) - extra_data['stored_mouse']
extra_data['move'] = move
# dragger===
class ModelingClothDrag(bpy.types.Operator):
"""Modal ray cast for dragging"""
bl_idname = "view3d.modeling_cloth_drag"
bl_label = "Modeling Cloth Drag"
def __init__(self):
bpy.ops.object.select_all(action='DESELECT')
extra_data['hit'] = None
extra_data['clicked'] = False
extra_data['stored_mouse'] = None
extra_data['vidx'] = None
extra_data['new_click'] = True
extra_data['target'] = None
for i in data:
data[i].clicked = False
def modal(self, context, event):
bpy.context.window.cursor_set("HAND")
if event.type in {'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}:
# allow navigation
return {'PASS_THROUGH'}
elif event.type == 'MOUSEMOVE':
main_drag(context, event)
return {'RUNNING_MODAL'}
elif event.type == 'LEFTMOUSE' and event.value == 'PRESS':
# when I click, If I have a hit, store the hit on press
extra_data['clicked'] = True
extra_data['vidx'] = []
elif event.type == 'LEFTMOUSE' and event.value == 'RELEASE':
extra_data['clicked'] = False
extra_data['stored_mouse'] = None
extra_data['vidx'] = None
extra_data['new_click'] = True
extra_data['target'] = None
for i in data:
data[i].clicked = False
elif event.type in {'RIGHTMOUSE', 'ESC'}:
extra_data['drag_alert'] = False
extra_data['clicked'] = False
extra_data['hit'] = None
bpy.context.window.cursor_set("DEFAULT")
extra_data['stored_mouse'] = None
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
cloth_objects = False
cloths = [i for i in bpy.data.objects if i.modeling_cloth] # so we can select an empty and keep the settings menu up
if len(cloths) > 0:
cloth_objects = True
extra_data['drag_alert'] = True
if context.space_data.type == 'VIEW_3D' and cloth_objects:
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "Active space must be a View3d")
extra_data['drag_alert'] = False
extra_data['stored_mouse'] = None
bpy.context.window.cursor_set("DEFAULT")
return {'CANCELLED'}
# drag===================================End
# drag===================================End
class DeletePins(bpy.types.Operator):
"""Delete modeling cloth pins and clear pin list for current object"""
bl_idname = "object.delete_modeling_cloth_pins"
bl_label = "Delete Modeling Cloth Pins"
def execute(self, context):
ob = get_last_object() # returns tuple with list and last cloth objects or None
if ob is not None:
data[ob[1].name].pin_list = []
for i in data[ob[1].name].hook_list:
bpy.data.objects.remove(i)
data[ob[1].name].hook_list = []
bpy.context.scene.objects.active = ob[1]
return {'FINISHED'}
class SelectPins(bpy.types.Operator):
"""Select modeling cloth pins for current object"""
bl_idname = "object.select_modeling_cloth_pins"
bl_label = "Select Modeling Cloth Pins"
def execute(self, context):
ob = get_last_object() # returns list and last cloth objects or None
if ob is not None:
bpy.ops.object.select_all(action='DESELECT')
for i in data[ob[1].name].hook_list:
i.select = True
return {'FINISHED'}
class PinSelected(bpy.types.Operator):
"""Add pins to verts selected in edit mode"""
bl_idname = "object.modeling_cloth_pin_selected"
bl_label = "Modeling Cloth Pin Selected"
def execute(self, context):
ob = bpy.context.object
bpy.ops.object.mode_set(mode='OBJECT')
sel = [i.index for i in ob.data.vertices if i.select]
name = ob.name
matrix = ob.matrix_world.copy()
matrix_inv = ob.matrix_world.inverted().copy()
for v in sel:
e = bpy.data.objects.new('modeling_cloth_pin', None)
bpy.context.scene.objects.link(e)
if ob.active_shape_key is None:
closest = matrix * ob.data.vertices[v].co# * matrix
else:
closest = matrix * ob.active_shape_key.data[v].co# * matrix
e.location = closest #* matrix
e.show_x_ray = True
e.select = True
e.empty_draw_size = .1
data[name].pin_list.append(v)
data[name].hook_list.append(e)
ob.select = False
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
class UpdataPinWeights(bpy.types.Operator):
"""Update Pin Weights"""
bl_idname = "object.modeling_cloth_update_pin_group"
bl_label = "Modeling Cloth Update Pin Weights"
def execute(self, context):
update_pin_group()
return {'FINISHED'}
class GrowSource(bpy.types.Operator):
"""Grow Source Shape"""
bl_idname = "object.modeling_cloth_grow"
bl_label = "Modeling Cloth Grow"
def execute(self, context):
scale_source(1.02)
return {'FINISHED'}
class ShrinkSource(bpy.types.Operator):
"""Shrink Source Shape"""
bl_idname = "object.modeling_cloth_shrink"
bl_label = "Modeling Cloth Shrink"
def execute(self, context):
scale_source(0.98)
return {'FINISHED'}
class ResetShapes(bpy.types.Operator):
"""Reset Shapes"""
bl_idname = "object.modeling_cloth_reset"
bl_label = "Modeling Cloth Reset"
def execute(self, context):
reset_shapes()
return {'FINISHED'}
def create_properties():
bpy.types.Object.modeling_cloth = bpy.props.BoolProperty(name="Modeling Cloth",
description="For toggling modeling cloth",
default=False, update=init_cloth)
bpy.types.Object.modeling_cloth_floor = bpy.props.BoolProperty(name="Modeling Cloth Floor",
description="Stop at floor",
default=False)
bpy.types.Object.modeling_cloth_pause = bpy.props.BoolProperty(name="Modeling Cloth Pause",
description="Stop without removing data",
default=True, update=pause_update)
bpy.types.Object.modeling_cloth_noise = bpy.props.FloatProperty(name="Modeling Cloth Noise",
description="Set the noise strength",
default=0.001, precision=4, min=0, max=1, update=refresh_noise)
bpy.types.Object.modeling_cloth_noise_decay = bpy.props.FloatProperty(name="Modeling Cloth Noise Decay",
description="Multiply the noise by this value each iteration",
default=0.99, precision=4, min=0, max=1)#, update=refresh_noise_decay)
bpy.types.Object.modeling_cloth_spring_force = bpy.props.FloatProperty(name="Modeling Cloth Spring Force",
description="Set the spring force",
default=0.9, precision=4, min=0, max=1.3)#, update=refresh_noise)
bpy.types.Object.modeling_cloth_gravity = bpy.props.FloatProperty(name="Modeling Cloth Gravity",
description="Modeling cloth gravity",
default=0.0, precision=4, min= -1, max=1)#, update=refresh_noise_decay)
bpy.types.Object.modeling_cloth_iterations = bpy.props.IntProperty(name="Stiffness",
description="How stiff the cloth is",
default=1, min=1, max=50)#, update=refresh_noise_decay)
bpy.types.Object.modeling_cloth_velocity = bpy.props.FloatProperty(name="Velocity",
description="Cloth keeps moving",
default=.9, min= -1.1, max=1.1, soft_min= -1, soft_max=1)#, update=refresh_noise_decay)
bpy.types.Scene.modeling_cloth_data_set = {}
bpy.types.Scene.modeling_cloth_data_set_extra = {}
def remove_properties():
'''Drives to the grocery store and buys a sandwich'''
del(bpy.types.Object.modeling_cloth)
del(bpy.types.Object.modeling_cloth_pause)
del(bpy.types.Object.modeling_cloth_noise)
del(bpy.types.Object.modeling_cloth_noise_decay)
del(bpy.types.Object.modeling_cloth_spring_force)
del(bpy.types.Object.modeling_cloth_gravity)
del(bpy.types.Object.modeling_cloth_iterations)
del(bpy.types.Object.modeling_cloth_velocity)
del(bpy.types.Scene.modeling_cloth_data_set)
del(bpy.types.Scene.modeling_cloth_data_set_extra)
class ModelingClothPanel(bpy.types.Panel):
"""Modeling Cloth Panel"""
bl_label = "Modeling Cloth Panel"
bl_idname = "Modeling Cloth"
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'
bl_category = "Extended Tools"
#gt_show = True
def draw(self, context):
status = False
layout = self.layout
col = layout.column(align=True)
col.label(text="Modeling Cloth")
ob = bpy.context.object
cloths = [i for i in bpy.data.objects if i.modeling_cloth] # so we can select an empty and keep the settings menu up
if len(cloths) > 0: #
status = extra_data['alert']
if ob is not None:
if ob.type != 'MESH' or status:
ob = extra_data['last_object'] #
if ob is not None:
if ob.type == 'MESH':
col.prop(ob ,"modeling_cloth", text="Modeling Cloth", icon='SURFACE_DATA')
pause = 'PAUSE'
if ob.modeling_cloth_pause:
pause = 'PLAY'
if ob.modeling_cloth:
col = layout.column(align=True)
col.scale_y = 2.0
col.prop(ob ,"modeling_cloth_pause", text=pause, icon=pause)
col.operator("object.modeling_cloth_reset", text="Reset")
col = layout.column(align=True)
col.scale_y = 2.0
col.alert = extra_data['drag_alert']
col.operator("view3d.modeling_cloth_drag", text="Grab")
col = layout.column(align=True)
col.prop(ob ,"modeling_cloth_iterations", text="Iterations")#, icon='OUTLINER_OB_LATTICE')
col.prop(ob ,"modeling_cloth_spring_force", text="Stiffness")#, icon='OUTLINER_OB_LATTICE')
col.prop(ob ,"modeling_cloth_noise", text="Noise")#, icon='PLAY')
col.prop(ob ,"modeling_cloth_noise_decay", text="Decay Noise")#, icon='PLAY')
col.prop(ob ,"modeling_cloth_gravity", text="Gravity")#, icon='PLAY')
col.prop(ob ,"modeling_cloth_velocity", text="Velocity")#, icon='PLAY')
col.prop(ob ,"modeling_cloth_floor", text="Floor")#, icon='PLAY')
col = layout.column(align=True)
col.scale_y = 1.5
col.alert = status
if ob.modeling_cloth:
if ob.mode == 'EDIT':
col.operator("object.modeling_cloth_pin_selected", text="Pin Selected")
else:
col.operator("view3d.modeling_cloth_pin", text="Create Pins")
col = layout.column(align=True)
col.operator("object.select_modeling_cloth_pins", text="Select Pins")
col.operator("object.delete_modeling_cloth_pins", text="Delete Pins")
col.operator("object.modeling_cloth_grow", text="Grow Source")
col.operator("object.modeling_cloth_shrink", text="Shrink Source")
def register():
create_properties()
bpy.utils.register_class(ModelingClothPanel)
bpy.utils.register_class(ModelingClothPin)
bpy.utils.register_class(ModelingClothDrag)
bpy.utils.register_class(DeletePins)
bpy.utils.register_class(SelectPins)
bpy.utils.register_class(PinSelected)
bpy.utils.register_class(GrowSource)
bpy.utils.register_class(ShrinkSource)
bpy.utils.register_class(ResetShapes)
bpy.utils.register_class(UpdataPinWeights)
def unregister():
remove_properties()
bpy.utils.unregister_class(ModelingClothPanel)
bpy.utils.unregister_class(ModelingClothPin)
bpy.utils.unregister_class(ModelingClothDrag)
bpy.utils.unregister_class(DeletePins)
bpy.utils.unregister_class(SelectPins)
bpy.utils.unregister_class(PinSelected)
bpy.utils.unregister_class(GrowSource)
bpy.utils.unregister_class(ShrinkSource)
bpy.utils.unregister_class(ResetShapes)
bpy.utils.unregister_class(UpdataPinWeights)
if __name__ == "__main__":
register()
for i in bpy.data.objects:
i.modeling_cloth = False
for i in bpy.app.handlers.scene_update_post:
if i.__name__ == 'modeling_cloth_handler':
bpy.app.handlers.scene_update_post.remove(i)