-
Notifications
You must be signed in to change notification settings - Fork 75
/
tessellate_numpy.py
3987 lines (3649 loc) · 164 KB
/
tessellate_numpy.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: 2017 Alessandro Zomparelli
#
# SPDX-License-Identifier: GPL-2.0-or-later
import bpy
from bpy.types import (
Operator,
Panel,
PropertyGroup,
)
from bpy.props import (
BoolProperty,
EnumProperty,
FloatProperty,
IntProperty,
StringProperty,
PointerProperty
)
from mathutils import Vector, Quaternion, Matrix
import numpy as np
from math import *
import random, time, copy
import bmesh
from .utils import *
from .weight_tools import *
from .numba_functions import *
from .tissue_properties import *
import os, mathutils
from pathlib import Path
from . import config
def allowed_objects():
return ('MESH', 'CURVE', 'SURFACE', 'FONT', 'META')
def tessellated(ob):
props = ob.tissue_tessellate
if props.generator not in list(bpy.data.objects):
return False
elif props.component_mode == 'OBJECT':
return props.component in list(bpy.data.objects)
elif props.component_mode == 'COLLECTION':
if props.component_coll in list(bpy.data.collections):
for o in list(props.component_coll.objects):
if o.type in allowed_objects():
return True
else:
for mat in props.generator.material_slots.keys():
if mat in bpy.data.objects.keys():
if bpy.data.objects[mat].type in allowed_objects():
return True
return False
def tessellate_patch(props):
tt = time.time()
ob = props['self']
_ob0 = props['generator']
components = props['component']
offset = props['offset']
zscale = props['zscale']
gen_modifiers = props['gen_modifiers']
com_modifiers = props['com_modifiers']
mode = props['mode']
fill_mode = props['fill_mode']
scale_mode = props['scale_mode']
rotation_mode = props['rotation_mode']
rotation_shift = props['rotation_shift']
rand_seed = props['rand_seed']
rand_step = props['rand_step']
bool_vertex_group = props['bool_vertex_group']
bool_selection = props['bool_selection']
bool_shapekeys = props['bool_shapekeys']
bool_material_id = props['bool_material_id']
material_id = props['material_id']
normals_mode = props['normals_mode']
bounds_x = props['bounds_x']
bounds_y = props['bounds_y']
use_origin_offset = props['use_origin_offset']
vertex_group_thickness = props['vertex_group_thickness']
invert_vertex_group_thickness = props['invert_vertex_group_thickness']
vertex_group_thickness_factor = props['vertex_group_thickness_factor']
vertex_group_frame_thickness = props['vertex_group_frame_thickness']
invert_vertex_group_frame_thickness = props['invert_vertex_group_frame_thickness']
vertex_group_frame_thickness_factor = props['vertex_group_frame_thickness_factor']
face_weight_frame = props['face_weight_frame']
vertex_group_distribution = props['vertex_group_distribution']
invert_vertex_group_distribution = props['invert_vertex_group_distribution']
vertex_group_distribution_factor = props['vertex_group_distribution_factor']
vertex_group_cap_owner = props['vertex_group_cap_owner']
vertex_group_cap = props['vertex_group_cap']
invert_vertex_group_cap = props['invert_vertex_group_cap']
vertex_group_bridge_owner = props['vertex_group_bridge_owner']
vertex_group_bridge = props['vertex_group_bridge']
invert_vertex_group_bridge = props['invert_vertex_group_bridge']
vertex_group_rotation = props['vertex_group_rotation']
invert_vertex_group_rotation = props['invert_vertex_group_rotation']
rotation_direction = props['rotation_direction']
target = props['target']
even_thickness = props['even_thickness']
even_thickness_iter = props['even_thickness_iter']
smooth_normals = props['smooth_normals']
smooth_normals_iter = props['smooth_normals_iter']
smooth_normals_uv = props['smooth_normals_uv']
vertex_group_smooth_normals = props['vertex_group_smooth_normals']
invert_vertex_group_smooth_normals = props['invert_vertex_group_smooth_normals']
#bool_multi_components = props['bool_multi_components']
component_mode = props['component_mode']
coll_rand_seed = props['coll_rand_seed']
consistent_wedges = props['consistent_wedges']
vertex_group_scale_normals = props['vertex_group_scale_normals']
invert_vertex_group_scale_normals = props['invert_vertex_group_scale_normals']
boundary_mat_offset = props['boundary_mat_offset']
preserve_quads = props['preserve_quads']
_props = props.copy()
# reset messages
ob.tissue_tessellate.warning_message_thickness = ''
if normals_mode == 'SHAPEKEYS':
if _ob0.data.shape_keys != None:
target = _ob0
else:
normals_mode = 'VERTS'
message = "Base mesh doesn't have Shape Keys"
ob.tissue_tessellate.warning_message_thickness = message
print("Tissue: " + message)
if normals_mode == 'OBJECT' and target == None:
normals_mode = 'VERTS'
message = "Please select a target object"
ob.tissue_tessellate.warning_message_thickness = message
print("Tissue: " + message)
random.seed(rand_seed)
if len(_ob0.modifiers) == 0: gen_modifiers = False
# Target mesh used for normals
if normals_mode in ('SHAPEKEYS', 'OBJECT'):
if fill_mode == 'PATCH':
ob0_sk = convert_object_to_mesh(target, True, rotation_mode!='UV')
else:
use_modifiers = gen_modifiers
if normals_mode == 'SHAPEKEYS' and not gen_modifiers:
target = _ob0
for m in target.modifiers:
m.show_viewport = False
use_modifiers = True
_props['use_modifiers'] = use_modifiers
if fill_mode == 'FAN': ob0_sk = convert_to_fan(target, _props, add_id_layer=id_layer)
elif fill_mode == 'FRAME': ob0_sk = convert_to_frame(target, _props)
elif fill_mode == 'TRI': ob0_sk = convert_to_triangles(target, _props)
elif fill_mode == 'QUAD': ob0_sk = reduce_to_quads(target, _props)
me0_sk = ob0_sk.data
normals_target = get_vertices_numpy(me0_sk)
bpy.data.objects.remove(ob0_sk)
if normals_mode == 'SHAPEKEYS':
key_values0 = [sk.value for sk in _ob0.data.shape_keys.key_blocks]
for sk in _ob0.data.shape_keys.key_blocks: sk.value = 0
# Base mesh
if fill_mode == 'PATCH':
ob0 = convert_object_to_mesh(_ob0, True, True, rotation_mode!='UV')
if boundary_mat_offset != 0:
bm=bmesh.new()
bm.from_mesh(ob0.data)
bm = offset_boundary_materials(
bm,
boundary_mat_offset = _props['boundary_mat_offset'],
boundary_variable_offset = _props['boundary_variable_offset'],
auto_rotate_boundary = _props['auto_rotate_boundary'])
bm.to_mesh(ob0.data)
bm.free()
ob0.data.update()
else:
if fill_mode == 'FAN':
id_layer = component_mode == 'COLLECTION' and consistent_wedges
ob0 = convert_to_fan(_ob0, _props, add_id_layer=id_layer)
elif fill_mode == 'FRAME': ob0 = convert_to_frame(_ob0, _props)
elif fill_mode == 'TRI': ob0 = convert_to_triangles(_ob0, _props)
elif fill_mode == 'QUAD': ob0 = reduce_to_quads(_ob0, _props)
ob0.name = "_tissue_tmp_ob0"
me0 = ob0.data
n_verts0 = len(me0.vertices)
# read vertices coordinates
verts0_co = get_vertices_numpy(me0)
# base normals
if normals_mode in ('SHAPEKEYS','OBJECT'):
if len(normals_target) != len(me0.vertices):
normals_mode = 'VERTS'
message = "Base mesh and Target mesh don't match"
ob.tissue_tessellate.warning_message_thickness = message
print("Tissue: " + message)
else:
if normals_mode == 'SHAPEKEYS':
for sk, val in zip(_ob0.data.shape_keys.key_blocks, key_values0): sk.value = val
verts0_normal = normals_target - verts0_co
'''
While in Relative thickness method the components are built
between the two surfaces, in Constant mode the thickness is uniform.
'''
if scale_mode == 'CONSTANT':
# Normalize vectors
verts0_normal /= np.linalg.norm(verts0_normal, axis=1).reshape((-1,1))
if not even_thickness:
pass
#original_normals = get_normals_numpy(me0)
#verts0_normal /= np.multiply(verts0_normal, original_normals).sum(1)[:,None]
else:
# Evaluate maximum components thickness
first_component = True
for com in components:
if com:
com = convert_object_to_mesh(com, com_modifiers, False, False)
com, com_area = tessellate_prepare_component(com, props)
com_verts = get_vertices_numpy(com.data)
bpy.data.objects.remove(com)
if first_component:
all_com_verts = com_verts
first_component = False
else:
all_com_verts = np.concatenate((all_com_verts, com_verts), axis=0)
pos_step_dist = abs(np.max(all_com_verts[:,2]))
neg_step_dist = abs(np.min(all_com_verts[:,2]))
# Rescale normalized vectors according to the angle with the normals
original_normals = get_normals_numpy(me0)
kd = mathutils.kdtree.KDTree(len(verts0_co))
for i, v in enumerate(verts0_co):
kd.insert(v, i)
kd.balance()
step_dist = [neg_step_dist, pos_step_dist]
mult = 1
sign = [-1,1]
for sgn, stp in zip(sign, step_dist):
if stp == 0:
if sgn == 1: verts0_normal_pos = verts0_normal
if sgn == -1: verts0_normal_neg = verts0_normal
continue
for i in range(even_thickness_iter):
test_dist = stp * mult
test_pts = verts0_co + verts0_normal * test_dist * sgn
# Find the closest point to the sample point
closest_dist = []
closest_co = []
closest_nor = []
closest_index = []
for find in test_pts:
co, index, dist = kd.find(find)
closest_co.append(co) # co, index, dist
closest_index.append(index) # co, index, dist
closest_co = np.array(closest_co)#[:,3,None]
closest_index = np.array(closest_index)
closest_nor = original_normals[closest_index]
closest_vec = test_pts - closest_co
projected_vectors = np.multiply(closest_vec, closest_nor).sum(1)[:,None]
closest_dist = np.linalg.norm(projected_vectors, axis=1)[:,None]
mult = mult*0.2 + test_dist/closest_dist*0.8 # Reduces bouncing effect
if sgn == 1: verts0_normal_pos = verts0_normal * mult
if sgn == -1: verts0_normal_neg = verts0_normal * mult
if normals_mode in ('VERTS','FACES'):
verts0_normal = get_normals_numpy(me0)
levels = 0
not_allowed = ['FLUID_SIMULATION', 'ARRAY', 'BEVEL', 'BOOLEAN', 'BUILD',
'DECIMATE', 'EDGE_SPLIT', 'MASK', 'MIRROR', 'REMESH',
'SCREW', 'SOLIDIFY', 'TRIANGULATE', 'WIREFRAME', 'SKIN',
'EXPLODE', 'PARTICLE_INSTANCE', 'PARTICLE_SYSTEM', 'SMOKE']
modifiers0 = list(_ob0.modifiers)
if len(modifiers0) == 0 or fill_mode != 'PATCH':
before_subsurf = me0
if fill_mode == 'PATCH':
fill_mode = 'QUAD'
else:
show_modifiers = [m.show_viewport for m in _ob0.modifiers]
show_modifiers.reverse()
modifiers0.reverse()
for m in modifiers0:
visible = m.show_viewport
if not visible: continue
#m.show_viewport = False
if m.type in ('SUBSURF', 'MULTIRES') and visible:
levels = m.levels
break
elif m.type in not_allowed:
bpy.data.meshes.remove(ob0.data)
#bpy.data.meshes.remove(me0)
return "modifiers_error"
before = _ob0.copy()
before.name = _ob0.name + "_before_subs"
bpy.context.collection.objects.link(before)
#if ob0.type == 'MESH': before.data = me0
before_mod = list(before.modifiers)
before_mod.reverse()
for m in before_mod:
if m.type in ('SUBSURF', 'MULTIRES') and m.show_viewport:
before.modifiers.remove(m)
break
else: before.modifiers.remove(m)
if rotation_mode!='UV':
before_subsurf = simple_to_mesh_mirror(before)
else:
before_subsurf = simple_to_mesh(before)
if boundary_mat_offset != 0:
bm=bmesh.new()
bm.from_mesh(before_subsurf)
bm = offset_boundary_materials(
bm,
boundary_mat_offset = _props['boundary_mat_offset'],
boundary_variable_offset = _props['boundary_variable_offset'],
auto_rotate_boundary = _props['auto_rotate_boundary'])
bm.to_mesh(before_subsurf)
bm.free()
before_subsurf.update()
bpy.data.objects.remove(before)
tt = tissue_time(tt, "Meshes preparation", levels=2)
### PATCHES ###
patch_faces = 4**levels
sides = int(sqrt(patch_faces))
step = 1/sides
sides0 = sides-2
patch_faces0 = int((sides-2)**2)
if fill_mode == 'PATCH':
all_verts, mask, materials = get_patches(before_subsurf, me0, 4, levels, bool_selection)
else:
all_verts, mask, materials = get_quads(me0, bool_selection)
n_patches = len(all_verts)
tt = tissue_time(tt, "Indexing", levels=2)
### WEIGHT ###
# Check if possible to use Weight Rotation
if rotation_mode == 'WEIGHT':
if not vertex_group_rotation in ob0.vertex_groups.keys():
rotation_mode = 'DEFAULT'
bool_vertex_group = bool_vertex_group and len(ob0.vertex_groups.keys()) > 0
bool_weight_smooth_normals = vertex_group_smooth_normals in ob0.vertex_groups.keys()
bool_weight_thickness = vertex_group_thickness in ob0.vertex_groups.keys()
bool_weight_distribution = vertex_group_distribution in ob0.vertex_groups.keys()
bool_weight_cap = vertex_group_cap_owner == 'BASE' and vertex_group_cap in ob0.vertex_groups.keys()
bool_weight_bridge = vertex_group_bridge_owner == 'BASE' and vertex_group_bridge in ob0.vertex_groups.keys()
bool_weight_normals = vertex_group_scale_normals in ob0.vertex_groups.keys()
read_vertex_groups = bool_vertex_group or rotation_mode == 'WEIGHT' or bool_weight_thickness or bool_weight_cap or bool_weight_bridge or bool_weight_smooth_normals or bool_weight_distribution or bool_weight_normals
weight = weight_thickness = weight_rotation = None
if read_vertex_groups:
if bool_vertex_group:
weight = [get_weight(vg, n_verts0) for vg in ob0.vertex_groups]
weight = np.array(weight)
n_vg = len(ob0.vertex_groups)
if rotation_mode == 'WEIGHT':
vg_id = ob0.vertex_groups[vertex_group_rotation].index
weight_rotation = weight[vg_id]
if bool_weight_smooth_normals:
vg_id = ob0.vertex_groups[bool_weight_smooth_normals].index
weight_rotation = weight[vg_id]
if bool_weight_distribution:
vg_id = ob0.vertex_groups[vertex_group_distribution].index
weight_distribution = weight[vg_id]
if bool_weight_normals:
vg_id = ob0.vertex_groups[vertex_group_scale_normals].index
weight_normals = weight[vg_id]
else:
if rotation_mode == 'WEIGHT':
vg = ob0.vertex_groups[vertex_group_rotation]
weight_rotation = get_weight_numpy(vg, n_verts0)
if bool_weight_smooth_normals:
vg = ob0.vertex_groups[vertex_group_smooth_normals]
weight_smooth_normals = get_weight_numpy(vg, n_verts0)
if bool_weight_distribution:
vg = ob0.vertex_groups[vertex_group_distribution]
weight_distribution = get_weight_numpy(vg, n_verts0)
if bool_weight_normals:
vg = ob0.vertex_groups[vertex_group_scale_normals]
weight_normals = get_weight_numpy(vg, n_verts0)
if component_mode == 'COLLECTION':
np.random.seed(coll_rand_seed)
if fill_mode == 'FAN' and consistent_wedges:
bm0 = bmesh.new()
bm0.from_mesh(me0)
bm0.faces.ensure_lookup_table()
lay_id = bm0.faces.layers.int["id"]
faces_id = np.array([f[lay_id] for f in bm0.faces])
bm0.clear()
n_original_faces = faces_id[-1]+1
coll_materials = np.random.randint(len(components),size=n_original_faces)
coll_materials = coll_materials[faces_id]
else:
coll_materials = np.random.randint(len(components),size=n_patches)
gradient_distribution = []
if bool_weight_distribution:
if invert_vertex_group_distribution:
weight_distribution = 1-weight_distribution
v00 = all_verts[:,0,0]
v01 = all_verts[:,0,-1]
v10 = all_verts[:,-1,0]
v11 = all_verts[:,-1,-1]
# Average method
face_weight = np.average(weight_distribution[all_verts.reshape((all_verts.shape[0], -1))], axis=1) * len(components)
# Corners Method
#face_weight = (weight_distribution[v00] + weight_distribution[v01] + weight_distribution[v10] + weight_distribution[v11])/4 * len(components)
if fill_mode == 'FAN' and consistent_wedges:
for i in range(n_original_faces):
face_mask = faces_id == i
face_weight[face_mask] = np.average(face_weight[face_mask])
face_weight = face_weight.clip(max=len(components)-1)
coll_materials = coll_materials.astype('float')
coll_materials = face_weight + (coll_materials - face_weight)*vertex_group_distribution_factor
coll_materials = coll_materials.astype('int')
random.seed(rand_seed)
bool_correct = False
tt = tissue_time(tt, "Reading Vertex Groups", levels=2)
### SMOOTH NORMALS
if smooth_normals:
weight_smooth_normals = 0.2
weight_smooth_normals0 = 0.2
if vertex_group_smooth_normals in ob0.vertex_groups.keys():
vg = ob0.vertex_groups[vertex_group_smooth_normals]
weight_smooth_normals0 = get_weight_numpy(vg, n_verts0)
if invert_vertex_group_smooth_normals:
weight_smooth_normals0 = 1-weight_smooth_normals0
weight_smooth_normals0 *= 0.2
verts0_normal = mesh_diffusion_vector(me0, verts0_normal, smooth_normals_iter, weight_smooth_normals0, smooth_normals_uv)
'''
While in Relative thickness method the components are built
between the two surfaces, in Constant mode the thickness is uniform.
'''
if scale_mode == 'CONSTANT':
# Normalize vectors
verts0_normal /= np.linalg.norm(verts0_normal, axis=1).reshape((-1,1))
# Compare to the original normals direction
original_normals = get_normals_numpy(me0)
verts0_normal /= np.multiply(verts0_normal, original_normals).sum(1)[:,None]
tt = tissue_time(tt, "Smooth Normals", levels=2)
if normals_mode in ('FACES', 'VERTS'):
normals_x = props['normals_x']
normals_y = props['normals_y']
normals_z = props['normals_z']
if bool_weight_normals:
if invert_vertex_group_scale_normals:
weight_normals = 1-weight_normals
w_normals_x = 1 - weight_normals * (1 - normals_x)
w_normals_y = 1 - weight_normals * (1 - normals_y)
w_normals_z = 1 - weight_normals * (1 - normals_z)
else:
w_normals_x = normals_x
w_normals_y = normals_y
w_normals_z = normals_z
if normals_x < 1: verts0_normal[:,0] *= w_normals_x
if normals_y < 1: verts0_normal[:,1] *= w_normals_y
if normals_z < 1: verts0_normal[:,2] *= w_normals_z
div_value = np.linalg.norm(verts0_normal, axis=1).reshape((-1,1))
div_value[div_value == 0] = 0.00001
verts0_normal /= div_value
### ROTATE PATCHES ###
if rotation_mode != 'DEFAULT' or rotation_shift != 0:
# Weight rotation
weight_shift = 0
if rotation_mode == 'WEIGHT':
corners_id = np.array(((0,0,-1,-1),(0,-1,-1,0)))
corners = all_verts[:,corners_id[0],corners_id[1]]
corners_weight = weight_rotation[corners]
if invert_vertex_group_rotation:
corners_weight = 1-corners_weight
ids4 = np.arange(4)
if rotation_direction == 'DIAG':
c0 = corners_weight[:,ids4]
c3 = corners_weight[:,(ids4+2)%4]
differential = c3 - c0
else:
c0 = corners_weight[:,ids4]
c1 = corners_weight[:,(ids4+1)%4]
c2 = corners_weight[:,(ids4+2)%4]
c3 = corners_weight[:,(ids4+3)%4]
differential = - c0 + c1 + c2 - c3
weight_shift = np.argmax(differential, axis=1)
# Random rotation
random_shift = 0
if rotation_mode == 'RANDOM':
np.random.seed(rand_seed)
random_shift = np.random.randint(0,4,size=n_patches)*rand_step
# UV rotation
UV_shift = 0
if rotation_mode == 'UV' and ob0.type == 'MESH':
bm = bmesh.new()
bm.from_mesh(before_subsurf)
uv_lay = bm.loops.layers.uv.active
UV_shift = [0]*len(mask)
for f in bm.faces:
ll = f.loops
if len(ll) == 4:
uv0 = ll[0][uv_lay].uv
uv1 = ll[3][uv_lay].uv
uv2 = ll[2][uv_lay].uv
uv3 = ll[1][uv_lay].uv
v01 = (uv0 + uv1) # not necessary to divide by 2
v32 = (uv3 + uv2)
v0132 = v32 - v01 # axis vector 1
v0132.normalize() # based on the rotation not on the size
v12 = (uv1 + uv2)
v03 = (uv0 + uv3)
v1203 = v03 - v12 # axis vector 2
v1203.normalize() # based on the rotation not on the size
dot1203 = v1203.x
dot0132 = v0132.x
if(abs(dot1203) < abs(dot0132)): # already vertical
if (dot0132 > 0): shift = 0
else: shift = 2 # rotate 180°
else: # horizontal
if(dot1203 < 0): shift = 3
else: shift = 1
#UV_shift.append(shift)
UV_shift[f.index] = shift
UV_shift = np.array(UV_shift)[mask]
bm.free()
# Rotate Patch
rotation_shift = np.zeros((n_patches))+rotation_shift
rot = weight_shift + random_shift + UV_shift + rotation_shift
rot = rot%4
flip_u = np.logical_or(rot==2,rot==3)
flip_v = np.logical_or(rot==1,rot==2)
flip_uv = np.logical_or(rot==1,rot==3)
all_verts[flip_u] = all_verts[flip_u,::-1,:]
all_verts[flip_v] = all_verts[flip_v,:,::-1]
all_verts[flip_uv] = np.transpose(all_verts[flip_uv],(0,2,1))
tt = tissue_time(tt, "Rotations", levels=2)
#for o in bpy.context.view_layer.objects: o.select_set(False)
new_patch = None
### COMPONENT ###
new_objects = []
# Store original values
_com_modifiers = com_modifiers
_bool_shapekeys = bool_shapekeys
for mat_id, _ob1 in enumerate(components):
if _ob1 == None: continue
# Set original values (for next commponents)
com_modifiers = _com_modifiers
bool_shapekeys = _bool_shapekeys
if component_mode != 'OBJECT':
if component_mode == 'COLLECTION':
mat_mask = coll_materials == mat_id
else:
mat_mask = materials == mat_id
if bool_material_id:
mat_mask = np.logical_and(mat_mask, materials == material_id)
masked_verts = all_verts[mat_mask]
masked_faces = mat_mask
elif bool_material_id:
masked_verts = all_verts[materials == material_id]
masked_faces = np.logical_and(mask, materials == material_id)
else:
masked_verts = all_verts
masked_faces = mask
n_patches = len(masked_verts)
if n_patches == 0: continue
if com_modifiers or _ob1.type != 'MESH': bool_shapekeys = False
# set Shape Keys to zero
original_key_values = None
if (bool_shapekeys or not com_modifiers) and _ob1.type == 'MESH':
if _ob1.data.shape_keys:
original_key_values = []
for sk in _ob1.data.shape_keys.key_blocks:
original_key_values.append(sk.value)
sk.value = 0
else:
bool_shapekeys = False
else: bool_shapekeys = False
if not com_modifiers and not bool_shapekeys:
mod_visibility = []
for m in _ob1.modifiers:
mod_visibility.append(m.show_viewport)
m.show_viewport = False
com_modifiers = True
ob1 = convert_object_to_mesh(_ob1, com_modifiers, False, False)
ob1, com_area = tessellate_prepare_component(ob1, props)
ob1.name = "_tissue_tmp_ob1"
# restore original modifiers visibility for component object
try:
for m, vis in zip(_ob1.modifiers, mod_visibility):
m.show_viewport = vis
except: pass
me1 = ob1.data
verts1 = [v.co for v in me1.vertices]
n_verts1 = len(verts1)
if n_verts1 == 0:
bpy.data.objects.remove(ob1)
continue
### COMPONENT GRID COORDINATES ###
# find relative UV component's vertices
if fill_mode == 'PATCH':
verts1_uv_quads = [0]*n_verts1
verts1_uv = [0]*n_verts1
for i, vert in enumerate(verts1):
# grid coordinates
u = int(vert[0]//step)
v = int(vert[1]//step)
u1 = min(u+1, sides)
v1 = min(v+1, sides)
if mode != 'BOUNDS':
if u > sides-1:
u = sides-1
u1 = sides
if u < 0:
u = 0
u1 = 1
if v > sides-1:
v = sides-1
v1 = sides
if v < 0:
v = 0
v1 = 1
verts1_uv_quads[i] = (u,v,u1,v1)
# factor coordinates
fu = (vert[0]-u*step)/step
fv = (vert[1]-v*step)/step
fw = vert.z
# interpolate Z scaling factor
verts1_uv[i] = Vector((fu,fv,fw))
else:
verts1_uv = verts1
if bool_shapekeys:
sk_uv_quads = []
sk_uv = []
for sk in ob1.data.shape_keys.key_blocks[1:]:
source = sk.data
_sk_uv_quads = [0]*n_verts1
_sk_uv = [0]*n_verts1
for i, sk_v in enumerate(source):
sk_vert = sk_v.co
# grid coordinates
u = int(sk_vert[0]//step)
v = int(sk_vert[1]//step)
u1 = min(u+1, sides)
v1 = min(v+1, sides)
if mode != 'BOUNDS':
if u > sides-1:
u = sides-1
u1 = sides
if u < 0:
u = 0
u1 = 1
if v > sides-1:
v = sides-1
v1 = sides
if v < 0:
v = 0
v1 = 1
_sk_uv_quads[i] = (u,v,u1,v1)
# factor coordinates
fu = (sk_vert[0]-u*step)/step
fv = (sk_vert[1]-v*step)/step
fw = sk_vert.z
_sk_uv[i] = Vector((fu,fv,fw))
sk_uv_quads.append(_sk_uv_quads)
sk_uv.append(_sk_uv)
store_sk_coordinates = [[] for t in ob1.data.shape_keys.key_blocks[1:]]
sk_uv_quads = np.array(sk_uv_quads)
sk_uv = np.array(sk_uv)
np_verts1_uv = np.array(verts1_uv)
if fill_mode == 'PATCH':
verts1_uv_quads = np.array(verts1_uv_quads)
np_u = verts1_uv_quads[:,0]
np_v = verts1_uv_quads[:,1]
np_u1 = verts1_uv_quads[:,2]
np_v1 = verts1_uv_quads[:,3]
else:
np_u = 0
np_v = 0
np_u1 = 1
np_v1 = 1
tt = tissue_time(tt, "Component preparation", levels=2)
### DEFORM PATCHES ###
verts_xyz = verts0_co[masked_verts]
v00 = verts_xyz[:, np_u, np_v].reshape((n_patches,-1,3))
v10 = verts_xyz[:, np_u1, np_v].reshape((n_patches,-1,3))
v01 = verts_xyz[:, np_u, np_v1].reshape((n_patches,-1,3))
v11 = verts_xyz[:, np_u1, np_v1].reshape((n_patches,-1,3))
vx = np_verts1_uv[:,0].reshape((1,n_verts1,1))
vy = np_verts1_uv[:,1].reshape((1,n_verts1,1))
vz = np_verts1_uv[:,2].reshape((1,n_verts1,1))
co2 = np_lerp2(v00, v10, v01, v11, vx, vy, 'verts')
### PATCHES WEIGHT ###
weight_thickness = None
if bool_vertex_group:
n_vg = len(weight)
patches_weight = weight[:, masked_verts]
w00 = patches_weight[:, :, np_u, np_v].reshape((n_vg, n_patches,-1,1))
w10 = patches_weight[:, :, np_u1, np_v].reshape((n_vg, n_patches,-1,1))
w01 = patches_weight[:, :, np_u, np_v1].reshape((n_vg, n_patches,-1,1))
w11 = patches_weight[:, :, np_u1, np_v1].reshape((n_vg, n_patches,-1,1))
store_weight = np_lerp2(w00,w10,w01,w11,vx[None,:,:,:],vy[None,:,:,:],'weight')
if vertex_group_thickness in ob0.vertex_groups.keys():
vg_id = ob0.vertex_groups[vertex_group_thickness].index
weight_thickness = store_weight[vg_id,:,:]
if invert_vertex_group_thickness:
weight_thickness = 1-weight_thickness
fact = vertex_group_thickness_factor
if fact > 0:
weight_thickness = weight_thickness*(1-fact) + fact
if vertex_group_smooth_normals in ob0.vertex_groups.keys():
vg_id = ob0.vertex_groups[vertex_group_smooth_normals].index
weight_smooth_normals = store_weight[vg_id,:,:]
else:
# Read vertex group Thickness
if vertex_group_thickness in ob0.vertex_groups.keys():
vg = ob0.vertex_groups[vertex_group_thickness]
weight_thickness = get_weight_numpy(vg, n_verts0)
wt = weight_thickness[masked_verts]
wt = wt[:,:,:,np.newaxis]
w00 = wt[:, np_u, np_v].reshape((n_patches, -1, 1))
w10 = wt[:, np_u1, np_v].reshape((n_patches, -1, 1))
w01 = wt[:, np_u, np_v1].reshape((n_patches, -1, 1))
w11 = wt[:, np_u1, np_v1].reshape((n_patches, -1, 1))
weight_thickness = np_lerp2(w00,w10,w01,w11,vx,vy,'verts')
try:
weight_thickness.shape
if invert_vertex_group_thickness:
weight_thickness = 1-weight_thickness
fact = vertex_group_thickness_factor
if fact > 0:
weight_thickness = weight_thickness*(1-fact) + fact
except: pass
# Read vertex group smooth normals
if vertex_group_smooth_normals in ob0.vertex_groups.keys():
vg = ob0.vertex_groups[vertex_group_smooth_normals]
weight_smooth_normals = get_weight_numpy(vg, n_verts0)
wt = weight_smooth_normals[masked_verts]
wt = wt[:,:,:,None]
w00 = wt[:, np_u, np_v].reshape((n_patches, -1, 1))
w10 = wt[:, np_u1, np_v].reshape((n_patches, -1, 1))
w01 = wt[:, np_u, np_v1].reshape((n_patches, -1, 1))
w11 = wt[:, np_u1, np_v1].reshape((n_patches, -1, 1))
weight_smooth_normals = np_lerp2(w00,w10,w01,w11,vx,vy,'verts')
try:
weight_smooth_normals.shape
if invert_vertex_group_smooth_normals:
weight_smooth_normals = 1-weight_smooth_normals
#fact = vertex_group_thickness_factor
#if fact > 0:
# weight_thickness = weight_thickness*(1-fact) + fact
except: pass
if normals_mode == 'FACES':
n2 = get_attribute_numpy(before_subsurf.polygons,'normal',3)
n2 = n2[masked_faces][:,None,:]
else:
if normals_mode == 'CUSTOM':
me0.calc_normals_split()
normals_split = [0]*len(me0.loops)*3
vertex_indexes = [0]*len(me0.loops)
me0.loops.foreach_get('normal', normals_split)
me0.loops.foreach_get('vertex_index', vertex_indexes)
normals_split = np.array(normals_split).reshape(-1,3)
vertex_indexes = np.array(vertex_indexes)
verts0_normal = np.zeros((len(me0.vertices),3))
np.add.at(verts0_normal, vertex_indexes, normals_split)
indexes, counts = np.unique(vertex_indexes,return_counts=True)
verts0_normal[indexes] /= counts[:,np.newaxis]
if 'Eval_Normals' in me1.uv_layers.keys():
bm1 = bmesh.new()
bm1.from_mesh(me1)
uv_co = np.array(uv_from_bmesh(bm1, 'Eval_Normals'))
vx_nor = uv_co[:,0]#.reshape((1,n_verts1,1))
#vy_nor = uv_co[:,1]#.reshape((1,n_verts1,1))
# grid coordinates
np_u = np.clip(vx_nor//step, 0, sides).astype('int')
#np_v = np.maximum(vy_nor//step, 0).astype('int')
np_u1 = np.clip(np_u+1, 0, sides).astype('int')
#np_v1 = np.minimum(np_v+1, sides).astype('int')
vx_nor = (vx_nor - np_u * step)/step
#vy_nor = (vy_nor - np_v * step)/step
vx_nor = vx_nor.reshape((1,n_verts1,1))
#vy_nor = vy_nor.reshape((1,n_verts1,1))
vy_nor = vy
bm1.free()
else:
vx_nor = vx
vy_nor = vy
if normals_mode in ('SHAPEKEYS','OBJECT') and scale_mode == 'CONSTANT' and even_thickness:
verts_norm_pos = verts0_normal_pos[masked_verts]
verts_norm_neg = verts0_normal_neg[masked_verts]
nor_mask = (vz<0).reshape((-1))
n00 = verts_norm_pos[:, np_u, np_v].reshape((n_patches,-1,3))
n10 = verts_norm_pos[:, np_u1, np_v].reshape((n_patches,-1,3))
n01 = verts_norm_pos[:, np_u, np_v1].reshape((n_patches,-1,3))
n11 = verts_norm_pos[:, np_u1, np_v1].reshape((n_patches,-1,3))
n00_neg = verts_norm_neg[:, np_u, np_v].reshape((n_patches,-1,3))
n10_neg = verts_norm_neg[:, np_u1, np_v].reshape((n_patches,-1,3))
n01_neg = verts_norm_neg[:, np_u, np_v1].reshape((n_patches,-1,3))
n11_neg = verts_norm_neg[:, np_u1, np_v1].reshape((n_patches,-1,3))
n00[:,nor_mask] = n00_neg[:,nor_mask]
n10[:,nor_mask] = n10_neg[:,nor_mask]
n01[:,nor_mask] = n01_neg[:,nor_mask]
n11[:,nor_mask] = n11_neg[:,nor_mask]
else:
verts_norm = verts0_normal[masked_verts]
n00 = verts_norm[:, np_u, np_v].reshape((n_patches,-1,3))
n10 = verts_norm[:, np_u1, np_v].reshape((n_patches,-1,3))
n01 = verts_norm[:, np_u, np_v1].reshape((n_patches,-1,3))
n11 = verts_norm[:, np_u1, np_v1].reshape((n_patches,-1,3))
n2 = np_lerp2(n00, n10, n01, n11, vx_nor, vy_nor, 'verts')
# thickness variation
mean_area = []
a2 = None
if scale_mode == 'ADAPTIVE':# and normals_mode not in ('SHAPEKEYS','OBJECT'):
#com_area = bb[0]*bb[1]
if mode != 'BOUNDS' or com_area == 0: com_area = 1
if normals_mode == 'FACES':
if levels == 0 and True:
areas = [0]*len(mask)
before_subsurf.polygons.foreach_get('area',areas)
areas = np.sqrt(np.array(areas)/com_area)[masked_faces]
a2 = areas[:,None,None]
else:
areas = calc_verts_area_bmesh(me0)
verts_area = np.sqrt(areas*patch_faces/com_area)
verts_area = verts_area[masked_verts]
verts_area = verts_area.mean(axis=(1,2)).reshape((n_patches,1,1))
a2 = verts_area
if normals_mode in ('SHAPEKEYS','OBJECT'):
verts_area = np.ones(n_verts0)
verts_area = verts_area[masked_verts]
else:
areas = calc_verts_area_bmesh(me0)
verts_area = np.sqrt(areas*patch_faces/com_area)
verts_area = verts_area[masked_verts]
a00 = verts_area[:, np_u, np_v].reshape((n_patches,-1,1))
a10 = verts_area[:, np_u1, np_v].reshape((n_patches,-1,1))
a01 = verts_area[:, np_u, np_v1].reshape((n_patches,-1,1))
a11 = verts_area[:, np_u1, np_v1].reshape((n_patches,-1,1))
# remapped z scale
a2 = np_lerp2(a00,a10,a01,a11,vx,vy,'verts')
store_coordinates = calc_thickness(co2,n2,vz,a2,weight_thickness)
co2 = n2 = vz = a2 = None
if bool_shapekeys:
tt_sk = time.time()
n_sk = len(sk_uv_quads)
# ids of face corners for each vertex (n_sk, n_verts1, 4)
np_u = np.clip(sk_uv_quads[:,:,0], 0, sides).astype('int')[:,None,:]
np_v = np.clip(sk_uv_quads[:,:,1], 0, sides).astype('int')[:,None,:]
np_u1 = np.clip(sk_uv_quads[:,:,2], 0, sides).astype('int')[:,None,:]
np_v1 = np.clip(sk_uv_quads[:,:,3], 0, sides).astype('int')[:,None,:]
# face corners for each vertex (n_patches, n_sk, n_verts1, 4)
v00 = verts_xyz[:,np_u,np_v].reshape((n_patches,n_sk,n_verts1,3))#.swapaxes(0,1)
v10 = verts_xyz[:,np_u1,np_v].reshape((n_patches,n_sk,n_verts1,3))#.swapaxes(0,1)
v01 = verts_xyz[:,np_u,np_v1].reshape((n_patches,n_sk,n_verts1,3))#.swapaxes(0,1)
v11 = verts_xyz[:,np_u1,np_v1].reshape((n_patches,n_sk,n_verts1,3))#.swapaxes(0,1)
vx = sk_uv[:,:,0].reshape((1,n_sk,n_verts1,1))
vy = sk_uv[:,:,1].reshape((1,n_sk,n_verts1,1))
vz = sk_uv[:,:,2].reshape((1,n_sk,n_verts1,1))
co2 = np_lerp2(v00,v10,v01,v11,vx,vy,mode='shapekeys')
if normals_mode == 'FACES':
n2 = n2[None,:,:,:]
else:
if normals_mode in ('SHAPEKEYS','OBJECT') and scale_mode == 'CONSTANT' and even_thickness:
verts_norm_pos = verts0_normal_pos[masked_verts]
verts_norm_neg = verts0_normal_neg[masked_verts]
nor_mask = (vz<0).reshape((-1))
n00 = verts_norm_pos[:, np_u, np_v].reshape((n_patches,n_sk,n_verts1,3))
n10 = verts_norm_pos[:, np_u1, np_v].reshape((n_patches,n_sk,n_verts1,3))
n01 = verts_norm_pos[:, np_u, np_v1].reshape((n_patches,n_sk,n_verts1,3))
n11 = verts_norm_pos[:, np_u1, np_v1].reshape((n_patches,n_sk,n_verts1,3))
n00_neg = verts_norm_neg[:, np_u, np_v].reshape((n_patches,n_sk,n_verts1,3))
n10_neg = verts_norm_neg[:, np_u1, np_v].reshape((n_patches,n_sk,n_verts1,3))
n01_neg = verts_norm_neg[:, np_u, np_v1].reshape((n_patches,n_sk,n_verts1,3))
n11_neg = verts_norm_neg[:, np_u1, np_v1].reshape((n_patches,n_sk,n_verts1,3))
n00[:,:,nor_mask] = n00_neg[:,:,nor_mask]
n10[:,:,nor_mask] = n10_neg[:,:,nor_mask]
n01[:,:,nor_mask] = n01_neg[:,:,nor_mask]
n11[:,:,nor_mask] = n11_neg[:,:,nor_mask]
else:
n00 = verts_norm[:, np_u, np_v].reshape((n_patches,n_sk,n_verts1,3))
n10 = verts_norm[:, np_u1, np_v].reshape((n_patches,n_sk,n_verts1,3))
n01 = verts_norm[:, np_u, np_v1].reshape((n_patches,n_sk,n_verts1,3))
n11 = verts_norm[:, np_u1, np_v1].reshape((n_patches,n_sk,n_verts1,3))
n2 = np_lerp2(n00,n10,n01,n11,vx,vy,'shapekeys')
# NOTE: weight thickness is based on the base position of the
# vertices, not on the coordinates of the shape keys
if scale_mode == 'ADAPTIVE':# and normals_mode not in ('OBJECT', 'SHAPEKEYS'): ### not sure
if normals_mode == 'FACES':
a2 = mean_area
else:
a00 = verts_area[:, np_u, np_v].reshape((n_patches,n_sk,n_verts1,1))
a10 = verts_area[:, np_u1, np_v].reshape((n_patches,n_sk,n_verts1,1))
a01 = verts_area[:, np_u, np_v1].reshape((n_patches,n_sk,n_verts1,1))
a11 = verts_area[:, np_u1, np_v1].reshape((n_patches,n_sk,n_verts1,1))
# remapped z scale
a2 = np_lerp2(a00,a10,a01,a11,vx,vy,'shapekeys')
store_sk_coordinates = calc_thickness(co2,n2,vz,a2,weight_thickness)
co2 = n2 = vz = a2 = weight_thickness = None
tissue_time(tt_sk, "Compute ShapeKeys", levels=3)
tt = tissue_time(tt, "Compute Coordinates", levels=2)
new_me = array_mesh(ob1, len(masked_verts))
tt = tissue_time(tt, "Repeat component", levels=2)
new_patch = bpy.data.objects.new("_tissue_tmp_patch", new_me)
bpy.context.collection.objects.link(new_patch)
store_coordinates = np.concatenate(store_coordinates, axis=0).reshape((-1)).tolist()
new_me.vertices.foreach_set('co',store_coordinates)
for area in bpy.context.screen.areas:
for space in area.spaces:
try: new_patch.local_view_set(space, True)
except: pass
tt = tissue_time(tt, "Inject coordinates", levels=2)
# Vertex Group
for vg in ob1.vertex_groups:
vg_name = vg.name
if vg_name in ob0.vertex_groups.keys():
if bool_vertex_group:
vg_name = '{} (Component)'.format(vg_name)
else:
vg_name = vg_name
#new_patch.vertex_groups.new(name=vg_name)
new_patch.vertex_groups[vg.name].name = vg_name
if bool_vertex_group:
new_groups = []
for vg in ob0.vertex_groups:
new_groups.append(new_patch.vertex_groups.new(name=vg.name))
for vg, w in zip(new_groups, store_weight):
set_weight_numpy(vg, w.reshape(-1))
tt = tissue_time(tt, "Write Vertex Groups", levels=2)
if bool_shapekeys:
for sk, val in zip(_ob1.data.shape_keys.key_blocks, original_key_values):
sk.value = val
new_patch.shape_key_add(name=sk.name, from_mix=False)
new_patch.data.shape_keys.key_blocks[sk.name].value = val
for i in range(n_sk):