-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsurface_particles.py
1057 lines (894 loc) · 41.3 KB
/
surface_particles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Copyright (C) 2018 Jean Da Costa machado.
Created by Jean Da Costa machado
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import bpy
import math
from itertools import product
from . import vector_fields
from .draw_3d import *
from .multifile import register_class
from mathutils import Vector
from mathutils.kdtree import KDTree
from mathutils.bvhtree import BVHTree
import bmesh
import numpy as np
from .interface import DebugText
import random
import traceback
def subdivide_split_triangles(bm):
bmesh.ops.subdivide_edges(bm, edges=bm.edges, cuts=1, use_grid_fill=True, smooth=True)
collapse = []
triangulate = set()
seen_verts = set()
for vert in bm.verts:
if len(vert.link_faces) == 5:
face_signature = tuple(sorted(len(face.verts) for face in vert.link_faces))
if face_signature == (3, 4, 4, 4, 4):
for face in vert.link_faces:
if len(face.verts) == 3:
for edge in face.edges:
verts = set(edge.verts)
if vert not in verts and not verts & seen_verts:
seen_verts |= verts
collapse.append(edge)
triangulate |= set(face for v in verts for face in v.link_faces)
bmesh.ops.triangulate(bm, faces=list(triangulate), quad_method="SHORT_EDGE")
bmesh.ops.collapse(bm, edges=collapse)
bmesh.ops.join_triangles(bm, faces=bm.faces, angle_face_threshold=3.16, angle_shape_threshold=3.16, cmp_seam=True)
def relax_topology(bm):
for vert in bm.verts:
if vert.is_boundary:
continue
avg = Vector()
n = len(vert.link_edges)
for edge in vert.link_edges:
if edge.seam:
n = 0
break
other = edge.other_vert(vert)
avg += other.co
if n in (3, 5, 0):
continue
avg /= n
avg -= vert.co
avg -= vert.normal * vert.normal.dot(avg)
vert.co += avg * 0.5
def straigthen_quad_topology(bm):
for vert in bm.verts:
if vert.is_boundary:
continue
if len(vert.link_edges) == 3:
valid = True
for edge in vert.link_edges:
if edge.seam:
valid = False
break
if valid:
pairs = [(e_a.other_vert(vert).co, e_b.other_vert(vert).co)
for e_a in vert.link_edges for e_b in vert.link_edges if e_a is not e_b]
best_pair = min(pairs, key=lambda pair: (pair[0] - pair[1]).length_squared)
vert.co = sum(best_pair, vert.co * 0.2) / 2.2
def bvh_snap(bvh, verts):
for vert in verts:
if vert.is_boundary:
continue
cont = False
for edge in vert.link_edges:
if edge.seam:
cont = True
break
if cont:
continue
final_co = None
start = vert.co
ray = vert.normal
location1, normal, index, distance1 = bvh.ray_cast(start, ray)
location2, normal, index, distance2 = bvh.ray_cast(start, -ray)
location3, normal, index, distance3 = bvh.find_nearest(vert.co)
if location1 and location2:
final_co = location2 if distance2 < distance1 else location1
elif location1:
final_co = location1
if location3:
if distance3 * 3 < distance1:
final_co = location3
elif location2:
final_co = location2
if location3:
if distance3 * 3 < distance2:
final_co = location3
else:
if location3:
final_co = location3
if final_co:
vert.co = final_co
def lerp(v, a, b):
return (1 - v) * a + v * b
class SpatialHash:
def __init__(self, cell_size=0.1):
self.buckets = {}
self.items = {}
self.size = cell_size
def get_key(self, location):
return (
round(location[0] / self.size),
round(location[1] / self.size),
round(location[2] / self.size)
)
def insert(self, item, key=None):
if not key:
key = self.get_key(item.co)
if key in self.buckets:
self.buckets[key].add(item)
else:
self.buckets[key] = {item, }
self.items[item] = self.buckets[key]
def remove(self, item):
self.items[item].remove(item)
del self.items[item]
def update(self, item):
self.remove(item)
self.insert(item)
def test_sphere(self, co, radius, exclude=()):
radius_sqr = radius ** 2
radius = radius / self.size
location = co / self.size
min_x = math.floor(location[0] - radius)
max_x = math.ceil(location[0] + radius)
min_y = math.floor(location[1] - radius)
max_y = math.ceil(location[1] + radius)
min_z = math.floor(location[2] - radius)
max_z = math.ceil(location[2] + radius)
for x in range(min_x, max_x + 1):
for y in range(min_y, max_y + 1):
for z in range(min_z, max_z + 1):
key = (x, y, z)
if key in self.buckets:
for item in self.buckets[key]:
if (item.co - co).length_squared <= radius_sqr:
if item in exclude:
continue
yield item
def nearest_in_sphere(self, co, radius, exclude=()):
try:
yield min(self.test_sphere(co, radius, exclude=exclude), key=lambda i: (i.co - co).length_squared)
except ValueError:
pass
class Particle:
def __init__(self, location, normal, bvh_tree=None):
self.color = Vector((1, 0, 0, 1))
self.radius = 0
self.co = location
self.normal = normal
self.bvh = bvh_tree
self.dir = Vector((1, 0, 0))
self.field = None
self.parent = None
self.tag = "PARTICLE"
self.tag_number = 0
self.accumulation = location
self.accumulation_counts = 1
self.normal_accumulation = normal
self.normal_accumulation_counts = 1
def add_location_sample(self, co, w=0.3):
self.accumulation += co * w
self.accumulation_counts += w
self.co = self.accumulation / self.accumulation_counts
def add_normal_sample(self, n, w):
self.normal_accumulation += n * w
self.normal_accumulation_counts += w
self.normal = self.normal_accumulation / self.normal_accumulation_counts
class SurfaceParticleSystem:
def __init__(self, obj, model_size=1, resolution=60, mask_resolution=100):
self.triangle_mode = False
self.particles = set()
self.field = vector_fields.Field(obj)
self.draw = DrawCallback()
self.draw.matrix = obj.matrix_world
self.particle_size = model_size / resolution
self.particle_size_mask = model_size / mask_resolution
self.field_sampling_method = "RUNGE_KUTTA"
self.grid = SpatialHash(self.particle_size * 2)
def curvature_spawn_particles(self, n=10):
d_sqr = self.particle_size ** 2
verts = sorted(self.field.bm.verts, key=vector_fields.average_curvature)
for i in range(n):
vert = verts[i]
not_valid = False
for particle in self.particles:
if (vert.co - particle.co).length_squared < d_sqr:
not_valid = True
break
if not not_valid:
self.new_particle(vert.co)
def gp_spawn_particles(self, context):
r = max(self.particle_size, self.particle_size_mask)
mat = self.field.matrix.inverted()
frame = vector_fields.get_gp_frame(context)
if frame:
for stroke in frame.strokes:
for point in stroke.points:
co = mat @ point.co
valid = True
for particle in self.grid.test_sphere(co, r):
d = co - particle.co
if d.length < particle.radius:
valid = False
if valid:
p = self.new_particle(co)
p.tag = "GREASE"
p.color = Vector((0, 1, 0, 1))
def singularity_spawn_particles(self):
r = max(self.particle_size, self.particle_size_mask)
for singularity in self.field.singularities:
valid = True
for particle in self.grid.test_sphere(singularity, r):
d = particle.co - singularity
if d.length < particle.radius * 3:
break
if valid:
self.new_particle(singularity)
def sharp_edge_spawn_particles(self, source_bm, sharp_angle=0.523599):
def sharp_particle_from_vert(vert):
p = self.new_particle(vert.co)
p.tag = "SHARP"
p.normal = vert.normal
p.dir = p.dir - p.normal * p.dir.dot(p.normal)
p.color = Vector((0, 1, 0, 1))
new_bm = bmesh.new()
for edge in source_bm.edges:
if edge.calc_face_angle(0) > sharp_angle or edge.is_boundary:
verts = [new_bm.verts.new(vert.co) for vert in edge.verts]
new_bm.edges.new(verts)
bmesh.ops.remove_doubles(new_bm,
verts=new_bm.verts,
dist=min(self.particle_size, self.particle_size_mask) * 0.001)
n = 10
while True:
subdivide = []
for edge in new_bm.edges:
center = (edge.verts[0].co + edge.verts[1].co) / 2
location, normal, dir, s, c = self.field.sample_point(center)
size = lerp(s, self.particle_size, self.particle_size_mask)
if edge.calc_length() > size * 0.1:
subdivide.append(edge)
if not subdivide or n <= 0:
break
n -= 1
bmesh.ops.subdivide_edges(new_bm, edges=subdivide, cuts=1)
for vert in new_bm.verts:
if vert.calc_edge_angle(0) > sharp_angle or len(vert.link_edges) > 2:
sharp_particle_from_vert(vert)
dir = Vector(np.random.sample((3,))).normalized()
for vert in sorted(new_bm.verts, key=lambda v: v.co.dot(dir)):
location, normal, dir, s, c = self.field.sample_point(vert.co)
size = lerp(s, self.particle_size, self.particle_size_mask)
valid = True
for neighbor in self.grid.test_sphere(location, radius=size):
valid = False
break
if valid:
sharp_particle_from_vert(vert)
def propagate_particles(self, relaxation=3, factor=0.5):
grid = self.grid
current_front = list(self.particles)
while len(current_front) > 0:
yield
new_front = []
for particle in current_front:
if particle.tag not in {"SHARP", "GREASE"}:
remove = False
for intruder in grid.test_sphere(particle.co, particle.radius * 1.5, exclude=(particle,)):
avg_rad = (intruder.radius + particle.radius) * 0.5
dist = (intruder.co - particle.co).length
avg_loc = (intruder.co + particle.co) * 0.5
if intruder.tag in {"SHARP", "GREASE"} and dist < avg_rad * 0.7:
remove = True
break
elif dist < avg_rad * 0.5:
remove = True
intruder.co = avg_loc
break
if remove:
self.remove_particle(particle)
continue
if self.triangle_mode:
vecs = vector_fields.hex_symmetry_space(particle.dir, particle.normal)
vecs = (vecs[0], vecs[1], vecs[4])
else:
vecs = vector_fields.symmetry_space(particle.dir, particle.normal)
vecs = (vecs[0], vecs[1], vecs[3])
for dir in vecs:
try:
if self.field_sampling_method == "EULER":
location, normal, dir, s, c = self.field.sample_point(particle.co + dir * particle.radius,
dir)
elif self.field_sampling_method == "MIDPOINT":
location, normal, dir, s, c = self.field.sample_point(
particle.co + dir * particle.radius * 0.5, dir)
n = normal * particle.radius * 0.1 * (1 if c > 0 else -1)
dir = (location - particle.co + (dir * particle.radius * 0.5)).normalized()
location, normal, dir2, s, c = self.field.sample_point(
n + particle.co + dir * particle.radius, dir)
elif self.field_sampling_method == "RUNGE_KUTTA":
location, normal, dir1, s, c = self.field.sample_point(
particle.co + dir * particle.radius * 0.3, dir)
n = normal * particle.radius * 0.1 * (1 if c > 0 else -1)
location, normal, dir2, s, c = self.field.sample_point(
n + particle.co + dir1 * particle.radius * 0.5, dir1)
location, normal, dir3, s, c = self.field.sample_point(
n + particle.co + dir2 * particle.radius, dir2)
dir = (dir + 2 * dir1 + 2 * dir2 + dir)
n = normal * particle.radius * 0.1 * (1 if c > 0 else -1)
location, normal, dir, s, c = self.field.sample_point(
n + particle.co + dir2 * particle.radius, dir)
except ValueError:
continue
valid = True
for neighbor in grid.test_sphere(location, particle.radius * 0.7, exclude=(particle,)):
if not neighbor.tag in {"SHARP", "GREASE"} and not neighbor is particle.parent:
# neighbor.co += location * 0.3
# neighbor.co /= 1.3
neighbor.add_location_sample(location, w=factor)
grid.update(neighbor)
valid = False
break
if valid:
p = self.new_particle(location, dir)
radius_diff = p.radius - particle.radius
if abs(radius_diff) > 0.5 * particle.radius:
p.radius = particle.radius * 1.5 if radius_diff > 0 else particle.radius * 0.5
p.parent = particle
grid.insert(p)
new_front.append(p)
location, normal, dir, _, _ = self.field.sample_point(particle.co)
particle.co = location
particle.normal = normal
particle.dir = dir
grid.update(particle)
if particle.tag_number < relaxation:
new_front.append(particle)
particle.tag_number += 1
current_front = new_front
# particles = list(self.particles)
# for particle in particles:
# if particle.tag not in {"SHARP", "REMOVED"}:
# remove = False
# for intruder in grid.test_sphere(particle.co, particle.radius * 0.7, exclude=(particle,)):
# remove = True
# break
# if remove:
# self.remove_particle(particle)
# particle.tag = "REMOVED"
def repeal_particles(self, iterations=20, factor=0.01):
particles = list(self.particles)
tree = KDTree(len(particles))
for index, particle in enumerate(particles):
tree.insert(particle.co, index)
tree.balance()
for i in range(iterations):
new_tree = KDTree(len(self.particles))
for index, particle in enumerate(particles):
if particle.tag in {"SHARP", "GREASE"}:
continue
d = Vector()
for loc, other_index, dist in tree.find_n(particle.co, 3):
if dist == 0:
continue
other = particles[other_index]
vec = particle.co - other.co
d += (vec / (dist ** 3))
if not self.triangle_mode:
u = particle.dir
v = u.cross(particle.normal)
for vec in (u + v, u - v, -u + v, -u - v):
vec *= particle.radius
vec += other.co
vec -= particle.co
dist = vec.length
d -= vec * 0.3 / (dist ** 3)
d.normalize()
location, normal, dir, s, c = self.field.sample_point(particle.co + (d * factor * particle.radius))
if location:
particle.co = location
particle.normal = normal
self.grid.update(particle)
particle.dir = dir
new_tree.insert(particle.co, index)
new_tree.balance()
tree = new_tree
yield i
def mirror_particles(self, axis):
particles = list(self.particles)
for particle in particles:
r = particle.radius * 0.5
if -r * 0.7 <= particle.co[axis] <= r:
particle.co[axis] = 0
elif particle.co[axis] < 0:
self.remove_particle(particle)
else:
mirror_co = particle.co.copy()
mirror_co[axis] *= -1
self.new_particle(mirror_co)
def new_particle(self, location, dir=None):
location, normal, dir, s, c = self.field.sample_point(location, dir)
particle = Particle(location, normal, self.field.bvh)
particle.dir = dir
particle.radius = lerp(s, self.particle_size, self.particle_size_mask)
self.particles.add(particle)
self.grid.insert(particle)
return particle
def remove_particle(self, particle):
self.particles.remove(particle)
self.grid.remove(particle)
particle.tag = "REMOVED"
def draw_particles(self, relaxation_steps=3):
self.draw.clear_data()
self.draw.point_size = 8
for particle in self.particles:
self.draw.add_point(particle.co,
particle.color * (particle.tag_number / relaxation_steps))
self.draw.update_batch()
def create_mesh(self, bm, sharp_angle=0.52):
bmesh.ops.triangulate(bm, faces=bm.faces)
source_bvh = BVHTree.FromBMesh(bm)
mask_layer = bm.verts.layers.paint_mask.verify()
n = 5
while True:
subdivide_edges = []
for edge in bm.edges:
le = edge.calc_length()
s = (edge.verts[0][mask_layer] + edge.verts[1][mask_layer]) / 2
target_le = lerp(s, self.particle_size, self.particle_size_mask)
if target_le * 0.5 <= le:
subdivide_edges.append(edge)
print(len(subdivide_edges))
print("subdivide", n)
n -= 1
if not subdivide_edges or n < 0:
break
print("subdivide")
bmesh.ops.subdivide_edges(bm, edges=subdivide_edges, cuts=1, use_grid_fill=True, use_only_quads=True)
bmesh.ops.triangulate(bm, faces=bm.faces, quad_method="SHORT_EDGE")
bmesh.ops.beautify_fill(bm, edges=bm.edges, faces=bm.faces, method="AREA")
print("done")
# ==========================================================================================
bm.verts.ensure_lookup_table()
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
n = len(bm.verts)
bvh = BVHTree.FromBMesh(bm)
sharp = 20
smooth = 10
particles = np.array([particle.co for particle in self.particles], dtype=np.float64, ndmin=2)
weights = np.array([smooth if particle.tag == "SHARP" else sharp for particle in self.particles], dtype=np.int8)
locations = np.array([vert.co for vert in bm.verts], dtype=np.float64, ndmin=2)
particles_mapping = np.full((n,), -1, dtype=np.int64)
current_front = set()
for i in range(len(self.particles)):
co = particles[i]
location, normal, index, dist = bvh.find_nearest(co)
if location:
vert = min(bm.faces[index].verts,
key=lambda v: (v.co - Vector(co)).length_squared * (
2 if particles_mapping[v.index] == -1 else 1))
vert.tag = True
particles_mapping[vert.index] = i
current_front.add(vert)
while current_front:
new_front = set()
for vert in current_front:
for edge in vert.link_edges:
other = edge.other_vert(vert)
if not other.tag:
new_front.add(other)
particles_mapping[other.index] = particles_mapping[vert.index]
other.tag = True
current_front = new_front
edges_limit = 10
edges = np.empty((n, edges_limit), dtype=np.int64)
edges_count = np.empty((n,), dtype=np.int64)
for vert in bm.verts:
edges_count[vert.index] = min(edges_limit, len(vert.link_edges))
for i, edge in enumerate(vert.link_edges):
if i >= edges_limit:
break
other = edge.other_vert(vert)
edges[vert.index][i] = other.index
ids = np.arange(n)
for i in range(30):
cols = np.random.randint(0, edges_limit) % edges_count
edge_indexes = edges[ids, cols]
edge_mappings = particles_mapping[edge_indexes]
distance = ((particles[particles_mapping] - locations) ** 2).sum(axis=1) * weights[particles_mapping]
edge_distance = ((particles[edge_mappings] - locations) ** 2).sum(axis=1) * weights[edge_mappings]
particles_mapping = np.where(edge_distance > distance, particles_mapping, edge_mappings)
# ==========================================================================================
new_bm = bmesh.new()
# ==========================================================================================
verts = [new_bm.verts.new(co) for co in particles]
for index, particle in enumerate(self.particles):
if particle.tag == "SHARP":
verts[index].tag = True
for face in bm.faces:
particles_indexes = set(particles_mapping[vert.index] for vert in face.verts)
if len(particles_indexes) == 3:
try:
new_bm.faces.new((verts[i] for i in particles_indexes))
except ValueError:
pass
bmesh.ops.recalc_face_normals(new_bm, faces=new_bm.faces)
# ==========================================================================================
for i in range(50):
stop = True
for vert in new_bm.verts:
le = len(vert.link_edges)
if le < 3:
new_bm.verts.remove(vert)
stop = False
for edge in new_bm.edges:
if len(edge.link_faces) < 2:
new_bm.edges.remove(edge)
stop = False
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=min(self.particle_size, self.particle_size_mask) * 0.1)
bmesh.ops.holes_fill(new_bm, edges=new_bm.edges)
bmesh.ops.triangulate(new_bm, faces=new_bm.faces, quad_method="SHORT_EDGE")
if stop:
break
bvh_snap(source_bvh, bm.verts)
bmesh.ops.holes_fill(new_bm, edges=new_bm.edges)
bmesh.ops.triangulate(new_bm, faces=new_bm.faces)
bmesh.ops.recalc_face_normals(new_bm, faces=new_bm.faces)
# ==========================================================================================
if sharp_angle < math.pi:
crease = new_bm.edges.layers.crease.verify()
for edge in new_bm.edges:
if edge.calc_face_angle(0) > sharp_angle:
edge[crease] = 1.0
edge.seam = True
# ==========================================================================================
if not self.triangle_mode:
for i in range(2):
stop = True
bmesh.ops.join_triangles(new_bm, faces=new_bm.faces,
angle_face_threshold=3.14,
angle_shape_threshold=3.14,
cmp_seam=True)
relax_topology(new_bm)
bvh_snap(source_bvh, new_bm.verts)
# ==========================================================================================
# merge_hints = {
# (5, 3, 5, 3), (3, 5, 3, 5),
# (4, 3, 4, 3), (3, 4, 3, 4),
# (5, 3, 4, 3), (3, 5, 3, 4), (4, 3, 5, 3), (3, 4, 3, 5)
# }
# merge_map = {}
# seen_verts = set()
# for face in new_bm.faces:
# face_signature = tuple((len(vert.link_edges) for vert in face.verts))
# if face_signature in merge_hints:
# loop = [loop for loop in face.loops if len(loop.vert.link_edges) == 3][0]
# vert0 = loop.vert
# vert1 = loop.link_loop_next.link_loop_next.vert
# co = (vert0.co + vert1.co) / 2
# vert0.co, vert1.co = co, co
# verts = {vert0, vert1}
# if not verts & seen_verts:
# seen_verts |= verts
# merge_map[vert0] = vert1
# bmesh.ops.weld_verts(new_bm, targetmap=merge_map)
# ==========================================================================================
# faces = []
# for face in new_bm.faces:
# tri_count = 0
# for edge in face.edges:
# for possible_tri in edge.link_faces:
# if possible_tri is not face and len(possible_tri.verts) == 3:
# tri_count += 1
# if tri_count == 3:
# faces.append(face)
# bmesh.ops.poke(new_bm, faces=faces)
# bmesh.ops.join_triangles(new_bm, faces=new_bm.faces, angle_face_threshold=sharp_angle,
# angle_shape_threshold=3.14,
# cmp_seam=True)
# ==========================================================================================
# collapse = []
# seen_verts = set()
# for edge in new_bm.edges:
# tri_count = 0
# for face in edge.link_faces:
# if len(face.verts) == 3:
# tri_count += 1
# if tri_count == 2:
# verts = set(edge.verts)
# if not verts & seen_verts:
# collapse.append(edge)
# seen_verts |= verts
# bmesh.ops.collapse(new_bm, edges=collapse)
# ==========================================================================================
relax_topology(new_bm)
bvh_snap(source_bvh, new_bm.verts)
return new_bm, source_bvh
@register_class
class ParticleRemesh(bpy.types.Operator):
bl_idname = "tesselator.remesh"
bl_label = "Particle Remesh"
bl_description = "Rebuilds the mesh by simulating a particle system."
bl_options = {"REGISTER", "UNDO"}
_timer = None
particle_relaxation: bpy.props.FloatProperty(
name="Relaxation Factor",
description="Relaxates points after placement",
min=0.0001,
max=2,
default=1
)
relaxation_steps: bpy.props.IntProperty(
name="Relaxation Steps",
description="Amount of smoothing steps applied to the particles.",
min=1,
default=2
)
repulsion_iterations: bpy.props.IntProperty(
name="Repulsion Iterations",
description="How many times to repeal particles to keep a uniform distribution",
min=0,
default=10
)
repulsion_strength: bpy.props.FloatProperty(
name="Repulstion_strength",
description="How much to repeal particles in each iteration",
min=0.00001,
max=1.0,
default=0.05
)
resolution: bpy.props.FloatProperty(
name="Resolution",
description="Distance between particles relative to object size",
min=0.0001,
default=45
)
mask_resolution: bpy.props.FloatProperty(
name="Mask Resolution",
description="Distance between particles relative to object size in masked areas\n"
"Notice, Particle size will also interpolate between smooth mask values",
min=0.0001,
default=100
)
mirror_axes: bpy.props.BoolVectorProperty(
name="Mirror Axes",
description="Mirror field and particles at specified axes.",
size=3,
default=(False, False, False)
)
subdivisions: bpy.props.IntProperty(
name="Subdivisions",
description="Amount of subudivisions applied to the final mesh",
min=0,
default=1
)
gp_influence: bpy.props.FloatProperty(
name="Annotation Influence",
description="How much annotations affect the resulting direction",
min=0,
max=1,
default=0.2
)
field_resolution: bpy.props.IntProperty(
name="Field Resolution",
description="Maximum amount of verts the guiding field should have. Increase to make topology more complex",
min=100,
default=8000
)
field_sampling_method: bpy.props.EnumProperty(
name="Field Sampling Method",
description="Precision level of sampling",
items=[
("EULER", "Euler", "Better suited to simpler meshes, very fast."),
("MIDPOINT", "Midpoint", "General purpose, slightly slower than Euler"),
("RUNGE_KUTTA", "Runge-Kutta Order 4", "Slow but snaps particles to edges and aligns better the topology,"
"better suited for preserving sharp features.")
],
default="MIDPOINT"
)
polygon_mode: bpy.props.EnumProperty(
name="Polygon Mode",
description="What kind of polygon to tesselate",
items=[("TRI", "Triangles", "Pure Triangles"),
("QUADS", "Quads", "Pure Quadrilaterals"),
("TRI_AND_QUADS", "Triangles and Quads", "Remesh with quadrilaterals bud add triangle bifurcations")],
default="QUADS"
)
field_smoothing_iterations: bpy.props.IntVectorProperty(
name="Repeat",
description="Amount of smoothing iterations for each round, the higher the values, the more smooth"
"the results will be",
size=3,
min=0,
default=(30, 30, 100),
)
field_smoothing_depth: bpy.props.IntVectorProperty(
name="Distance",
description="Amount of random walk steps used to average the field for each round, higher values yield less"
"complex curves",
size=3,
min=0,
default=(100, 30, 0)
)
sharp_angle: bpy.props.FloatProperty(
name="Sharp Angle",
description="Snaps edge to sharp features based on face angles (180° = Disable)",
default=math.pi,
min=0,
max=math.pi,
subtype="ANGLE"
)
def draw(self, context):
layout = self.layout
row = layout.row(align=True)
row.prop_enum(self, "polygon_mode", value="QUADS")
row.prop_enum(self, "polygon_mode", value="TRI")
row.prop_enum(self, "polygon_mode", value="TRI_AND_QUADS")
layout.prop(self, "sharp_angle")
layout.separator()
layout.prop(self, "resolution")
layout.prop(self, "mask_resolution")
layout.prop(self, "subdivisions")
layout.separator()
layout.prop(self, "particle_relaxation", slider=True)
layout.prop(self, "relaxation_steps")
layout.prop(self, "repulsion_iterations")
layout.prop(self, "repulsion_strength")
layout.prop(self, "field_sampling_method")
layout.separator()
row = layout.row()
split = row.split(factor=0.5)
split.label(text="Symmetry Axes")
row = split.row(align=True)
row.prop(self, "mirror_axes", text="X", index=0, toggle=True)
row.prop(self, "mirror_axes", text="Y", index=1, toggle=True)
row.prop(self, "mirror_axes", text="Z", index=2, toggle=True)
layout.separator()
layout.label(text="Cross Field Smoothing")
layout.prop(self, "gp_influence", slider=True)
layout.prop(self, "field_resolution")
row0 = layout.row(align=True)
for text in ("", "Round 1", "Round 2", "Round 3"):
row0.label(text=text)
row1 = layout.row(align=True)
row2 = layout.row(align=True)
row1.label(text="Repeat")
row2.label(text="Distance")
for i in range(3):
row1.prop(self, "field_smoothing_iterations", index=i, text="")
row2.prop(self, "field_smoothing_depth", index=i, text="")
def algorithm(self, context):
obj = context.active_object
bm = bmesh.new()
bm.from_mesh(obj.data)
for vert in bm.verts:
if len(vert.link_faces) < 1:
bm.verts.remove(vert)
bmesh.ops.holes_fill(bm, edges=bm.edges)
bmesh.ops.triangulate(bm, faces=bm.faces)
bm.to_mesh(obj.data)
DebugText.lines = ["Decimating mesh."]
yield
model_size = max(context.active_object.dimensions)
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="SELECT")
bpy.ops.mesh.decimate(ratio=self.field_resolution / len(bm.verts))
bpy.ops.object.mode_set(mode="OBJECT")
yield
self.particle_manager = SurfaceParticleSystem(context.active_object, model_size, self.resolution,
self.mask_resolution)
self.particle_manager.field_sampling_method = self.field_sampling_method
self.particle_manager.triangle_mode = (self.polygon_mode == "TRI")
self.particle_manager.field.hex_mode = (self.polygon_mode == "TRI")
self.particle_manager.field.draw.setup_handler()
self.particle_manager.draw.setup_handler()
self.particle_manager.field.preview_fast()
yield
if self.gp_influence > 0:
self.particle_manager.field.initialize_from_gp(context)
self.particle_manager.field.weights /= max(0.00000001, 1 - self.gp_influence)
self.particle_manager.field.weights = self.particle_manager.field.weights.clip(0, 1)
self.particle_manager.gp_spawn_particles(context)
for i in range(3):
self.particle_manager.field.smooth(self.field_smoothing_iterations[i], self.field_smoothing_depth[i])
for axis in range(3):
if self.mirror_axes[axis]:
self.particle_manager.field.mirror(axis)
DebugText.lines = ["Creating Cross Field",
f"Step: {i + 1}"]
yield
self.particle_manager.field.preview()
if self.sharp_angle < math.pi:
self.particle_manager.sharp_edge_spawn_particles(bm, self.sharp_angle)
if len(self.particle_manager.particles) == 0:
self.particle_manager.field.detect_singularities()
self.particle_manager.singularity_spawn_particles()
if len(self.particle_manager.particles) == 0:
self.particle_manager.curvature_spawn_particles(5)
for i, _ in enumerate(
self.particle_manager.propagate_particles(self.relaxation_steps, self.particle_relaxation)):
self.particle_manager.draw_particles(self.relaxation_steps)
DebugText.lines = [f"Propagating particles {('.', '..', '...')[i % 3]}"]
yield
for i, _ in enumerate(self.particle_manager.repeal_particles(iterations=self.repulsion_iterations,
factor=self.repulsion_strength)):
self.particle_manager.draw_particles()
DebugText.lines = ["Particle repulsion:",
f"Step {i + 1}"]
yield
for i in range(3):
if self.mirror_axes[i]:
self.particle_manager.mirror_particles(axis=i)
print("Mirror")
self.particle_manager.draw_particles()
DebugText.lines = ["Tesselating."]
yield
bm, bvh = self.particle_manager.create_mesh(bm, self.sharp_angle)
if self.polygon_mode == "QUADS":
bm.to_mesh(obj.data)
yield