forked from lazytiger/unityai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnav_mesh_tile_carving.go
More file actions
1572 lines (1388 loc) · 47.1 KB
/
nav_mesh_tile_carving.go
File metadata and controls
1572 lines (1388 loc) · 47.1 KB
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
package unityai
import (
"math"
"reflect"
"sort"
"unsafe"
)
type CarveResultStatus int32
const (
kReplaceTile CarveResultStatus = iota
kRestoreTile
kRemoveTile
)
type ClippedDetailMesh struct {
polyIndex int
vertices []Vector3f
triangles []uint16
}
func NewClippedDetailMesh() *ClippedDetailMesh {
return &ClippedDetailMesh{
polyIndex: 0,
vertices: nil,
triangles: nil,
}
}
type DetailMeshBVNode struct {
min Vector3f
max Vector3f
idx int32
}
type DetailMeshPoly struct {
vertBase int32
vertCount int32
triBase int32
triCount int32
bvBase int32
bvCount int32
}
type Triangles []uint16
func (t *Triangles) resize_uninitialized(size int) {
if cap(*t) >= size {
*t = (*t)[:size]
} else {
*t = append(*t, make([]uint16, size-len(*t))...)
}
}
type PolyContainer []DetailMeshPoly
func (c *PolyContainer) resize_uninitialized(size int) {
if cap(*c) >= size {
*c = (*c)[:size]
} else {
*c = append(*c, make([]DetailMeshPoly, size-len(*c))...)
}
}
type DetailMesh struct {
vertices []Vector3f
triangles Triangles
polys PolyContainer
bvNodes DetailMeshBVNodeContainer
}
type DetailMeshBVNodeContainer []DetailMeshBVNode
func (this *DetailMeshBVNodeContainer) resize_uninitialized(size int32) {
if cap(*this) >= int(size) {
*this = (*this)[:size]
}else {
*this = append(*this, make([]DetailMeshBVNode, int(size) - len(*this))...)
}
}
func NewDetailMesh() *DetailMesh {
return &DetailMesh{}
}
func CarveNavMeshTile(tileData *[]byte, tileDataSize *uint32,
sourceData []byte, sourceDataSize int32,
shapes []NavMeshCarveShape, shapeCount int,
carveDepth float32, carveWidth float32, quantSize float32,
position Vector3f, rotation Quaternionf) CarveResultStatus {
Assert(sourceData != nil)
Assert(sourceDataSize > 0)
*tileData = nil
*tileDataSize = 0
if shapeCount == 0 {
return kRestoreTile
}
tile := NewNavMeshTile()
if !PatchMeshTilePointers(tile, sourceData, sourceDataSize) {
// remove tile altogether if we cannot patch source data pointers
return kRemoveTile
}
Assert(tile.header != nil)
tileOffset := tile.header.bmin.Add(tile.header.bmax).Mulf(0.5)
detailMesh := NewDetailMesh()
UnpackDetailMesh(detailMesh, tile, tileOffset)
var mat Matrix4x4f
mat.SetTRInverse(position, rotation)
hull := Hull{}
var carveHulls DetailHullContainer
for i := 0; i < shapeCount; i++ {
var localShape NavMeshCarveShape
localShape.shape = shapes[i].shape
localShape.center = mat.MultiplyPoint3(shapes[i].center)
localShape.extents = shapes[i].extents
localShape.xAxis = mat.MultiplyVector3(shapes[i].xAxis)
localShape.yAxis = mat.MultiplyVector3(shapes[i].yAxis)
localShape.zAxis = mat.MultiplyVector3(shapes[i].zAxis)
TransformAABBSlow(shapes[i].bounds, mat, &localShape.bounds)
validHull := false
var localBounds MinMaxAABB
if localShape.shape == kObstacleShapeCapsule {
validHull = CalculateCapsuleHull(&hull, &localBounds, &localShape, tileOffset, carveDepth, carveWidth)
} else if localShape.shape == kObstacleShapeBox {
validHull = CalculateBoxHull(&hull, &localBounds, &localShape, tileOffset, carveDepth, carveWidth)
}
if !validHull {
continue
}
localBounds.m_Min = localBounds.m_Min.Sub(NewVector3f(quantSize, quantSize, quantSize))
localBounds.m_Max = localBounds.m_Max.Add(NewVector3f(quantSize, quantSize, quantSize))
// Find potentially intersecting polygons and create new cutter
// based on the intersection points in detail mesh.
var detailHulls DetailHullContainer
validHull = BuildDetailHulls(&detailHulls, hull, localBounds, detailMesh, tile, tileOffset, quantSize)
if validHull {
carveHulls = append(carveHulls, detailHulls...)
}
}
// The vertex quantization factor needs to match the tile size
// in order to not get any gaps at tile boundaries.
// As long as the divider is large enough and divisible by 2
// (because tileOffset is at tile center during carving),
// things should work fine.
quantFactor := quantSize
dynamicMesh := NewDynamicMesh(quantFactor)
TileToDynamicMesh(tile, dynamicMesh, tileOffset)
// Restore if nothing was clipped
if !dynamicMesh.ClipPolys2(carveHulls) {
return kRestoreTile
}
// Remove if nothing is left
if dynamicMesh.PolyCount() == 0 {
return kReplaceTile
}
// Project new vertices to detail meshes.
ProjectNewVerticesToDetailMesh(dynamicMesh, detailMesh)
dynamicMesh.FindNeighbors()
// Clip the detail triangles of the original polygons to match each new polygon.
var clipped []*ClippedDetailMesh
clipped = make([]*ClippedDetailMesh, dynamicMesh.PolyCount())
ClipDetailMeshes(clipped, dynamicMesh, detailMesh, tile, tileOffset, quantFactor)
*tileData = DynamicMeshToTile(tileDataSize, dynamicMesh, clipped, tile, tileOffset)
return kReplaceTile
}
func PatchMeshTilePointers(tile *NavMeshTile, data []byte, dataSize int32) bool {
header := (*NavMeshDataHeader)(unsafe.Pointer(&(data[0])))
tile.header = nil
if header.magic != kNavMeshMagic {
return false
}
if header.version != kNavMeshVersion {
return false
}
tile.header = header
// Patch header pointers.
headerSize := Align4(unsafe.Sizeof(NavMeshDataHeader{}))
vertsSize := Align4(unsafe.Sizeof(Vector3f{}) * uintptr(header.vertCount))
polysSize := Align4(unsafe.Sizeof(NavMeshPoly{}) * uintptr(header.polyCount))
detailMeshesSize := Align4(unsafe.Sizeof(NavMeshPolyDetail{}) * uintptr(header.detailMeshCount))
detailVertsSize := Align4(unsafe.Sizeof(Vector3f{}) * uintptr(header.detailVertCount))
detailTrisSize := Align4(unsafe.Sizeof(NavMeshPolyDetailIndex(0)) * 4 * uintptr(header.detailTriCount))
bvtreeSize := Align4(unsafe.Sizeof(NavMeshBVNode{}) * uintptr(header.bvNodeCount))
d := headerSize
var verts []Vector3f
sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&(verts)))
sliceHeader.Cap = int(header.vertCount)
sliceHeader.Len = int(header.vertCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += vertsSize
var polys []NavMeshPoly
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(polys)))
sliceHeader.Cap = int(header.polyCount)
sliceHeader.Len = int(header.polyCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += polysSize
var detailMeshes []NavMeshPolyDetail
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(detailMeshes)))
sliceHeader.Cap = int(header.detailMeshCount)
sliceHeader.Len = int(header.detailMeshCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += detailMeshesSize
var detailVerts []Vector3f
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(detailVerts)))
sliceHeader.Cap = int(header.detailVertCount)
sliceHeader.Len = int(header.detailVertCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += detailVertsSize
var detailTris []NavMeshPolyDetailIndex
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(detailTris)))
sliceHeader.Cap = int(header.detailTriCount * 4)
sliceHeader.Len = int(header.detailTriCount * 4)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += detailTrisSize
var bvTree []NavMeshBVNode
sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(bvTree)))
sliceHeader.Cap = int(header.bvNodeCount)
sliceHeader.Len = int(header.bvNodeCount)
sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d])))
d += bvtreeSize
tile.verts = verts
tile.polys = polys
tile.detailMeshes = detailMeshes
tile.detailVerts = detailVerts
tile.detailTris = detailTris
tile.bvTree = bvTree
// If there are no items in the bvtree, reset the tree pointer.
if bvtreeSize == 0 {
tile.bvTree = nil
}
return true
}
func HullPolygonIntersection(inside *Polygon, hull *Hull, temp *Polygon, quantFactor float32) {
planeCount := len(*hull)
for ic := 0; ic < planeCount; ic++ {
plane := (*hull)[ic]
result := SplitPoly(temp, *inside, plane, quantFactor, nil, 0)
if result == 0 {
inside.resize_uninitialized(len(*temp))
copy(*inside, *temp)
} else if result == 1 {
inside.resize_uninitialized(0)
return
}
}
}
type DetailNodeXSorter []DetailMeshBVNode
func (d DetailNodeXSorter) Len() int {
return len(d)
}
func (d DetailNodeXSorter) Less(i, j int) bool {
ra := d[i]
rb := d[j]
a := (ra.min.x + ra.max.x) * 0.5
b := (rb.min.x + rb.max.x) * 0.5
return a < b
}
func (d DetailNodeXSorter) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
type DetailNodeYSorter []DetailMeshBVNode
func (d DetailNodeYSorter) Len() int {
return len(d)
}
func (d DetailNodeYSorter) Less(i, j int) bool {
ra := d[i]
rb := d[j]
a := (ra.min.y + ra.max.y) * 0.5
b := (rb.min.y + rb.max.y) * 0.5
return a < b
}
func (d DetailNodeYSorter) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
type DetailNodeZSorter []DetailMeshBVNode
func (d DetailNodeZSorter) Len() int {
return len(d)
}
func (d DetailNodeZSorter) Less(i, j int) bool {
ra := d[i]
rb := d[j]
a := (ra.min.z + ra.max.z) * 0.5
b := (rb.min.z + rb.max.z) * 0.5
return a < b
}
func (d DetailNodeZSorter) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
func OverlapBoundsXZ(amin Vector3f, amax Vector3f,
bmin Vector3f, bmax Vector3f) bool {
if amin.x > bmax.x || amax.x < bmin.x {
return false
}
if amin.z > bmax.z || amax.z < bmin.z {
return false
}
return true
}
func DetailLongestAxis(v Vector3f) int32 {
axis := int32(0)
max := v.x
if v.y > max {
axis = 1
max = v.y
}
if v.z > max {
axis = 2
max = v.z
}
return axis
}
func Subdivide(nodes *[]DetailMeshBVNode,
items []DetailMeshBVNode,
imin int32, imax int32) {
inum := imax - imin
*nodes = append(*nodes, DetailMeshBVNode{})
icur := len(*nodes) - 1
node := &(*nodes)[icur]
// Update bounds
node.min = items[imin].min
node.max = items[imin].max
for i := imin + 1; i < imax; i++ {
node.min = MinVector3f(node.min, items[i].min)
node.max = MaxVector3f(node.max, items[i].max)
}
if (imax - imin) <= 1 {
// Leaf, copy triangles.
node.idx = items[imin].idx
} else {
// Split remaining items along longest axis
axis := DetailLongestAxis(node.max.Sub(node.min))
if axis == 0 {
sort.Sort(DetailNodeXSorter(items[imin:imax]))
} else if axis == 1 {
sort.Sort(DetailNodeYSorter(items[imin:imax]))
} else {
sort.Sort(DetailNodeZSorter(items[imin:imax]))
}
isplit := imin + inum/2
// Left
Subdivide(nodes, items, imin, isplit)
// Right
Subdivide(nodes, items, isplit, imax)
iescape := (len(*nodes) - 1) - icur
// Negative index means escape.
(*nodes)[icur].idx = int32(-iescape) // 'node' ref may be invalid because of realloc.
}
}
func BuildBVTree(nodes *[]DetailMeshBVNode,
vertices []Vector3f,
tris []uint16, triCount int32) bool {
*nodes = (*nodes)[:0]
// Build input items
items := make([]DetailMeshBVNode, triCount)
for i := int32(0); i < triCount; i++ {
t := tris[i*4:]
it := &items[i]
it.idx = int32(i)
// Calc triangle bounds.
it.min = vertices[t[0]]
it.max = vertices[t[0]]
it.min = MinVector3f(it.min, vertices[t[1]])
it.max = MaxVector3f(it.max, vertices[t[1]])
it.min = MinVector3f(it.min, vertices[t[2]])
it.max = MaxVector3f(it.max, vertices[t[2]])
}
Subdivide(nodes, items, 0, triCount)
return true
}
type QueryDetailBVTreeCallback interface {
process(detailMesh *DetailMesh, poly *DetailMeshPoly, tris []int32, triCount int32)
}
const BATCH_SIZE = 32
func QueryDetailBVTree(detailMesh *DetailMesh, poly *DetailMeshPoly,
queryMin Vector3f, queryMax Vector3f,
callback QueryDetailBVTreeCallback) {
var batch [BATCH_SIZE]int32
batchCount := int32(0)
// Clip all detail triangles against the polygon.
if poly.bvCount > 0 {
nodes := detailMesh.bvNodes[poly.bvBase:]
n := int32(0)
for n < poly.bvCount {
node := &nodes[n]
overlap := OverlapBoundsXZ(queryMin, queryMax, node.min, node.max)
isLeafNode := node.idx >= int32(0)
if isLeafNode && overlap {
if batchCount+1 > BATCH_SIZE {
callback.process(detailMesh, poly, batch[:], batchCount)
batchCount = 0
}
batch[batchCount] = poly.triBase + node.idx
batchCount++
}
if overlap || isLeafNode {
n++
} else {
escapeIndex := -node.idx
n += escapeIndex
}
}
} else {
for j := int32(0); j < poly.triCount; j++ {
if batchCount+1 > BATCH_SIZE {
callback.process(detailMesh, poly, batch[:], batchCount)
batchCount = 0
}
batch[batchCount] = poly.triBase + j
batchCount++
}
}
if batchCount > 0 {
callback.process(detailMesh, poly, batch[:], batchCount)
batchCount = 0
}
}
func UnpackDetailMesh(detailMesh *DetailMesh, tile *NavMeshTile, tileOffset Vector3f) {
// Unpack
polyCount := tile.header.polyCount
detailTriCount := tile.header.detailTriCount
detailPolyCount := tile.header.detailMeshCount
Assert(polyCount == detailPolyCount)
detailMesh.triangles.resize_uninitialized(int(detailTriCount) * 4)
detailMesh.polys.resize_uninitialized(int(detailPolyCount))
bvTriCount := int32(0)
maxTriCount := int32(0)
kBVTreeThreshold := int32(6)
for i := int32(0); i < polyCount; i++ {
p := &tile.polys[i]
pd := &tile.detailMeshes[i]
poly := &detailMesh.polys[i]
poly.bvBase = 0
poly.bvCount = 0
poly.vertBase = int32(len(detailMesh.vertices))
poly.vertCount = int32(p.vertCount) + int32(pd.vertCount)
for j := uint8(0); j < p.vertCount; j++ {
detailMesh.vertices = append(detailMesh.vertices, tile.verts[p.verts[j]].Sub(tileOffset))
}
for j := uint32(0); j < uint32(pd.vertCount); j++ {
detailMesh.vertices = append(detailMesh.vertices, tile.detailVerts[pd.vertBase+j].Sub(tileOffset))
}
poly.triBase = int32(pd.triBase)
poly.triCount = int32(pd.triCount)
for j := uint32(0); j < uint32(pd.triCount); j++ {
t := tile.detailTris[(pd.triBase+j)*4:]
detailMesh.triangles[(pd.triBase+j)*4+0] = uint16(t[0])
detailMesh.triangles[(pd.triBase+j)*4+1] = uint16(t[1])
detailMesh.triangles[(pd.triBase+j)*4+2] = uint16(t[2])
detailMesh.triangles[(pd.triBase+j)*4+3] = uint16(t[3])
}
if poly.triCount > kBVTreeThreshold {
bvTriCount += poly.triCount
if maxTriCount < poly.triCount {
maxTriCount = poly.triCount
}
}
}
if bvTriCount > 0 {
// Build BV-tree for polys which have many detail triangles.
var nodes []DetailMeshBVNode
for i := int32(0); i < polyCount; i++ {
poly := &detailMesh.polys[i]
if poly.triCount > kBVTreeThreshold {
BuildBVTree(&nodes, detailMesh.vertices[poly.vertBase:], detailMesh.triangles[poly.triBase*4:], poly.triCount)
nodeCount := int32(len(nodes))
if nodeCount > 0 {
poly.bvBase = int32(len(detailMesh.bvNodes))
poly.bvCount = nodeCount
detailMesh.bvNodes.resize_uninitialized(poly.bvBase + nodeCount)
for j := int32(0); j < nodeCount; j++ {
detailMesh.bvNodes[poly.bvBase+j] = nodes[j]
}
}
}
}
}
}
func ClosestHeightToTriangleEdge(height *float32, dmin *float32,
samplePos, va, vb, vc Vector3f) {
var d, t float32
*dmin = math.MaxFloat32
d = SqrDistancePointSegment2D(&t, samplePos, va, vb)
if d < *dmin {
*height = va.y + (vb.y-va.y)*t
*dmin = d
}
d = SqrDistancePointSegment2D(&t, samplePos, vb, vc)
if d < *dmin {
*height = vb.y + (vc.y-vb.y)*t
*dmin = d
}
d = SqrDistancePointSegment2D(&t, samplePos, vc, va)
if d < *dmin {
*height = vc.y + (va.y-vc.y)*t
*dmin = d
}
}
func PickDetailTriHeight(height *float32, dmin *float32,
samplePos, va, vb, vc Vector3f) {
var h float32
if ClosestHeightPointTriangle(&h, samplePos, va, vb, vc) {
*height = h
*dmin = 0.0
}
if *dmin > 0.0 {
var dist float32
ClosestHeightToTriangleEdge(&h, &dist, samplePos, va, vb, vc)
if dist < *dmin {
*height = h
*dmin = dist
}
}
}
type PickHeightCallback struct {
samplePos Vector3f
height, dmin float32
}
func NewPickHeightCallback(pos Vector3f) *PickHeightCallback {
return &PickHeightCallback{
samplePos: pos,
height: pos.y,
dmin: math.MaxFloat32,
}
}
func (this *PickHeightCallback) process(detailMesh *DetailMesh, poly *DetailMeshPoly, tris []int32, triCount int32) {
for i := int32(0); i < triCount; i++ {
t := detailMesh.triangles[tris[i]*4:]
va := detailMesh.vertices[poly.vertBase+int32(t[0])]
vb := detailMesh.vertices[poly.vertBase+int32(t[1])]
vc := detailMesh.vertices[poly.vertBase+int32(t[2])]
PickDetailTriHeight(&this.height, &this.dmin, this.samplePos, va, vb, vc)
}
}
func PickDetailPolyHeight(detailMesh *DetailMesh, polyIdx int32, samplePos Vector3f) float32 {
poly := &detailMesh.polys[polyIdx]
sampleExt := NewVector3f(0.1, 0, 0.1)
queryMin := samplePos.Sub(sampleExt)
queryMax := samplePos.Add(sampleExt)
callback := NewPickHeightCallback(samplePos)
QueryDetailBVTree(detailMesh, poly, queryMin, queryMax, callback)
return callback.height
}
func ProjectNewVerticesToDetailMesh(mesh *DynamicMesh, detailMesh *DetailMesh) {
vertCount := mesh.VertCount()
polyCount := mesh.PolyCount()
vertexSourcePoly := make([]int32, vertCount)
for i := range vertexSourcePoly {
vertexSourcePoly[i] = -1
}
// Check which vertices have changed and store their original polygon too.
// TODO: check if we need to store all source polys, now just projecting to the last one.
for i := 0; i < polyCount; i++ {
p := mesh.GetPoly(i)
if p.m_Status != kOriginalPolygon {
sourcePolyIndex := *mesh.GetData(i)
for j := uint8(0); j < p.m_VertexCount; j++ {
vertexSourcePoly[p.m_VertexIDs[j]] = int32(sourcePolyIndex)
}
}
}
for i := 0; i < vertCount; i++ {
ip := vertexSourcePoly[i]
if ip == -1 {
continue
}
pos := mesh.GetVertex(i)
pos.y = PickDetailPolyHeight(detailMesh, ip, pos)
mesh.SetVertex(i, pos)
}
}
func CalcPolyDetailBounds(bounds *MinMaxAABB, detailMesh *DetailMesh, ip int32) {
poly := detailMesh.polys[ip]
bounds.m_Min = detailMesh.vertices[poly.vertBase]
bounds.m_Max = detailMesh.vertices[poly.vertBase]
for i := int32(1); i < poly.vertCount; i++ {
bounds.EncapsulateV(detailMesh.vertices[poly.vertBase+i])
}
}
func HasBoundaryVertices(verts Vertex2Array, bmin Vector2f, bmax Vector2f) bool {
if len(verts) == 0 {
return false
}
var vmin, vmax Vector2f
vmin.x = verts[0].x
vmax.x = verts[0].x
vmin.y = verts[0].y
vmax.y = verts[0].y
for i := 1; i < len(verts); i++ {
vmin = MinVector2f(vmin, verts[i])
vmax = MaxVector2f(vmax, verts[i])
}
dmin := vmin.Sub(bmin)
if Sqr(dmin.x) < Sqr(MAGIC_EDGE_DISTANCE) {
return true
}
if Sqr(dmin.y) < Sqr(MAGIC_EDGE_DISTANCE) {
return true
}
dmax := vmax.Sub(bmax)
if Sqr(dmax.x) < Sqr(MAGIC_EDGE_DISTANCE) {
return true
}
if Sqr(dmax.y) < Sqr(MAGIC_EDGE_DISTANCE) {
return true
}
return false
}
type ClipCallback struct {
m_Hull *Hull
m_Inside *Polygon
m_Temp *Polygon
m_Footprint *Vertex2Array
m_QuantFactor float32
m_Hit bool
}
func NewClipCallback(hull *Hull, inside *Polygon, temp *Polygon, footPrint *Vertex2Array, quantFactor float32) *ClipCallback {
return &ClipCallback{
m_Hull: hull,
m_Inside: inside,
m_Temp: temp,
m_Footprint: footPrint,
m_QuantFactor: quantFactor,
m_Hit: false,
}
}
func (this *ClipCallback) process(detailMesh *DetailMesh, poly *DetailMeshPoly, tris []int32, triCount int32) {
for i := int32(0); i < triCount; i++ {
t := detailMesh.triangles[tris[i]*4:]
this.m_Inside.resize_uninitialized(3)
(*this.m_Inside)[0] = detailMesh.vertices[poly.vertBase+int32(t[0])]
(*this.m_Inside)[1] = detailMesh.vertices[poly.vertBase+int32(t[1])]
(*this.m_Inside)[2] = detailMesh.vertices[poly.vertBase+int32(t[2])]
HullPolygonIntersection(this.m_Inside, this.m_Hull, this.m_Temp, this.m_QuantFactor)
if len(*this.m_Inside) == 0 {
continue
}
for i := 0; i < len(*this.m_Inside); i++ {
*this.m_Footprint = append(*this.m_Footprint, Vector2f{})
v := &(*this.m_Footprint)[len(*this.m_Footprint)-1]
v.x = (*this.m_Inside)[i].x
v.y = (*this.m_Inside)[i].z
}
this.m_Hit = true
}
}
func BuildDetailHulls(detailHulls *DetailHullContainer,
hull Hull, bounds MinMaxAABB,
detailMesh *DetailMesh, tile *NavMeshTile, tileOffset Vector3f, quantSize float32) bool {
polyCount := tile.header.polyCount
var inside Polygon
var temp Polygon
var footPrint Vertex2Array = make([]Vector2f, 0, 32)
// Find polygons that potentially intersect with the cave hull.
// We'll use detail mesh for this to capture all cases.
// As we go we keep track of the polygons that were touched
// as well as the vertices of the detail mesh intersection.
// These intersection points will later be used to create a new infinite
// carver which is actually used for carving.
kTouched := byte(1)
kVisited := byte(2)
visited := make([]byte, polyCount)
// TODO: we should be able to use BV-tree for this.
nTouched := 0
for ip := int32(0); ip < polyCount; ip++ {
var polyBounds MinMaxAABB
CalcPolyDetailBounds(&polyBounds, detailMesh, ip)
if !IntersectAABBAABB(bounds, polyBounds) {
continue
}
visited[ip] = kTouched
nTouched++
}
var stack []int32
// Merge connecting regions.
for ip := int32(0); ip < polyCount; ip++ {
if visited[ip] != kTouched {
continue
}
var detailHull DetailHull
stack = stack[:0]
stack = append(stack, ip)
for len(stack) != 0 {
curLen := len(stack)
cur := stack[curLen-1]
stack = stack[:curLen-1]
detailHull.polysIds = append(detailHull.polysIds, int(cur))
poly := &tile.polys[cur]
for j := uint8(0); j < poly.vertCount; j++ {
// Skip if no neighbour or if at tile border.
if poly.neis[j] == uint16(0) || poly.neis[j]&uint16(0x8000) != 0 {
continue
}
nei := poly.neis[j] - 1
if visited[nei] == kTouched {
visited[nei] = kVisited
stack = append(stack, int32(nei))
}
}
}
*detailHulls = append(*detailHulls, detailHull)
}
if len(*detailHulls) == 0 {
return false
}
var convexHull Vertex2Array
detailHullCount := len(*detailHulls)
for hi := 0; hi < detailHullCount; hi++ {
detailHull := &(*detailHulls)[hi]
footPrint = footPrint[:0]
for i := 0; i < len(detailHull.polysIds); i++ {
ip := detailHull.polysIds[i]
dpoly := &detailMesh.polys[ip]
callback := NewClipCallback(&hull, &inside, &temp, &footPrint, quantSize)
QueryDetailBVTree(detailMesh, dpoly, bounds.m_Min, bounds.m_Max, callback)
if !callback.m_Hit {
polyIdLen := len(detailHull.polysIds)
detailHull.polysIds[i] = detailHull.polysIds[polyIdLen-1]
detailHull.polysIds = detailHull.polysIds[:polyIdLen-1]
i--
}
}
// TODO: Optimization, if all the potentially intersecting polygons are flat, we could
// just use the original hull.
// Build carve hull from a convex hull of footprint.
if len(footPrint) == 0 {
detailHull.polysIds = detailHull.polysIds[:0]
continue
}
CalculateConvexHull(&convexHull, &footPrint)
// Avoid simplifying the hull if it touches the tile boundary.
tileOffset2 := NewVector2f(tileOffset.x, tileOffset.z)
bmin := NewVector2f(tile.header.bmin.x, tile.header.bmin.z).Sub(tileOffset2)
bmax := NewVector2f(tile.header.bmax.x, tile.header.bmax.z).Sub(tileOffset2)
if !HasBoundaryVertices(convexHull, bmin, bmax) {
SimplifyPolyline(&convexHull, quantSize)
}
if len(convexHull) < 3 {
detailHull.polysIds = detailHull.polysIds[:0]
continue
}
// Create hull planes from the polygon
detailHull.hull = detailHull.hull[:0]
convexHullCount := len(convexHull)
for i := 0; i < convexHullCount; i++ {
position2 := convexHull[i]
dir2 := convexHull[NextIndex(int32(i), int32(convexHullCount))].Sub(position2)
len2 := Magnitude2(dir2)
if len2 <= kEpsilon {
continue
}
dir2 = dir2.Div(len2)
position := NewVector3f(position2.x, 0, position2.y)
normal := NewVector3f(-dir2.y, 0, dir2.x)
detailHull.hull.emplace_back_uninitialized().SetNormalAndPosition(normal, position)
}
}
return true
}
func HullFromPoly(hull *Hull, poly []Vector3f) {
vertCount := len(poly)
*hull = make([]Plane, vertCount)
for i := 0; i < vertCount; i++ {
position := poly[i]
dir := poly[NextIndex(int32(i), int32(vertCount))].Sub(position)
normal := NewVector3f(-dir.z, 0, dir.x)
normal = NormalizeSafe(normal, NewVector3f(0, 0, 0))
(*hull)[i].SetNormalAndPosition(normal, position)
}
}
type ClipDetailMeshCallback struct {
dmesh *ClippedDetailMesh
hull *Hull
welder *VertexWelder //64
inside *Polygon
temp *Polygon
quantFactor float32
}
func NewDetailMeshClipCallback(dmeshIn *ClippedDetailMesh, hullIn *Hull, welderIn *VertexWelder,
insideIn *Polygon, tempIn *Polygon, quantFactorIn float32) *ClipDetailMeshCallback {
return &ClipDetailMeshCallback{
dmesh: dmeshIn,
hull: hullIn,
welder: welderIn,
inside: insideIn,
temp: tempIn,
quantFactor: quantFactorIn,
}
}
const MAGIC_EDGE_DISTANCE = 1e-2
func (this *ClipDetailMeshCallback) process(detailMesh *DetailMesh, poly *DetailMeshPoly, tris []int32, triCount int32) {
for i := int32(0); i < triCount; i++ {
t := detailMesh.triangles[tris[i]*4:]
this.inside.resize_uninitialized(3)
(*this.inside)[0] = detailMesh.vertices[poly.vertBase+int32(t[0])]
(*this.inside)[1] = detailMesh.vertices[poly.vertBase+int32(t[1])]
(*this.inside)[2] = detailMesh.vertices[poly.vertBase+int32(t[2])]
HullPolygonIntersection(this.inside, this.hull, this.temp, this.quantFactor)
vertexCount := len(*this.inside)
if vertexCount < 3 {
continue
}
v0 := this.welder.AddUnique((*this.inside)[0])
v1 := this.welder.AddUnique((*this.inside)[1])
for i := 2; i < vertexCount; i++ {
v2 := this.welder.AddUnique((*this.inside)[i])
triArea2 := TriArea2D((*this.inside)[0], (*this.inside)[i-1], (*this.inside)[i])
if triArea2 < MAGIC_EDGE_DISTANCE*MAGIC_EDGE_DISTANCE {
v1 = v2
continue
}
if v0 != v1 && v1 != v2 && v2 != v0 {
this.dmesh.triangles = append(this.dmesh.triangles, uint16(v0))
this.dmesh.triangles = append(this.dmesh.triangles, uint16(v1))
this.dmesh.triangles = append(this.dmesh.triangles, uint16(v2))
}
v1 = v2
}
}
}
func ClipDetailMeshes(clipped []*ClippedDetailMesh,
mesh *DynamicMesh, detailMesh *DetailMesh,
tile *NavMeshTile,
tileOffset Vector3f,
quantFactor float32) {
queryPadding := NewVector3f(quantFactor*2.0, 0, quantFactor*2.0)
polyCount := mesh.PolyCount()
var hull Hull = make([]Plane, 0, 8)
verts := make([]Vector3f, 0, 8)
var inside Polygon = make([]Vector3f, 0, 32)
var temp Polygon = make([]Vector3f, 0, 32)
welder := NewVertexWelder(64, nil, quantFactor)
for i := 0; i < polyCount; i++ {
p := mesh.GetPoly(i)
// Process only new polygons
if p.m_Status == kOriginalPolygon {
continue
}
ip := *mesh.GetData(i)
dpoly := &detailMesh.polys[ip]
// If the detail mesh does not have any extra vertices,
// no need to clip, just retriangulate later.
if dpoly.vertCount == int32(p.m_VertexCount) {
continue
}
// Build clip hull from the polygons
verts = make([]Vector3f, p.m_VertexCount)
for j := uint8(0); j < p.m_VertexCount; j++ {
verts[j] = mesh.GetVertex(int(p.m_VertexIDs[j]))
}
HullFromPoly(&hull, verts)
// Build query box from the polygon.
var queryMin, queryMax Vector3f
queryMin = verts[0]
queryMax = verts[0]
vertsCount := len(verts)
for j := 0; j < vertsCount; j++ {
queryMin = MinVector3f(queryMin, verts[j])
queryMax = MaxVector3f(queryMax, verts[j])
}
queryMin = queryMin.Sub(queryPadding)
queryMax = queryMax.Add(queryPadding)
clipped[i] = NewClippedDetailMesh()
dmesh := clipped[i]
dmesh.polyIndex = i
welder.SetVertexArray(&dmesh.vertices)
welder.Reset()
// Clip all detail triangles against the polygon.
callback := NewDetailMeshClipCallback(dmesh, &hull, welder, &inside, &temp, quantFactor)
QueryDetailBVTree(detailMesh, dpoly, queryMin, queryMax, callback)
// Offset dmesh back to tile location.
vertCount := len(dmesh.vertices)
for j := 0; j < vertCount; j++ {
dmesh.vertices[j] = dmesh.vertices[j].Add(tileOffset)
}
if len(dmesh.vertices) < 3 || len(dmesh.triangles) < 3 {
clipped[i] = nil
}
}
}
func AreColinear(u, v Vector3f, cosAngleAccept float32) bool {
return FloatAbs(DotVector3f(v, u)) > cosAngleAccept
}
func DistancePointSegmentSqr(pt, s1, s2 Vector2f) float32 {
ds := s2.Sub(s1)
dp := pt.Sub(s1)
den := DotVector2f(ds, ds)
if den == 0 {