From b52e1f7059a0a32fae97e294770a6993707bdb7c Mon Sep 17 00:00:00 2001 From: flswld Date: Fri, 13 Dec 2024 14:55:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=AF=BB=E8=B7=AF?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- multi/handle/anticheat.go | 6 +- multi/handle/query_path.go | 214 ++- pkg/alg/bfs_pathfinding.go | 2 +- pkg/navmesh/aabb.go | 140 ++ pkg/navmesh/dynamic_mesh.cpp.go | 821 ++++++++++ pkg/navmesh/dynamic_mesh.go | 165 ++ pkg/navmesh/format/nav_mesh_types.go | 738 +++++++++ pkg/navmesh/hull_avoidance.go | 100 ++ pkg/navmesh/math.go | 341 ++++ pkg/navmesh/matrix.go | 143 ++ pkg/navmesh/nav_mesh.cpp.go | 2077 +++++++++++++++++++++++ pkg/navmesh/nav_mesh.go | 359 ++++ pkg/navmesh/nav_mesh_build_setting.go | 32 + pkg/navmesh/nav_mesh_carve_types.go | 182 ++ pkg/navmesh/nav_mesh_carving.cpp.go | 264 +++ pkg/navmesh/nav_mesh_carving.go | 44 + pkg/navmesh/nav_mesh_data.go | 221 +++ pkg/navmesh/nav_mesh_manager.go | 588 +++++++ pkg/navmesh/nav_mesh_node.cpp.go | 112 ++ pkg/navmesh/nav_mesh_node.go | 108 ++ pkg/navmesh/nav_mesh_path.go | 97 ++ pkg/navmesh/nav_mesh_query.cpp.go | 2189 +++++++++++++++++++++++++ pkg/navmesh/nav_mesh_query.go | 31 + pkg/navmesh/nav_mesh_tile_carving.go | 1606 ++++++++++++++++++ pkg/navmesh/nav_mesh_types.go | 56 + pkg/navmesh/path_corridor.go | 350 ++++ pkg/navmesh/plane.go | 21 + pkg/navmesh/quaternion.go | 175 ++ pkg/navmesh/query_filter.go | 63 + pkg/navmesh/util.go | 199 +++ pkg/navmesh/vector.go | 206 +++ pkg/navmesh/vertex_welder.go | 104 ++ 32 files changed, 11671 insertions(+), 83 deletions(-) create mode 100644 pkg/navmesh/aabb.go create mode 100644 pkg/navmesh/dynamic_mesh.cpp.go create mode 100644 pkg/navmesh/dynamic_mesh.go create mode 100644 pkg/navmesh/format/nav_mesh_types.go create mode 100644 pkg/navmesh/hull_avoidance.go create mode 100644 pkg/navmesh/math.go create mode 100644 pkg/navmesh/matrix.go create mode 100644 pkg/navmesh/nav_mesh.cpp.go create mode 100644 pkg/navmesh/nav_mesh.go create mode 100644 pkg/navmesh/nav_mesh_build_setting.go create mode 100644 pkg/navmesh/nav_mesh_carve_types.go create mode 100644 pkg/navmesh/nav_mesh_carving.cpp.go create mode 100644 pkg/navmesh/nav_mesh_carving.go create mode 100644 pkg/navmesh/nav_mesh_data.go create mode 100644 pkg/navmesh/nav_mesh_manager.go create mode 100644 pkg/navmesh/nav_mesh_node.cpp.go create mode 100644 pkg/navmesh/nav_mesh_node.go create mode 100644 pkg/navmesh/nav_mesh_path.go create mode 100644 pkg/navmesh/nav_mesh_query.cpp.go create mode 100644 pkg/navmesh/nav_mesh_query.go create mode 100644 pkg/navmesh/nav_mesh_tile_carving.go create mode 100644 pkg/navmesh/nav_mesh_types.go create mode 100644 pkg/navmesh/path_corridor.go create mode 100644 pkg/navmesh/plane.go create mode 100644 pkg/navmesh/quaternion.go create mode 100644 pkg/navmesh/query_filter.go create mode 100644 pkg/navmesh/util.go create mode 100644 pkg/navmesh/vector.go create mode 100644 pkg/navmesh/vertex_welder.go diff --git a/multi/handle/anticheat.go b/multi/handle/anticheat.go index 4a99aba3..58753b34 100644 --- a/multi/handle/anticheat.go +++ b/multi/handle/anticheat.go @@ -227,9 +227,5 @@ func GetEntityType(entityId uint32) int { } func GetDistance(v1 *proto.Vector, v2 *proto.Vector) float32 { - return float32(math.Sqrt( - float64((v1.X-v2.X)*(v1.X-v2.X)) + - float64((v1.Y-v2.Y)*(v1.Y-v2.Y)) + - float64((v1.Z-v2.Z)*(v1.Z-v2.Z)), - )) + return float32(math.Sqrt(float64((v1.X-v2.X)*(v1.X-v2.X)) + float64((v1.Y-v2.Y)*(v1.Y-v2.Y)) + float64((v1.Z-v2.Z)*(v1.Z-v2.Z)))) } diff --git a/multi/handle/query_path.go b/multi/handle/query_path.go index f07acc27..bcb622f5 100644 --- a/multi/handle/query_path.go +++ b/multi/handle/query_path.go @@ -4,72 +4,38 @@ import ( "bytes" "encoding/gob" "os" + "runtime" "hk4e/pkg/alg" "hk4e/pkg/logger" + "hk4e/pkg/navmesh" + "hk4e/pkg/navmesh/format" "hk4e/protocol/cmd" "hk4e/protocol/proto" pb "google.golang.org/protobuf/proto" ) -func (h *Handle) ConvPbVecToMeshVec(pbVec *proto.Vector) alg.MeshVector { - return alg.MeshVector{ - X: int16(pbVec.X), - Y: int16(pbVec.Y), - Z: int16(pbVec.Z), - } -} - -func (h *Handle) ConvMeshVecToPbVec(meshVec alg.MeshVector) *proto.Vector { - return &proto.Vector{ - X: float32(meshVec.X), - Y: float32(meshVec.Y), - Z: float32(meshVec.Z), - } -} - -func (h *Handle) ConvPbVecListToMeshVecList(pbVecList []*proto.Vector) []alg.MeshVector { - ret := make([]alg.MeshVector, 0) - for _, pbVec := range pbVecList { - ret = append(ret, h.ConvPbVecToMeshVec(pbVec)) - } - return ret -} - -func (h *Handle) ConvMeshVecListToPbVecList(meshVecList []alg.MeshVector) []*proto.Vector { - ret := make([]*proto.Vector, 0) - for _, meshVec := range meshVecList { - ret = append(ret, h.ConvMeshVecToPbVec(meshVec)) - } - return ret -} - func (h *Handle) QueryPath(userId uint32, gateAppId string, payloadMsg pb.Message) { req := payloadMsg.(*proto.QueryPathReq) logger.Debug("query path req: %v, uid: %v, gateAppId: %v", req, userId, gateAppId) - var ok = false - var path []alg.MeshVector = nil for _, destinationPos := range req.DestinationPos { - ok, path = h.worldStatic.Pathfinding(h.ConvPbVecToMeshVec(req.SourcePos), h.ConvPbVecToMeshVec(destinationPos)) + corners, ok := h.worldStatic.NavMeshPathfinding(req.SceneId, req.SourcePos, destinationPos) if ok { - break + rsp := &proto.QueryPathRsp{ + QueryId: req.QueryId, + QueryStatus: proto.QueryPathRsp_STATUS_SUCC, + Corners: corners, + } + h.SendMsg(cmd.QueryPathRsp, userId, gateAppId, rsp) + return } } - if !ok { - queryPathRsp := &proto.QueryPathRsp{ - QueryId: req.QueryId, - QueryStatus: proto.QueryPathRsp_STATUS_FAIL, - } - h.SendMsg(cmd.QueryPathRsp, userId, gateAppId, queryPathRsp) - return - } - queryPathRsp := &proto.QueryPathRsp{ + rsp := &proto.QueryPathRsp{ QueryId: req.QueryId, - QueryStatus: proto.QueryPathRsp_STATUS_SUCC, - Corners: h.ConvMeshVecListToPbVecList(path), + QueryStatus: proto.QueryPathRsp_STATUS_FAIL, } - h.SendMsg(cmd.QueryPathRsp, userId, gateAppId, queryPathRsp) + h.SendMsg(cmd.QueryPathRsp, userId, gateAppId, rsp) } func (h *Handle) ObstacleModifyNotify(userId uint32, gateAppId string, payloadMsg pb.Message) { @@ -78,27 +44,58 @@ func (h *Handle) ObstacleModifyNotify(userId uint32, gateAppId string, payloadMs } type WorldStatic struct { + navMeshManagerMap map[uint32]*navmesh.NavMeshManager // x y z -> if terrain exist - terrain map[alg.MeshVector]bool + terrain map[alg.MeshVector]struct{} } func NewWorldStatic() (r *WorldStatic) { r = new(WorldStatic) - r.terrain = make(map[alg.MeshVector]bool) + r.navMeshManagerMap = make(map[uint32]*navmesh.NavMeshManager) + r.terrain = make(map[alg.MeshVector]struct{}) return r } func (w *WorldStatic) InitTerrain() bool { + fileList, err := os.ReadDir("./NavMesh") + if err != nil { + logger.Error("open navmesh dir error: %v", err) + } else { + for _, file := range fileList { + if file.IsDir() { + continue + } + fileName := file.Name() + navMeshDataFormat, err := format.LoadFromMhyFile("./NavMesh/" + fileName) + if err != nil { + logger.Error("parse navmesh file error: %v", err) + continue + } + navMeshManager, exist := w.navMeshManagerMap[navMeshDataFormat.M_NavMeshDataID] + if !exist { + navMeshManager = navmesh.NewNavMeshManager() + w.navMeshManagerMap[navMeshDataFormat.M_NavMeshDataID] = navMeshManager + } + navMeshData := navmesh.NewDataFromFormat(navMeshDataFormat) + err = navMeshManager.LoadData(navMeshData) + if err != nil { + logger.Error("load navmesh file error: %v", err) + continue + } + logger.Info("load navmesh file ok, fileName: %v", fileName) + runtime.GC() + } + } data, err := os.ReadFile("./world_terrain.bin") if err != nil { logger.Error("read world terrain file error: %v", err) - return false - } - decoder := gob.NewDecoder(bytes.NewReader(data)) - err = decoder.Decode(&w.terrain) - if err != nil { - logger.Error("unmarshal world terrain data error: %v", err) - return false + } else { + decoder := gob.NewDecoder(bytes.NewReader(data)) + err = decoder.Decode(&w.terrain) + if err != nil { + logger.Error("unmarshal world terrain data error: %v", err) + return false + } } return true } @@ -120,42 +117,105 @@ func (w *WorldStatic) SaveTerrain() bool { } func (w *WorldStatic) GetTerrain(x int16, y int16, z int16) (exist bool) { - pos := alg.MeshVector{ - X: x, - Y: y, - Z: z, - } - exist = w.terrain[pos] + pos := alg.MeshVector{X: x, Y: y, Z: z} + _, exist = w.terrain[pos] return exist } func (w *WorldStatic) SetTerrain(x int16, y int16, z int16) { - pos := alg.MeshVector{ - X: x, - Y: y, - Z: z, - } - w.terrain[pos] = true + pos := alg.MeshVector{X: x, Y: y, Z: z} + w.terrain[pos] = struct{}{} } -func (w *WorldStatic) Pathfinding(startPos alg.MeshVector, endPos alg.MeshVector) (bool, []alg.MeshVector) { +func ConvPbVecToSvoVec(pbVec *proto.Vector) alg.MeshVector { + return alg.MeshVector{X: int16(pbVec.X), Y: int16(pbVec.Y), Z: int16(pbVec.Z)} +} + +func ConvSvoVecToPbVec(svoVec alg.MeshVector) *proto.Vector { + return &proto.Vector{X: float32(svoVec.X), Y: float32(svoVec.Y), Z: float32(svoVec.Z)} +} + +func ConvPbVecListToSvoVecList(pbVecList []*proto.Vector) []alg.MeshVector { + ret := make([]alg.MeshVector, 0, len(pbVecList)) + for _, pbVec := range pbVecList { + ret = append(ret, ConvPbVecToSvoVec(pbVec)) + } + return ret +} + +func ConvSvoVecListToPbVecList(svoVecList []alg.MeshVector) []*proto.Vector { + ret := make([]*proto.Vector, 0, len(svoVecList)) + for _, svoVec := range svoVecList { + ret = append(ret, ConvSvoVecToPbVec(svoVec)) + } + return ret +} + +func (w *WorldStatic) SvoPathfinding(sceneId uint32, startPos *proto.Vector, endPos *proto.Vector) ([]*proto.Vector, bool) { defer func() { if err := recover(); err != nil { - logger.Error("pathfinding error, panic, startPos: %v, endPos: %v", startPos, endPos) + logger.Error("svo pathfinding error, panic, startPos: %v, endPos: %v", startPos, endPos) } }() bfs := alg.NewBFS() bfs.InitMap( w.terrain, - startPos, - endPos, + ConvPbVecToSvoVec(startPos), + ConvPbVecToSvoVec(endPos), 0, ) pathVectorList := bfs.Pathfinding() if pathVectorList == nil { - logger.Error("could not find path") - return false, nil + logger.Error("svo could not find path, sceneId: %v, startPos: %v, endPos: %v", sceneId, startPos, endPos) + return nil, false } - logger.Debug("find path success, path: %v", pathVectorList) - return true, pathVectorList + return ConvSvoVecListToPbVecList(pathVectorList), true +} + +func ConvPbVecToNavMeshVec(pbVec *proto.Vector) navmesh.Vector3f { + var ret navmesh.Vector3f + ret.Set(pbVec.X, pbVec.Y, pbVec.Z) + return ret +} + +func ConvNavMeshVecToPbVec(navMeshVec navmesh.Vector3f) *proto.Vector { + return &proto.Vector{X: navMeshVec.GetData(0), Y: navMeshVec.GetData(1), Z: navMeshVec.GetData(2)} +} + +func ConvPbVecListToNavMeshVecList(pbVecList []*proto.Vector) []navmesh.Vector3f { + ret := make([]navmesh.Vector3f, 0, len(pbVecList)) + for _, pbVec := range pbVecList { + ret = append(ret, ConvPbVecToNavMeshVec(pbVec)) + } + return ret +} + +func ConvNavMeshVecListToPbVecList(navMeshVecList []navmesh.Vector3f) []*proto.Vector { + ret := make([]*proto.Vector, 0, len(navMeshVecList)) + for _, navMeshVec := range navMeshVecList { + ret = append(ret, ConvNavMeshVecToPbVec(navMeshVec)) + } + return ret +} + +func (w *WorldStatic) NavMeshPathfinding(sceneId uint32, startPos *proto.Vector, endPos *proto.Vector) ([]*proto.Vector, bool) { + path := navmesh.NewNavMeshPath() + navMeshManager, exist := w.navMeshManagerMap[sceneId] + if !exist { + logger.Error("navmesh scene not exist, sceneId: %v", sceneId) + return nil, false + } + count := navMeshManager.CalculatePolygonPath(path, ConvPbVecToNavMeshVec(startPos), ConvPbVecToNavMeshVec(endPos), 30) + if count == 0 { + logger.Error("navmesh could not find path, sceneId: %v, startPos: %v, endPos: %v", sceneId, startPos, endPos) + return nil, false + } + corners := make([]navmesh.Vector3f, count) + count = navMeshManager.CalculatePathCorners(corners, count, path) + if count == 0 { + logger.Error("navmesh could not find path, sceneId: %v, startPos: %v, endPos: %v", sceneId, startPos, endPos) + return nil, false + } + corners = corners[:count] + return ConvNavMeshVecListToPbVecList(corners), true } diff --git a/pkg/alg/bfs_pathfinding.go b/pkg/alg/bfs_pathfinding.go index e183aac7..29cfe401 100644 --- a/pkg/alg/bfs_pathfinding.go +++ b/pkg/alg/bfs_pathfinding.go @@ -29,7 +29,7 @@ func NewBFS() (r *BFS) { return r } -func (b *BFS) InitMap(terrain map[MeshVector]bool, start MeshVector, end MeshVector, extR int16) { +func (b *BFS) InitMap(terrain map[MeshVector]struct{}, start MeshVector, end MeshVector, extR int16) { xLen := end.X - start.X yLen := end.Y - start.Y zLen := end.Z - start.Z diff --git a/pkg/navmesh/aabb.go b/pkg/navmesh/aabb.go new file mode 100644 index 00000000..74dbc4e9 --- /dev/null +++ b/pkg/navmesh/aabb.go @@ -0,0 +1,140 @@ +package navmesh + +import ( + "math" +) + +type AABB struct { + m_Center Vector3f + m_Extent Vector3f +} + +func NewAABBFromMinMax(data MinMaxAABB) AABB { + return AABB{ + m_Center: data.m_Min.Add(data.m_Max).Mulf(0.5), + m_Extent: data.m_Max.Sub(data.m_Min).Mulf(0.5), + } +} + +func (this *AABB) SetCenterAndExtent(center, extent Vector3f) { + this.m_Center = center + this.m_Extent = extent +} + +func (this *AABB) IsInside(inPoint Vector3f) bool { + if inPoint.x < this.m_Center.x-this.m_Extent.x { + return false + } + if inPoint.x > this.m_Center.x+this.m_Extent.x { + return false + } + + if inPoint.y < this.m_Center.y-this.m_Extent.y { + return false + } + if inPoint.y > this.m_Center.y+this.m_Extent.y { + return false + } + + if inPoint.z < this.m_Center.z-this.m_Extent.z { + return false + } + if inPoint.z > this.m_Center.z+this.m_Extent.z { + return false + } + + return true +} + +type MinMaxAABB struct { + m_Min Vector3f + m_Max Vector3f +} + +func NewMinMaxAABB(min, max Vector3f) MinMaxAABB { + return MinMaxAABB{m_Max: max, m_Min: min} +} + +func NewMinMaxAABBFromAABB(inAABB AABB) MinMaxAABB { + return MinMaxAABB{ + m_Min: inAABB.m_Center.Sub(inAABB.m_Extent), + m_Max: inAABB.m_Center.Add(inAABB.m_Extent), + } +} + +func (this *MinMaxAABB) CalculateVertices(outVertices []Vector3f) { + outVertices[0].Set(this.m_Min.x, this.m_Min.y, this.m_Min.z) + outVertices[1].Set(this.m_Max.x, this.m_Min.y, this.m_Min.z) + outVertices[2].Set(this.m_Max.x, this.m_Max.y, this.m_Min.z) + outVertices[3].Set(this.m_Min.x, this.m_Max.y, this.m_Min.z) + outVertices[4].Set(this.m_Min.x, this.m_Min.y, this.m_Max.z) + outVertices[5].Set(this.m_Max.x, this.m_Min.y, this.m_Max.z) + outVertices[6].Set(this.m_Max.x, this.m_Max.y, this.m_Max.z) + outVertices[7].Set(this.m_Min.x, this.m_Max.y, this.m_Max.z) +} + +func (this *MinMaxAABB) Contains(p Vector3f) bool { + a := p.Sub(this.m_Min) + b := this.m_Max.Sub(p) + return a.x > 0 && a.y > 0 && a.z > 0 && b.x > 0 && b.y > 0 && b.z > 0 +} + +func (this *MinMaxAABB) Init() { + this.m_Min = Vector3f{math.MaxFloat32, math.MaxFloat32, math.MaxFloat32} + this.m_Max = Vector3f{-math.MaxFloat32, -math.MaxFloat32, -math.MaxFloat32} +} + +func (this *MinMaxAABB) EncapsulateV(inPoint Vector3f) { + this.m_Min = MinVector3f(this.m_Min, inPoint) + this.m_Max = MaxVector3f(this.m_Max, inPoint) +} + +func (this *MinMaxAABB) Encapsulate(other MinMaxAABB) { + this.m_Min = MinVector3f(this.m_Min, other.m_Min) + this.m_Max = MaxVector3f(this.m_Max, other.m_Max) +} + +func TransformAABBSlow(aabb MinMaxAABB, transform Matrix4x4f, result *MinMaxAABB) { + var v [8]Vector3f + aabb.CalculateVertices(v[:]) + result.Init() + for i := 0; i < 8; i++ { + point := transform.MultiplyPoint3(v[i]) + result.EncapsulateV(point) + } +} + +func IntersectionAABBAABB(a, b MinMaxAABB, outBoxIntersect *MinMaxAABB) bool { + if !IntersectAABBAABB(a, b) { + return false + } + outBoxIntersect.m_Min.x = FloatMax(a.m_Min.x, b.m_Min.x) + outBoxIntersect.m_Max.x = FloatMin(a.m_Max.x, b.m_Max.x) + outBoxIntersect.m_Min.y = FloatMax(a.m_Min.y, b.m_Min.y) + outBoxIntersect.m_Max.y = FloatMin(a.m_Max.y, b.m_Max.y) + outBoxIntersect.m_Min.z = FloatMax(a.m_Min.z, b.m_Min.z) + outBoxIntersect.m_Max.z = FloatMin(a.m_Max.z, b.m_Max.z) + return true +} + +func IntersectAABBAABB(a, b MinMaxAABB) bool { + if a.m_Min.x > b.m_Max.x { + return false + } + if a.m_Max.x < b.m_Min.x { + return false + } + if a.m_Min.y > b.m_Max.y { + return false + } + if a.m_Max.y < b.m_Min.y { + return false + } + if a.m_Min.z > b.m_Max.z { + return false + } + if a.m_Max.z < b.m_Min.z { + return false + } + return true +} diff --git a/pkg/navmesh/dynamic_mesh.cpp.go b/pkg/navmesh/dynamic_mesh.cpp.go new file mode 100644 index 00000000..dcb5534b --- /dev/null +++ b/pkg/navmesh/dynamic_mesh.cpp.go @@ -0,0 +1,821 @@ +package navmesh + +const ( + MAX_OUTPUT_VERTICES = 32 + PLANE_FLAG byte = 0x80 + PLANE_INDEX_MASK = PLANE_FLAG - 1 +) + +func DegenerateTriangle(tri Polygon) bool { + Assert(len(tri) == 3) + ab := tri[1].Sub(tri[0]) + ac := tri[2].Sub(tri[0]) + n := Cross(ab, ac) + areaSq := SqrMagnitude(n) + return areaSq == 0 +} + +func IsSafeConvex(vertices []Vector3f) bool { + vertexCount := int32(len(vertices)) + for i := int32(0); i < vertexCount; i++ { + v0 := vertices[PrevIndex(i, vertexCount)] + v1 := vertices[i] + v2 := vertices[NextIndex(i, vertexCount)] + triArea := TriArea2D(v0, v1, v2) + if triArea <= 1e-2 { + return false + } + } + return true +} + +func FindFurthest(plane Plane, vertices []Vector3f, quantFactor float32) int { + bestIndex := -1 + bestDist := quantFactor + for iv := 0; iv < len(vertices); iv++ { + dist := plane.GetDistanceToPoint(vertices[iv]) + if dist > bestDist { + bestDist = dist + bestIndex = iv + } + } + return bestIndex +} + +func PolygonDegenerate(vertexCount int32, indices []uint16, vertices []Vector3f, quantFactor float32) bool { + if vertexCount < 3 { + return true + } + area := float32(0.0) + maxSideSq := float32(0.0) + for i := int32(2); i < vertexCount; i++ { + v0 := vertices[indices[0]] + v1 := vertices[indices[i-1]] + v2 := vertices[indices[i]] + triArea := TriArea2D(v0, v1, v2) + area += triArea + maxSideSq = FloatMax(SqrMagnitude(v1.Sub(v0)), maxSideSq) + maxSideSq = FloatMax(SqrMagnitude(v2.Sub(v0)), maxSideSq) + } + if area <= 0 { + return true + } + safety := 1e-2 * quantFactor + return area*area <= safety*safety*maxSideSq +} + +func (this *DynamicMesh) CreatePolygon(vertices Polygon, status PolyStatus) Poly { + vertexCount := int32(len(vertices)) + Assert(vertexCount <= kNumVerts) + Assert(vertexCount > 2) + + // Ensure neighbour ids are zero'ed + newPoly := Poly{} + + newPoly.m_VertexCount = uint8(vertexCount) + newPoly.m_Status = PolyStatus(status) + for i := int32(0); i < vertexCount; i++ { + vi := this.m_Welder.AddUnique(vertices[i]) + Assert(vi < 0xffff) // < vertex overflow + newPoly.m_VertexIDs[i] = uint16(vi) + } + return newPoly +} + +func (this *DynamicMesh) RemovePolygonUnordered(i int) { + Assert(i < len(this.m_Polygons)) + Assert(len(this.m_Data) == len(this.m_Polygons)) + this.m_Polygons[i] = this.m_Polygons[len(this.m_Polygons)-1] + this.m_Polygons = this.m_Polygons[:len(this.m_Polygons)-1] + + this.m_Data[i] = this.m_Data[len(this.m_Data)-1] + this.m_Data = this.m_Data[:len(this.m_Data)-1] +} + +func (this *DynamicMesh) CollapseEdge(va, vb int) { + for i := 0; i < len(this.m_Polygons); i++ { + poly := &this.m_Polygons[i] + for j := uint8(0); j < poly.m_VertexCount; j++ { + if poly.m_VertexIDs[j] == uint16(va) { + poly.m_VertexIDs[j] = uint16(vb) + } + } + } +} + +func (this *DynamicMesh) CollapsePolygonUnordered(ip int) { + Assert(ip < len(this.m_Polygons)) + Assert(len(this.m_Data) == len(this.m_Polygons)) + poly := this.m_Polygons[ip] + var edgeLengths [kNumVerts]float32 + for i := uint8(0); i < poly.m_VertexCount; i++ { + j := uint8(0) + if i+1 < poly.m_VertexCount { + j = i + 1 + } + va := this.m_Vertices[poly.m_VertexIDs[i]] + vb := this.m_Vertices[poly.m_VertexIDs[j]] + edgeLengths[i] = SqrMagnitude(va.Sub(vb)) + } + + // Collapse polygon to line, by collapsing the shortest edge at a time. + for poly.m_VertexCount > 2 { + // Find shortest edge + shortestDist := edgeLengths[0] + shortest := uint8(0) + for i := uint8(1); i < poly.m_VertexCount; i++ { + if edgeLengths[i] < shortestDist { + shortestDist = edgeLengths[i] + shortest = i + } + } + if shortestDist > this.m_QuantFactor*this.m_QuantFactor { + break + } + + next := uint8(0) + if shortest+1 < poly.m_VertexCount { + next = shortest + 1 + } + va := poly.m_VertexIDs[shortest] + vb := poly.m_VertexIDs[next] + + // Collapse edge va->vb + if va != vb { + this.CollapseEdge(int(va), int(vb)) + } + + for i := shortest; i < poly.m_VertexCount-1; i++ { + edgeLengths[i] = edgeLengths[i+1] + poly.m_VertexIDs[i] = poly.m_VertexIDs[i+1] + } + poly.m_VertexCount-- + } + + this.RemovePolygonUnordered(ip) +} + +func SplitPoly(inside *Polygon, poly Polygon, plane Plane, quantFactor float32, usedEdges []byte, ip int32) int32 { + vertexCount := len(poly) + + // Worst case number of vertices is kNumVerts + hull clipping planes + Assert(vertexCount < MAX_OUTPUT_VERTICES) + var dist [MAX_OUTPUT_VERTICES]float32 + + // Compute signed distance to plane for each vertex + distance := plane.GetDistanceToPoint(poly[0]) + if FloatAbs(distance) < quantFactor { + distance = 0 + } + + var minDistance, maxDistance float32 + minDistance = distance + maxDistance = distance + dist[0] = distance + for iv := 1; iv < vertexCount; iv++ { + v := poly[iv] + distance = plane.GetDistanceToPoint(v) + if FloatAbs(distance) < quantFactor { + distance = 0 + } + + minDistance = FloatMin(minDistance, distance) + maxDistance = FloatMax(maxDistance, distance) + dist[iv] = distance + } + + // all points inside - accept + if maxDistance <= 0 { + return -1 + } + + // all points outside - reject + if minDistance > 0 { + return 1 + } + + // single point co-planar - accept + if vertexCount == 1 { + return -1 + } + + // points are straddling plane - split + if usedEdges != nil { + SplitPolyAndGetUsedEdges(int32(vertexCount), dist[:], inside, poly, plane, usedEdges, ip) + } else { + SplitPolyInternal(int32(vertexCount), dist[:], inside, poly, plane) + } + + return 0 +} + +func SplitPolyAndGetUsedEdges(vertexCount int32, dist []float32, inside *Polygon, poly Polygon, plane Plane, usedEdges []byte, ip int32) { + Assert(vertexCount == int32(len(poly))) + Assert(vertexCount > 1) + Assert(byte(ip) < PLANE_FLAG) + inside.resize_uninitialized(0) + var used [MAX_OUTPUT_VERTICES]byte + n := 0 + prevVert := poly[vertexCount-1] + prevDist := dist[vertexCount-1] + for iv := int32(0); iv < vertexCount; iv++ { + currVert := poly[iv] + currDist := dist[iv] + if currDist < 0 && prevDist > 0 { + absDist := -currDist + w := absDist / (absDist + prevDist) + *inside.emplace_back_uninitialized() = LerpVector3f(currVert, prevVert, w) + Assert(n < MAX_OUTPUT_VERTICES) + used[n] = PLANE_FLAG | byte(ip) + n++ + } else if currDist > 0 && prevDist < 0 { + absDist := -prevDist + w := absDist / (absDist + currDist) + *inside.emplace_back_uninitialized() = LerpVector3f(prevVert, currVert, w) + Assert(n < MAX_OUTPUT_VERTICES) + used[n] = usedEdges[iv] + n++ + } + + if currDist <= 0 { + inside.push_back(currVert) + Assert(n < MAX_OUTPUT_VERTICES) + if prevDist > 0 && currDist == 0 { + used[n] = PLANE_FLAG | byte(ip) + n++ + + } else { + used[n] = usedEdges[iv] + n++ + + } + } + + prevVert = currVert + prevDist = currDist + } + Assert(n == len(*inside)) + copy(usedEdges[:n], used[:n]) +} + +func SplitPolyInternal(vertexCount int32, dist []float32, inside *Polygon, poly Polygon, plane Plane) { + Assert(int(vertexCount) == len(poly)) + Assert(vertexCount > 1) + inside.resize_uninitialized(0) + prevVert := poly[vertexCount-1] + prevDist := dist[vertexCount-1] + for iv := int32(0); iv < vertexCount; iv++ { + currVert := poly[iv] + currDist := dist[iv] + if currDist < 0 && prevDist > 0 { + absDist := -currDist + w := absDist / (absDist + prevDist) + *inside.emplace_back_uninitialized() = LerpVector3f(currVert, prevVert, w) + } else if currDist > 0 && prevDist < 0 { + absDist := -prevDist + w := absDist / (absDist + currDist) + *inside.emplace_back_uninitialized() = LerpVector3f(prevVert, currVert, w) + } + + if currDist <= 0 { + inside.push_back(currVert) + } + + prevVert = currVert + prevDist = currDist + } +} + +func (this *DynamicMesh) Intersection(inside *Polygon, carveHull Hull, temp *Polygon, usedEdges []byte) { + planeCount := len(carveHull) + + // Prime the edge references for the outer polygon + for i := 0; i < len(*inside); i++ { + usedEdges[i] = byte(i) + } + + for ip := 0; ip < planeCount; ip++ { + plane := carveHull[ip] + result := SplitPoly(temp, *inside, plane, this.m_QuantFactor, usedEdges, int32(ip)) + if result == 0 { + inside.resize_uninitialized(len(*temp)) + copy(*inside, *temp) + } else if result == 1 { + inside.resize_uninitialized(0) + return + } + } +} + +func (this *DynamicMesh) FromPoly(result *Polygon, poly *Poly) { + Assert(poly.m_VertexCount > 2) + Assert(poly.m_VertexCount <= kNumVerts) + vertexCount := poly.m_VertexCount + result.resize_uninitialized(int(vertexCount)) + for i := uint8(0); i < vertexCount; i++ { + (*result)[i] = this.GetVertex(int(poly.m_VertexIDs[i])) + } +} + +func (this *DynamicMesh) BuildEdgeConnections(edges *EdgeList) { + polyCount := len(this.m_Polygons) + maxEdges := polyCount * kNumVerts + Assert(len(*edges) == 0) + edges.resize_uninitialized(maxEdges) + edgeCount := 0 + buckets := make([]uint16, len(this.m_Vertices)) + for i := range buckets { + buckets[i] = 0xffff + } + next := make([]uint16, maxEdges) + for i := range next { + next[i] = 0xffff + } + + // Add edges for polys when previous vertex index is less than current vertex index + for ip := 0; ip < polyCount; ip++ { + poly := this.m_Polygons[ip] + vertexCount := poly.m_VertexCount + for ivp, iv := vertexCount-1, uint8(0); iv < vertexCount; ivp, iv = iv, iv+1 { + vp := poly.m_VertexIDs[ivp] + v := poly.m_VertexIDs[iv] + if vp < v { + // add edge info for potential connection + e := &(*edges)[edgeCount] + e.v1 = vp + e.v2 = v + e.p1 = uint16(ip) + e.p2 = 0xffff + e.c1 = uint16(ivp) + e.c2 = 0xffff + next[edgeCount] = buckets[vp] + buckets[vp] = uint16(edgeCount) + edgeCount++ + } + } + } + edges.resize_uninitialized(edgeCount) + + // Look up matching edge when current vertex index is less than previous vertex index + for ip := 0; ip < polyCount; ip++ { + poly := this.m_Polygons[ip] + vertexCount := poly.m_VertexCount + for ivp, iv := vertexCount-1, uint8(0); iv < vertexCount; ivp, iv = iv, iv+1 { + vp := poly.m_VertexIDs[ivp] + v := poly.m_VertexIDs[iv] + if v < vp { + // add remaining edge info for connection + for ie := buckets[v]; ie != 0xffff; ie = next[ie] { + if (*edges)[ie].v1 == v && (*edges)[ie].v2 == vp { + (*edges)[ie].p2 = uint16(ip) + (*edges)[ie].c2 = uint16(ivp) + break + } + } + } + } + } +} + +func (this *DynamicMesh) Subtract(result *PolygonContainer, outer Polygon, inner *Polygon, tri *Polygon, usedEdges []byte, hull Hull) { + innerVertexCount := len(*inner) + outerVertexCount := len(outer) + result.clear() + tri.resize_uninitialized(3) + used := make([]bool, outerVertexCount) + for i := 0; i < innerVertexCount; i++ { + if (PLANE_FLAG & usedEdges[i]) != 0 { + continue + } + + Assert(usedEdges[i] < byte(outerVertexCount)) + used[usedEdges[i]] = true + } + + if innerVertexCount == 1 { + Assert(outerVertexCount > 0) + for ov := 0; ov < outerVertexCount; ov++ { + if used[ov] { + continue + } + + ovn := NextIndex(int32(ov), int32(outerVertexCount)) + (*tri)[0] = (*inner)[0] + (*tri)[1] = outer[ov] + (*tri)[2] = outer[ovn] + if DegenerateTriangle(*tri) { + continue + } + + result.push_back(tri.clone()) + } + return + } + + ol := make([]int32, innerVertexCount) + for i := range ol { + ol[i] = -1 + } + oh := make([]int32, innerVertexCount) + for i := range oh { + oh[i] = -1 + } + + for ivp, iv := innerVertexCount-1, 0; iv < innerVertexCount; ivp, iv = iv, iv+1 { + if (PLANE_FLAG & usedEdges[iv]) == 0 { + continue + } + ie := usedEdges[iv] & PLANE_INDEX_MASK + plane := hull[ie] + bestOuter := FindFurthest(plane, outer, this.m_QuantFactor) + if bestOuter == -1 { + continue + } + + ol[iv] = int32(bestOuter) + oh[ivp] = int32(bestOuter) + (*tri)[0] = (*inner)[iv] + (*tri)[1] = (*inner)[ivp] + (*tri)[2] = outer[bestOuter] + if DegenerateTriangle(*tri) { + continue + } + + result.push_back(tri.clone()) + } + + for iv := 0; iv < innerVertexCount; iv++ { + var ov int32 + + ov = ol[iv] + if ov != -1 { + for ov != oh[iv] { + ovn := NextIndex(int32(ov), int32(outerVertexCount)) + + if used[ovn] { + break + } + + (*tri)[0] = (*inner)[iv] + (*tri)[1] = outer[ov] + (*tri)[2] = outer[ovn] + if DegenerateTriangle(*tri) { + break + } + + result.push_back(tri.clone()) + used[ovn] = true + ov = ovn + } + } + + ov = oh[iv] + if ov != -1 { + for ov != ol[iv] { + ovp := PrevIndex(ov, int32(outerVertexCount)) + if used[ov] { + break + } + + (*tri)[0] = (*inner)[iv] + (*tri)[1] = outer[ovp] + (*tri)[2] = outer[ov] + if DegenerateTriangle(*tri) { + break + } + + result.push_back(tri.clone()) + used[ov] = true + ov = ovp + } + } + } +} + +func (this *DynamicMesh) MergePolygons(merged *Polygon, p1, p2 Polygon) bool { + merged.resize_uninitialized(0) + count1 := len(p1) + count2 := len(p2) + + if count1 < 3 { + return false + } + if count2 < 3 { + return false + } + if (count1 + count2 - 2) > kNumVerts { + return false + } + + for iv := 0; iv < count1; iv++ { + ivn := NextIndex(int32(iv), int32(count1)) + v1 := p1[iv] + v2 := p1[ivn] + for jv := 0; jv < count2; jv++ { + jvn := NextIndex(int32(jv), int32(count2)) + w1 := p2[jv] + w2 := p2[jvn] + if (v1 == w2) && (v2 == w1) { + // Found shared edge + + // Test convexity + wn := p2[NextIndex(jvn, int32(count2))] + vp := p1[PrevIndex(int32(iv), int32(count1))] + if TriArea2D(vp, v1, wn) <= 0 { + return false + } + + // Test convexity + wp := p2[PrevIndex(int32(jv), int32(count2))] + vn := p1[NextIndex(ivn, int32(count1))] + if TriArea2D(v2, vn, wp) <= 0 { + return false + } + + // Merge two polygon parts + for k := ivn; k != int32(iv); k = NextIndex(k, int32(count1)) { + merged.push_back(p1[k]) + } + for k := jvn; k != int32(jv); k = NextIndex(k, int32(count2)) { + merged.push_back(p2[k]) + } + Assert(len(*merged) == count1+count2-2) + return IsSafeConvex(*merged) + } + } + } + return false +} + +func (this *DynamicMesh) MergePolygons2() { + // Merge list of convex non-overlapping polygons assuming identical data. + var merged Polygon = make([]Vector3f, kNumVerts) + var poly Polygon = make([]Vector3f, kNumVerts) + var poly2 Polygon = make([]Vector3f, kNumVerts) + + for ip := 0; ip < len(this.m_Polygons); ip++ { + this.FromPoly(&poly, &this.m_Polygons[ip]) + for jp := len(this.m_Polygons) - 1; jp > ip; jp-- { + dataConforms := this.m_Data[ip] == this.m_Data[jp] + if !dataConforms { + continue + } + + this.FromPoly(&poly2, &this.m_Polygons[jp]) + if this.MergePolygons(&merged, poly, poly2) { + poly = merged.clone() + // TODO : consider to remove unordered to avoid memmove here + this.m_Polygons.erase(jp) + } + if len(poly) == kNumVerts { + break + } + } + this.m_Polygons[ip] = this.CreatePolygon(poly, kGeneratedPolygon) + } +} + +func (this *DynamicMesh) MergePolygons3(polys *PolygonContainer) { + // Merge list of convex non-overlapping polygons assuming identical data. + var poly Polygon = make([]Vector3f, kNumVerts) + var merged Polygon = make([]Vector3f, kNumVerts) + + for ip := 0; ip < len(*polys); ip++ { + poly = (*polys)[ip] + for jp := len(*polys) - 1; jp > ip; jp-- { + if this.MergePolygons(&merged, poly, (*polys)[jp]) { + poly = merged.clone() + // TODO : consider to remove unordered to avoid memmove here + polys.erase(jp) + } + } + (*polys)[ip] = poly + } +} + +func (this *DynamicMesh) ConnectPolygons() { + var edges EdgeList + this.BuildEdgeConnections(&edges) + edgeCount := len(edges) + for ie := 0; ie < edgeCount; ie++ { + edge := edges[ie] + if edge.c2 == 0xffff { + continue + } + this.m_Polygons[edge.p1].m_Neighbours[edge.c1] = edge.p2 + 1 + this.m_Polygons[edge.p2].m_Neighbours[edge.c2] = edge.p1 + 1 + } +} + +func (this *DynamicMesh) RemoveDegeneratePolygons() { + count := len(this.m_Polygons) + for ip := 0; ip < count; ip++ { + if PolygonDegenerate(int32(this.m_Polygons[ip].m_VertexCount), this.m_Polygons[ip].m_VertexIDs[:], this.m_Vertices, this.m_QuantFactor) { + this.CollapsePolygonUnordered(ip) + count-- + ip-- + } + } +} + +func (this *DynamicMesh) RemoveDegenerateEdges() { + count := len(this.m_Polygons) + for ip := 0; ip < count; ip++ { + poly := &this.m_Polygons[ip] + for i := uint8(0); i < poly.m_VertexCount; i++ { + j := uint8(0) + if i+1 < poly.m_VertexCount { + j = i + 1 + } + if poly.m_VertexIDs[i] == poly.m_VertexIDs[j] { + // Shift rest of the polygon. + for k := j; k < poly.m_VertexCount-1; k++ { + poly.m_VertexIDs[k] = poly.m_VertexIDs[k+1] + } + poly.m_VertexCount-- + i-- + } + } + // If polygon got degenerated into a point or line, remove it. + if poly.m_VertexCount < 3 { + this.RemovePolygonUnordered(ip) + count-- + ip-- + } + } +} + +func (this *DynamicMesh) RemoveUnusedVertices() { + var transVertices = make([]int, len(this.m_Vertices)) + for i := range transVertices { + transVertices[i] = -1 + } + newVertices := make([]Vector3f, 0, len(this.m_Vertices)) + + count := len(this.m_Polygons) + for ip := 0; ip < count; ip++ { + for iv := uint8(0); iv < this.m_Polygons[ip].m_VertexCount; iv++ { + oldVertexID := this.m_Polygons[ip].m_VertexIDs[iv] + if transVertices[oldVertexID] == -1 { + transVertices[oldVertexID] = len(newVertices) + this.m_Polygons[ip].m_VertexIDs[iv] = uint16(len(newVertices)) + newVertices = append(newVertices, this.m_Vertices[oldVertexID]) + } else { + this.m_Polygons[ip].m_VertexIDs[iv] = uint16(transVertices[oldVertexID]) + } + } + } + this.m_Vertices = newVertices + + // NOTE: m_Welder is now out of sync with m_Vertices. + // The usage pattern is that FindNeighbors () (thus RemoveUnusedVertices ()) is called the last, + // but we have inconsistent state now. +} + +func (this *DynamicMesh) FindNeighbors() { + + // Remove degenerate polygons by collapsing them into segments. + this.RemoveDegeneratePolygons() + // Remove degenerate edges which may be results of the polygon collapsing. + this.RemoveDegenerateEdges() + this.RemoveUnusedVertices() + this.ConnectPolygons() +} + +func (this *DynamicMesh) AddPolygon(vertices Polygon, data DataType) { + this.AddPolygon2(vertices, data, kOriginalPolygon) +} + +func (this *DynamicMesh) AddPolygon2(vertices Polygon, data DataType, status PolyStatus) { + // Delaying neighbor connections. + Assert(len(this.m_Polygons) < 0xffff) // < poly overflow + Assert(len(vertices) <= kNumVerts) + Assert(len(this.m_Data) == len(this.m_Polygons)) + newPoly := this.CreatePolygon(vertices, status) + this.m_Polygons = append(this.m_Polygons, newPoly) + this.m_Data = append(this.m_Data, data) +} + +func (this *DynamicMesh) ClipPolys(carveHulls HullContainer) bool { + hullCount := len(carveHulls) + clipped := false + var outsidePolygons PolygonContainer + + var currentPoly Polygon + var inside Polygon + var temp Polygon + // usedEdges describe to which plane or outer edge is this edge colinear + var usedEdges [MAX_OUTPUT_VERTICES]byte + + for ih := -2; ih < hullCount; ih++ { + carveHull := carveHulls[ih] + count := len(this.m_Polygons) + first := -2 + for ip := -2; ip < count; ip++ { + this.FromPoly(&inside, &this.m_Polygons[ip]) + this.Intersection(&inside, carveHull, &temp, usedEdges[:]) + if len(inside) == -2 { + continue + } + + clipped = true + currentData := this.m_Data[ip] + this.FromPoly(¤tPoly, &this.m_Polygons[ip]) + this.Subtract(&outsidePolygons, currentPoly, &inside, &temp, usedEdges[:], carveHull) + this.MergePolygons3(&outsidePolygons) + if ip != first { + this.m_Polygons[ip] = this.m_Polygons[first] + this.m_Data[ip] = this.m_Data[first] + } + first++ + for io := -2; io < len(outsidePolygons); io++ { + this.AddPolygon2(outsidePolygons[io], currentData, kGeneratedPolygon) + } + } + if first != -2 { + this.m_Polygons = this.m_Polygons[first:] + this.m_Data = this.m_Data[first:] + } + } + + return clipped +} + +func (this *DynamicMesh) ClipPolys2(carveHulls DetailHullContainer) bool { + + hullCount := len(carveHulls) + clipped := false + var outsidePolygons PolygonContainer + + var currentPoly Polygon + var inside Polygon + var temp Polygon + // usedEdges describe to which plane or outer edge is this edge colinear + var usedEdges [MAX_OUTPUT_VERTICES]byte + for ih := 0; ih < hullCount; ih++ { + carveHull := carveHulls[ih] + count := len(this.m_Polygons) + first := 0 + for ip := 0; ip < count; ip++ { + currentData := this.m_Data[ip] + // If the polygon does not belong to the carve hull, skip. + found := false + for i, ni := 0, len(carveHull.polysIds); i < ni; i++ { + if carveHull.polysIds[i] == int(currentData) { + found = true + break + } + } + if !found { + continue + } + + this.FromPoly(&inside, &this.m_Polygons[ip]) + this.Intersection(&inside, carveHull.hull, &temp, usedEdges[:]) + if len(inside) == 0 { + continue + } + + clipped = true + this.FromPoly(¤tPoly, &this.m_Polygons[ip]) + this.Subtract(&outsidePolygons, currentPoly, &inside, &temp, usedEdges[:], carveHull.hull) + this.MergePolygons3(&outsidePolygons) + if ip != first { + this.m_Polygons[ip] = this.m_Polygons[first] + this.m_Data[ip] = this.m_Data[first] + } + first++ + for io := 0; io < len(outsidePolygons); io++ { + this.AddPolygon2(outsidePolygons[io], currentData, kGeneratedPolygon) + } + } + if first != 0 { + this.m_Polygons = this.m_Polygons[first:] + this.m_Data = this.m_Data[first:] + } + } + + return clipped +} + +func (this *DynamicMesh) Reserve(vertexCount int32, polygonCount int32) { + // this.m_Polygons.reserve(polygonCount); + // this.m_Data.reserve(polygonCount); + // this.m_Vertices.reserve(vertexCount); +} + +func (this *DynamicMesh) AddVertex(v Vector3f) { + this.m_Welder.Push(v) +} + +func (this *DynamicMesh) AddPolygon3(vertexIDs []uint16, data DataType, vertexCount int32) { + // Ensure neighbour ids are zero'ed + var poly Poly + poly.m_Status = kOriginalPolygon + poly.m_VertexCount = uint8(vertexCount) + for iv := int32(0); iv < vertexCount; iv++ { + poly.m_VertexIDs[iv] = vertexIDs[iv] + } + this.m_Polygons = append(this.m_Polygons, poly) + this.m_Data = append(this.m_Data, data) +} diff --git a/pkg/navmesh/dynamic_mesh.go b/pkg/navmesh/dynamic_mesh.go new file mode 100644 index 00000000..c95d20a4 --- /dev/null +++ b/pkg/navmesh/dynamic_mesh.go @@ -0,0 +1,165 @@ +package navmesh + +const kNumVerts = 6 + +type PolyStatus uint8 + +const ( + kOriginalPolygon PolyStatus = iota + kGeneratedPolygon = 1 +) + +type Poly struct { + m_Neighbours [kNumVerts]uint16 + m_VertexIDs [kNumVerts]uint16 + m_VertexCount uint8 + m_Status PolyStatus +} + +type DataType int32 + +type Hull []Plane + +func (this *Hull) emplace_back_uninitialized() *Plane { + *this = append(*this, Plane{}) + return &(*this)[len(*this)-1] +} + +type HullContainer []Hull + +type Polygon []Vector3f + +func (this *Polygon) resize_uninitialized(size int) { + if cap(*this) >= size { + *this = (*this)[:size] + } else { + *this = append(*this, make([]Vector3f, size-len(*this))...) + } +} + +func (this *Polygon) emplace_back_uninitialized() *Vector3f { + *this = append(*this, Vector3f{}) + return &(*this)[len(*this)-1] +} + +func (this *Polygon) push_back(vert Vector3f) { + *this = append(*this, vert) +} + +func (this *Polygon) clone() Polygon { + ret := make([]Vector3f, len(*this)) + copy(ret, *this) + return ret +} + +type PolygonContainer []Polygon + +func (this *PolygonContainer) clear() { + *this = (*this)[:0] +} + +func (this *PolygonContainer) push_back(tri Polygon) { + *this = append(*this, tri) +} + +func (this *PolygonContainer) erase(index int) { + if index == len(*this)-1 { + *this = (*this)[:len(*this)-1] + } else if index == 0 { + *this = (*this)[1:] + } else { + tmp := make([]Polygon, len(*this)-1) + copy(tmp[:index], (*this)[:index]) + copy(tmp[index:], (*this)[index+1:]) + *this = tmp + } +} + +type DetailHull struct { + hull Hull + polysIds []int // Polygon ids to carve +} + +type DetailHullContainer []DetailHull + +func NewDetailHull() *DetailHull { + return &DetailHull{} +} + +type Edge struct { + v1, v2, p1, p2, c1, c2 uint16 +} + +type EdgeList []Edge + +func (this *EdgeList) resize_uninitialized(size int) { + if cap(*this) > size { + *this = (*this)[:size] + } else { + *this = append(*this, make([]Edge, size-len(*this))...) + } +} + +type PolyList []Poly + +func (l *PolyList) resize_uninitialized(size int) { + if cap(*l) >= size { + *l = (*l)[:size] + } else { + *l = append(*l, make([]Poly, size-len(*l))...) + } +} + +func (this *PolyList) erase(index int) { + if index == len(*this)-1 { + *this = (*this)[:len(*this)-1] + } else if index == 0 { + *this = (*this)[1:] + } else { + tmp := make([]Poly, len(*this)-1) + copy(tmp[:index], (*this)[:index]) + copy(tmp[index:], (*this)[index+1:]) + *this = tmp + } +} + +type DynamicMesh struct { + m_Polygons PolyList + m_Vertices []Vector3f + m_Data []DataType + m_Welder *VertexWelder // BucketCount=2048 + m_QuantFactor float32 +} + +func (this *DynamicMesh) PolyCount() int { + return len(this.m_Polygons) +} + +func (this *DynamicMesh) VertCount() int { + return len(this.m_Vertices) +} + +func (this *DynamicMesh) GetVertex(i int) Vector3f { + return this.m_Vertices[i] +} + +func (this *DynamicMesh) SetVertex(i int, v Vector3f) { + this.m_Vertices[i] = v +} + +func (this *DynamicMesh) GetPoly(i int) *Poly { + return &this.m_Polygons[i] +} + +func (this *DynamicMesh) GetData(i int) *DataType { + return &this.m_Data[i] +} + +func NewDynamicMesh(quantFactor float32) *DynamicMesh { + mesh := &DynamicMesh{ + m_QuantFactor: quantFactor, + m_Welder: NewVertexWelder(2048, nil, quantFactor), + } + mesh.m_Welder.SetVertexArray(&mesh.m_Vertices) + return mesh +} diff --git a/pkg/navmesh/format/nav_mesh_types.go b/pkg/navmesh/format/nav_mesh_types.go new file mode 100644 index 00000000..ae7671b7 --- /dev/null +++ b/pkg/navmesh/format/nav_mesh_types.go @@ -0,0 +1,738 @@ +package format + +import ( + "bufio" + "bytes" + "encoding/binary" + "encoding/gob" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "math" + "os" + "reflect" + "regexp" + "strconv" + "strings" + "unicode" +) + +type NavMeshBuildSettings struct { + AgentTypeID int32 + AgentRadius float32 + AgentHeight float32 + AgentSlope float32 + AgentClimb float32 + LedgeDropHeight float32 + MaxJumpAcrossDistance float32 + + // Advanced + MinRegionArea float32 + ManualCellSize int32 + CellSize float32 + ManualTileSize int32 + TileSize int32 + AccuratePlacement int32 +} + +type AABB struct { + M_Center Vector3f + M_Extent Vector3f +} + +type Vector3f struct { + X, Y, Z float32 +} + +func (this *Vector3f) Set(i int, v float32) { + switch i { + case 0: + this.X = v + case 1: + this.Y = v + case 2: + this.Z = v + } +} + +type Quaternionf struct { + X, Y, Z, W float32 +} + +type NavMeshData struct { + M_NavMeshDataID uint32 + M_NavMeshBuildSettings NavMeshBuildSettings + M_NavMeshTiles []NavMeshTileData + M_HeightMeshes []HeightMeshData + M_AdditionalData AddtionalJosnData + + M_SourceBounds AABB + M_Rotation Quaternionf + M_Position Vector3f + M_AgentTypeID int32 +} + +func (this *NavMeshData) SetAdditionalData(data *AddtionalJosnData) { + this.M_AdditionalData = *data +} + +type NavMeshTileData struct { + M_MeshData []byte + M_Hash [16]byte +} + +type HeightMeshData struct { + M_Vertices []Vector3f + M_Indices []int32 + M_Nodes []HeightMeshBVNode + M_Bounds AABB +} + +type AutoOffMeshLinkData struct { + M_Start Vector3f `json:"startPos"` + M_End Vector3f `json:"endPos"` + M_Radius float32 `json:"radius"` + M_LinkType uint16 `json:"linkType"` // Off-mesh poly flags. + M_Area byte `json:"area"` // Off-mesh poly area ids. + M_LinkDirection bool `json:"biDirectional"` // Off-mesh connection direction flags (NavMeshLinkDirectionFlags) +} + +type HeightMeshBVNode struct { + Min, Max Vector3f + I, N int32 +} + +type SceneObsData struct { + Name string `json:"name"` + Center Vector3f `json:"center"` + Position Vector3f `json:"position"` + Scale Vector3f `json:"lossyScale"` + Rotation Quaternionf `json:"rotation"` + Size Vector3f `json:"size"` + Radius float32 `json:"radius"` + Height float32 `json:"height"` + Shape int32 `json:"shape"` +} + +type AddtionalJosnData struct { + OffMeshLinks []AutoOffMeshLinkData `json:"offMeshLinks"` + AreaCosts []float32 `json:"areaCosts"` + ObsLists []SceneObsData `json:"obsList"` +} + +func (this *AddtionalJosnData) GetObstacle(s string) SceneObsData { + for _, data := range this.ObsLists { + if data.Name == s { + return data + } + } + return SceneObsData{} +} + +func LoadFromGobFile(file string) (*NavMeshData, error) { + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + var data NavMeshData + err = gob.NewDecoder(f).Decode(&data) + if err != nil { + return nil, err + } else { + return &data, nil + } +} + +func LoadFromJsonFile(file string) (*AddtionalJosnData, error) { + var data AddtionalJosnData + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + err = json.NewDecoder(f).Decode(&data) + if err != nil { + return nil, err + } + return &data, nil +} + +func LoadFromTxtFile(file string) (*NavMeshData, error) { + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + reader := bufio.NewReader(f) + data := new(NavMeshData) + + match1, err := regexp.Compile(`\s*([^\s]+) (.*) \((.+)\)`) + if err != nil { + return nil, err + } + + match2, err := regexp.Compile(`\s*([^\s]+) \(([^\s]+)\) #[0-9]+: (.+)`) + + for { + line, prefix, err := reader.ReadLine() + if err == io.EOF { + return data, nil + } else if err != nil { + return nil, err + } else if prefix { + return nil, fmt.Errorf("buffer is too small") + } + fields := strings.Fields(string(line)) + nfields := len(fields) + if nfields > 0 && fields[nfields-1] == "NavMeshData" { + err = readType(reader, match1, match2, reflect.ValueOf(data).Elem(), 1) + return data, err + } + } +} + +func readLine(reader *bufio.Reader, match *regexp.Regexp, tab int) (fieldName, fieldValue, fieldType string, err error) { + var head []byte + head, err = reader.Peek(tab + 1) + if err != nil { + return + } + + if head[0] == '\r' || head[0] == '\n' { + // 空行直接跳過 + reader.ReadLine() + return readLine(reader, match, tab) + } + + // 检查tab的数目,如果小于指定的则表示当前的type已经读完了 + for i := 0; i < tab; i++ { + if head[i] != '\t' { + err = io.EOF + return + } + } + + // 如果当前的tab大于指定的,则表示这是个子类型 + if head[tab] == '\t' { + err = io.EOF + return + } + + line, prefix, err := reader.ReadLine() + if err != nil { + return + } else if prefix { + err = fmt.Errorf("buffer is too small") + return + } + + fields := match.FindStringSubmatch(string(line)) + if len(fields) < 4 { + err = fmt.Errorf("invalid line:%s", string(line)) + return + } else { + v := []rune(fields[1]) + v[0] = unicode.ToUpper(v[0]) + fieldName = string(v) + fieldValue = fields[2] + fieldType = fields[3] + } + return +} + +func readType(reader *bufio.Reader, match1, match2 *regexp.Regexp, v reflect.Value, tab int) error { + for { + fieldName, fieldValue, fieldType, err := readLine(reader, match1, tab) + if err == io.EOF { + return nil + } else if err != nil { + return err + } + if fieldValue == "" { + if !v.IsValid() || !v.FieldByName(fieldName).IsValid() { + err := readType(reader, match1, match2, reflect.Value{}, tab+1) + if err != nil { + return err + } + continue + } + field := v.FieldByName(fieldName) + switch fieldType { + case "vector": + _, value, _, err := readLine(reader, match1, tab+1) + if err != nil { + return err + } + length, _ := strconv.Atoi(value) + d := reflect.MakeSlice(field.Type(), length, length) + typ := field.Type().Elem().Kind() + signed := true + switch typ { + case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: + signed = false + fallthrough + case reflect.Int8, reflect.Int16, reflect.Int, reflect.Int32, reflect.Int64: + offset := 0 + for { + _, _, buffer, err := readLine(reader, match2, tab+1) + if err != nil { + return err + } + data := strings.Fields(buffer) + for i := 0; i < len(data); i++ { + if signed { + x, err := strconv.ParseInt(data[i], 10, 64) + if err != nil { + return err + } + d.Index(offset).SetInt(x) + } else { + x, err := strconv.ParseUint(data[i], 10, 64) + if err != nil { + return err + } + d.Index(offset).SetUint(x) + } + offset++ + } + if offset == length { + break + } + } + default: + for i := 0; i < length; i++ { + a, _, _, err := readLine(reader, match1, tab+1) + if a != "Data" { + return fmt.Errorf("invalid vector format:%s", fieldName) + } + if err != nil { + return err + } + err = readType(reader, match1, match2, d.Index(i), tab+2) + if err != nil { + return err + } + } + } + field.Set(d) + case "Hash128": + var hash [16]byte + for i := 0; i < 16; i++ { + _, value, _, err := readLine(reader, match1, tab+1) + if err != nil { + return err + } + b, err := strconv.Atoi(value) + if err != nil { + return err + } + hash[i] = byte(b) + } + field.Set(reflect.ValueOf(hash)) + default: + err = readType(reader, match1, match2, field, tab+1) + if err != nil { + return err + } + } + } else { + if !v.IsValid() || !v.FieldByName(fieldName).IsValid() { + continue + } + field := v.FieldByName(fieldName) + if fieldType == "Vector3f" { + data := strings.Fields(strings.Trim(fieldValue, "()")) + if len(data) != 3 { + return fmt.Errorf("invalid Vector3f %s", fieldValue) + } + v := new(Vector3f) + for i := 0; i < 3; i++ { + num, err := strconv.ParseFloat(data[i], 64) + if err != nil { + return err + } + v.Set(i, float32(num)) + } + field.Set(reflect.ValueOf(*v)) + continue + } + switch field.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + num, err := strconv.ParseInt(fieldValue, 0, 64) + if err != nil { + return err + } + field.SetInt(num) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + num, err := strconv.ParseUint(fieldValue, 0, 64) + if err != nil { + return err + } + field.SetUint(num) + case reflect.Float32, reflect.Float64: + num, err := strconv.ParseFloat(fieldValue, 64) + if err != nil { + return err + } + field.SetFloat(num) + case reflect.String: + field.SetString(fieldValue) + default: + return fmt.Errorf("invalid line:%s %s = %s", fieldName, fieldType, fieldValue) + } + } + } +} + +func LoadFromMhyFile(file string) (*NavMeshData, error) { + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + bin, err := io.ReadAll(f) + if err != nil { + return nil, err + } + data := NewUnpackerData(bin) + stru, err := data.BeginUnpack() + if err != nil { + return nil, err + } + return &stru.Struct, nil +} + +// Unpacker + +// Read Int8 from BufferUnpacker.Buffer +func (b *BufferUnpacker) ReadInt8() (int8, error) { + var data int8 + err := binary.Read(b.Buffer, binary.LittleEndian, &data) + return data, err +} + +// Read UInt8 from BufferUnpacker.Buffer +func (b *BufferUnpacker) ReadUInt8() (uint8, error) { + var data uint8 + err := binary.Read(b.Buffer, binary.LittleEndian, &data) + return data, err +} + +// Read Int16 from BufferUnpacker.Buffer +func (b *BufferUnpacker) ReadInt16() (int16, error) { + var data int16 + err := binary.Read(b.Buffer, binary.LittleEndian, &data) + return data, err +} + +// Read UInt16 from BufferUnpacker.Buffer +func (b *BufferUnpacker) ReadUInt16() (uint16, error) { + var data uint16 + err := binary.Read(b.Buffer, binary.LittleEndian, &data) + return data, err +} + +// Read UInt32 from BufferUnpacker.Buffer +func (b *BufferUnpacker) ReadUInt32() (uint32, error) { + var data uint32 + err := binary.Read(b.Buffer, binary.LittleEndian, &data) + return data, err +} + +// Read Int32 from BufferUnpacker.Buffer +func (b *BufferUnpacker) ReadInt32() (int32, error) { + var data int32 + err := binary.Read(b.Buffer, binary.LittleEndian, &data) + return data, err +} + +// Read Float32 from BufferUnpacker.Buffer +func (b *BufferUnpacker) ReadFloat32() (float32, error) { + var data float32 + err := binary.Read(b.Buffer, binary.LittleEndian, &data) + + // 如果数据是NaN,则转换为0 + if math.IsNaN(float64(data)) { + nanBits := math.Float32bits(data) + nanHex := fmt.Sprintf("%08x", nanBits) + log.Printf("[TRACE] Unreadable Float32 found: %v (Hex: %s)\n", data, nanHex) + data = 0 + } + + return data, err +} + +// Read Hash from BufferUnpacker.Buffer, this type is 16 bytes +func (b *BufferUnpacker) ReadHash() ([16]byte, error) { + var hashBytes [16]byte + _, err := b.Buffer.Read(hashBytes[:]) + if err != nil { + return [16]byte{}, err + } + return hashBytes, nil +} + +func (b *BufferUnpacker) LeftBytes() int { + return b.Buffer.Len() +} + +// Workflow: +// (SceneID)NavMeshDataID | int32 | 4 bytes +// NavMeshTile | struct | [:4] bytes for len +// NavMeshBuildSettings | struct | [:4] bytes for len +// OffMeshLinks | struct | [:4] bytes for len +func (b *BufferUnpacker) BeginUnpack() (*UnpackerReturn, error) { + if err := b.UnpackNavMeshDataID(); err != nil { + return nil, fmt.Errorf("Error reading m_NavMeshDataID: %v", err) + } + + if err := b.UnpackNavMeshTilesData(); err != nil { + return nil, fmt.Errorf("Error reading m_NavMeshTiles: %v", err) + } + + if err := b.UnpackNavMeshBuildSettings(); err != nil { + return nil, fmt.Errorf("Error reading m_NavMeshBuildSettings: %v", err) + } + + if err := b.UnpackOffMeshLinks(); err != nil { + return nil, fmt.Errorf("Error reading m_OffMeshLinks: %v", err) + } + + return &UnpackerReturn{Struct: *b.Struct}, nil +} + +func (b *BufferUnpacker) UnpackNavMeshDataID() error { + meshID, err := b.ReadUInt32() + if err != nil { + return err + } + + b.Struct.M_NavMeshDataID = meshID + return nil +} + +func (b *BufferUnpacker) UnpackNavMeshTilesData() error { + var tiles []NavMeshTileData + + counts, err := b.ReadInt32() + if err != nil { + return err + } + + for i := int32(0); i < counts; i++ { + var tile NavMeshTileData + + size, err := b.ReadInt32() + if err != nil { + return err + } + + data := make([]byte, int(size)) + if err := binary.Read(b.Buffer, binary.LittleEndian, &data); err != nil { + return err + } + tile.M_MeshData = data + + hash, err := b.ReadHash() + if err != nil { + return err + } + tile.M_Hash = hash + + tiles = append(tiles, tile) + } + + b.Struct.M_NavMeshTiles = tiles + return nil +} + +func (b *BufferUnpacker) UnpackNavMeshBuildSettings() error { + settings := NavMeshBuildSettings{} + if err := readStructFromBuffer(b, &settings); err != nil { + return err + } + + b.Struct.M_NavMeshBuildSettings = settings + return nil +} + +func (b *BufferUnpacker) UnpackOffMeshLinks() error { + counts, err := b.ReadInt32() + if err != nil { + return err + } + + var autoOffMeshLinks []AutoOffMeshLinkData + for i := int32(0); i < counts; i++ { + autoOffMeshLink := AutoOffMeshLinkData{} + if err := readStructFromBuffer(b, &autoOffMeshLink); err != nil { + return err + } + autoOffMeshLinks = append(autoOffMeshLinks, autoOffMeshLink) + } + + b.Struct.M_AdditionalData.OffMeshLinks = autoOffMeshLinks + return nil +} + +func readStructFromBuffer(b *BufferUnpacker, s interface{}) error { + structValue := reflect.ValueOf(s) + if structValue.Kind() != reflect.Ptr || structValue.IsNil() { + return errors.New("expecting a non-nil pointer to a struct") + } + + structType := structValue.Elem().Type() + + for i := 0; i < structType.NumField(); i++ { + field := structType.Field(i) + value := structValue.Elem().Field(i) + + // Read corresponding type from BufferUnpacker + switch field.Type.Kind() { + case reflect.Bool: + continue + case reflect.Int8: + val, err := b.ReadInt8() + if err != nil { + return err + } + value.Set(reflect.ValueOf(val)) + case reflect.Uint8: + val, err := b.ReadUInt8() + if err != nil { + return err + } + value.Set(reflect.ValueOf(val)) + case reflect.Int16: + val, err := b.ReadInt16() + if err != nil { + return err + } + value.Set(reflect.ValueOf(val)) + case reflect.Uint16: + val, err := b.ReadUInt16() + if err != nil { + return err + } + value.Set(reflect.ValueOf(val)) + case reflect.Int32: + val, err := b.ReadInt32() + if err != nil { + return err + } + value.Set(reflect.ValueOf(val)) + case reflect.Uint32: + val, err := b.ReadUInt32() + if err != nil { + return err + } + value.Set(reflect.ValueOf(val)) + case reflect.Float32: + val, err := b.ReadFloat32() + if err != nil { + return err + } + value.Set(reflect.ValueOf(val)) + case reflect.Struct: + nestedStructPtr := reflect.New(field.Type).Interface() + if err := readStructFromBuffer(b, nestedStructPtr); err != nil { + return err + } + value.Set(reflect.ValueOf(nestedStructPtr).Elem()) + case reflect.Array: + // Check if the field type is an array + if field.Type.Kind() != reflect.Array { + return fmt.Errorf("unsupported field type: %v", field.Type.Kind()) + } + + // Get the length of the array + arrayLen := field.Type.Len() + + // Create a slice to store the elements of the array + array := reflect.New(field.Type).Elem() + + // Iterate through each element of the array + for j := 0; j < arrayLen; j++ { + element := array.Index(j) + // Read corresponding type from BufferUnpacker + switch field.Type.Elem().Kind() { + case reflect.Int8: + val, err := b.ReadInt8() + if err != nil { + return err + } + element.Set(reflect.ValueOf(val)) + case reflect.Uint8: + val, err := b.ReadUInt8() + if err != nil { + return err + } + element.Set(reflect.ValueOf(val)) + case reflect.Int16: + val, err := b.ReadInt16() + if err != nil { + return err + } + element.Set(reflect.ValueOf(val)) + case reflect.Uint16: + val, err := b.ReadUInt16() + if err != nil { + return err + } + element.Set(reflect.ValueOf(val)) + case reflect.Int32: + val, err := b.ReadInt32() + if err != nil { + return err + } + element.Set(reflect.ValueOf(val)) + case reflect.Uint32: + val, err := b.ReadUInt32() + if err != nil { + return err + } + element.Set(reflect.ValueOf(val)) + case reflect.Float32: + val, err := b.ReadFloat32() + if err != nil { + return err + } + element.Set(reflect.ValueOf(val)) + case reflect.Struct: + nestedStructPtr := reflect.New(field.Type).Interface() + if err := readStructFromBuffer(b, nestedStructPtr); err != nil { + return err + } + element.Set(reflect.ValueOf(nestedStructPtr).Elem()) + default: + return fmt.Errorf("unsupported array element type: %v", field.Type.Elem().Kind()) + } + } + value.Set(array) + default: + return fmt.Errorf("unsupported field type: %v", field.Type.Kind()) + } + } + + return nil +} + +// Basic Unpacker Data Struct +type BufferUnpacker struct { + Buffer *bytes.Buffer + Struct *NavMeshData +} + +func NewUnpackerData(buffer []byte) *BufferUnpacker { + return &BufferUnpacker{ + Buffer: bytes.NewBuffer(buffer), + Struct: &NavMeshData{}, + } +} + +type UnpackerReturn struct { + Struct NavMeshData +} diff --git a/pkg/navmesh/hull_avoidance.go b/pkg/navmesh/hull_avoidance.go new file mode 100644 index 00000000..c278d8c1 --- /dev/null +++ b/pkg/navmesh/hull_avoidance.go @@ -0,0 +1,100 @@ +package navmesh + +import ( + "sort" +) + +type Vertex2Array []Vector2f + +func (this Vertex2Array) Len() int { + return len(this) +} + +func (this Vertex2Array) Less(i, j int) bool { + a := this[i] + b := this[j] + return a.x < b.x || (a.x == b.x && a.y < b.y) +} + +func (this Vertex2Array) Swap(i, j int) { + this[i], this[j] = this[j], this[i] +} + +func (this *Vertex2Array) resize_uninitialized(size int) { + if cap(*this) >= size { + *this = (*this)[:size] + } else { + *this = append(*this, make([]Vector2f, size-len(*this))...) + } +} + +func (this *Vertex2Array) empty() bool { + return len(*this) == 0 +} + +func (this *Vertex2Array) pop_back() { + *this = (*this)[:this.Len()-1] +} + +func (this *Vertex2Array) push_back(point Vector2f) { + *this = append(*this, point) +} + +func (this *Vertex2Array) erase(index int) { + if index == len(*this)-1 { + *this = (*this)[:len(*this)-1] + } else if index == 0 { + *this = (*this)[1:] + } else { + tmp := make([]Vector2f, len(*this)-1) + copy(tmp[:index], (*this)[:index]) + copy(tmp[index:], (*this)[index+1:]) + *this = tmp + } +} + +func CalculatePointSide(l0, l1, point Vector2f) float32 { + return (l1.y-l0.y)*(point.x-l0.x) - (l1.x-l0.x)*(point.y-l0.y) +} + +func CalculateConvexHull(hull *Vertex2Array, points *Vertex2Array) { + // TODO : prune (near) duplicate points before calculating hull + hull.resize_uninitialized(0) + if points.empty() { + return + } + + sort.Sort(points) + + // Andrews monotone chain + for i := 0; i < points.Len(); i++ { + for hull.Len() >= 2 && CalculatePointSide((*hull)[hull.Len()-2], (*hull)[hull.Len()-1], (*points)[i]) <= 0 { + hull.pop_back() + } + hull.push_back((*points)[i]) + } + + for i, j := points.Len()-2, hull.Len()+1; i >= 0; i-- { + for hull.Len() >= j && CalculatePointSide((*hull)[hull.Len()-2], (*hull)[hull.Len()-1], (*points)[i]) <= 0 { + hull.pop_back() + } + hull.push_back((*points)[i]) + } + hull.pop_back() +} + +func FitCapsuleToExtents(radius, height *float32, capsuleExtents Vector3f) { + r := FloatMax(capsuleExtents.x, capsuleExtents.z) + *radius = r + *height = FloatMax(0.0, capsuleExtents.y-r) +} + +func CalcCapsuleWorldExtents(worldExtents *Vector3f, localExtents, xAxis, yAxis, zAxis Vector3f) { + var radius, height float32 + FitCapsuleToExtents(&radius, &height, localExtents) + *worldExtents = AbsVector3f(yAxis).Mulf(height).Add(NewVector3f(radius, radius, radius)) +} + +func CalcBoxWorldExtents(worldExtents *Vector3f, localExtents, xAxis, yAxis, zAxis Vector3f) { + *worldExtents = AbsVector3f(xAxis).Mulf(localExtents.x).Add(AbsVector3f(yAxis).Mulf(localExtents.y)).Add(AbsVector3f(zAxis).Mulf(localExtents.z)) +} diff --git a/pkg/navmesh/math.go b/pkg/navmesh/math.go new file mode 100644 index 00000000..9a48952e --- /dev/null +++ b/pkg/navmesh/math.go @@ -0,0 +1,341 @@ +package navmesh + +import ( + "math" + "math/rand" +) + +func SqrDistancePointSegment(t *float32, pt Vector3f, s1 Vector3f, s2 Vector3f) float32 { + ds := s2.Sub(s1) + dp := pt.Sub(s1) + den := DotVector3f(ds, ds) + if den == 0 { + *t = 0 + return DotVector3f(dp, dp) + } + tt := DotVector3f(ds, dp) / den + tt = FloatClamp(tt, 0.0, 1.0) + v := ds.Mulf(tt).Sub(dp) + *t = tt + return DotVector3f(v, v) +} + +func SqrDistance(a, b Vector3f) float32 { + return SqrMagnitudeV(b.Sub(a)) +} + +func SqrMagnitudeV(inV Vector3f) float32 { + return DotVector3f(inV, inV) +} + +func SqrMagnitudeQ(inV Quaternionf) float32 { + return DotQuaternionf(inV, inV) +} + +func FloatMin(l, r float32) float32 { + if l > r { + return r + } else { + return l + } +} + +func FloatMax(l, r float32) float32 { + if l > r { + return l + } else { + return r + } +} + +func FloatAbs(d float32) float32 { + return float32(math.Abs(float64(d))) +} + +func Sqr(x float32) float32 { + return x * x +} + +func FloatClamp(v, min, max float32) float32 { + if v < min { + return min + } else if v > max { + return max + } else { + return v + } +} + +var kBiggestFloatSmallerThanOne float32 = 0.99999994 + +func FloorfToInt(f float32) int32 { + if f > 0 { + return int32(f) + } else { + return int32(f - kBiggestFloatSmallerThanOne) + } +} + +func RotateExtents(extents Vector3f, rotation Matrix3x3f) Vector3f { + var newExtents Vector3f + for i := 0; i < 3; i++ { + d := FloatAbs(rotation.Get(i, 0)*extents.x) + FloatAbs(rotation.Get(i, 1)*extents.y) + FloatAbs(rotation.Get(i, 2)*extents.z) + newExtents.SetData(i, d) + } + return newExtents +} + +func InverseTransformAABB(aabb AABB, position Vector3f, rotation Quaternionf, result *AABB) { + var m Matrix3x3f + QuaternionToMatrix3(InverseQuaternion(rotation), &m) + extents := RotateExtents(aabb.m_Extent, m) + center := aabb.m_Center.Sub(position) + center = m.MultiplyPoint3(center) + result.SetCenterAndExtent(center, extents) +} + +func OverlapBounds(amin, amax, bmin, bmax Vector3f) bool { + overlap := true + if amin.x > bmax.x || amax.x < bmin.x { + overlap = false + } + if amin.y > bmax.y || amax.y < bmin.y { + overlap = false + } + if amin.z > bmax.z || amax.z < bmin.z { + overlap = false + } + return overlap +} + +func Align4(value uintptr) uint32 { + alignment := uintptr(4) + return uint32((value + (alignment - 1)) & ^(alignment - 1)) +} + +func TransformAABB(aabb AABB, position Vector3f, rotation Quaternionf, result *AABB) { + var m Matrix3x3f + QuaternionToMatrix3(rotation, &m) + extents := RotateExtents(aabb.m_Extent, m) + center := m.MultiplyPoint3(aabb.m_Center) + center = center.Add(position) + result.SetCenterAndExtent(center, extents) +} + +func CompareApproximatelyV(inV0, inV1 Vector3f, inMaxDist float32) bool { + return SqrMagnitudeV(inV1.Sub(inV0)) <= inMaxDist*inMaxDist +} + +func CompareApproximatelyQ(q1, q2 Quaternionf, epsilon float32) bool { + // return SqrMagnitude (q1 - q2) < epsilon * epsilon; + return (SqrMagnitudeQ(q1.Sub(q2)) <= epsilon*epsilon) || (SqrMagnitudeQ(q1.Add(q2)) <= epsilon*epsilon) + // return Abs (Dot (q1, q2)) > (1 - epsilon * epsilon); +} + +func SqrDistancePointSegment2D(t *float32, pt, s1, s2 Vector3f) float32 { + dsx := s2.x - s1.x + dsz := s2.z - s1.z + dpx := pt.x - s1.x + dpz := pt.z - s1.z + den := dsx*dsx + dsz*dsz + if den == 0 { + *t = 0 + return dpx*dpx + dpz*dpz + } + tt := (dsx*dpx + dsz*dpz) / den + tt = FloatClamp(tt, 0.0, 1.0) + x := tt*dsx - dpx + z := tt*dsz - dpz + *t = tt + return x*x + z*z +} + +func IntersectSegmentPoly2D(tmin, tmax *float32, segMin, segMax *int32, p0, p1 Vector3f, verts []Vector3f, nverts int32) bool { + EPS := float32(0.00000001) + ttmin := float32(0) + ttmax := float32(1) + tSegMin := int32(-1) + tSegMax := int32(-1) + dir := p1.Sub(p0) + + i := int32(0) + for j := nverts - 1; i < nverts; j, i = i, i+1 { + edge := verts[i].Sub(verts[j]) + diff := p0.Sub(verts[j]) + n := Perp2D(edge, diff) + d := Perp2D(dir, edge) + if FloatAbs(d) < EPS { + // S is nearly parallel to this edge + if n < 0 { + break + } else { + continue + } + } + t := n / d + if d < 0 { + // segment S is entering across this edge + if t > ttmin { + ttmin = t + tSegMin = j + // S enters after leaving polygon + if ttmin > ttmax { + break + } + } + } else { + // segment S is leaving across this edge + if t < ttmax { + ttmax = t + tSegMax = j + // S leaves before entering polygon + if ttmax < ttmin { + break + } + } + } + } + *tmin = ttmin + *tmax = ttmax + *segMin = tSegMin + *segMax = tSegMax + return i == nverts +} + +const ( + kEpsilon float32 = 0.000001 + FLT_EPSILON float32 = 1.192092896e-07 +) + +func IsPowerOfTwo(mask int32) bool { + return (mask & (mask - 1)) == 0 +} + +func Sqrt(v float32) float32 { + return float32(math.Sqrt(float64(v))) +} + +func NextPowerOfTwo(v uint32) uint32 { + v -= 1 + v |= v >> 16 + v |= v >> 8 + v |= v >> 4 + v |= v >> 2 + v |= v >> 1 + return v + 1 +} + +func LerpFloat32(from, to, t float32) float32 { + return to*t + from*(1.0-t) +} + +func RotateVectorByQuat(lhs Quaternionf, rhs Vector3f) Vector3f { + // Matrix3x3f m; + // QuaternionToMatrix (lhs, &m); + // Vector3f restest = m.MultiplyVector3 (rhs); + x := lhs.x * 2.0 + y := lhs.y * 2.0 + z := lhs.z * 2.0 + xx := lhs.x * x + yy := lhs.y * y + zz := lhs.z * z + xy := lhs.x * y + xz := lhs.x * z + yz := lhs.y * z + wx := lhs.w * x + wy := lhs.w * y + wz := lhs.w * z + var res Vector3f + res.x = (1.0-(yy+zz))*rhs.x + (xy-wz)*rhs.y + (xz+wy)*rhs.z + res.y = (xy+wz)*rhs.x + (1.0-(xx+zz))*rhs.y + (yz-wx)*rhs.z + res.z = (xz-wy)*rhs.x + (yz+wx)*rhs.y + (1.0-(xx+yy))*rhs.z + + // Assert (CompareApproximately (restest, res)); + return res +} + +func ClosestHeightPointTriangle(h *float32, p, a, b, c Vector3f) bool { + v0 := c.Sub(a) + v1 := b.Sub(a) + v2 := p.Sub(a) + dot00 := Dot2D(v0, v0) + dot01 := Dot2D(v0, v1) + dot02 := Dot2D(v0, v2) + dot11 := Dot2D(v1, v1) + dot12 := Dot2D(v1, v2) + + // Compute barycentric coordinates + invDenom := 1.0 / (dot00*dot11 - dot01*dot01) + u := (dot11*dot02 - dot01*dot12) * invDenom + v := (dot00*dot12 - dot01*dot02) * invDenom + + // The (sloppy) epsilon is needed to allow to get height of points which + // are interpolated along the edges of the triangles. + EPS := float32(1e-4) + + // If point lies inside the triangle, return interpolated ycoord. + if u >= -EPS && v >= -EPS && (u+v) <= 1.0+EPS { + *h = a.y + v0.y*u + v1.y*v + return true + } + + return false +} + +// calculate xz plan area of the triangle +// https://www.mathopenref.com/coordtrianglearea.html +func TriangleAreaXZ(pa, pb, pc Vector3f) float32 { + aa := pa.x * (pb.z - pc.z) + ab := pb.x * (pc.z - pa.z) + ac := pc.x * (pa.z - pb.z) + area := (aa + ab + ac) / 2 + if area < 0 { + area = -area + } + return area +} + +// Returns a random point in a convex polygon. +// Adapted from Graphics Gems article. +func RandomPointInConvexPoly(pts []Vector3f, npts int) Vector3f { + areasum := float32(0.0) + areas := make([]float32, npts) + for i := 2; i < npts; i++ { + areas[i] = TriangleAreaXZ(pts[0], pts[i-1], pts[i]) + areasum += areas[i] + } + // Find sub triangle weighted by area. + targtSum := rand.Float32() * areasum + var searchSum float32 + tri := npts - 1 + for i := 2; i < npts; i++ { + searchSum += areas[i] + if searchSum >= targtSum { + tri = i + break + } + } + + // Find random point in triangle + // https://adamswaab.wordpress.com/2009/12/11/random-point-in-a-triangle-barycentric-coordinates/ + r := rand.Float32() + s := rand.Float32() + if r+s > 1 { + r = 1 - r + s = 1 - s + } + + pa := pts[0] + pb := pts[tri-1] + pc := pts[tri] + ab := pb.Sub(pa) + ac := pc.Sub(pa) + + return pa.Add(ab.Mulf(r).Add(ac.Mulf(s))) +} + +func SqrDistance2D(a, b Vector3f) float32 { + c := b.Sub(a) + c.y = 0.0 + return SqrMagnitude(c) +} diff --git a/pkg/navmesh/matrix.go b/pkg/navmesh/matrix.go new file mode 100644 index 00000000..68083d7f --- /dev/null +++ b/pkg/navmesh/matrix.go @@ -0,0 +1,143 @@ +package navmesh + +type Matrix4x4f struct { + m_Data [16]float32 +} + +func (this *Matrix4x4f) SetTR(pos Vector3f, q Quaternionf) { + QuaternionToMatrix4(q, this) + this.m_Data[12] = pos.x + this.m_Data[13] = pos.y + this.m_Data[14] = pos.z +} + +func (this *Matrix4x4f) SetTRS(pos Vector3f, q Quaternionf, s Vector3f) { + QuaternionToMatrix4(q, this) + this.m_Data[0] *= s.x + this.m_Data[1] *= s.x + this.m_Data[2] *= s.x + this.m_Data[4] *= s.y + this.m_Data[5] *= s.y + this.m_Data[6] *= s.y + this.m_Data[8] *= s.z + this.m_Data[9] *= s.z + this.m_Data[10] *= s.z + this.m_Data[12] = pos.x + this.m_Data[13] = pos.y + this.m_Data[14] = pos.z +} + +func (this *Matrix4x4f) GetLossyScale() Vector3f { + var result Vector3f + result.x = Magnitude(this.GetAxisX()) + result.y = Magnitude(this.GetAxisY()) + result.z = Magnitude(this.GetAxisZ()) + return result +} + +func (this *Matrix4x4f) SetTRInverse(pos Vector3f, q Quaternionf) { + QuaternionToMatrix4(InverseQuaternion(q), this) + var v Vector3f + v.x = -pos.x + v.y = -pos.y + v.z = -pos.z + this.Translate(v) +} + +func (this *Matrix4x4f) Get(row, col int) float32 { + return this.m_Data[row+col*4] +} + +func (this *Matrix4x4f) Set(row, col int, data float32) { + this.m_Data[row+col*4] = data +} + +func (this *Matrix4x4f) Translate(inTrans Vector3f) { + d := this.Get(0, 0)*inTrans.x + this.Get(0, 1)*inTrans.y + this.Get(0, 2)*inTrans.z + this.Get(0, 3) + this.Set(0, 3, d) + d = this.Get(1, 0)*inTrans.x + this.Get(1, 1)*inTrans.y + this.Get(1, 2)*inTrans.z + this.Get(1, 3) + this.Set(1, 3, d) + d = this.Get(2, 0)*inTrans.x + this.Get(2, 1)*inTrans.y + this.Get(2, 2)*inTrans.z + this.Get(2, 3) + this.Set(2, 3, d) + d = this.Get(3, 0)*inTrans.x + this.Get(3, 1)*inTrans.y + this.Get(3, 2)*inTrans.z + this.Get(3, 3) + this.Set(3, 3, d) +} + +func (this *Matrix4x4f) MultiplyPoint3(v Vector3f) Vector3f { + var res Vector3f + res.x = this.m_Data[0]*v.x + this.m_Data[4]*v.y + this.m_Data[8]*v.z + this.m_Data[12] + res.y = this.m_Data[1]*v.x + this.m_Data[5]*v.y + this.m_Data[9]*v.z + this.m_Data[13] + res.z = this.m_Data[2]*v.x + this.m_Data[6]*v.y + this.m_Data[10]*v.z + this.m_Data[14] + return res +} + +func (this *Matrix4x4f) MultiplyVector3(v Vector3f) Vector3f { + var res Vector3f + res.x = this.m_Data[0]*v.x + this.m_Data[4]*v.y + this.m_Data[8]*v.z + res.y = this.m_Data[1]*v.x + this.m_Data[5]*v.y + this.m_Data[9]*v.z + res.z = this.m_Data[2]*v.x + this.m_Data[6]*v.y + this.m_Data[10]*v.z + return res +} + +func (this *Matrix4x4f) Scale(scale Vector3f) { + this.m_Data[0+0*4] *= scale.x + this.m_Data[1+0*4] *= scale.x + this.m_Data[2+0*4] *= scale.x + this.m_Data[3+0*4] *= scale.x + this.m_Data[0+1*4] *= scale.y + this.m_Data[1+1*4] *= scale.y + this.m_Data[2+1*4] *= scale.y + this.m_Data[3+1*4] *= scale.y + this.m_Data[0+2*4] *= scale.z + this.m_Data[1+2*4] *= scale.z + this.m_Data[2+2*4] *= scale.z + this.m_Data[3+2*4] *= scale.z +} + +func (this *Matrix4x4f) GetAxisX() Vector3f { + return NewVector3f(this.Get(0, 0), this.Get(1, 0), this.Get(2, 0)) +} + +func (this *Matrix4x4f) GetAxisY() Vector3f { + return NewVector3f(this.Get(0, 1), this.Get(1, 1), this.Get(2, 1)) +} + +func (this *Matrix4x4f) GetAxisZ() Vector3f { + return NewVector3f(this.Get(0, 2), this.Get(1, 2), this.Get(2, 2)) +} + +type Matrix3x3f struct { + m_Data [9]float32 +} + +func (this *Matrix3x3f) Get(row, column int) float32 { + return this.m_Data[row+(column*3)] +} + +func (this *Matrix3x3f) MultiplyPoint3(v Vector3f) Vector3f { + return this.MultiplyVector3(v) +} + +func (this *Matrix3x3f) MultiplyVector3(v Vector3f) Vector3f { + var res Vector3f + res.x = this.m_Data[0]*v.x + this.m_Data[3]*v.y + this.m_Data[6]*v.z + res.y = this.m_Data[1]*v.x + this.m_Data[4]*v.y + this.m_Data[7]*v.z + res.z = this.m_Data[2]*v.x + this.m_Data[5]*v.y + this.m_Data[8]*v.z + return res +} + +func (this *Matrix3x3f) GetColumn(i int) Vector3f { + return NewVector3f(this.Get(0, i), this.Get(1, i), this.Get(2, i)) +} + +func (this *Matrix3x3f) GetAxisX() Vector3f { + return NewVector3f(this.Get(0, 0), this.Get(1, 0), this.Get(2, 0)) +} + +func (this *Matrix3x3f) GetAxisY() Vector3f { + return NewVector3f(this.Get(0, 1), this.Get(1, 1), this.Get(2, 1)) +} + +func (this *Matrix3x3f) GetAxisZ() Vector3f { + return NewVector3f(this.Get(0, 2), this.Get(1, 2), this.Get(2, 2)) +} diff --git a/pkg/navmesh/nav_mesh.cpp.go b/pkg/navmesh/nav_mesh.cpp.go new file mode 100644 index 00000000..ead35b63 --- /dev/null +++ b/pkg/navmesh/nav_mesh.cpp.go @@ -0,0 +1,2077 @@ +package navmesh + +import ( + "math" + "reflect" + "sort" + "unsafe" +) + +type PortalArea struct { + min, max float32 +} + +func GetWorldTileBounds(tile NavMeshTile) MinMaxAABB { + Assert(tile.header != nil) + tileBounds := NewMinMaxAABB(tile.header.bmin, tile.header.bmax) + if tile.transformed != 0 { + var mat Matrix4x4f + mat.SetTR(tile.position, tile.rotation) + TransformAABBSlow(tileBounds, mat, &tileBounds) + } + return tileBounds +} + +func OverlapSlabs(amin Vector2f, amax Vector2f, bmin Vector2f, bmax Vector2f, px float32, py float32) bool { + // Check for horizontal overlap. + // The segment is shrunken a little so that slabs which touch + // at end points are not connected. + minx := FloatMax(amin.x+px, bmin.x+px) + maxx := FloatMin(amax.x-px, bmax.x-px) + if minx > maxx { + return false + } + + // Check vertical overlap. + ad := (amax.y - amin.y) / (amax.x - amin.x) + ak := amin.y - ad*amin.x + bd := (bmax.y - bmin.y) / (bmax.x - bmin.x) + bk := bmin.y - bd*bmin.x + aminy := ad*minx + ak + amaxy := ad*maxx + ak + bminy := bd*minx + bk + bmaxy := bd*maxx + bk + dmin := bminy - aminy + dmax := bmaxy - amaxy + + // Crossing segments always overlap. + if dmin*dmax < 0 { + return true + } + + // Check for overlap at endpoints. + thr := Sqr(py * 2) + if dmin*dmin <= thr || dmax*dmax <= thr { + return true + } + return false +} + +func OverlapDetailSlabs(aslabs []Vector2f, acount int32, bslabs []Vector2f, bcount int32, px float32, py float32) bool { + for i := int32(0); i < acount-1; i++ { + amin := aslabs[i] + amax := aslabs[i+1] + for j := int32(0); j < bcount-1; j++ { + bmin := bslabs[j] + bmax := bslabs[j+1] + if OverlapSlabs(amin, amax, bmin, bmax, px, py) { + return true + } + } + } + return false +} + +func GetSlabCoord(va Vector3f, side int32) float32 { + if side == 0 || side == 4 { + return va.x + } else if side == 2 || side == 6 { + return va.z + } + return 0 +} + +func MakeDetailEdgeSlabs(slabs []Vector2f, pts []Vector3f, npts int32, side int32) { + va := pts[0] + vb := pts[npts-1] + if side == 0 || side == 4 { + if va.z < vb.z { + for i := int32(0); i < npts; i++ { + slabs[i].x = pts[i].z + slabs[i].y = pts[i].y + } + } else { + for i := int32(0); i < npts; i++ { + slabs[i].x = pts[npts-1-i].z + slabs[i].y = pts[npts-1-i].y + } + } + } else if side == 2 || side == 6 { + if va.x < vb.x { + for i := int32(0); i < npts; i++ { + slabs[i].x = pts[i].x + slabs[i].y = pts[i].y + } + } else { + for i := int32(0); i < npts; i++ { + slabs[i].x = pts[npts-1-i].x + slabs[i].y = pts[npts-1-i].y + } + } + } else { + // fix warning of uninitialized bmin, bmax + Assert(false) + for i := int32(0); i < npts; i++ { + slabs[i].x = 0 + slabs[i].y = 0 + } + } +} + +func OppositeTile(side int32) int32 { + return (side + 4) & 0x7 +} + +func NeighbourLocation(x *int32, y *int32, side int32) { + nx := *x + ny := *y + switch side { + case 0: + nx++ + case 1: + nx++ + ny++ + case 2: + ny++ + case 3: + nx-- + ny++ + case 4: + nx-- + case 5: + nx-- + ny-- + case 6: + ny-- + case 7: + nx++ + ny-- + } + *x = nx + *y = ny +} + +// It's assumed the triangle (a,b,c) is not degenerate - otherwise division by zero might occur +func ClosestPtPointTriangle(p Vector3f, a Vector3f, b Vector3f, c Vector3f) Vector3f { + // Check if P in vertex region outside A + ab := b.Sub(a) + ac := c.Sub(a) + ap := p.Sub(a) + d1 := DotVector3f(ab, ap) + d2 := DotVector3f(ac, ap) + if d1 <= 0.0 && d2 <= 0.0 { + // barycentric coordinates (1,0,0) + return a + } + + // Check if P in vertex region outside B + bp := p.Sub(b) + d3 := DotVector3f(ab, bp) + d4 := DotVector3f(ac, bp) + if d3 >= 0.0 && d4 <= d3 { + // barycentric coordinates (0,1,0) + return b + } + + // Check if P in edge region of AB, if so return projection of P onto AB + vc := d1*d4 - d3*d2 + if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 { + // barycentric coordinates (1-v,v,0) + v := d1 / (d1 - d3) + return a.Add(ab.Mulf(v)) + } + + // Check if P in vertex region outside C + cp := p.Sub(c) + d5 := DotVector3f(ab, cp) + d6 := DotVector3f(ac, cp) + if d6 >= 0.0 && d5 <= d6 { + // barycentric coordinates (0,0,1) + return c + } + + // Check if P in edge region of AC, if so return projection of P onto AC + vb := d5*d2 - d1*d6 + if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 { + // barycentric coordinates (1-w,0,w) + w := d2 / (d2 - d6) + return a.Add(ac.Mulf(w)) + } + + // Check if P in edge region of BC, if so return projection of P onto BC + va := d3*d6 - d5*d4 + if va <= 0.0 && (d4-d3) >= 0.0 && (d5-d6) >= 0.0 { + // barycentric coordinates (0,1-w,w) + w := (d4 - d3) / ((d4 - d3) + (d5 - d6)) + return LerpVector3f(b, c, w) + } + + // P inside face region. Compute Q through its barycentric coordinates (u,v,w) + denom := 1.0 / (va + vb + vc) + v := vb * denom + w := vc * denom + return a.Add(ab.Mulf(v)).Add(ac.Mulf(w)) +} + +func OverlapQuantBounds(amin []uint16, amax []uint16, bmin []uint16, bmax []uint16) bool { + overlap := true + if amin[0] > bmax[0] || amax[0] < bmin[0] { + overlap = false + } + if amin[1] > bmax[1] || amax[1] < bmin[1] { + overlap = false + } + if amin[2] > bmax[2] || amax[2] < bmin[2] { + overlap = false + } + return overlap +} + +func NewNavMesh() *NavMesh { + mesh := &NavMesh{ + m_firstOffMeshConnection: kNavMeshNullLink, + m_timeStamp: 1, + m_SurfaceIDToData: make(map[int32]*SurfaceData), + } + mesh.m_tiles.Init() + mesh.m_links.Init() + mesh.m_offMeshConnections.Init() + return mesh +} + +// Creates a surface - set of tiles sharing some data +// Reserves room for tiles belonging for a given surface. +// Params: +// tileCount - (in) number of tiles to reserve memory for. +// settings - (in) settings for tiles belonging to this surface. +func (this *NavMesh) CreateSurface(reserveTileCount int, settings NavMeshBuildSettings, pos Vector3f, rot Quaternionf) int32 { + // Find an unused and non-zero id + var id int32 + for { + id = NexSurfaceId() + if _, ok := this.m_SurfaceIDToData[id]; ok { + continue + } else { + break + } + } + data := NewSurfaceData() + data.m_Settings = settings + data.m_Position = pos + data.m_Rotation = rot + data.m_TileLUT = make(map[TileLoc]uint32, reserveTileCount) + this.m_SurfaceIDToData[id] = data + return id +} + +// Removes a surface +// Params: +// surfaceID - (in) id of surface to remove. +func (this *NavMesh) RemoveSurface(surfaceID int32) { + delete(this.m_SurfaceIDToData, surfaceID) +} + +func (this *NavMesh) GetSurfaceSettings(surfaceID int32) *NavMeshBuildSettings { + data, ok := this.m_SurfaceIDToData[surfaceID] + if ok { + return &data.m_Settings + } else { + return nil + } +} + +func (this *NavMesh) SetSurfaceSettings(surfaceID int32, settings NavMeshBuildSettings) { + data := this.m_SurfaceIDToData[surfaceID] + data.m_Settings = settings + this.m_SurfaceIDToData[surfaceID] = data +} + +func (this *NavMesh) GetSurfaceTransform(surfaceID int32, pos *Vector3f, rot *Quaternionf) NavMeshStatus { + data, ok := this.m_SurfaceIDToData[surfaceID] + if !ok { + return kNavMeshFailure + } + + *pos = data.m_Position + *rot = data.m_Rotation + return kNavMeshSuccess +} + +const kMaxPoints = 16 + +// Returns all polygons in neighbour tile based on portal defined by the segment. +func (this *NavMesh) FindConnectingPolys(fromPoints []Vector3f, fromPointCount int32, + tile *NavMeshTile, side int32, con []NavMeshPolyRef, conarea []PortalArea, + maxcon int32, portalHeight float32) int32 { + if tile == nil { + return 0 + } + if fromPointCount < 2 { + return 0 + } + portalHalfHeight := 0.5 * portalHeight // Slab check is symmetrical (kinda like radius). + var fromSlabs [kMaxPoints]Vector2f + MakeDetailEdgeSlabs(fromSlabs[:], fromPoints, fromPointCount, side) + fromMin := fromSlabs[0] + fromMax := fromSlabs[fromPointCount-1] + fromCoord := GetSlabCoord(fromPoints[0], side) + var toPoints [kMaxPoints]Vector3f + var toSlabs [kMaxPoints]Vector2f + var toPointCount int32 = 0 + + // Remove links pointing to 'side' and compact the links array. + m := kNavMeshExtLink | uint16(side) + n := int32(0) + base := this.GetPolyRefBase(tile) + for i := int32(0); i < tile.header.polyCount; i++ { + poly := &tile.polys[i] + nv := poly.vertCount + for j := uint8(0); j < nv; j++ { + // Skip edges which do not point to the right side. + if poly.neis[j] != m { + continue + } + + // Segments are not close enough along the border. + toCoord := GetSlabCoord(tile.verts[poly.verts[j]], side) + if FloatAbs(fromCoord-toCoord) > 0.01 { + continue + } + + this.GetPolyEdgeDetailPoints(tile, i, int32(j), toPoints[:], &toPointCount, kMaxPoints) + if toPointCount == 0 { + continue + } + MakeDetailEdgeSlabs(toSlabs[:], toPoints[:], toPointCount, side) + toMin := toSlabs[0] + toMax := toSlabs[toPointCount-1] + + // Check if the segments touch. + if !OverlapDetailSlabs(fromSlabs[:], fromPointCount, toSlabs[:], toPointCount, 0.01, portalHalfHeight) { + continue + } + + // Add return value. + if n < maxcon { + conarea[n].min = FloatMax(fromMin.x, toMin.x) + conarea[n].max = FloatMin(fromMax.x, toMax.x) + con[n] = base | EncodeBasePolyId(kPolyTypeGround, uint32(i)) + n++ + } + break + } + } + return n +} + +func (this *NavMesh) RemoveLinkBetween(from NavMeshPolyRef, to NavMeshPolyRef) { + if DecodePolyIdType(from) == kPolyTypeOffMeshConnection { + con := this.GetOffMeshConnectionUnsafe(from) + if con != nil { + // Remove link from connect polygon. + k := con.firstLink + pk := kNavMeshNullLink + for k != kNavMeshNullLink { + if this.m_links.Get(k).ref == to { + nk := this.m_links.Get(k).next + if pk == kNavMeshNullLink { + con.firstLink = nk + } else { + Assert(pk != nk) + this.m_links.Get(pk).next = nk + } + con.endPoints[this.m_links.Get(k).edge].tileRef = 0 + this.m_links.Release(k) + break + } + pk = k + k = this.m_links.Get(k).next + } + } + } else { + var neiTile *NavMeshTile + var neiPoly *NavMeshPoly + if NavMeshStatusSucceed(this.GetTileAndPolyByRef(from, &neiTile, &neiPoly)) { + // Remove link from connect polygon. + ip := GetPolyIndex(neiTile, neiPoly) + k := uint32(neiTile.polyLinks[ip]) + pk := kNavMeshNullLink + for k != kNavMeshNullLink { + if this.m_links.Get(k).ref == to { + nk := this.m_links.Get(k).next + if pk == kNavMeshNullLink { + neiTile.polyLinks[ip] = nk + } else { + Assert(pk != nk) + this.m_links.Get(pk).next = nk + } + this.m_links.Release(k) + break + } + pk = k + k = this.m_links.Get(k).next + } + } + } +} + +// Removes all internal and external links from a tile. +func (this *NavMesh) UnconnectLinks(tile *NavMeshTile) { + Assert(tile != nil) + Assert(tile.header != nil) + Assert(tile.polyLinks != nil) + base := this.GetPolyRefBase(tile) + for i := int32(0); i < tile.header.polyCount; i++ { + polyRef := base | EncodeBasePolyId(kPolyTypeGround, uint32(i)) + j := tile.polyLinks[i] + for j != kNavMeshNullLink { + next := this.m_links.Get(j).next + + // Remove link to this polygon + this.RemoveLinkBetween(this.m_links.Get(j).ref, polyRef) + this.m_links.Release(j) + j = next + } + tile.polyLinks[i] = kNavMeshNullLink + } +} + +type EdgePointSample struct { + t float32 + pt Vector3f +} + +type EdgePointSamples []EdgePointSample + +var _ sort.Interface = EdgePointSamples{} + +func (this EdgePointSamples) Len() int { + return len(this) +} + +func (this EdgePointSamples) Less(i, j int) bool { + return this[i].t < this[j].t +} + +func (this EdgePointSamples) Swap(i, j int) { + this[i], this[j] = this[j], this[i] +} + +const kMaxSamples = 64 + +// Returns polygon edge points based on detail mesh. +// If 'maxPoints' is less than the number of points on the edge, the edge is simplified. +// Params: +// tile - (in) pointer to tile where the polygon lies. +// poly - (in) polygon index +// edge - (in) edge index +// points - (out) array to store the edge points (maxPoints*3). +// pointCount - (out) number of points stored. +// maxPoints - (in) max number of points that can fit into points, must be >= 2. +func (this *NavMesh) GetPolyEdgeDetailPoints(tile *NavMeshTile, p int32, edge int32, + points []Vector3f, pointCount *int32, maxPoints int32) NavMeshStatus { + Assert(maxPoints > 2) + poly := &tile.polys[p] + pd := &tile.detailMeshes[p] + ndv := pd.vertCount + vertCount := poly.vertCount + v0 := tile.verts[poly.verts[edge]] + v1 := tile.verts[poly.verts[NextIndex(edge, int32(vertCount))]] + var samples [kMaxSamples]EdgePointSample + + // Add first edge vertex + samples[0].t = 0.0 + samples[0].pt = v0 + sampleCount := int32(1) + + // Collect detail vertices close to the edge. + // adds up to kMaxSamples-2 detail vertices. + if ndv != 0 { + EPS := float32(0.0001) + dvx := v1.x - v0.x + dvz := v1.z - v0.z + lenSq := dvx*dvx + dvz*dvz + if lenSq < EPS { + *pointCount = 0 + return kNavMeshFailure + } + + distanceThr := Sqr(0.01) + nrm := 1.0 / lenSq + dverts := tile.detailVerts[pd.vertBase:] + for i := 0; i < int(ndv); i++ { + dv := dverts[i] + dpx := dv.x - v0.x + dpz := dv.z - v0.z + t := FloatClamp((dvx*dpx+dvz*dpz)*nrm, 0.0, 1.0) + + // Skip points projected to end points of edge + if t < EPS || t > (1.0-EPS) { + continue + } + + // Skip points not close to edge + x := t*dvx - dpx + z := t*dvz - dpz + distSqr := x*x + z*z + if distSqr > distanceThr { + continue + } + + // Accept and add point. + samples[sampleCount].t = t + samples[sampleCount].pt = dv + sampleCount++ + + // Leave room for last vertex + if sampleCount == kMaxSamples-1 { + break + } + } + + // Order the collected detail vertices + sort.Sort(EdgePointSamples(samples[1:sampleCount])) + } + + // Add last edge vertex + samples[sampleCount].t = 1.0 + samples[sampleCount].pt = v1 + sampleCount++ + + // Simplify if needed. + for sampleCount > maxPoints { + // Find + removeIdx := int32(-1) + minDist := float32(math.MaxFloat32) + for i := int32(1); i < sampleCount-1; i++ { + var t float32 + d := SqrDistancePointSegment(&t, samples[i].pt, samples[i-1].pt, samples[i+1].pt) + if d < minDist { + minDist = d + removeIdx = i + } + } + // Remove removeIdx + for i := removeIdx; i < sampleCount-1; i++ { + samples[i] = samples[i+1] + } + sampleCount-- + } + + for i := int32(0); i < sampleCount; i++ { + points[i] = samples[i].pt + } + *pointCount = sampleCount + return kNavMeshSuccess +} + +// Builds external polygon links for a tile. +func (this *NavMesh) ConnectExtLinks(tile *NavMeshTile, target *NavMeshTile, side int32, portalHeight float32) { + if tile == nil { + return + } + + // Unity specific: Do not connect tiles from different surfaces. + // We expect each navmesh surface to be separate and connected to each other only via off-mesh connections. + if tile.surfaceID != target.surfaceID { + return + } + + // Connect border links. + for i := int32(0); i < tile.header.polyCount; i++ { + poly := &tile.polys[i] + nv := poly.vertCount + for j := uint8(0); j < nv; j++ { + // Skip non-portal edges. + if (poly.neis[j] & kNavMeshExtLink) == 0 { + continue + } + + dir := poly.neis[j] & 0xff + if side != -1 && dir != uint16(side) { + continue + } + + // Create new links + va := tile.verts[poly.verts[j]] + vb := tile.verts[poly.verts[NextIndex(int32(j), int32(nv))]] + var points [kMaxPoints]Vector3f + var pointCount = int32(0) + this.GetPolyEdgeDetailPoints(tile, i, int32(j), points[:], &pointCount, kMaxPoints) + var nei [4]NavMeshPolyRef + var neia [4]PortalArea + nnei := this.FindConnectingPolys(points[:], pointCount, target, OppositeTile(int32(dir)), nei[:], neia[:], 4, portalHeight) + for k := int32(0); k < nnei; k++ { + idx := this.m_links.Alloc() + if idx != kNavMeshNullLink { + link := this.m_links.Get(idx) + link.ref = nei[k] + link.edge = j + link.side = uint8(dir) + Assert(idx != tile.polyLinks[i]) + link.next = tile.polyLinks[i] + tile.polyLinks[i] = idx + + // Compress portal limits to a byte value. + if dir == 0 || dir == 4 { + tmin := (neia[k].min - va.z) / (vb.z - va.z) + tmax := (neia[k].max - va.z) / (vb.z - va.z) + if tmin > tmax { + tmin, tmax = tmax, tmin + } + link.bmin = uint8(FloatClamp(tmin, 0.0, 1.0) * 255.0) + link.bmax = uint8(FloatClamp(tmax, 0.0, 1.0) * 255.0) + } else if dir == 2 || dir == 6 { + tmin := (neia[k].min - va.x) / (vb.x - va.x) + tmax := (neia[k].max - va.x) / (vb.x - va.x) + if tmin > tmax { + tmin, tmax = tmax, tmin + } + link.bmin = uint8(FloatClamp(tmin, 0.0, 1.0) * 255.0) + link.bmax = uint8(FloatClamp(tmax, 0.0, 1.0) * 255.0) + } + } + } + } + } +} + +// Builds internal polygons links for a tile. +func (this *NavMesh) ConnectIntLinks(tile *NavMeshTile) { + Assert(tile != nil) + Assert(tile.header != nil) + polyCount := tile.header.polyCount + + // Allocate and nullify per poly links + Assert(tile.polyLinks == nil) + tile.polyLinks = make([]uint32, polyCount) + for i := int32(0); i < polyCount; i++ { + tile.polyLinks[i] = kNavMeshNullLink + } + + base := this.GetPolyRefBase(tile) + for i := int32(0); i < polyCount; i++ { + poly := &tile.polys[i] + + // Build edge links backwards so that the links will be + // in the linked list from lowest index to highest. + for j := int32(poly.vertCount) - 1; j >= 0; j-- { + // Skip hard and non-internal edges. + if poly.neis[j] == 0 || (poly.neis[j]&kNavMeshExtLink) != 0 { + continue + } + + idx := this.m_links.Alloc() + if idx != kNavMeshNullLink { + link := this.m_links.Get(idx) + link.ref = base | EncodeBasePolyId(kPolyTypeGround, uint32(poly.neis[j]-1)) + link.edge = uint8(j) + link.side = 0xff + link.bmin = 0 + link.bmax = 0 + // Add to linked list. + Assert(idx != tile.polyLinks[i]) + link.next = tile.polyLinks[i] + tile.polyLinks[i] = idx + } + } + } +} + +// Returns closest point on polygon. +func (this *NavMesh) ClosestPointOnPolyInTileLocal(tile *NavMeshTile, poly *NavMeshPoly, pos Vector3f, closest *Vector3f) { + ip := GetPolyIndex(tile, poly) + pd := &tile.detailMeshes[ip] + closestDistSqr := float32(math.MaxFloat32) + for j := 0; j < int(pd.triCount); j++ { + t := tile.detailTris[(int(pd.triBase)+j)*4:] + var v [3]Vector3f + for k := 0; k < 3; k++ { + if uint8(t[k]) < poly.vertCount { + v[k] = tile.verts[poly.verts[t[k]]] + } else { + v[k] = tile.detailVerts[uint8(pd.vertBase)+(uint8(t[k])-poly.vertCount)] + } + } + + pt := ClosestPtPointTriangle(pos, v[0], v[1], v[2]) + d := SqrDistance(pos, pt) + if d < closestDistSqr { + *closest = pt + closestDistSqr = d + } + } +} + +type NearestQuery struct { + m_NavMesh *NavMesh + m_PolyRef NavMeshPolyRef + m_DistanceSqr float32 + m_Center Vector3f + m_Point Vector3f +} + +func NewNearestQuery(navmesh *NavMesh, center Vector3f) NearestQuery { + return NearestQuery{ + navmesh, 0, math.MaxFloat32, center, Vector3f{0, 0, 0}, + } +} + +func (this *NearestQuery) ProcessPolygons(tile *NavMeshTile, polyRefs []NavMeshPolyRef, polys []*NavMeshPoly, itemCount int) { + localPosition := WorldToTile(tile, this.m_Center) + // Find nearest polygon amongst the nearby polygons. + for i := 0; i < itemCount; i++ { + ref := polyRefs[i] + poly := polys[i] + var closestPtPoly Vector3f + this.m_NavMesh.ClosestPointOnPolyInTileLocal(tile, poly, localPosition, &closestPtPoly) + d := SqrDistance(localPosition, closestPtPoly) + if d < this.m_DistanceSqr { + this.m_Point = closestPtPoly + this.m_DistanceSqr = d + this.m_PolyRef = ref + } + } +} + +// Find nearest polygon within a tile. +func (this *NavMesh) FindNearestPoly(typeID int32, center Vector3f, extents Vector3f, nearestPt *Vector3f) NavMeshPolyRef { + + // Get nearby polygons from proximity grid. + nearest := NewNearestQuery(this, center) + this.QueryPolygons(typeID, center, extents, &nearest) + if nearest.m_PolyRef == 0 { + return 0 + } + if nearestPt != nil { + tile := this.GetTileByRef(NavMeshTileRef(nearest.m_PolyRef)) + if tile != nil { + *nearestPt = TileToWorld(tile, nearest.m_Point) + } + } + + return nearest.m_PolyRef +} + +// Returns polygons which overlap the query box. +// Params: +// typeID - (in) query surfaces with this id. -1 means query all surfaces. +// center[3] - (in) the center of the search box. +// extents[3] - (in) the extents of the search box. +// callback - (in/out) pointer to callback interface to batch-process the results, see NavMeshProcessCallback. +func (this *NavMesh) QueryPolygons(typeID int32, cen Vector3f, ext Vector3f, callback NavMeshProcessCallback) { + bounds := NewMinMaxAABB(cen.Sub(ext), cen.Add(ext)) + for _, surf := range this.m_SurfaceIDToData { + if typeID != -1 && typeID != surf.m_Settings.agentTypeID { + continue + } + + var overlap MinMaxAABB + if !IntersectionAABBAABB(bounds, surf.m_WorldBounds, &overlap) { + continue + } + + var localBounds AABB + InverseTransformAABB(NewAABBFromMinMax(overlap), surf.m_Position, surf.m_Rotation, &localBounds) + invTileSize := 1.0 / (float32(surf.m_Settings.tileSize) * surf.m_Settings.cellSize) + iminx := FloorfToInt((localBounds.m_Center.x - localBounds.m_Extent.x) * invTileSize) + imaxx := FloorfToInt((localBounds.m_Center.x + localBounds.m_Extent.x) * invTileSize) + jminz := FloorfToInt((localBounds.m_Center.z - localBounds.m_Extent.z) * invTileSize) + jmaxz := FloorfToInt((localBounds.m_Center.z + localBounds.m_Extent.z) * invTileSize) + for i := iminx; i <= imaxx; i++ { + for j := jminz; j <= jmaxz; j++ { + key := TileLoc{i, j} + tileIndex, ok := surf.m_TileLUT[key] + if !ok { + continue + } + this.QueryPolygonsInTile(this.m_tiles.Get(tileIndex), localBounds.m_Center, localBounds.m_Extent, callback) + } + } + } +} + +const kBufferSize = 32 + +// Queries polygons within a tile. +func (this *NavMesh) QueryPolygonsInTile(tile *NavMeshTile, center Vector3f, extents Vector3f, callback NavMeshProcessCallback) { + var polyRefs [kBufferSize]NavMeshPolyRef + var polys [kBufferSize]*NavMeshPoly + qmin := center.Sub(extents) + qmax := center.Add(extents) + if tile.bvTree != nil { + offset := int32(0) + node := &tile.bvTree[offset] + // The final node is garbage as we allocate 2*polyCount but need one less for the tree. + // Here we make sure the end node is not reached by subtracting 1 + end := &tile.bvTree[tile.header.bvNodeCount-1] + tbmin := tile.header.bmin + tbmax := tile.header.bmax + qfac := tile.header.bvQuantFactor + + // Calculate quantized box + var bmin, bmax [3]uint16 + // FloatClamp query box to world box. + minx := FloatClamp(qmin.x, tbmin.x, tbmax.x) - tbmin.x + miny := FloatClamp(qmin.y, tbmin.y, tbmax.y) - tbmin.y + minz := FloatClamp(qmin.z, tbmin.z, tbmax.z) - tbmin.z + maxx := FloatClamp(qmax.x, tbmin.x, tbmax.x) - tbmin.x + maxy := FloatClamp(qmax.y, tbmin.y, tbmax.y) - tbmin.y + maxz := FloatClamp(qmax.z, tbmin.z, tbmax.z) - tbmin.z + // Quantize + bmin[0] = uint16(qfac*minx) & 0xfffe + bmin[1] = uint16(qfac*miny) & 0xfffe + bmin[2] = uint16(qfac*minz) & 0xfffe + bmax[0] = uint16(qfac*maxx+1) | 1 + bmax[1] = uint16(qfac*maxy+1) | 1 + bmax[2] = uint16(qfac*maxz+1) | 1 + + // Traverse tree + base := this.GetPolyRefBase(tile) + n := 0 + for uintptr(unsafe.Pointer(node)) < uintptr(unsafe.Pointer(end)) { + overlap := OverlapQuantBounds(bmin[:], bmax[:], node.bmin[:], node.bmax[:]) + isLeafNode := node.i >= 0 + if isLeafNode && overlap { + if n >= kBufferSize { + callback.ProcessPolygons(tile, polyRefs[:], polys[:], n) + n = 0 + } + polyRefs[n] = base | EncodeBasePolyId(kPolyTypeGround, uint32(node.i)) + polys[n] = &tile.polys[node.i] + n++ + } + + if overlap || isLeafNode { + offset++ + node = &tile.bvTree[offset] + } else { + escapeIndex := -node.i + offset += escapeIndex + node = &tile.bvTree[offset] + } + } + if n > 0 { + callback.ProcessPolygons(tile, polyRefs[:], polys[:], n) + } + } else { + var bmin, bmax Vector3f + n := 0 + base := this.GetPolyRefBase(tile) + for i := int32(0); i < tile.header.polyCount; i++ { + // Calc polygon bounds. + p := &tile.polys[i] + bmax = tile.verts[p.verts[0]] + bmin = bmax + for j := uint8(1); j < p.vertCount; j++ { + v := tile.verts[p.verts[j]] + bmin = MinVector3f(bmin, v) + bmax = MaxVector3f(bmax, v) + } + if OverlapBounds(qmin, qmax, bmin, bmax) { + if n >= kBufferSize { + callback.ProcessPolygons(tile, polyRefs[:], polys[:], n) + n = 0 + } + polyRefs[n] = base | EncodeBasePolyId(kPolyTypeGround, uint32(i)) + polys[n] = p + n++ + } + } + if n > 0 { + callback.ProcessPolygons(tile, polyRefs[:], polys[:], n) + } + } +} + +// Adds new tile into the navmesh. +// The add will fail if the data is in wrong format, +// there is not enough tiles left, or if there is a tile already at the location. +// Params: +// data - (in) Data of the new tile mesh. +// dataSize - (in) Data size of the new tile mesh. +// flags - (in) Tile flags, see NavMeshTileFlags. +// surfaceID - (in) surface identifier for the tile. +// result - (out,optional) tile ref if the tile was successfully added. +func (this *NavMesh) AddTile(data []byte, dataSize int32, flags NavMeshTileFlags, surfaceID int32, result *NavMeshTileRef) NavMeshStatus { + // Make sure the data is in right format. + header := (*NavMeshDataHeader)(unsafe.Pointer(&(data[0]))) + if header.magic != kNavMeshMagic { + return kNavMeshFailure | kNavMeshWrongMagic + } + if header.version != kNavMeshVersion { + return kNavMeshFailure | kNavMeshWrongVersion + } + + // 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)) + polyRegionsSize := Align4(unsafe.Sizeof(NavMeshPolyRegion(0)) * uintptr(header.polyCount)) + d := headerSize + + var verts []Vector3f + sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&(verts))) + sliceHeader.Cap = int(header.vertCount) + sliceHeader.Len = int(header.vertCount) + sliceHeader.Data = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d]))) + } + d += bvtreeSize + + var polyRegions []NavMeshPolyRegion + sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(polyRegions))) + sliceHeader.Cap = int(header.polyCount) + sliceHeader.Len = int(header.polyCount) + sliceHeader.Data = 0x00 + if sliceHeader.Len > 0 { + sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d]))) + } + d += polyRegionsSize + + if d != uint32(dataSize) { + println(d, dataSize) + return kNavMeshFailure + } + + // Allocate a tile. + newTileIndex := this.m_tiles.Alloc() + + // Make sure we could allocate a tile. + if newTileIndex == kNavMeshNullLink { + return kNavMeshFailure | kNavMeshOutOfMemory + } + _, ok := this.m_SurfaceIDToData[surfaceID] + Assert(ok) + tile := this.m_tiles.Get(newTileIndex) + + // Insert tile into the position lut. + surfaceData := this.m_SurfaceIDToData[surfaceID] + lut := surfaceData.m_TileLUT + lut[TileLoc{header.x, header.y}] = newTileIndex + + position := surfaceData.m_Position + rotation := surfaceData.m_Rotation + + // Consider: Post process all these + var tileWorldBounds AABB + tilebounds := NewMinMaxAABB(header.bmin, header.bmax) + TransformAABB(NewAABBFromMinMax(tilebounds), position, rotation, &tileWorldBounds) + surfaceData.m_WorldBounds.Encapsulate(NewMinMaxAABBFromAABB(tileWorldBounds)) + + // Patch header pointers. + 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 + } + + // Init tile. + tile.surfaceID = surfaceID + tile.header = header + tile.polyLinks = nil + tile.data = data + tile.dataSize = dataSize + tile.flags = int32(flags) + epsilon := float32(0.00001) + if (CompareApproximatelyV(Vector3f{0, 0, 0}, position, epsilon) && + CompareApproximatelyQ(Quaternionf{0, 0, 0, 1}, rotation, epsilon)) { + tile.rotation = Quaternionf{0, 0, 0, 1} + tile.position = Vector3f{0, 0, 0} + tile.transformed = 0 + } else { + tile.rotation = rotation + tile.position = position + tile.transformed = 1 + } + + this.ConnectIntLinks(tile) + + // Create connections to the 4 nearest neighbour tiles. + portalHeight := surfaceData.m_Settings.cellSize + for i := int32(0); i < 8; i += 2 { + x := tile.header.x + y := tile.header.y + NeighbourLocation(&x, &y, i) + tileIndex, ok := lut[TileLoc{x, y}] + if !ok { + continue + } + ntile := this.m_tiles.Get(tileIndex) + this.ConnectExtLinks(tile, ntile, i, portalHeight) + this.ConnectExtLinks(ntile, tile, OppositeTile(i), portalHeight) + } + + this.ConnectOffMeshConnectionsToTile(tile) + if result != nil { + *result = this.GetTileRef(tile) + } + return kNavMeshSuccess +} + +// Returns tile based on references. +func (this *NavMesh) GetTileByRef(ref NavMeshTileRef) *NavMeshTile { + if ref == 0 { + return nil + } + tileIndex := DecodePolyIdTile(NavMeshPolyRef(ref)) + tileSalt := DecodePolyIdSalt(NavMeshPolyRef(ref)) + if tileIndex >= uint32(this.m_tiles.Capacity()) { + return nil + } + tile := this.m_tiles.Get(tileIndex) + if tile.salt != tileSalt { + return nil + } + return tile +} + +// Returns pointer to tile and polygon pointed by the polygon reference. +// Params: +// ref - (in) reference to a polygon. +// tile - (out) pointer to the tile containing the polygon. +// poly - (out) pointer to the polygon. +func (this *NavMesh) GetTileAndPolyByRef(ref NavMeshPolyRef, tile **NavMeshTile, poly **NavMeshPoly) NavMeshStatus { + if ref == 0 { + return kNavMeshFailure + } + + var salt, it, typ, ip uint32 + DecodePolyId(&salt, &it, &typ, &ip, ref) + if it >= this.m_tiles.Capacity() { + return kNavMeshFailure | kNavMeshInvalidParam + } + if this.m_tiles.Get(it).salt != salt || this.m_tiles.Get(it).header == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + if typ == kPolyTypeOffMeshConnection { + *tile = nil + *poly = nil + } else { + if int32(ip) >= this.m_tiles.Get(it).header.polyCount { + return kNavMeshFailure | kNavMeshInvalidParam + } + *tile = this.m_tiles.Get(it) + *poly = &this.m_tiles.Get(it).polys[ip] + } + return kNavMeshSuccess +} + +// Returns pointer to tile and polygon pointed by the polygon reference. +// Note: this function does not check if 'ref' s valid, and is thus faster. Use only with valid refs! +// Params: +// ref - (in) reference to a polygon. +// tile - (out) pointer to the tile containing the polygon. +// poly - (out) pointer to the polygon. +func (this *NavMesh) GetTileAndPolyByRefUnsafe(ref NavMeshPolyRef, tile **NavMeshTile, poly **NavMeshPoly) { + var salt, it, typ, ip uint32 + DecodePolyId(&salt, &it, &typ, &ip, ref) + if typ == kPolyTypeOffMeshConnection { + *tile = nil + *poly = nil + } else { + *tile = this.m_tiles.Get(it) + *poly = &this.m_tiles.Get(it).polys[ip] + } +} + +// Returns true if polygon reference points to valid data. +func (this *NavMesh) IsValidPolyRef(ref NavMeshPolyRef) bool { + if ref == 0 { + return false + } + var salt, it, typ, ip uint32 + DecodePolyId(&salt, &it, &typ, &ip, ref) + if typ == kPolyTypeOffMeshConnection { + if ip >= this.m_offMeshConnections.Capacity() { + return false + } + if this.m_offMeshConnections.Get(ip).salt != salt { + return false + } + } else { + if it >= this.m_tiles.Capacity() { + return false + } + if this.m_tiles.Get(it).salt != salt || this.m_tiles.Get(it).header == nil { + return false + } + if int32(ip) >= this.m_tiles.Get(it).header.polyCount { + return false + } + } + return true +} + +// Returns the agentTypeId that is allowed to use the polygon. +func (this *NavMesh) GetAgentTypeIdForPolyRef(ref NavMeshPolyRef) int32 { + if ref == 0 { + return 0 + } + + var salt, it, typ, ip uint32 + DecodePolyId(&salt, &it, &typ, &ip, ref) + if typ == kPolyTypeOffMeshConnection { + if ip >= this.m_offMeshConnections.Capacity() { + return kInvalidAgentTypeID + } + + if this.m_offMeshConnections.Get(ip).salt != salt { + return kInvalidAgentTypeID + } + + return this.m_offMeshConnections.Get(ip).agentTypeID + } else { + if it >= this.m_tiles.Capacity() { + return kInvalidAgentTypeID + } + + if this.m_tiles.Get(it).salt != salt || this.m_tiles.Get(it).header == nil { + return kInvalidAgentTypeID + } + + if int32(ip) >= this.m_tiles.Get(it).header.polyCount { + return kInvalidAgentTypeID + } + + return int32(this.m_tiles.Get(it).header.agentTypeId) + } +} + +// Removes specified tile. +// Params: +// ref - (in) Reference to the tile to remove. +// surfaceID - (in) surface identifier for the tile +// data - (out) Data associated with deleted tile. +// dataSize - (out) Size of the data associated with deleted tile. +func (this *NavMesh) RemoveTile(ref NavMeshTileRef, surfaceID int32, data *[]byte, dataSize *int32) NavMeshStatus { + if ref == 0 { + return kNavMeshFailure | kNavMeshInvalidParam + } + tileIndex := DecodePolyIdTile(NavMeshPolyRef(ref)) + tileSalt := DecodePolyIdSalt(NavMeshPolyRef(ref)) + if tileIndex >= this.m_tiles.Capacity() { + return kNavMeshFailure | kNavMeshInvalidParam + } + tile := this.m_tiles.Get(tileIndex) + if tile.salt != tileSalt { + return kNavMeshFailure | kNavMeshInvalidParam + } + + // Remove tile from hash lookup. + surfaceData, ok := this.m_SurfaceIDToData[surfaceID] + Assert(ok) + lut := surfaceData.m_TileLUT + delete(lut, TileLoc{tile.header.x, tile.header.y}) + + // Remove links to connected tiles. + this.UnconnectLinks(tile) + // Remove off-mesh connections connected to the tile. + // unconnectLinks() unconnects most of them, but one-directional + // links may not be unconnected. + this.UnconnectOffMeshConnectionsToTile(ref) + + // Reset tile. + if tile.flags&int32(kTileFreeData) != 0 { + // We own the data - it's ok to cast away const and free it. + if data != nil { + *data = nil + } + if dataSize != nil { + *dataSize = 0 + } + } else { + if data != nil { + *data = tile.data + } + if dataSize != nil { + *dataSize = tile.dataSize + } + } + tile.data = nil + tile.dataSize = 0 + tile.polyLinks = nil + tile.header = nil + tile.flags = 0 + tile.polys = nil + tile.verts = nil + tile.detailMeshes = nil + tile.detailVerts = nil + tile.detailTris = nil + tile.bvTree = nil + + // Update salt, salt should never be zero. + tile.salt = (tile.salt + 1) & ((1 << kPolyRefSaltBits) - 1) + if tile.salt == 0 { + tile.salt++ + } + + // Add to free list. + this.m_tiles.Release(tileIndex) + return kNavMeshSuccess +} + +// Returns tile references of a tile based on tile pointer. +func (this *NavMesh) GetTileRef(tile *NavMeshTile) NavMeshTileRef { + if tile == nil { + return 0 + } + it := GetTileIndex(this.m_tiles.Get(0), tile) + return NavMeshTileRef(EncodePolyId(tile.salt, uint32(it), 0, 0)) +} + +// Returns base poly id for specified tile, polygon refs can be deducted from this. +func (this *NavMesh) GetPolyRefBase(tile *NavMeshTile) NavMeshPolyRef { + if tile == nil { + return NavMeshPolyRef(0) + } + + it := GetTileIndex(this.m_tiles.Get(0), tile) + return EncodePolyId(tile.salt, uint32(it), 0, 0) +} + +// Returns start and end location of an off-mesh link polygon. +// As seen when approached from prevRef. +// Returns start and end location of an off-mesh link polygon. +// Params: +// prevRef - (in) ref to the polygon before the link (used to select direction). +// polyRef - (in) ref to the off-mesh link polygon. +// startPos[3] - (out) start point of the link. +// endPos[3] - (out) end point of the link. +// Returns: true if link is found. +func (this *NavMesh) GetOffMeshConnectionEndPoints(prevRef NavMeshPolyRef, offMeshPolyRef NavMeshPolyRef, startPos *Vector3f, endPos *Vector3f) NavMeshStatus { + // Make sure that the current poly is indeed off-mesh link. + if DecodePolyIdType(offMeshPolyRef) != kPolyTypeOffMeshConnection { + + return kNavMeshFailure | kNavMeshInvalidParam + } + + con := this.GetOffMeshConnection(offMeshPolyRef) + if con == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + + // Find link which leads to previous polygon to figure out which way we are traversing the off-mesh connection. + var foundLink *NavMeshLink + for link := this.GetLink(con.firstLink); link != nil; link = this.GetNextLink(link) { + if link.ref == prevRef { + foundLink = link + break + } + } + if foundLink == nil { + return kNavMeshFailure + } + + // OffMesh connection can only have edge 0 or 1 + Assert(foundLink.edge == 0 || foundLink.edge == 1) + + // Set endpoints based on direction + if foundLink.edge == 0 { + *startPos = con.endPoints[0].pos + *endPos = con.endPoints[1].pos + return kNavMeshSuccess + } else if foundLink.edge == 1 { + *startPos = con.endPoints[1].pos + *endPos = con.endPoints[0].pos + return kNavMeshSuccess + } + + return kNavMeshFailure +} + +func (this *NavMesh) GetNearestOffMeshConnectionEndPoints(prevRef NavMeshPolyRef, offMeshPolyRef NavMeshPolyRef, nextRef NavMeshPolyRef, currentPos Vector3f, startPos *Vector3f, endPos *Vector3f) NavMeshStatus { + // Make sure that the current poly is indeed off-mesh link. + if DecodePolyIdType(offMeshPolyRef) != kPolyTypeOffMeshConnection { + return kNavMeshFailure | kNavMeshInvalidParam + } + con := this.GetOffMeshConnection(offMeshPolyRef) + if con == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + + // Find link which leads to previous polygon to figure out which way we are traversing the off-mesh connection. + var prevLink *NavMeshLink + for link := this.GetLink(con.firstLink); link != nil; link = this.GetNextLink(link) { + if link.ref == prevRef { + prevLink = link + break + } + } + if prevLink == nil { + return kNavMeshFailure + } + + // Find link which leads to next polygon to figure out which way we are traversing the off-mesh connection. + var nextLink *NavMeshLink + for link := this.GetLink(con.firstLink); link != nil; link = this.GetNextLink(link) { + if link.ref == nextRef { + nextLink = link + break + } + } + if nextLink == nil { + return kNavMeshFailure + } + + // OffMesh connection can only have edge 0 or 1 + Assert(prevLink.edge == 0 || prevLink.edge == 1) + if con.width > 0.0 { + // For wide connections we try to go across at the same relative locations. + // I.e. of the nearest point along the entry segment is at t=0.3, then we try + // to choose the same proportional location at the exit segment too. + // We clamp the entry and exit locations to the links. This is done since + // the connection can be linked to many polygons at the destination. + // Note: It should be possible to constrain the link traversal during the search + // so that we only exit at links which overlap the input range. That way + // we could have the proportional locations to match at entry and exit. + var startP, startQ, endP, endQ Vector3f + if prevLink.edge == 0 { + startP = con.endPoints[0].mapped[0] + startQ = con.endPoints[0].mapped[1] + endP = con.endPoints[1].mapped[0] + endQ = con.endPoints[1].mapped[1] + } else if prevLink.edge == 1 { + startP = con.endPoints[1].mapped[0] + startQ = con.endPoints[1].mapped[1] + endP = con.endPoints[0].mapped[0] + endQ = con.endPoints[0].mapped[1] + } else { + startP = Vector3f{0, 0, 0} + startQ = Vector3f{0, 0, 0} + endP = Vector3f{0, 0, 0} + endQ = Vector3f{0, 0, 0} + } + + // Find proportional location on entry segment. + t0 := float32(0.0) + SqrDistancePointSegment2D(&t0, currentPos, startP, startQ) + t1 := 1.0 - t0 // Exit segment points are in reverse. + + // Clamp both factors to link range. + s := float32(1.0) / 255.0 + startTmin := FloatMax(float32(prevLink.bmin)*s, 0.0) + startTmax := FloatMin(float32(prevLink.bmax)*s, 1.0) + endTmin := FloatMax(float32(nextLink.bmin)*s, 0.0) + endTmax := FloatMin(float32(nextLink.bmax)*s, 1.0) + t0 = FloatClamp(t0, startTmin, startTmax) + t1 = FloatClamp(t1, endTmin, endTmax) + *startPos = LerpVector3f(startP, startQ, t0) + *endPos = LerpVector3f(endP, endQ, t1) + return kNavMeshSuccess + } else { + // For point-to-point connections we use the end points provided by the user. + // Set endpoints based on direction + if prevLink.edge == 0 { + *startPos = con.endPoints[0].pos + *endPos = con.endPoints[1].pos + } else if prevLink.edge == 1 { + *startPos = con.endPoints[1].pos + *endPos = con.endPoints[0].pos + } + + return kNavMeshSuccess + } +} + +// polyRef - polyRef of the offmeshlink polygon +// costOverride - use this as cost OffMeshLink cost modifier instead of what is specified by areas. +func (this *NavMesh) SetOffMeshConnectionCostModifier(ref NavMeshPolyRef, costOverride float32) NavMeshStatus { + if DecodePolyIdType(ref) != kPolyTypeOffMeshConnection { + return kNavMeshFailure | kNavMeshInvalidParam + } + con := this.GetOffMeshConnectionUnsafe(ref) + if con == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + if costOverride >= 0.0 { + con.costModifier = costOverride + } else { + con.costModifier = -1.0 + } + this.BumpTimeStamp() + return kNavMeshSuccess +} + +func (this *NavMesh) SetOffMeshConnectionFlags(ref NavMeshPolyRef, flags uint32) NavMeshStatus { + if DecodePolyIdType(ref) != kPolyTypeOffMeshConnection { + return kNavMeshFailure | kNavMeshInvalidParam + } + con := this.GetOffMeshConnectionUnsafe(ref) + if con == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + + con.flags = flags + this.BumpTimeStamp() + return kNavMeshSuccess +} + +func (this *NavMesh) GetOffMeshConnectionUserID(ref NavMeshPolyRef, userID *int32) NavMeshStatus { + if DecodePolyIdType(ref) != kPolyTypeOffMeshConnection { + return kNavMeshFailure | kNavMeshInvalidParam + } + + con := this.GetOffMeshConnection(ref) + if con == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + *userID = con.userID + return kNavMeshSuccess +} + +func (this *NavMesh) SetOffMeshConnectionUserID(ref NavMeshPolyRef, userID int32) NavMeshStatus { + if DecodePolyIdType(ref) != kPolyTypeOffMeshConnection { + return kNavMeshFailure | kNavMeshInvalidParam + } + con := this.GetOffMeshConnectionUnsafe(ref) + if con == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + + con.userID = userID + return kNavMeshSuccess +} + +func (this *NavMesh) GetOffMeshConnection(ref NavMeshPolyRef) *OffMeshConnection { + if DecodePolyIdType(ref) != kPolyTypeOffMeshConnection { + + return nil + } + index := DecodePolyIdPoly(ref) + if index >= this.m_offMeshConnections.Capacity() { + return nil + } + salt := DecodePolyIdSalt(ref) + if salt != this.m_offMeshConnections.Get(index).salt { + return nil + } + return this.m_offMeshConnections.Get(index) +} + +func (this *NavMesh) GetOffMeshConnectionUnsafe(ref NavMeshPolyRef) *OffMeshConnection { + if DecodePolyIdType(ref) != kPolyTypeOffMeshConnection { + return nil + } + + index := DecodePolyIdPoly(ref) + if index >= this.m_offMeshConnections.Capacity() { + return nil + } + + salt := DecodePolyIdSalt(ref) + if salt != this.m_offMeshConnections.Get(index).salt { + return nil + } + + return this.m_offMeshConnections.Get(index) +} + +func TestPointInCylinder(point Vector3f, center Vector3f, halfHeight float32, radius float32) bool { + if Sqr(point.x-center.x)+Sqr(point.z-center.z) > Sqr(radius) { + return false + } + return FloatAbs(point.y-center.y) <= halfHeight +} + +func (this *NavMesh) ConnectOffMeshConnectionsToTile(tile *NavMeshTile) { + tileBounds := GetWorldTileBounds(*tile) + agentTypeID := tile.header.agentTypeId + settings := this.m_SurfaceIDToData[tile.surfaceID].m_Settings + for i := this.m_firstOffMeshConnection; i != kNavMeshNullLink; i = this.m_offMeshConnections.Get(i).next { + con := this.m_offMeshConnections.Get(i) + if con.agentTypeID != int32(agentTypeID) { + continue + } + // TODO: it might be possible that adding a new tile allows the end point to be mapped closer. + // if (con.endPoints[0].tileRef && con.endPoints[1].tileRef) + // continue; + if IntersectAABBAABB(con.bounds, tileBounds) { + this.ConnectOffMeshConnection(i, settings.agentRadius, settings.agentClimb) + } + } +} + +type OverlapQuery struct { + m_NavMesh *NavMesh + m_Start Vector3f + m_End Vector3f + m_Height float32 + m_Polys []NavMeshPolyRef + m_OverlapMinMax []float32 + m_PolyCount int + m_MaxPolys int +} + +func NewOverlapQuery( + navmesh *NavMesh, start Vector3f, end Vector3f, height float32, polys []NavMeshPolyRef, overlapMinMax []float32, maxPolys int) OverlapQuery { + return OverlapQuery{ + m_NavMesh: navmesh, m_Start: start, m_End: end, m_Height: height, + m_Polys: polys, m_OverlapMinMax: overlapMinMax, m_PolyCount: 0, m_MaxPolys: maxPolys, + } +} + +func (this *OverlapQuery) ProcessPolygons(tile *NavMeshTile, polyRefs []NavMeshPolyRef, polys []*NavMeshPoly, itemCount int) { + localStart := WorldToTile(tile, this.m_Start) + localEnd := WorldToTile(tile, this.m_End) + + // Find nearest polygon amongst the nearby polygons. + for i := 0; i < itemCount; i++ { + ref := polyRefs[i] + var verts [kNavMeshVertsPerPoly]Vector3f + nverts := this.m_NavMesh.GetPolyGeometry(ref, verts[:], nil, 0) + if nverts == 0 { + continue + } + + var tmin, tmax float32 + var segMin, segMax int32 + if !IntersectSegmentPoly2D(&tmin, &tmax, &segMin, &segMax, localStart, localEnd, verts[:], nverts) { + continue + } + + tmin = FloatClamp(tmin, 0, 1) + tmax = FloatClamp(tmax, 0, 1) + if tmin >= tmax { + continue + } + + if this.m_PolyCount >= this.m_MaxPolys { + return + } + + this.m_Polys[this.m_PolyCount] = ref + this.m_OverlapMinMax[this.m_PolyCount*2+0] = tmin + this.m_OverlapMinMax[this.m_PolyCount*2+1] = tmax + this.m_PolyCount++ + } +} + +func (this *NavMesh) FindPolygonsOverlappingSegment(typeID int32, pa Vector3f, pb Vector3f, height float32, polys []NavMeshPolyRef, overlapMinMax []float32, polyCount *int, maxPolys int) { + + bmin := MinVector3f(pa, pb) + bmax := MaxVector3f(pa, pb) + bmin.y -= height + bmax.y += height + + // Get nearby polygons from proximity grid. + overlap := NewOverlapQuery(this, pa, pb, height, polys, overlapMinMax, maxPolys) + this.QueryPolygons(typeID, bmax.Add(bmin).Mulf(0.5), bmax.Sub(bmin).Mulf(0.5), &overlap) + *polyCount = overlap.m_PolyCount +} + +const kMaxResults = 32 + +func (this *NavMesh) ConnectOffMeshConnection(index uint32, connectRadius float32, connectHeight float32) { + con := this.m_offMeshConnections.Get(index) + conRef := EncodeLinkId(con.salt, index) + if con.width > 0.0 { + // Segment-to-segment connection + + this.UnconnectOffMeshConnection(index) + for i := 0; i < 2; i++ { + var extent Vector3f + if i == 0 { + extent = NormalizeSafe(con.axisX, Vector3f{0, 0, 0}) + } else { + extent = NormalizeSafe(con.axisX, Vector3f{0, 0, 0}).Mulf(con.width * 0.5).Neg() + } + con.endPoints[i].mapped[0] = con.endPoints[i].pos.Sub(extent) + con.endPoints[i].mapped[1] = con.endPoints[i].pos.Add(extent) + var polys [kMaxResults]NavMeshPolyRef + var overlapMinMax [kMaxResults * 2]float32 + count := 0 + this.FindPolygonsOverlappingSegment(con.agentTypeID, con.endPoints[i].mapped[0], con.endPoints[i].mapped[1], connectHeight, polys[:], overlapMinMax[:], &count, kMaxResults) + for j := 0; j < count; j++ { + mappedRef := polys[j] + if mappedRef == 0 { + continue + } + var mappedTile *NavMeshTile + var mappedPoly *NavMeshPoly + if NavMeshStatusFailed(this.GetTileAndPolyByRef(mappedRef, &mappedTile, &mappedPoly)) { + continue + } + + con.endPoints[i].tileRef = NavMeshTileRef(mappedRef) + tmin := overlapMinMax[j*2+0] * 255.0 + tmax := overlapMinMax[j*2+1] * 255.0 + if tmin >= tmax { + continue + } + + // Link off-mesh connection to target poly. + idx := this.m_links.Alloc() + if idx != kNavMeshNullLink { + link := this.m_links.Get(idx) + link.ref = mappedRef + link.edge = uint8(i) + link.side = 0xff + link.bmin = uint8(tmin) + link.bmax = uint8(tmax) + // Add to linked list. + Assert(idx != con.firstLink) + link.next = con.firstLink + con.firstLink = idx + } + + // Start end-point is always connect back to off-mesh connection, + // Destination end-point only if it is bidirectional link. + if i == 0 || (i == 1 && con.linkDirection&byte(kLinkDirectionTwoWay) != 0) { + // Link target poly to off-mesh connection. + idx := this.m_links.Alloc() + if idx != kNavMeshNullLink { + link := this.m_links.Get(idx) + link.ref = conRef + link.edge = uint8(i) + link.side = 0xff + link.bmin = uint8(tmin) + link.bmax = uint8(tmax) + + // Add to linked list. + ip := GetPolyIndex(mappedTile, mappedPoly) + Assert(idx != mappedTile.polyLinks[ip]) + link.next = mappedTile.polyLinks[ip] + mappedTile.polyLinks[ip] = idx + } + } + } + } + } else { + // Point-to-point connection + ext := Vector3f{connectRadius, connectHeight, connectRadius} + for i := 0; i < 2; i++ { + if con.endPoints[i].tileRef != 0 { + continue + } + searchPos := con.endPoints[i].pos + var mappedPos Vector3f + mappedRef := this.FindNearestPoly(con.agentTypeID, searchPos, ext, &mappedPos) + if mappedRef == 0 { + continue + } + if !TestPointInCylinder(mappedPos, searchPos, connectHeight, connectRadius) { + continue + } + + var mappedTile *NavMeshTile + var mappedPoly *NavMeshPoly + if NavMeshStatusFailed(this.GetTileAndPolyByRef(mappedRef, &mappedTile, &mappedPoly)) { + continue + } + + con.endPoints[i].mapped[0] = mappedPos + con.endPoints[i].mapped[1] = mappedPos + con.endPoints[i].tileRef = NavMeshTileRef(mappedRef) + + // Link off-mesh connection to target poly. + idx := this.m_links.Alloc() + if idx != kNavMeshNullLink { + link := this.m_links.Get(idx) + link.ref = mappedRef + link.edge = uint8(i) + link.side = 0xff + link.bmin = 0 + link.bmax = 0 + // Add to linked list. + Assert(idx != con.firstLink) + link.next = con.firstLink + con.firstLink = idx + } + + // Start end-point is always connect back to off-mesh connection, + // Destination end-point only if it is bidirectional link. + if i == 0 || (i == 1 && con.linkDirection&byte(kLinkDirectionTwoWay) != 0) { + // Link target poly to off-mesh connection. + idx := this.m_links.Alloc() + if idx != kNavMeshNullLink { + link := this.m_links.Get(idx) + link.ref = conRef + link.edge = uint8(i) + link.side = 0xff + link.bmin = 0 + link.bmax = 0 + + // Add to linked list. + ip := GetPolyIndex(mappedTile, mappedPoly) + Assert(idx != mappedTile.polyLinks[ip]) + link.next = mappedTile.polyLinks[ip] + mappedTile.polyLinks[ip] = idx + } + } + } + } +} + +func (this *NavMesh) AddOffMeshConnection(params *OffMeshConnectionParams, connectRadius float32, connectHeight float32) NavMeshPolyRef { + index := this.m_offMeshConnections.Alloc() + if index >= uint32(kPolyRefPolyMask) { + this.m_offMeshConnections.Release(index) + return 0 + } + con := this.m_offMeshConnections.Get(index) + + // Retain salt. + salt := con.salt + *con = OffMeshConnection{} + con.salt = salt + + // Add to active off-mesh connection list. + con.next = this.m_firstOffMeshConnection + this.m_firstOffMeshConnection = index + + // fill out connection struct + con.endPoints[0].pos = params.startPos + con.endPoints[1].pos = params.endPos + dir := NormalizeSafe(params.endPos.Sub(params.startPos), Vector3f{0, 0, 0}) + if Magnitude(dir) < 0.00001 { + dir = Vector3f{0, 0, 1} + } + con.axisY = params.up + con.axisX = Cross(con.axisY, dir) + con.axisZ = Cross(con.axisX, con.axisY) + con.width = params.width + con.costModifier = params.costModifier + con.linkDirection = params.linkDirection + con.flags = params.flags + con.area = params.area + con.linkType = params.linkType + con.userID = params.userID + con.agentTypeID = params.agentTypeID + con.bounds.Init() + if con.width > 0.0 { + extent := NormalizeSafe(con.axisX, Vector3f{0, 0, 0}).Mulf(con.width * 0.5) + con.bounds.EncapsulateV(con.endPoints[0].pos.Sub(extent)) + con.bounds.EncapsulateV(con.endPoints[0].pos.Add(extent)) + con.bounds.EncapsulateV(con.endPoints[1].pos.Sub(extent)) + con.bounds.EncapsulateV(con.endPoints[1].pos.Add(extent)) + } else { + con.bounds.EncapsulateV(con.endPoints[0].pos) + con.bounds.EncapsulateV(con.endPoints[1].pos) + } + + con.firstLink = kNavMeshNullLink + dynRef := EncodeLinkId(con.salt, index) + + // Connect + this.ConnectOffMeshConnection(index, connectRadius, connectHeight) + this.BumpTimeStamp() + return dynRef +} + +func (this *NavMesh) UnconnectOffMeshConnectionsToTile(ref NavMeshTileRef) { + tileIndex := DecodePolyIdTile(NavMeshPolyRef(ref)) + for i := this.m_firstOffMeshConnection; i != kNavMeshNullLink; i = this.m_offMeshConnections.Get(i).next { + con := this.m_offMeshConnections.Get(i) + ref := EncodeLinkId(con.salt, i) + for j := 0; j < 2; j++ { + if con.endPoints[j].tileRef == 0 { + continue + } + + // Remove links associated with the tile. + k := con.firstLink + for k != kNavMeshNullLink { + next := this.m_links.Get(k).next + targetTileIndex := DecodePolyIdTile(NavMeshPolyRef(this.m_links.Get(k).ref)) + if targetTileIndex == tileIndex { + this.RemoveLinkBetween(ref, this.m_links.Get(k).ref) + this.RemoveLinkBetween(this.m_links.Get(k).ref, ref) + } + k = next + } + } + } +} + +func (this *NavMesh) UnconnectOffMeshConnection(index uint32) { + // Remove links + con := this.m_offMeshConnections.Get(index) + ref := EncodeLinkId(con.salt, index) + i := con.firstLink + for i != kNavMeshNullLink { + next := this.m_links.Get(i).next + this.RemoveLinkBetween(this.m_links.Get(i).ref, ref) + this.m_links.Release(i) + i = next + } + con.firstLink = kNavMeshNullLink +} + +func (this *NavMesh) RemoveOffMeshConnection(ref NavMeshPolyRef) NavMeshStatus { + if DecodePolyIdType(ref) != kPolyTypeOffMeshConnection { + return kNavMeshFailure | kNavMeshInvalidParam + } + + index := DecodePolyIdPoly(ref) + if index >= this.m_offMeshConnections.Capacity() { + return kNavMeshFailure | kNavMeshInvalidParam + } + + salt := DecodePolyIdSalt(ref) + if salt != this.m_offMeshConnections.Get(index).salt { + return kNavMeshFailure | kNavMeshInvalidParam + } + + // Remove links + this.UnconnectOffMeshConnection(index) + + // Find previous offmesh link to be able to remove from the list. + i := this.m_firstOffMeshConnection + prev := kNavMeshNullLink + for i != kNavMeshNullLink { + if i == index { + break + } + prev = i + i = this.m_offMeshConnections.Get(i).next + } + // Remove from linked list + next := this.m_offMeshConnections.Get(index).next + if prev == kNavMeshNullLink { + this.m_firstOffMeshConnection = next + } else { + this.m_offMeshConnections.Get(prev).next = next + } + + // Bump salt to distinguish deleted connections. + this.m_offMeshConnections.Get(index).salt++ + if this.m_offMeshConnections.Get(index).salt == 0 { + + this.m_offMeshConnections.Get(index).salt = 1 + } + + this.m_offMeshConnections.Release(index) + this.BumpTimeStamp() + return kNavMeshSuccess +} + +func (this *NavMesh) GetFirstLink(ref NavMeshPolyRef) *NavMeshLink { + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.GetOffMeshConnection(ref) + if con == nil { + return nil + } + if con.firstLink == kNavMeshNullLink { + return nil + } + return this.m_links.Get(con.firstLink) + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusFailed(this.GetTileAndPolyByRef(ref, &tile, &poly)) { + return nil + } + + ip := GetPolyIndex(tile, poly) + firstLink := tile.polyLinks[ip] + if firstLink == kNavMeshNullLink { + return nil + } + return this.m_links.Get(firstLink) + } +} + +func (this *NavMesh) GetFirstOffMeshConnection() *OffMeshConnection { + if this.m_firstOffMeshConnection == kNavMeshNullLink { + return nil + } + return this.m_offMeshConnections.Get(this.m_firstOffMeshConnection) +} + +func (this *NavMesh) GetNextOffMeshConnection(data *OffMeshConnection) *OffMeshConnection { + if data == nil { + return nil + } + if data.next == kNavMeshNullLink { + return nil + } + Assert(data.next < this.m_offMeshConnections.Capacity()) + return this.m_offMeshConnections.Get(data.next) +} + +func (this *NavMesh) GetPolyFlags(ref NavMeshPolyRef) uint32 { + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.GetOffMeshConnection(ref) + if con == nil { + return 0 + } + return con.flags + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusFailed(this.GetTileAndPolyByRef(ref, &tile, &poly)) { + return 0 + } + return poly.flags + } +} + +func (this *NavMesh) GetPolyArea(ref NavMeshPolyRef) byte { + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.GetOffMeshConnection(ref) + if con == nil { + return 0 + } + return con.area + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusFailed(this.GetTileAndPolyByRef(ref, &tile, &poly)) { + return 0 + } + return poly.area + } +} + +func (this *NavMesh) GetPolyFlagsAndArea(ref NavMeshPolyRef, flags *uint32, area *byte) { + if flags != nil { + *flags = 0 + } + if area != nil { + *area = 0 + } + + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.GetOffMeshConnection(ref) + if con == nil { + return + } + if flags != nil { + *flags = con.flags + } + if area != nil { + *area = con.area + } + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusFailed(this.GetTileAndPolyByRef(ref, &tile, &poly)) { + + return + } + if flags != nil { + *flags = poly.flags + } + if area != nil { + *area = poly.area + } + } +} + +// Returns vertices and neighbours of polygon pointed to by the polygon reference. +// Note: this function returns 0 if ref is invalid +// Params: +// ref - (in) reference to a polygon. +// verts - (out, optional) pointer to polygon vertices, must have a capacity of at least kNavMeshVertsPerPoly. +// neighbours - (out, optional) pointer to the polygon neighbours, must have a capacity of at least kNavMeshVertsPerPoly*maxNeisPerEdge. +// maxNeisPerEdge - (int) maximum number of neighbours stored in 'neighbours' per edge. +func (this *NavMesh) GetPolyGeometry(ref NavMeshPolyRef, verts []Vector3f, neighbours []NavMeshPolyRef, maxNeisPerEdge int32) int32 { + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + // TODO: should we return off-mesh link geometry? + return 0 + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusFailed(this.GetTileAndPolyByRef(ref, &tile, &poly)) { + + return 0 + } + nverts := poly.vertCount + + // Copy vertices + if verts != nil { + for i := uint8(0); i < nverts; i++ { + verts[i] = tile.verts[poly.verts[i]] + } + } + + // Copy neighbours + if neighbours != nil { + for i := int32(0); i < int32(nverts)*maxNeisPerEdge; i++ { + neighbours[i] = 0 + } + + ip := GetPolyIndex(tile, poly) + firstLink := tile.polyLinks[ip] + for link := this.GetLink(firstLink); link != nil; link = this.GetNextLink(link) { + // Only accept polygon connections. + if DecodePolyIdType(link.ref) == kPolyTypeOffMeshConnection { + continue + } + index := link.edge + if index < nverts { + // find empty slot + for j := int32(0); j < maxNeisPerEdge; j++ { + if neighbours[int32(index)*maxNeisPerEdge+j] == 0 { + neighbours[int32(index)*maxNeisPerEdge+j] = link.ref + break + } + } + } + } + } + return int32(nverts) + } +} diff --git a/pkg/navmesh/nav_mesh.go b/pkg/navmesh/nav_mesh.go new file mode 100644 index 00000000..44262789 --- /dev/null +++ b/pkg/navmesh/nav_mesh.go @@ -0,0 +1,359 @@ +package navmesh + +import ( + "sync" + "unsafe" +) + +const ( + // Maximum number of vertices per navigation polygon. + kNavMeshVertsPerPoly int32 = 6 + kMaxNeis int32 = 4 + kNavMeshMagic int32 = 'D'<<24 | 'N'<<16 | 'A'<<8 | 'V' // 'DNAV'; + kNavMeshVersion int32 = 17 + kNavMeshExtLink uint16 = 0x8000 + kNavMeshNullLink uint32 = 0xffffffff +) + +// Flags for addTile +type NavMeshTileFlags int32 + +const ( + kTileLeakData NavMeshTileFlags = 0x00 // memory is owned by someone else - navmesh should not free it. + kTileFreeData NavMeshTileFlags = 0x01 // Navmesh owns the tile memory and should free it. +) + +type NavMeshLinkDirectionFlags int32 + +const ( + kLinkDirectionOneWay NavMeshLinkDirectionFlags = 0 + kLinkDirectionTwoWay NavMeshLinkDirectionFlags = 1 +) + +// Flags returned by FindStraightPath(). +type NavMeshStraightPathFlags int32 + +const ( + kStraightPathStart NavMeshStraightPathFlags = 0x01 // The vertex is the start position. + kStraightPathEnd NavMeshStraightPathFlags = 0x02 // The vertex is the end position. + kStraightPathOffMeshConnection NavMeshStraightPathFlags = 0x04 // The vertex is start of an off-mesh link. +) + +// Flags describing polygon properties. +type NavMeshPolyTypes int32 + +const ( + kPolyTypeGround uint32 = 0 // Regular ground polygons. + kPolyTypeOffMeshConnection uint32 = 1 // Off-mesh connections. +) + +// Structure describing the navigation polygon data. +type NavMeshPoly struct { + verts [kNavMeshVertsPerPoly]uint16 // Indices to vertices of the poly. + neis [kNavMeshVertsPerPoly]uint16 // Refs to neighbours of the poly. + flags uint32 // Flags (see NavMeshPolyFlags). + vertCount uint8 // Number of vertices. + area uint8 // Area type of the polygon +} + +// The type for the detail mesh vertices index. +type NavMeshPolyDetailIndex uint16 + +type NavMeshPolyRegion uint32 + +// Structure describing polygon detail triangles. +type NavMeshPolyDetail struct { + vertBase uint32 // Offset to detail vertex array. + triBase uint32 // Offset to detail triangle array. + vertCount NavMeshPolyDetailIndex // Number of vertices in the detail mesh. + triCount NavMeshPolyDetailIndex // Number of triangles. +} + +// Structure describing a link to another polygon. +type NavMeshLink struct { + ref NavMeshPolyRef // Neighbour reference. + next uint32 // Index to next link. + edge uint8 // Index to polygon edge which owns this link. + side uint8 // If boundary link, defines on which side the link is. + bmin, bmax uint8 // If boundary link, defines the sub edge area. +} + +type NavMeshBVNode struct { + bmin, bmax [3]uint16 // BVnode bounds + i int32 // Index to item or if negative, escape index. +} + +type OffMeshConnectionParams struct { + startPos Vector3f + endPos Vector3f + up Vector3f + width float32 // If width > 0.0f, link is segment-to-segment. + costModifier float32 // Modify navmesh cost (multiplier applied to euclidean distance) + linkDirection uint8 // Link connection direction flags (NavMeshLinkDirectionFlags) + flags uint32 + area uint8 + linkType uint16 // enum OffMeshLinkType + userID int32 // User ID to identify this connection. + agentTypeID int32 // Which agent type can use this link +} + +type OffMeshLinkEndPoint struct { + pos Vector3f // Position of the end point (based on input) + mapped [2]Vector3f // Position mapped on navmesh + tileRef NavMeshTileRef // Reference to tile when the point is connected - otherwise zero +} + +type OffMeshConnection struct { + agentTypeID int32 // Which agent type can use this link + bounds MinMaxAABB + endPoints [2]OffMeshLinkEndPoint // Connection end points + axisX, axisY, axisZ Vector3f + width float32 // Width of the link. + costModifier float32 // Modify navmesh cost (multiplier applied to euclidean distance) + linkDirection uint8 // Link connection direction flags (NavMeshLinkDirectionFlags) + flags uint32 // Poly flags + area uint8 // Area type + linkType uint16 // enum OffMeshLinkType + userID int32 // User ID to identify this connection. + firstLink uint32 // Index to first link + salt uint32 // Salt of the connection, increased on delete + next uint32 // Next offmesh con in the active linked list, or freelist. +} + +func NewOffMeshConnection() *OffMeshConnection { + return &OffMeshConnection{salt: 1} +} + +type NavMeshDataHeader struct { + magic int32 // Magic number, used to identify the data. + version int32 // Data version number. + x, y int32 // Location of the tile on the grid. + agentTypeId uint32 // User ID of the tile. + polyCount int32 // Number of polygons in the tile. + vertCount int32 // Number of vertices in the tile. + detailMeshCount int32 // Number of detail meshes. + detailVertCount int32 // Number of detail vertices. + detailTriCount int32 // Number of detail triangles. + bvNodeCount int32 // Number of BVtree nodes. + bmin, bmax Vector3f // Bounding box of the tile. + bvQuantFactor float32 // BVtree quantization factor (world to bvnode coords) +} + +type NavMeshTile struct { + surfaceID int32 // Surface where the tile belongs to. + salt uint32 // Counter describing modifications to the tile. + header *NavMeshDataHeader // Pointer to tile header. + polyLinks []uint32 // First link index for each polygon. + polys []NavMeshPoly // Pointer to the polygons (will be updated when tile is added). + verts []Vector3f // Pointer to the vertices (will be updated when tile added). + detailMeshes []NavMeshPolyDetail // Pointer to detail meshes (will be updated when tile added). + detailVerts []Vector3f // Pointer to detail vertices (will be updated when tile added). + detailTris []NavMeshPolyDetailIndex // Pointer to detail triangles (will be updated when tile added). + bvTree []NavMeshBVNode // Pointer to BVtree nodes (will be updated when tile added). + polyRegions []NavMeshPolyRegion + data []byte // Pointer to tile data. + dataSize int32 // Size of the tile data. + flags int32 // Tile flags, see NavMeshTileFlags. + next uint32 // Next tile in spatial grid, or next in freelist. + + // Transform support - consider sharing between a number of tiles + rotation Quaternionf + position Vector3f + transformed int32 +} + +func NewNavMeshTile() *NavMeshTile { + return &NavMeshTile{salt: 1, header: nil} +} + +type NavMeshProcessCallback interface { + ProcessPolygons(tile *NavMeshTile, polyRefs []NavMeshPolyRef, polys []*NavMeshPoly, itemCount int) +} + +type NavMesh struct { + m_SurfaceIDToData map[int32]*SurfaceData + m_tiles TileFreeList + m_links LinkFreeList + m_offMeshConnections OffMeshFreeList + m_firstOffMeshConnection uint32 + m_timeStamp uint32 +} + +// Returns the number of tiles currently allocated. +// Use together with GetTile to access all tiles. +func (this *NavMesh) GetMaxTiles() uint32 { + return this.m_tiles.Capacity() +} + +// Returns a pointer to tile in the tile free list. +// If the tile 'header' pointer is 0, the tile is invalid. +// Params: +// i - (in) Index to the tile to retrieve, max index is GetMaxTiles()-1. +// Returns: Pointer to specified tile. +func (this *NavMesh) GetTile(i int32) *NavMeshTile { + return this.m_tiles.Get(uint32(i)) +} + +func EncodeLinkId(salt uint32, ip uint32) NavMeshPolyRef { + tileMax := uint32(1<> (kPolyRefPolyBits + kPolyRefTypeBits + kPolyRefTileBits) & kPolyRefSaltMask) + *it = uint32(ref >> (kPolyRefPolyBits + kPolyRefTypeBits) & kPolyRefTileMask) + *typ = uint32(ref >> kPolyRefPolyBits & kPolyRefTypeMask) + *ip = uint32(ref & kPolyRefPolyMask) +} + +// Decodes a tile salt. +func DecodePolyIdSalt(ref NavMeshPolyRef) uint32 { + return uint32(ref >> (kPolyRefPolyBits + kPolyRefTypeBits + kPolyRefTileBits) & kPolyRefSaltMask) +} + +// Decodes a tile id. +func DecodePolyIdTile(ref NavMeshPolyRef) uint32 { + return uint32(ref >> (kPolyRefPolyBits + kPolyRefTypeBits) & kPolyRefTileMask) +} + +// Decodes a type. +func DecodePolyIdType(ref NavMeshPolyRef) uint32 { + return uint32(ref >> kPolyRefPolyBits & kPolyRefTypeMask) +} + +// Decodes a poly id. +func DecodePolyIdPoly(ref NavMeshPolyRef) uint32 { + return uint32(ref & kPolyRefPolyMask) +} + +func IsSameTile(ref1, ref2 NavMeshPolyRef) bool { + return DecodePolyIdTile(ref1) == DecodePolyIdTile(ref2) && DecodePolyIdSalt(ref1) == DecodePolyIdSalt(ref2) +} + +func (this *NavMesh) GetNextLink(link *NavMeshLink) *NavMeshLink { + if link == nil { + return nil + } + if link.next == kNavMeshNullLink { + return nil + } + Assert(link.next < this.m_links.Capacity()) + return this.m_links.Get(link.next) +} + +func (this *NavMesh) GetLink(i uint32) *NavMeshLink { + if i == kNavMeshNullLink { + return nil + } + Assert(uint32(i) < this.m_links.Capacity()) + return this.m_links.Get(i) +} + +func (this *NavMesh) BumpTimeStamp() { + this.m_timeStamp += 1 + if this.m_timeStamp == 0 { // use 0 for forcing stale + this.m_timeStamp = 1 + } +} + +func (this *NavMesh) GetTimeStamp() uint32 { + return this.m_timeStamp +} + +type TileLoc struct { + x, y int32 +} + +type SurfaceData struct { + m_Settings NavMeshBuildSettings + m_WorldBounds MinMaxAABB + m_Rotation Quaternionf + m_Position Vector3f + m_TileLUT map[TileLoc]uint32 +} + +func NewSurfaceData() *SurfaceData { + var data SurfaceData + data.m_WorldBounds.Init() + return &data +} + +var ( + s_SurfaceIDGen = int32(1) + s_SurfaceMutex sync.Mutex +) + +func NexSurfaceId() int32 { + s_SurfaceMutex.Lock() + id := s_SurfaceIDGen + s_SurfaceIDGen++ + s_SurfaceMutex.Unlock() + return id +} + +var navMeshPolySize = unsafe.Sizeof(NavMeshPoly{}) + +func GetPolyIndex(tile *NavMeshTile, poly *NavMeshPoly) uint32 { + Assert(poly != nil) + Assert(tile != nil) + Assert(tile.header != nil) + start := uintptr(unsafe.Pointer(&tile.polys[0])) + end := uintptr(unsafe.Pointer(poly)) + ip := int32((end - start) / navMeshPolySize) + Assert(ip < tile.header.polyCount) + return uint32(ip) +} + +func TileToWorld(tile *NavMeshTile, position Vector3f) Vector3f { + if tile.transformed == 0 { + return position + } + var mat Matrix4x4f + mat.SetTR(tile.position, tile.rotation) + return mat.MultiplyPoint3(position) +} + +func TileToWorldVector(tile *NavMeshTile, direction Vector3f) Vector3f { + if tile.transformed == 0 { + return direction + } + var mat Matrix4x4f + mat.SetTR(tile.position, tile.rotation) + return mat.MultiplyVector3(direction) +} + +func TileToWorldBatch(worldPositions []Vector3f, tile *NavMeshTile, npositions int, positions []Vector3f) { + if tile.transformed != 0 { + var mat Matrix4x4f + mat.SetTR(tile.position, tile.rotation) + for i := 0; i < npositions; i++ { + worldPositions[i] = mat.MultiplyPoint3(positions[i]) + } + return + } + + for i := 0; i < npositions; i++ { + worldPositions[i] = positions[i] + } +} + +func WorldToTile(tile *NavMeshTile, position Vector3f) Vector3f { + if tile.transformed == 0 { + return position + } + var mat Matrix4x4f + mat.SetTRInverse(tile.position, tile.rotation) + return mat.MultiplyPoint3(position) +} diff --git a/pkg/navmesh/nav_mesh_build_setting.go b/pkg/navmesh/nav_mesh_build_setting.go new file mode 100644 index 00000000..b0463fe0 --- /dev/null +++ b/pkg/navmesh/nav_mesh_build_setting.go @@ -0,0 +1,32 @@ +package navmesh + +var ( + kMinAgentRadius float32 = 0.05 + kMinAgentHeight float32 = 0.001 + kMaxSlopeAngle float32 = 60.0 + kMinCellSize float32 = 0.01 +) + +const ( + kInvalidAgentTypeID int32 = -1 + kDefaultAgentTypeID int32 = 0 + kAreaCount int32 = 32 +) + +type NavMeshBuildSettings struct { + agentTypeID int32 + agentRadius float32 + agentHeight float32 + agentSlope float32 + agentClimb float32 + ledgeDropHeight float32 + maxJumpAcrossDistance float32 + + // Advanced + minRegionArea float32 + manualCellSize int32 + cellSize float32 + manualTileSize int32 + tileSize int32 + accuratePlacement int32 +} diff --git a/pkg/navmesh/nav_mesh_carve_types.go b/pkg/navmesh/nav_mesh_carve_types.go new file mode 100644 index 00000000..4fd19857 --- /dev/null +++ b/pkg/navmesh/nav_mesh_carve_types.go @@ -0,0 +1,182 @@ +package navmesh + +type NavMeshObstacleShape int32 + +const ( + kObstacleShapeCapsule NavMeshObstacleShape = iota + kObstacleShapeBox +) + +type NavMeshCarveShape struct { + shape NavMeshObstacleShape // NavMeshObstacleShape + center Vector3f + extents Vector3f + xAxis Vector3f + yAxis Vector3f + zAxis Vector3f + bounds MinMaxAABB +} + +func (this *NavMeshCarveShape) GetBounds() MinMaxAABB { + return this.bounds +} + +type CarveData struct { + m_SurfaceID int32 + m_TileIndex int32 + m_Position Vector3f + m_Rotation Quaternionf + m_Shapes []NavMeshCarveShape +} + +type Shapes []NavMeshCarveShape + +func (this Shapes) Len() int { + return len(this) +} + +func (this Shapes) Less(i, j int) bool { + lhs := this[i] + rhs := this[j] + if lhs.center.x < rhs.center.x { + return true + } + if rhs.center.x < lhs.center.x { + return false + } + + // rhs.x == lhs.x + if lhs.center.z < rhs.center.z { + return true + } + if rhs.center.z < lhs.center.z { + return false + } + + // rhs.x == lhs.x && rhs.z == lhs.z + if lhs.center.y < rhs.center.y { + return true + } + if rhs.center.y < lhs.center.y { + return false + } + + // all same - favour the biggest + return SqrMagnitude(lhs.extents) > SqrMagnitude(rhs.extents) +} + +func (this Shapes) Swap(i, j int) { + this[i], this[j] = this[j], this[i] +} + +func NewCarveData(surfaceID int32, tileIndex int32) *CarveData { + return &CarveData{ + m_SurfaceID: surfaceID, + m_TileIndex: tileIndex, + } +} + +func (this *CarveData) AddShape(shape NavMeshCarveShape) { + this.m_Shapes = append(this.m_Shapes, shape) +} + +func (this *CarveData) Empty() bool { + return len(this.m_Shapes) == 0 +} + +type NavMeshObstacle struct { + m_VersionStamp int32 + m_Shape NavMeshObstacleShape + m_Extents Vector3f + m_Scale Vector3f + m_Center Vector3f + m_Position Vector3f + m_Rotation Quaternionf +} + +func NewNavMeshObstacle(shape NavMeshObstacleShape, position, scale Vector3f, rotation Quaternionf) *NavMeshObstacle { + obs := &NavMeshObstacle{ + m_VersionStamp: 0, + m_Shape: shape, + m_Extents: NewVector3f(0.5, 0.5, 0.5), + m_Center: NewVector3f(0, 0, 0), + m_Scale: scale, + m_Rotation: rotation, + m_Position: position, + } + return obs +} + +func (this *NavMeshObstacle) SetSize(size Vector3f) { + this.SetExtents(size.Mulf(0.5)) +} + +func (this *NavMeshObstacle) SetCenter(center Vector3f) { + this.m_Center = center +} + +func (this *NavMeshObstacle) GetVersionStamp() int32 { + return this.m_VersionStamp +} + +func (this *NavMeshObstacle) GetCarveShape(shape *NavMeshCarveShape) { + shape.shape = this.m_Shape + shape.extents = this.GetWorldExtents() + this.GetWorldCenterAndAxes(&shape.center, &shape.xAxis, &shape.yAxis, &shape.zAxis) + var worldExtents Vector3f + if this.m_Shape == kObstacleShapeCapsule { + CalcCapsuleWorldExtents(&worldExtents, shape.extents, shape.xAxis, shape.yAxis, shape.zAxis) + } else { + CalcBoxWorldExtents(&worldExtents, shape.extents, shape.xAxis, shape.yAxis, shape.zAxis) + } + shape.bounds = NewMinMaxAABB(shape.center.Sub(worldExtents), shape.center.Add(worldExtents)) +} + +func (this *NavMeshObstacle) GetWorldExtents() Vector3f { + var matrix Matrix4x4f + matrix.SetTRS(this.m_Position, this.m_Rotation, this.m_Scale) + absScale := matrix.GetLossyScale() + if this.m_Shape == kObstacleShapeCapsule { + scaledRadius := this.m_Extents.x * FloatMax(absScale.x, absScale.z) + scaledHeight := this.m_Extents.y * absScale.y + return NewVector3f(scaledRadius, scaledHeight, scaledRadius) + } else { + return ScaleVector3f(this.m_Extents, absScale) + } +} + +func (this *NavMeshObstacle) GetWorldCenterAndAxes(center, xAxis, yAxis, zAxis *Vector3f) { + // const Transform& transform = GetComponent(); + + // center = transform.TransformPoint(m_Center); + // Quaternionf rotation = transform.GetRotation(); + var matrix Matrix4x4f + matrix.SetTRS(this.m_Position, this.m_Rotation, this.m_Scale) + *center = matrix.MultiplyPoint3(this.m_Center) + + var rotationMatrix Matrix3x3f + QuaternionToMatrix3(this.m_Rotation, &rotationMatrix) + *xAxis = rotationMatrix.GetAxisX() + *yAxis = rotationMatrix.GetAxisY() + *zAxis = rotationMatrix.GetAxisZ() +} + +func (this *NavMeshObstacle) SetExtents(mulf Vector3f) { + this.m_Extents = mulf +} + +func EnsurePositive(value float32) float32 { + return FloatMax(0.00001, value) +} + +func (this *NavMeshObstacle) SetHeight(value float32) { + positiveHeight := EnsurePositive(value) + newExtents := NewVector3f(this.m_Extents.x, positiveHeight*0.5, this.m_Extents.z) + this.SetExtents(newExtents) +} + +func (this *NavMeshObstacle) SetRadius(value float32) { + positiveRadius := EnsurePositive(value) + newExtents := NewVector3f(positiveRadius, this.m_Extents.y, positiveRadius) + this.SetExtents(newExtents) +} diff --git a/pkg/navmesh/nav_mesh_carving.cpp.go b/pkg/navmesh/nav_mesh_carving.cpp.go new file mode 100644 index 00000000..8130e542 --- /dev/null +++ b/pkg/navmesh/nav_mesh_carving.cpp.go @@ -0,0 +1,264 @@ +package navmesh + +import ( + "sort" +) + +func (this *NavMeshCarving) AddObstacle(obstacle *NavMeshObstacle, handle *int32) { + size := len(this.m_ObstacleFreelist) + if size != 0 { + *handle = this.m_ObstacleFreelist[size-1] + this.m_ObstacleFreelist = this.m_ObstacleFreelist[:size-1] + } else { + *handle = int32(len(this.m_ObstacleInfo)) + this.m_ObstacleInfo = append(this.m_ObstacleInfo, ObstacleCarveInfo{}) + } + + info := &this.m_ObstacleInfo[*handle] + info.obstacle = obstacle + info.versionStamp = -1 + info.shape = NavMeshCarveShape{} +} + +func (this *NavMeshCarving) RemoveObstacle(handle *int32) { + Assert(*handle >= 0 && *handle < int32(len(this.m_ObstacleInfo))) + this.m_ObstacleInfo[*handle].obstacle = nil + this.m_DirtyBounds = append(this.m_DirtyBounds, this.m_ObstacleInfo[*handle].bounds) + this.m_ObstacleFreelist = append(this.m_ObstacleFreelist, *handle) + *handle = -1 +} + +func (this *NavMeshCarving) Carve() { + Assert(len(this.m_TileCarveData) == len(this.m_CarveResults)) + if len(this.m_TileCarveData) == 0 { + return + } + + for i := range this.m_TileCarveData { + this.CarveOne(&this.m_TileCarveData[i], &this.m_CarveResults[i]) + } +} + +func (this *NavMeshCarving) CarveOne(carveData *CarveData, res *CarveResult) { + surfaceID := carveData.m_SurfaceID + tileIndex := carveData.m_TileIndex + res.status = kRemoveTile + res.carvedData = nil + res.carvedDataSize = 0 + + // Get source tile data + sourceTile := this.m_NavMeshManager.GetSourceTileData(surfaceID, tileIndex) + if sourceTile == nil { + return + } + + settings := this.m_NavMeshManager.GetNavMeshBuildSettings(surfaceID) + height := settings.agentHeight + radius := settings.agentRadius + cellSize := settings.cellSize + quantSize := cellSize / 64.0 + + // This tile requires carving, carve based on source data. + sourceData := sourceTile.GetData() + sourceDataSize := len(sourceData) + + sort.Sort(Shapes(carveData.m_Shapes)) + res.status = CarveNavMeshTile(&res.carvedData, &res.carvedDataSize, sourceData, int32(sourceDataSize), + carveData.m_Shapes, len(carveData.m_Shapes), + height, radius, quantSize, carveData.m_Position, carveData.m_Rotation) +} + +type TileLocation struct { + m_Bounds MinMaxAABB + m_SurfaceID int32 + m_TileIndex int32 +} + +func (this *NavMeshCarving) PrepareCarving() { + if len(this.m_ObstacleInfo) == 0 && len(this.m_DirtyBounds) == 0 { + return + } + + // Update the bounds for carving + // Dirty previously carved bounds if obstacle moves + var updateBounds []MinMaxAABB + obstacleCount := len(this.m_ObstacleInfo) + for i := 0; i < obstacleCount; i++ { + if this.m_ObstacleInfo[i].obstacle == nil { + continue + } + + // If the obstacle has not changed, no need to update. + if this.m_ObstacleInfo[i].versionStamp == this.m_ObstacleInfo[i].obstacle.GetVersionStamp() { + continue + } + + this.m_ObstacleInfo[i].versionStamp = this.m_ObstacleInfo[i].obstacle.GetVersionStamp() + + // Mark previously carved bounds as dirty. + // this.m_DirtyBounds = append(this.m_DirtyBounds, this.m_ObstacleInfo[i].bounds) + + // Get new carve data and mark the new location to be updated. + shape := &this.m_ObstacleInfo[i].shape + this.m_ObstacleInfo[i].obstacle.GetCarveShape(shape) + this.m_ObstacleInfo[i].bounds = shape.bounds + updateBounds = append(updateBounds, this.m_ObstacleInfo[i].bounds) + } + + // No tiles or obstacles changed + if len(updateBounds) == 0 && len(this.m_DirtyBounds) == 0 { + return + } + + var locations []TileLocation + manager := this.m_NavMeshManager + manager.GetSourceTileDataBounds(&locations) + + currentSurfaceID := int32(0) + cachedIsDirty := false + var cachedTilePosition Vector3f + var cachedTileRotation Quaternionf + var cachedTileTransform Matrix4x4f + navmesh := manager.GetNavMesh() + + for i := 0; i < len(locations); i++ { + loc := locations[i] + tileBounds := loc.m_Bounds + settings := manager.GetNavMeshBuildSettings(loc.m_SurfaceID) + walkableHeight := settings.agentHeight + walkableRadius := settings.agentRadius + + // Extend the tile bounds by the carving dimensions + // Note that the asymmetry in the vertical direction - which includes tiles below carving object, but not above + // Carve hull is expanded so that some corners are offset up to (and a little over) sqrt (2) * radius. + kOffsetRadius := walkableRadius * 1.415 + tileBounds.m_Min.x -= kOffsetRadius + tileBounds.m_Min.z -= kOffsetRadius + + tileBounds.m_Max.x += kOffsetRadius + tileBounds.m_Max.y += walkableHeight + tileBounds.m_Max.z += kOffsetRadius + + // TODO: clean up - the outer loop should be over surfaces + if currentSurfaceID != loc.m_SurfaceID { + navmesh.GetSurfaceTransform(loc.m_SurfaceID, &cachedTilePosition, &cachedTileRotation) + cachedTileTransform.SetTR(cachedTilePosition, cachedTileRotation) + cachedIsDirty = false + currentSurfaceID = loc.m_SurfaceID + } + + var worldTileBounds MinMaxAABB + TransformAABBSlow(tileBounds, cachedTileTransform, &worldTileBounds) + carveData := NewCarveData(loc.m_SurfaceID, loc.m_TileIndex) + carveData.m_Position = cachedTilePosition + carveData.m_Rotation = cachedTileRotation + if cachedIsDirty { + // Surface is dirty - this tile should be carved if any obstacle overlaps + for j := 0; j < len(this.m_ObstacleInfo); j++ { + info := this.m_ObstacleInfo[j] + if info.obstacle != nil { + if IntersectAABBAABB(info.bounds, worldTileBounds) { + carveData.AddShape(info.shape) + } + } + } + if !carveData.Empty() { + this.m_TileCarveData = append(this.m_TileCarveData, *carveData) + } + + // Intentionally ignore the dirty-bounds vs. dirty-tile overlap (restore tile) + // assuming the dirty-tile is just loaded - and hence restoring is needless. + } else { + if this.NeedsUpdateCollectCarveData(carveData, worldTileBounds, updateBounds) { + this.m_TileCarveData = append(this.m_TileCarveData, *carveData) + } + } + } + + this.m_CarveResults.resize_initialized(len(this.m_TileCarveData)) + this.m_DirtyBounds = this.m_DirtyBounds[:0] +} + +func CompareCarveShapes(lhs, rhs *NavMeshCarveShape) bool { + if lhs.center.x < rhs.center.x { + return true + } + if rhs.center.x < lhs.center.x { + return false + } + + // rhs.x == lhs.x + if lhs.center.z < rhs.center.z { + return true + } + if rhs.center.z < lhs.center.z { + return false + } + + // rhs.x == lhs.x && rhs.z == lhs.z + if lhs.center.y < rhs.center.y { + return true + } + if rhs.center.y < lhs.center.y { + return false + } + + // all same - favour the biggest + return SqrMagnitude(lhs.extents) > SqrMagnitude(rhs.extents) +} + +func (this *NavMeshCarving) ApplyCarveResults() bool { + carved := false + + Assert(len(this.m_TileCarveData) == len(this.m_CarveResults)) + manager := this.m_NavMeshManager + for i := 0; i < len(this.m_TileCarveData); i++ { + carveData := &this.m_TileCarveData[i] + surfaceID := carveData.m_SurfaceID + tileIndex := carveData.m_TileIndex + res := &this.m_CarveResults[i] + status := res.status + if status == kRestoreTile { + manager.RestoreTile(surfaceID, tileIndex) + } else if status == kReplaceTile { + carved = true + manager.RemoveTile(surfaceID, tileIndex) + if res.carvedData != nil && res.carvedDataSize > 0 { + manager.ReplaceTile(surfaceID, tileIndex, res.carvedData, int32(res.carvedDataSize)) + } + } else { + Assert(status == kRemoveTile) + carved = true + manager.RemoveTile(surfaceID, tileIndex) + } + } + + this.m_TileCarveData = this.m_TileCarveData[:0] + this.m_CarveResults = this.m_CarveResults[:0] + return carved +} + +func AnyOverlaps(arrayOfBounds []MinMaxAABB, bounds MinMaxAABB) bool { + count := len(arrayOfBounds) + for i := 0; i < count; i++ { + if IntersectAABBAABB(arrayOfBounds[i], bounds) { + return true + } + } + return false +} + +func (this *NavMeshCarving) NeedsUpdateCollectCarveData(carveData *CarveData, bounds MinMaxAABB, + updateBounds []MinMaxAABB) bool { + dirtyOverlaps := AnyOverlaps(this.m_DirtyBounds, bounds) + if dirtyOverlaps || AnyOverlaps(updateBounds, bounds) { + for i := 0; i < len(this.m_ObstacleInfo); i++ { + if this.m_ObstacleInfo[i].obstacle != nil { + if IntersectAABBAABB(this.m_ObstacleInfo[i].bounds, bounds) { + carveData.AddShape(this.m_ObstacleInfo[i].shape) + } + } + } + } + return dirtyOverlaps || !carveData.Empty() +} diff --git a/pkg/navmesh/nav_mesh_carving.go b/pkg/navmesh/nav_mesh_carving.go new file mode 100644 index 00000000..d7041062 --- /dev/null +++ b/pkg/navmesh/nav_mesh_carving.go @@ -0,0 +1,44 @@ +package navmesh + +type CarveResult struct { + carvedData []byte + carvedDataSize uint32 + status CarveResultStatus // CarveResultStatus +} + +type ObstacleCarveInfo struct { + shape NavMeshCarveShape // Current shape + bounds MinMaxAABB // Current bounds, cached from shape to allow matching add/remove. + obstacle *NavMeshObstacle + versionStamp int32 +} + +type CarveResultContainer []CarveResult + +func (c *CarveResultContainer) resize_initialized(size int) { + if cap(*c) >= size { + *c = (*c)[:size] + } else { + *c = append(*c, make([]CarveResult, size-len(*c))...) + } +} + +type NavMeshCarving struct { + m_NavMeshManager *NavMeshManager + m_TileCarveData []CarveData + m_ObstacleInfo []ObstacleCarveInfo + m_ObstacleFreelist []int32 + m_DirtyBounds []MinMaxAABB + m_CarveResults CarveResultContainer +} + +func NewNavMeshCarving(manager *NavMeshManager) *NavMeshCarving { + return &NavMeshCarving{ + m_NavMeshManager: manager, + m_TileCarveData: nil, + m_ObstacleInfo: nil, + m_ObstacleFreelist: nil, + m_DirtyBounds: nil, + m_CarveResults: nil, + } +} diff --git a/pkg/navmesh/nav_mesh_data.go b/pkg/navmesh/nav_mesh_data.go new file mode 100644 index 00000000..8df68e99 --- /dev/null +++ b/pkg/navmesh/nav_mesh_data.go @@ -0,0 +1,221 @@ +package navmesh + +import ( + "hk4e/pkg/navmesh/format" +) + +type NavMeshData struct { + m_NavMeshBuildSettings NavMeshBuildSettings + m_NavMeshTiles []NavMeshTileData + m_HeightMeshes []HeightMeshData + m_OffMeshLinks []AutoOffMeshLinkData + m_FilterAreaCosts []float32 + m_SourceBounds AABB + m_Rotation Quaternionf + m_Position Vector3f + m_AgentTypeID int32 +} + +func (this *NavMeshData) GetPosition() Vector3f { + return this.m_Position +} + +func (this *NavMeshData) GetRotation() Quaternionf { + return this.m_Rotation +} + +func (this *NavMeshData) GetNavMeshTiles() []NavMeshTileData { + return this.m_NavMeshTiles +} + +func (this *NavMeshData) GetNavMeshBuildSettings() NavMeshBuildSettings { + return this.m_NavMeshBuildSettings +} + +func (this *NavMeshData) GetOffMeshLinks() []AutoOffMeshLinkData { + return this.m_OffMeshLinks +} + +func (this *NavMeshData) GetFilterAreaCosts() []float32 { + return this.m_FilterAreaCosts +} + +func (this *NavMeshData) AddOffMeshLink(source, target Vector3f, area, linkDirection byte) { + this.m_OffMeshLinks = append(this.m_OffMeshLinks, + AutoOffMeshLinkData{m_Start: source, m_End: target, + m_Area: area, m_LinkDirection: linkDirection}) +} + +func (this *NavMeshData) GetAgentTypeId() int32 { + return this.m_AgentTypeID +} + +func (this *NavMeshData) Clone() *NavMeshData { + data := NavMeshData{} + data.m_NavMeshBuildSettings = this.m_NavMeshBuildSettings + data.m_SourceBounds = this.m_SourceBounds + data.m_Rotation = this.m_Rotation + data.m_Position = this.m_Position + data.m_AgentTypeID = this.m_AgentTypeID + + data.m_NavMeshTiles = make([]NavMeshTileData, len(this.m_NavMeshTiles)) + for i := range this.m_NavMeshTiles { + otile := this.m_NavMeshTiles[i] + ntile := &data.m_NavMeshTiles[i] + ntile.m_Hash = otile.m_Hash + ntile.m_MeshData = make([]byte, len(otile.m_MeshData)) + copy(ntile.m_MeshData, otile.m_MeshData) + } + + data.m_HeightMeshes = make([]HeightMeshData, len(this.m_HeightMeshes)) + for i := range this.m_HeightMeshes { + omesh := this.m_HeightMeshes[i] + nmesh := &this.m_HeightMeshes[i] + nmesh.m_Bounds = omesh.m_Bounds + nmesh.m_Vertices = make([]Vector3f, len(omesh.m_Vertices)) + copy(nmesh.m_Vertices, omesh.m_Vertices) + nmesh.m_Indices = make([]int32, len(omesh.m_Indices)) + copy(nmesh.m_Indices, omesh.m_Indices) + nmesh.m_Nodes = make([]HeightMeshBVNode, len(omesh.m_Nodes)) + copy(nmesh.m_Nodes, omesh.m_Nodes) + } + + data.m_OffMeshLinks = make([]AutoOffMeshLinkData, len(this.m_OffMeshLinks)) + copy(data.m_OffMeshLinks, this.m_OffMeshLinks) + + data.m_FilterAreaCosts = make([]float32, len(this.m_FilterAreaCosts)) + copy(data.m_FilterAreaCosts, this.m_FilterAreaCosts) + return &data +} + +type NavMeshTileData struct { + m_MeshData []byte + m_Hash [16]byte +} + +func (this NavMeshTileData) GetData() []byte { + return this.m_MeshData +} + +type HeightMeshData struct { + m_Vertices []Vector3f + m_Indices []int32 + m_Nodes []HeightMeshBVNode + m_Bounds AABB +} + +type AutoOffMeshLinkData struct { + m_Start Vector3f + m_End Vector3f + m_Radius float32 + m_LinkType uint16 // Off-mesh poly flags. + m_Area byte // Off-mesh poly area ids. + m_LinkDirection byte // Off-mesh connection direction flags (NavMeshLinkDirectionFlags) +} + +type HeightMeshBVNode struct { + min, max Vector3f + i, n int32 +} + +func fromVector3f(data format.Vector3f) Vector3f { + return Vector3f{data.X, data.Y, data.Z} +} + +func fromAABB(data format.AABB) AABB { + return AABB{ + fromVector3f(data.M_Center), fromVector3f(data.M_Extent), + } +} + +func fromHeightMeshBVNode(data *format.HeightMeshBVNode) HeightMeshBVNode { + return HeightMeshBVNode{ + fromVector3f(data.Min), fromVector3f(data.Max), data.I, data.N, + } +} + +func fromHeightMeshData(data *format.HeightMeshData) HeightMeshData { + var nvData HeightMeshData + nvData.m_Indices = data.M_Indices + nvData.m_Bounds = fromAABB(data.M_Bounds) + nvData.m_Nodes = make([]HeightMeshBVNode, len(data.M_Nodes), len(data.M_Nodes)) + for i := range data.M_Nodes { + nvData.m_Nodes[i] = fromHeightMeshBVNode(&data.M_Nodes[i]) + } + nvData.m_Vertices = make([]Vector3f, len(data.M_Vertices), len(data.M_Vertices)) + for i := range data.M_Vertices { + nvData.m_Vertices[i] = fromVector3f(data.M_Vertices[i]) + } + return nvData +} + +func fromNavMeshBuildSetting(data *format.NavMeshBuildSettings) NavMeshBuildSettings { + return NavMeshBuildSettings{ + data.AgentTypeID, data.AgentRadius, data.AgentHeight, + data.AgentSlope, data.AgentClimb, data.LedgeDropHeight, + data.MaxJumpAcrossDistance, data.MinRegionArea, data.ManualCellSize, + data.CellSize, data.ManualTileSize, data.TileSize, data.AccuratePlacement, + } +} + +func fromQuaterionf(data format.Quaternionf) Quaternionf { + return Quaternionf{ + data.X, data.Y, data.Z, data.W, + } +} + +func fromNavMeshTileData(data *format.NavMeshTileData) NavMeshTileData { + return NavMeshTileData{ + data.M_MeshData, data.M_Hash, + } +} + +func fromOffMeshLinkData(data *format.AutoOffMeshLinkData) AutoOffMeshLinkData { + var linkDirection byte + if data.M_LinkDirection { + linkDirection = 1 + } + return AutoOffMeshLinkData{ + fromVector3f(data.M_Start), fromVector3f(data.M_End), data.M_Radius, + data.M_LinkType, data.M_Area, linkDirection, + } +} + +func NewDataFromFormat(data *format.NavMeshData) *NavMeshData { + var nvData NavMeshData + nvData.m_AgentTypeID = data.M_AgentTypeID + nvData.m_Position = fromVector3f(data.M_Position) + nvData.m_NavMeshBuildSettings = fromNavMeshBuildSetting(&data.M_NavMeshBuildSettings) + nvData.m_SourceBounds = fromAABB(data.M_SourceBounds) + nvData.m_Rotation = fromQuaterionf(data.M_Rotation) + nvData.m_HeightMeshes = make([]HeightMeshData, len(data.M_HeightMeshes), len(data.M_HeightMeshes)) + for i := range data.M_HeightMeshes { + nvData.m_HeightMeshes[i] = fromHeightMeshData(&data.M_HeightMeshes[i]) + } + nvData.m_NavMeshTiles = make([]NavMeshTileData, len(data.M_NavMeshTiles), len(data.M_NavMeshTiles)) + for i := range data.M_NavMeshTiles { + nvData.m_NavMeshTiles[i] = fromNavMeshTileData(&data.M_NavMeshTiles[i]) + } + nvData.m_OffMeshLinks = make([]AutoOffMeshLinkData, len(data.M_AdditionalData.OffMeshLinks), len(data.M_AdditionalData.OffMeshLinks)) + for i := range data.M_AdditionalData.OffMeshLinks { + nvData.m_OffMeshLinks[i] = fromOffMeshLinkData(&data.M_AdditionalData.OffMeshLinks[i]) + } + nvData.m_FilterAreaCosts = make([]float32, kMaxAreas, kMaxAreas) + copy(nvData.m_FilterAreaCosts, data.M_AdditionalData.AreaCosts) + return &nvData +} + +func NewNavMeshObstacleFromFormat(obsInfo format.SceneObsData) *NavMeshObstacle { + position := fromVector3f(obsInfo.Position) + scale := fromVector3f(obsInfo.Scale) + rotation := fromQuaterionf(obsInfo.Rotation) + obs := NewNavMeshObstacle(NavMeshObstacleShape(obsInfo.Shape), position, scale, rotation) + obs.SetCenter(fromVector3f(obsInfo.Center)) + if obsInfo.Shape == 1 { + obs.SetSize(fromVector3f(obsInfo.Size)) + } else { + obs.SetHeight(obsInfo.Height) + obs.SetRadius(obsInfo.Radius) + } + return obs +} diff --git a/pkg/navmesh/nav_mesh_manager.go b/pkg/navmesh/nav_mesh_manager.go new file mode 100644 index 00000000..8d168f9e --- /dev/null +++ b/pkg/navmesh/nav_mesh_manager.go @@ -0,0 +1,588 @@ +package navmesh + +import ( + "fmt" + "math" + "math/rand" + "unsafe" + + "hk4e/pkg/navmesh/format" +) + +const kNodePoolSize int32 = 4096 + +type NavMeshHit struct { + position Vector3f + normal Vector3f + distance float32 + mask uint32 + hit bool +} + +func (this *NavMeshHit) GetPosition() Vector3f { + return this.position +} + +func (this *NavMeshHit) GetNormal() Vector3f { + return this.normal +} + +func (this *NavMeshHit) GetDistance() float32 { + return this.distance +} + +func (this *NavMeshHit) GetMask() uint32 { + return this.mask +} + +func (this *NavMeshHit) Hit() bool { + return this.hit +} + +type NavMeshManager struct { + m_SurfaceID int32 + m_CarvingSystem *NavMeshCarving + m_NavMeshData *NavMeshData + m_NavMesh *NavMesh + m_NavMeshQuery *NavMeshQuery + m_Filter *QueryFilter + m_LegacyQueryExtents Vector3f + m_LegacyLinkQueryExtents Vector3f + m_AddedTileRefs []NavMeshTileRef +} + +func NewManagerFromData(nvData *format.NavMeshData) (*NavMeshManager, error) { + data := NewDataFromFormat(nvData) + manager := NewNavMeshManager() + err := manager.LoadData(data) + return manager, err +} + +func NewNavMeshManager() *NavMeshManager { + navMesh := NewNavMesh() + query := NewNavMeshQuery(navMesh, kNodePoolSize) + return &NavMeshManager{0, nil, + nil, + navMesh, + query, + NewQueryFilter(), + Vector3f{0, 0, 0}, + Vector3f{0, 0, 0}, nil, + } +} + +func (this *NavMeshManager) Clone() *NavMeshManager { + filter := *this.m_Filter + return &NavMeshManager{this.m_SurfaceID, nil, + nil, + this.m_NavMesh, NewNavMeshQuery(this.m_NavMesh, kNodePoolSize), &filter, + this.m_LegacyQueryExtents, this.m_LegacyLinkQueryExtents, nil, + } +} + +func (this *NavMeshManager) DeepClone() *NavMeshManager { + manager := NewNavMeshManager() + // data := this.m_NavMeshData.Clone() + manager.LoadData(this.m_NavMeshData) + return manager +} + +func (this *NavMeshManager) LoadData(nvData *NavMeshData) error { + this.m_NavMeshData = nvData + this.m_CarvingSystem = NewNavMeshCarving(this) + position := nvData.GetPosition() + rotation := nvData.GetRotation() + settings := nvData.GetNavMeshBuildSettings() + + this.m_Filter.SetAreaCosts(nvData.GetFilterAreaCosts()) + this.m_LegacyQueryExtents = Vector3f{settings.agentRadius, settings.agentHeight, settings.agentRadius} + this.m_LegacyLinkQueryExtents = Vector3f{settings.agentRadius, settings.agentClimb, settings.agentRadius} + tiles := nvData.GetNavMeshTiles() + surfaceID := this.m_NavMesh.CreateSurface(len(tiles), settings, position, rotation) + this.m_SurfaceID = surfaceID + this.m_AddedTileRefs = make([]NavMeshTileRef, len(tiles)) + for i := range tiles { + tile := tiles[i] + data := tile.GetData() + if len(data) == 0 { + continue + } + var ref NavMeshTileRef + status := this.m_NavMesh.AddTile(data, int32(len(data)), kTileLeakData, surfaceID, &ref) + if NavMeshStatusFailed(status) { + if NavMeshStatusDetail(status, kNavMeshWrongMagic) || NavMeshStatusDetail(status, kNavMeshWrongVersion) { + return fmt.Errorf("Loading NavMesh failed - wrong format. Please rebake the NavMesh") + } else if NavMeshStatusDetail(status, kNavMeshOutOfMemory) { + return fmt.Errorf("Loading NavMesh failed - out of memory") + } else { + return fmt.Errorf("Loading NavMesh tile #%d failed. Error code:%x", i, status) + } + } + this.m_AddedTileRefs[i] = ref + } + + // server temporarily no use offMeshLinks data + offMeshLinks := nvData.GetOffMeshLinks() + for i := range offMeshLinks { + continue + data := offMeshLinks[i] + var conn OffMeshConnectionParams + conn.startPos = data.m_Start + conn.endPos = data.m_End + conn.up = Vector3f{0, 1, 0} + conn.width = 0.0 + conn.costModifier = -1.0 + conn.linkDirection = data.m_LinkDirection + conn.flags = 1 << data.m_Area + conn.area = data.m_Area + conn.linkType = data.m_LinkType + conn.userID = 0 + conn.agentTypeID = nvData.GetAgentTypeId() + ref := this.m_NavMesh.AddOffMeshConnection(&conn, settings.agentRadius, settings.agentClimb) + if ref == 0 { + return fmt.Errorf("add offmeshlink failed") + } + } + + return nil +} + +func InvalidateNavMeshHit(hit *NavMeshHit) { + inf := float32(math.MaxFloat32) + hit.position = Vector3f{inf, inf, inf} + hit.normal.SetZero() + hit.distance = inf + hit.mask = 0 + hit.hit = false +} + +func (this *NavMeshManager) Raycast(hit *NavMeshHit, sourcePosition, targetPosition Vector3f) bool { + var mappedPolyRef NavMeshPolyRef + var mappedPosition Vector3f + ext := this.m_LegacyQueryExtents + if !this.MapPosition(&mappedPolyRef, &mappedPosition, sourcePosition, ext) { + InvalidateNavMeshHit(hit) + return false + } + + var result NavMeshRaycastResult + status := this.m_NavMeshQuery.Raycast(mappedPolyRef, mappedPosition, targetPosition, + this.m_Filter, &result, nil, nil, 0) + if NavMeshStatusFailed(status) { + InvalidateNavMeshHit(hit) + return false + } + + lpos := LerpVector3f(mappedPosition, targetPosition, result.t) + var pos Vector3f + this.m_NavMeshQuery.ProjectToPoly(&pos, result.lastPoly, lpos) + blocked := result.t < 1.0 + hit.position = pos + hit.normal = result.normal + hit.distance = Magnitude(hit.position.Sub(sourcePosition)) + hit.mask = this.m_NavMesh.GetPolyFlags(result.hitPoly) + hit.hit = blocked + return blocked +} + +func (this *NavMeshManager) DistanceToEdge(hit *NavMeshHit, sourcePosition Vector3f) bool { + var mappedPolyRef NavMeshPolyRef + var mappedPosition Vector3f + ext := this.m_LegacyQueryExtents + if !this.MapPosition(&mappedPolyRef, &mappedPosition, sourcePosition, ext) { + InvalidateNavMeshHit(hit) + return false + } + + mask := uint32(0) + status := this.m_NavMeshQuery.FindDistanceToWall(mappedPolyRef, mappedPosition, this.m_Filter, + &hit.distance, &hit.position, &hit.normal, + &mask) + hit.mask = mask + if NavMeshStatusFailed(status) { + InvalidateNavMeshHit(hit) + return false + } + hit.hit = true + return true +} + +func (this *NavMeshManager) SamplePosition(hit *NavMeshHit, sourcePosition Vector3f, maxDistance float32) bool { + var mappedPolyRef NavMeshPolyRef + var mappedPosition Vector3f + extents := Vector3f{maxDistance, maxDistance, maxDistance} + if !this.MapPosition(&mappedPolyRef, &mappedPosition, sourcePosition, extents) { + InvalidateNavMeshHit(hit) + return false + } + + distance := Magnitude(mappedPosition.Sub(sourcePosition)) + if distance > maxDistance { + InvalidateNavMeshHit(hit) + return false + } + + hit.position = mappedPosition + hit.normal.SetZero() + hit.distance = distance + hit.mask = this.m_NavMesh.GetPolyFlags(mappedPolyRef) + hit.hit = true + return true +} + +func (this *NavMeshManager) MapPosition(mappedPolyRef *NavMeshPolyRef, mappedPosition *Vector3f, position, extents Vector3f) bool { + if this.m_NavMeshQuery == nil { + return false + } + this.m_NavMeshQuery.FindNearestPoly(position, extents, this.m_Filter, mappedPolyRef, mappedPosition) + return *mappedPolyRef != 0 +} + +func (this *NavMeshManager) CalculatePolygonPath(path *NavMeshPath, sourcePosition, targetPosition Vector3f, maxIter int32) int32 { + path.SetTimeStamp(0) + path.SetPolygonCount(0) + path.SetStatus(kPathInvalid) + if this.m_NavMeshQuery == nil { + return 0 + } + + var targetMappedPos, sourceMappedPos Vector3f + query := this.m_NavMeshQuery + ext := this.m_LegacyQueryExtents + + var targetPolyRef NavMeshPolyRef + query.FindNearestPoly(targetPosition, ext, this.m_Filter, &targetPolyRef, &targetMappedPos) + if targetPolyRef == 0 { + return 0 + } + + var sourcePolyRef NavMeshPolyRef + query.FindNearestPoly(sourcePosition, ext, this.m_Filter, &sourcePolyRef, &sourceMappedPos) + if sourcePolyRef == 0 { + return 0 + } + + polygonCount := int32(0) + + status := query.InitSlicedFindPath2(sourcePolyRef, targetPolyRef, sourceMappedPos, targetMappedPos, this.m_Filter) + if !NavMeshStatusFailed(status) { + status = query.UpdateSlicedFindPath(maxIter, nil) + } + if !NavMeshStatusFailed(status) { + status = query.FinalizeSlicedFindPath(&polygonCount) + } + path.ReservePolygons(polygonCount) + if !NavMeshStatusFailed(status) { + status = query.GetPath(path.GetPolygonPath(), &polygonCount, path.GetPolygonCapacity()) + } + + path.SetTimeStamp(this.m_NavMesh.GetTimeStamp()) + path.SetPolygonCount(polygonCount) + path.SetSourcePosition(sourceMappedPos) + path.SetTargetPosition(targetMappedPos) + if NavMeshStatusFailed(status) || polygonCount == 0 { + path.SetStatus(kPathInvalid) + return 0 + } + + if NavMeshStatusDetail(status, kNavMeshPartialResult) { + // when path is partial we project the target position + // to the last polygon in the path. + + polygonPath := path.GetPolygonPath() + lastPolyRef := polygonPath[polygonCount-1] + var partialTargetPos Vector3f + status := query.ClosestPointOnPoly(lastPolyRef, targetMappedPos, &partialTargetPos) + if NavMeshStatusFailed(status) { + path.SetStatus(kPathInvalid) + return 0 + } + + path.SetStatus(kPathPartial) + path.SetTargetPosition(partialTargetPos) + + // If the pathfinding req ran out of nodes - we mark the path as stale + // i.e. outdating the path by settings the time-stamp to 0 + if NavMeshStatusDetail(status, kNavMeshOutOfNodes) { + path.SetTimeStamp(0) + } + } else { + path.SetStatus(kPathComplete) + } + + return polygonCount +} + +func (this *NavMeshManager) CalculatePathCorners(corners []Vector3f, maxCorners int32, path *NavMeshPath) int32 { + if this.m_NavMeshQuery == nil || corners == nil || maxCorners < 2 || path.GetPolygonCount() < 1 { + return 0 + } + + cornerCount := int32(0) + var result NavMeshStatus + sourcePos := path.GetSourcePosition() + targetPos := path.GetTargetPosition() + refs := make([]NavMeshPolyRef, maxCorners) + flags := make([]uint8, maxCorners) + query := this.m_NavMeshQuery + result = query.FindStraightPath(sourcePos, targetPos, + path.GetPolygonPath(), path.GetPolygonCount(), + corners, flags, refs, &cornerCount, maxCorners) + Assert(cornerCount <= maxCorners) + if NavMeshStatusFailed(result) { + return 0 + } + return cornerCount +} + +func (this *NavMeshManager) WalkableBetween(source, target Vector3f) bool { + var sourceRef, targetRef NavMeshPolyRef + this.m_NavMeshQuery.FindNearestPoly(source, this.m_LegacyQueryExtents, this.m_Filter, &sourceRef, &source) + if sourceRef == 0 { + return false + } + + this.m_NavMeshQuery.FindNearestPoly(target, this.m_LegacyQueryExtents, this.m_Filter, &targetRef, &target) + if targetRef == 0 { + return false + } + + visited := make(map[NavMeshPolyRef]bool) + openList := make([]NavMeshPolyRef, 1, 10) + openList[0] = sourceRef + for count := 1; count > 0; count = len(openList) { + ref := openList[count-1] + visited[ref] = true + openList = openList[:count-1] + for link := this.m_NavMesh.GetFirstLink(ref); link != nil; link = this.m_NavMesh.GetNextLink(link) { + if link.ref == targetRef { + return true + } + if !visited[link.ref] { + openList = append(openList, link.ref) + } + } + } + return false +} + +func (this *NavMeshManager) CalculatePath(source, target Vector3f, maxIter int32) ([]Vector3f, bool) { + path := NewNavMeshPath() + if this.CalculatePolygonPath(path, source, target, maxIter) <= 0 { + return []Vector3f{}, true + } + cornerCount := path.GetPolygonCount() + 2 + corners := make([]Vector3f, cornerCount) + cornerCount = this.CalculatePathCorners(corners, cornerCount, path) + return corners[:cornerCount], path.m_status == kPathPartial +} + +func (this *NavMeshManager) GetNavMesh() *NavMesh { + return this.m_NavMesh +} + +func (this *NavMeshManager) GetNavMeshQuery() *NavMeshQuery { + return this.m_NavMeshQuery +} + +func (this *NavMeshManager) GetFilter() *QueryFilter { + return this.m_Filter +} + +func (this *NavMeshManager) FindNearestPoly(center Vector3f, nearestRef *NavMeshPolyRef, nearestPt *Vector3f) { + this.m_NavMeshQuery.FindNearestPoly(center, this.m_LegacyQueryExtents, + this.m_Filter, nearestRef, nearestPt) +} + +func (this *NavMeshManager) MoveAlongSurface(startRef NavMeshPolyRef, startPos Vector3f, endPos Vector3f, resultPos *Vector3f, visited []NavMeshPolyRef, visitedCount *int32, maxVisitedSize int32) NavMeshStatus { + status := this.m_NavMeshQuery.MoveAlongSurface(startRef, startPos, endPos, this.m_Filter, resultPos, visited, visitedCount, maxVisitedSize) + if !NavMeshStatusSucceed(status) { + return status + } + + var resultRef = startRef + for index, viRef := range visited { + if viRef == 0 && index > 0 { + resultRef = visited[index-1] + break + } + } + + var height float32 + status = this.m_NavMeshQuery.GetPolyHeightLocal(resultRef, *resultPos, &height) + if !NavMeshStatusSucceed(status) { + return status + } + + resultPos.SetData(1, height) + return status +} + +func (this *NavMeshManager) FindRandomPointInCircle(center Vector3f, radius float32, maxCount int) (Vector3f, error) { + var result Vector3f + var centerRef NavMeshPolyRef + this.m_NavMeshQuery.FindNearestPoly(center, this.m_LegacyQueryExtents, this.m_Filter, ¢erRef, &result) + if centerRef == 0 { + return result, fmt.Errorf("center:%v not found in navmesh", center) + } + var resultRef [32]NavMeshPolyRef + var refCount int32 + status := this.m_NavMeshQuery.FindLocalNeighbourhood(centerRef, center, radius, this.m_Filter, resultRef[:], nil, &refCount, 32) + if !NavMeshStatusSucceed(status) { + return result, fmt.Errorf("find local neighbourhood failed") + } + + // calculate all the polygon area, randomed with weight as area + var verts [kNavMeshVertsPerPoly]Vector3f + weights := make([]float32, refCount) + var areaSum float32 + for i := int32(0); i < refCount; i++ { + vertCount := this.m_NavMesh.GetPolyGeometry(resultRef[i], verts[:], nil, 0) + var polyArea float32 + for i := int32(2); i < vertCount; i++ { + va := verts[0] + vb := verts[i-1] + vc := verts[i-2] + polyArea += TriangleAreaXZ(va, vb, vc) + } + weights[i] = polyArea + areaSum += polyArea + } + targetArea := rand.Float32() * areaSum + var searchArea float32 + var targetPolyRef NavMeshPolyRef + for i := int32(0); i < refCount; i++ { + searchArea += weights[i] + if searchArea >= targetArea { + targetPolyRef = resultRef[i] + break + } + } + + for i := 0; i < maxCount; i++ { + // find the targeted polygon, random a point in the polygon + vertCount := this.m_NavMesh.GetPolyGeometry(targetPolyRef, verts[:], nil, 0) + result = RandomPointInConvexPoly(verts[:], int(vertCount)) + result = TileToWorld(this.m_NavMesh.GetTileByRef(NavMeshTileRef(targetPolyRef)), result) + + // fix height + var height float32 + status = this.m_NavMeshQuery.GetPolyHeightLocal(targetPolyRef, result, &height) + if !NavMeshStatusSucceed(status) { + return result, fmt.Errorf("find poly height failed") + } + result.y = height + + if Distance(center, result) <= radius { + return result, nil + } + } + + return result, fmt.Errorf("center %+v radius %v points not found at this random", center, radius) +} + +func (this *NavMeshManager) GetSourceTileData(id int32, index int32) *NavMeshTileData { + return &this.m_NavMeshData.m_NavMeshTiles[index] +} + +func (this *NavMeshManager) GetNavMeshBuildSettings(id int32) *NavMeshBuildSettings { + return &this.m_NavMeshData.m_NavMeshBuildSettings +} + +func (this *NavMeshManager) AddObstacle(obs *NavMeshObstacle) int32 { + var handle int32 + this.m_CarvingSystem.AddObstacle(obs, &handle) + return handle +} + +func (this *NavMeshManager) RemoveObstacle(handle int32) { + this.m_CarvingSystem.RemoveObstacle(&handle) +} + +func (this *NavMeshManager) UpdateCarvingImmediately() bool { + this.m_CarvingSystem.PrepareCarving() + this.m_CarvingSystem.Carve() + return this.m_CarvingSystem.ApplyCarveResults() +} + +func (this *NavMeshManager) GetSourceTileDataBounds(locations *[]TileLocation) { + navMeshData := this.m_NavMeshData + tiles := navMeshData.GetNavMeshTiles() + for i := 0; i < len(tiles); i++ { + header := (*NavMeshDataHeader)(unsafe.Pointer(&tiles[i].m_MeshData[0])) + var loc TileLocation + loc.m_Bounds = NewMinMaxAABB(header.bmin, header.bmax) + loc.m_SurfaceID = this.m_SurfaceID + loc.m_TileIndex = int32(i) + *locations = append(*locations, loc) + } +} + +func (this *NavMeshManager) RemoveTile(surfaceID int32, tileIndex int32) { + Assert(this.m_NavMesh != nil) + if surfaceID != this.m_SurfaceID { + return + } + + ref := this.m_AddedTileRefs[tileIndex] + this.m_NavMesh.RemoveTile(ref, surfaceID, nil, nil) + this.m_AddedTileRefs[tileIndex] = 0 +} + +func (this *NavMeshManager) RestoreTile(surfaceID int32, tileIndex int32) { + Assert(this.m_NavMesh != nil) + if surfaceID != this.m_SurfaceID { + return + } + + navMeshData := this.m_NavMeshData + tiles := navMeshData.GetNavMeshTiles() + tileData := &tiles[tileIndex] + byteData := tileData.m_MeshData + dataSize := len(tileData.m_MeshData) + + ref := this.m_AddedTileRefs[tileIndex] + if ref != 0 { + tile := this.m_NavMesh.GetTileByRef(ref) + if len(tile.data) == len(byteData) { + equal := true + for i := range tile.data { + if tile.data[i] != byteData[i] { + equal = false + break + } + } + if equal { + return + } + } + + this.m_NavMesh.RemoveTile(ref, surfaceID, nil, nil) + this.m_AddedTileRefs[tileIndex] = 0 + } + + var addRef NavMeshTileRef = 0 + this.m_NavMesh.AddTile(byteData, int32(dataSize), kTileLeakData, surfaceID, &addRef) + this.m_AddedTileRefs[tileIndex] = addRef +} + +func (this *NavMeshManager) ReplaceTile(surfaceID int32, tileIndex int32, tileData []byte, tileDataSize int32) { + Assert(this.m_NavMesh != nil) + Assert(this.m_SurfaceID == surfaceID) // < assumes the surface exists + Assert(this.m_AddedTileRefs[tileIndex] == 0) // < assumes tile in this place was first removed + + var ref NavMeshTileRef = 0 + status := this.m_NavMesh.AddTile(tileData, tileDataSize, kTileFreeData, surfaceID, &ref) + if NavMeshStatusFailed(status) { + } else { + this.m_AddedTileRefs[tileIndex] = ref + } +} + +func (this *NavMeshManager) GetSurfaceId() int32 { + return this.m_SurfaceID +} + +func (this *NavMeshManager) GetMaxTileIndex() int { + return len(this.m_AddedTileRefs) +} diff --git a/pkg/navmesh/nav_mesh_node.cpp.go b/pkg/navmesh/nav_mesh_node.cpp.go new file mode 100644 index 00000000..1739c88d --- /dev/null +++ b/pkg/navmesh/nav_mesh_node.cpp.go @@ -0,0 +1,112 @@ +package navmesh + +func HashRef(a NavMeshPolyRef) uint32 { + // Thomas Wang's 64bit to 32bit. + a = (^a) + (a << 18) // key = (key << 18) - key - 1; + a = a ^ (a >> 31) + a = a * 21 // key = (key + (key << 2)) + (key << 4); + a = a ^ (a >> 11) + a = a + (a << 6) + a = a ^ (a >> 22) + return uint32(a) +} + +func NewNavMeshNodePool(maxNavMeshNodes, hashSize int32) *NavMeshNodePool { + Assert(hashSize != 0) + Assert(IsPowerOfTwo(hashSize)) + pool := new(NavMeshNodePool) + pool.m_MaxNavMeshNodes = maxNavMeshNodes + pool.m_HashSize = hashSize + pool.m_NavMeshNodeCount = 0 + pool.m_NavMeshNodes = make([]NavMeshNode, maxNavMeshNodes, maxNavMeshNodes) + pool.m_First = make([]NavMeshNodeIndex, hashSize, hashSize) + for i := range pool.m_First { + pool.m_First[i] = kNavMeshNodeNullIndex + } + pool.m_Next = make([]NavMeshNodeIndex, maxNavMeshNodes, maxNavMeshNodes) + for i := range pool.m_Next { + pool.m_Next[i] = kNavMeshNodeNullIndex + } + return pool +} + +func (this *NavMeshNodePool) Clear() { + for i := range this.m_First { + this.m_First[i] = kNavMeshNodeNullIndex + } + this.m_NavMeshNodeCount = 0 +} + +func (this *NavMeshNodePool) FindNavMeshNode(id NavMeshPolyRef) *NavMeshNode { + bucket := HashRef(id) & uint32(this.m_HashSize-1) + i := this.m_First[bucket] + for i != kNavMeshNodeNullIndex { + if this.m_NavMeshNodes[i].id == id { + + return &this.m_NavMeshNodes[i] + } + i = this.m_Next[i] + } + return nil +} + +func (this *NavMeshNodePool) GetNode(id NavMeshPolyRef) *NavMeshNode { + bucket := HashRef(id) & uint32(this.m_HashSize-1) + i := this.m_First[bucket] + var node *NavMeshNode + for i != kNavMeshNodeNullIndex { + if this.m_NavMeshNodes[i].id == id { + return &this.m_NavMeshNodes[i] + } + i = this.m_Next[i] + } + + if this.m_NavMeshNodeCount >= this.m_MaxNavMeshNodes { + return nil + } + + i = NavMeshNodeIndex(this.m_NavMeshNodeCount) + this.m_NavMeshNodeCount++ + + // Init node + node = &this.m_NavMeshNodes[i] + node.pidx = 0 + node.cost = 0 + node.total = 0 + node.id = id + node.flags = kNew + + this.m_Next[i] = this.m_First[bucket] + this.m_First[bucket] = i + return node +} + +func NewNavMeshNodeQueue(n int32) *NavMeshNodeQueue { + queue := new(NavMeshNodeQueue) + queue.m_Heap = make([]*NavMeshNode, n+1, n+1) + return queue +} + +func (this *NavMeshNodeQueue) BubbleUp(i int32, node *NavMeshNode) { + parent := (i - 1) / 2 + // note: (index > 0) means there is a parent + for (i > 0) && (this.m_Heap[parent].total > node.total) { + this.m_Heap[i] = this.m_Heap[parent] + i = parent + parent = (i - 1) / 2 + } + this.m_Heap[i] = node +} + +func (this *NavMeshNodeQueue) TrickleDown(i int32, node *NavMeshNode) { + child := (i * 2) + 1 + for child < this.m_Size { + if ((child + 1) < this.m_Size) && (this.m_Heap[child].total > this.m_Heap[child+1].total) { + child++ + } + this.m_Heap[i] = this.m_Heap[child] + i = child + child = (i * 2) + 1 + } + this.BubbleUp(i, node) +} diff --git a/pkg/navmesh/nav_mesh_node.go b/pkg/navmesh/nav_mesh_node.go new file mode 100644 index 00000000..514ae8be --- /dev/null +++ b/pkg/navmesh/nav_mesh_node.go @@ -0,0 +1,108 @@ +package navmesh + +import ( + "unsafe" +) + +type NavMeshNodeFlags uint8 + +const ( + kNew NavMeshNodeFlags = 0x00 + kOpen NavMeshNodeFlags = 0x01 + kClosed NavMeshNodeFlags = 0x02 +) + +type NavMeshNode struct { + pos Vector3f // Position of the node. + cost float32 // Cost from previous node to current node. + total float32 // Cost up to the node. + pidx uint32 // Index to parent node. + flags NavMeshNodeFlags // NavMeshNode flags new/open/closed. + id NavMeshPolyRef // Polygon ref the node corresponds to. +} + +type NavMeshNodeIndex uint16 + +const ( + kNavMeshNodeNullIndex NavMeshNodeIndex = 0xffff +) + +type NavMeshNodePool struct { + m_MaxNavMeshNodes int32 + m_HashSize int32 + m_NavMeshNodeCount int32 + m_NavMeshNodes []NavMeshNode + m_First []NavMeshNodeIndex + m_Next []NavMeshNodeIndex +} + +var navMeshNodeSize = unsafe.Sizeof(NavMeshNode{}) + +func GetNavMeshNodeIndex(start, end *NavMeshNode) int32 { + nstart := uintptr(unsafe.Pointer(start)) + nend := uintptr(unsafe.Pointer(end)) + return int32((nend - nstart) / navMeshNodeSize) +} + +func (this *NavMeshNodePool) GetNodeIdx(node *NavMeshNode) uint32 { + if node == nil { + return 0 + } + idx := GetNavMeshNodeIndex(&this.m_NavMeshNodes[0], node) + 1 + Assert(idx <= this.m_MaxNavMeshNodes) + return uint32(idx) +} + +func (this *NavMeshNodePool) GetNodeAtIdx(idx uint32) *NavMeshNode { + Assert(idx <= uint32(this.m_MaxNavMeshNodes)) + if idx == 0 { + return nil + } + return &this.m_NavMeshNodes[idx-1] +} + +func (this *NavMeshNodePool) GetHashSize() int32 { + return this.m_HashSize +} + +func (this *NavMeshNodePool) GetFirst(bucket int32) NavMeshNodeIndex { + return this.m_First[bucket] +} + +func (this *NavMeshNodePool) GetNext(i int32) NavMeshNodeIndex { + return this.m_Next[i] +} + +type NavMeshNodeQueue struct { + m_Heap []*NavMeshNode + m_Size int32 +} + +func (this *NavMeshNodeQueue) empty() bool { + return this.m_Size == 0 +} + +func (this *NavMeshNodeQueue) Clear() { + this.m_Size = 0 +} + +func (this *NavMeshNodeQueue) Pop() *NavMeshNode { + result := this.m_Heap[0] + this.m_Size-- + this.TrickleDown(0, this.m_Heap[this.m_Size]) + return result +} + +func (this *NavMeshNodeQueue) Push(node *NavMeshNode) { + this.m_Size++ + this.BubbleUp(this.m_Size-1, node) +} + +func (this *NavMeshNodeQueue) Modify(node *NavMeshNode) { + for i := int32(0); i < this.m_Size; i++ { + if this.m_Heap[i] == node { + this.BubbleUp(i, node) + return + } + } +} diff --git a/pkg/navmesh/nav_mesh_path.go b/pkg/navmesh/nav_mesh_path.go new file mode 100644 index 00000000..9814800b --- /dev/null +++ b/pkg/navmesh/nav_mesh_path.go @@ -0,0 +1,97 @@ +package navmesh + +type NavMeshPath struct { + m_timeStamp uint32 + m_status NavMeshPathStatus + m_polygons []NavMeshPolyRef + m_sourcePosition Vector3f + m_targetPosition Vector3f + m_Size int32 +} + +type NavMeshPathStatus int32 + +const ( + kPathComplete NavMeshPathStatus = 0 + kPathPartial NavMeshPathStatus = 1 + kPathInvalid NavMeshPathStatus = 2 +) + +func (this *NavMeshPath) GetSourcePosition() Vector3f { + return this.m_sourcePosition +} + +func (this *NavMeshPath) SetSourcePosition(sourcePosition Vector3f) { + this.m_sourcePosition = sourcePosition +} + +func (this *NavMeshPath) GetTargetPosition() Vector3f { + return this.m_targetPosition +} + +func (this *NavMeshPath) SetTargetPosition(targetPosition Vector3f) { + this.m_targetPosition = targetPosition +} + +func (this *NavMeshPath) GetPolygonCount() int32 { + return this.m_Size +} + +func (this *NavMeshPath) GetPolygonCapacity() int32 { + return int32(len(this.m_polygons)) +} + +func (this *NavMeshPath) SetPolygonCount(polygonCount int32) { + if this.GetPolygonCapacity() < polygonCount { + this.ReservePolygons(polygonCount) + } + this.m_Size = polygonCount +} + +func (this *NavMeshPath) GetPolygonPath() []NavMeshPolyRef { + return this.m_polygons +} + +func (this *NavMeshPath) GetPolygonData() []NavMeshPolyRef { + return this.m_polygons[:this.m_Size] +} + +func (this *NavMeshPath) GetStatus() NavMeshPathStatus { + return this.m_status +} + +func (this *NavMeshPath) IsComplete() bool { + return this.m_status == kPathComplete +} + +func (this *NavMeshPath) IsPartial() bool { + return this.m_status == kPathPartial +} + +func (this *NavMeshPath) IsInvalid() bool { + return this.m_status == kPathInvalid +} + +func (this *NavMeshPath) SetStatus(status NavMeshPathStatus) { + this.m_status = status +} + +func (this *NavMeshPath) SetTimeStamp(timeStamp uint32) { + this.m_timeStamp = timeStamp +} + +func NewNavMeshPath() *NavMeshPath { + var path NavMeshPath + path.m_status = kPathInvalid + return &path +} + +func (this *NavMeshPath) ReservePolygons(size int32) { + kSizeInc := int32(32) + capNum := ((size + kSizeInc - 1) / kSizeInc) * kSizeInc + if cap(this.m_polygons) < int(capNum) { + d := make([]NavMeshPolyRef, capNum, capNum) + copy(d, this.m_polygons) + this.m_polygons = d + } +} diff --git a/pkg/navmesh/nav_mesh_query.cpp.go b/pkg/navmesh/nav_mesh_query.cpp.go new file mode 100644 index 00000000..9a796b28 --- /dev/null +++ b/pkg/navmesh/nav_mesh_query.cpp.go @@ -0,0 +1,2189 @@ +package navmesh + +import ( + "math" +) + +const ( + H_SCALE float32 = 0.999 // Search heuristic scale. +) + +func GetCostModifier(navmesh *NavMesh, filter *QueryFilter, ref NavMeshPolyRef) float32 { + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := navmesh.GetOffMeshConnection(ref) + cost := con.costModifier + if cost != -1.0 { + return cost + } + return filter.GetAreaCost(int32(con.area)) + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + navmesh.GetTileAndPolyByRef(ref, &tile, &poly) + return filter.GetAreaCost(int32(poly.area)) + } + Assert(false) // bad + return float32(math.MaxFloat32) +} + +func SqrDistancePointPolyEdge(pt Vector3f, verts []Vector3f, nverts int32, ed, et []float32) bool { + // TODO: Replace pnpoly with triArea2D tests? + c := false + for i, j := int32(0), nverts-1; i < nverts; j, i = i, i+1 { + vi := verts[i] + vj := verts[j] + if ((vi.z > pt.z) != (vj.z > pt.z)) && (pt.x < (vj.x-vi.x)*(pt.z-vi.z)/(vj.z-vi.z)+vi.x) { + c = !c + } + ed[j] = SqrDistancePointSegment2D(&et[j], pt, vj, vi) + } + return c +} + +func ProjectPoly(rmin, rmax *float32, axis Vector3f, poly []Vector3f, npoly int32) { + var min, max float32 + max = DotVector3f(axis, poly[0]) + min = max + for i := int32(1); i < npoly; i++ { + d := DotVector3f(axis, poly[i]) + min = FloatMin(min, d) + max = FloatMax(max, d) + } + *rmin = min + *rmax = max +} + +func OverlapRange(amin, amax, bmin, bmax, eps float32) bool { + if (amin+eps) > bmax || (amax-eps) < bmin { + return false + } else { + return true + } +} + +func OverlapPolyPoly2D(polya []Vector3f, npolya int32, polyb []Vector3f, npolyb int32) bool { + eps := float32(1e-4) + for i, j := int32(0), npolya-1; i < npolya; j, i = i, i+1 { + va := polya[j] + vb := polya[i] + n := Vector3f{vb.z - va.z, 0, va.x - vb.x} + var amin, amax, bmin, bmax float32 + ProjectPoly(&amin, &amax, n, polya, npolya) + ProjectPoly(&bmin, &bmax, n, polyb, npolyb) + if !OverlapRange(amin, amax, bmin, bmax, eps) { + // Found separating axis + return false + } + } + for i, j := int32(0), npolyb-1; i < npolyb; j, i = i, i+1 { + va := polyb[j] + vb := polyb[i] + n := Vector3f{vb.z - va.z, 0, -va.x - vb.x} + var amin, amax, bmin, bmax float32 + ProjectPoly(&amin, &amax, n, polya, npolya) + ProjectPoly(&bmin, &bmax, n, polyb, npolyb) + if !OverlapRange(amin, amax, bmin, bmax, eps) { + // Found separating axis + return false + } + } + return true +} + +func PointInPolygon2D(pt Vector3f, verts []Vector3f, nverts int32) bool { + // Assume clockwise and convex + prev := verts[nverts-1] + for i := int32(0); i < nverts; i++ { + curr := verts[i] + dlx := curr.x - prev.x + dlz := curr.z - prev.z + dpx := pt.x - prev.x + dpz := pt.z - prev.z + if dpx*dlz < dpz*dlx { + return false + } + prev = curr + } + return true +} + +func NewNavMeshQuery(navmesh *NavMesh, maxNodes int32) *NavMeshQuery { + query := new(NavMeshQuery) + query.InitPools(navmesh, maxNodes) + return query +} + +// Initializes the nav mesh query. +// Params: +// nav - (in) pointer to navigation mesh data. +// maxNodes - (in) Maximum number of search nodes to use (max 65536). +func (this *NavMeshQuery) InitPools(nav *NavMesh, maxNodes int32) NavMeshStatus { + Assert(this.m_TinyNodePool == nil) + Assert(this.m_NodePool == nil) + Assert(this.m_OpenList == nil) + this.m_NavMesh = nav + this.m_TinyNodePool = NewNavMeshNodePool(64, 32) + if this.m_TinyNodePool == nil { + return kNavMeshFailure | kNavMeshOutOfMemory + } + if maxNodes == 0 { + return kNavMeshSuccess + } + this.m_NodePool = NewNavMeshNodePool(maxNodes, int32(NextPowerOfTwo(uint32(maxNodes)/4))) + if this.m_NodePool == nil { + return kNavMeshFailure | kNavMeshOutOfMemory + } + this.m_OpenList = NewNavMeshNodeQueue(maxNodes) + if this.m_OpenList == nil { + return kNavMeshFailure | kNavMeshOutOfMemory + } + return kNavMeshSuccess +} + +// Returns closest point on navigation polygon. +// Uses detail polygons to find the closest point to the navigation polygon surface. +// Params: +// ref - (in) ref to the polygon. +// pos[3] - (in) the point to check. +// closest[3] - (out) closest point. +// Returns: true if closest point found. +func (this *NavMeshQuery) ClosestPointOnPoly(ref NavMeshPolyRef, pos Vector3f, closest *Vector3f) NavMeshStatus { + Assert(this.m_NavMesh != nil) + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.m_NavMesh.GetOffMeshConnection(ref) + if con == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + if con.endPoints[0].tileRef == 0 || con.endPoints[1].tileRef == 0 { + return kNavMeshFailure + } + + // TODO: Handle segment + d0 := SqrDistance(con.endPoints[0].mapped[0], pos) + d1 := SqrDistance(con.endPoints[1].mapped[0], pos) + if d0 < d1 { + *closest = con.endPoints[0].mapped[0] + } else { + *closest = con.endPoints[1].mapped[0] + } + return kNavMeshSuccess + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusFailed(this.m_NavMesh.GetTileAndPolyByRef(ref, &tile, &poly)) { + return kNavMeshFailure | kNavMeshInvalidParam + } + if tile == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + localPos := WorldToTile(tile, pos) + var localClosest Vector3f + this.ClosestPointOnPolyInTileLocal(tile, poly, ref, localPos, &localClosest) + *closest = TileToWorld(tile, localClosest) + } + + return kNavMeshSuccess +} + +func ProjectPointToPoly2DLocal(pos Vector3f, poly *NavMeshPoly, tile *NavMeshTile, projectedPos *Vector3f) bool { + Assert(poly != nil) + Assert(tile != nil) + var verts [kNavMeshVertsPerPoly]Vector3f + var edged [kNavMeshVertsPerPoly]float32 + var edget [kNavMeshVertsPerPoly]float32 + nv := poly.vertCount + for i := uint8(0); i < nv; i++ { + verts[i] = tile.verts[poly.verts[i]] + } + + inside := SqrDistancePointPolyEdge(pos, verts[:], int32(nv), edged[:], edget[:]) + if inside { + // Point is inside the polygon, return the point. + *projectedPos = pos + } else { + // Point is outside the polygon, clamp to nearest edge. + dmin := float32(math.MaxFloat32) + imin := int32(-1) + for i := uint8(0); i < nv; i++ { + if edged[i] < dmin { + dmin = edged[i] + imin = int32(i) + } + } + Assert(imin < int32(nv)) + var iminnext int32 + if imin+1 == int32(nv) { + iminnext = 0 + } else { + iminnext = imin + 1 + } + va := verts[imin] + vb := verts[iminnext] + *projectedPos = LerpVector3f(va, vb, edget[imin]) + // points that are on (or very close to) an edge are also considered to be inside the polygon + inside = dmin < FLT_EPSILON + } + return inside +} + +func (this *NavMeshQuery) GetUpAxis(ref NavMeshPolyRef, up *Vector3f) NavMeshStatus { + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.m_NavMesh.GetOffMeshConnection(ref) + if con != nil { + *up = con.axisY + return kNavMeshSuccess + } + return kNavMeshFailure | kNavMeshInvalidParam + } + + yAxis := Vector3f{0.0, 1.0, 0.0} + tile := this.m_NavMesh.GetTileByRef(NavMeshTileRef(ref)) + if tile != nil { + *up = RotateVectorByQuat(tile.rotation, yAxis) + return kNavMeshSuccess + } + + return kNavMeshFailure | kNavMeshInvalidParam +} + +// Local space input/output +// Calculate the closest point on a polygon +// Returns true unless the 2D projected point is outside the polygon +func (this *NavMeshQuery) ClosestPointOnPolyInTileLocal(tile *NavMeshTile, poly *NavMeshPoly, ref NavMeshPolyRef, + pos Vector3f, closest *Vector3f) bool { + inside := ProjectPointToPoly2DLocal(pos, poly, tile, closest) + // Find height at the location. + this.GetPolyHeightLocal(ref, *closest, &closest.y) + return inside +} + +// Returns closest point on navigation polygon boundary. +// Uses the navigation polygon boundary to snap the point to poly boundary +// if it is outside the polygon. Much faster than ClosestPointToPoly. Does not affect height. +// Params: +// ref - (in) ref to the polygon. +// pos[3] - (in) the point to check. +// closest[3] - (out) closest point. +// Returns: true if closest point found. +func (this *NavMeshQuery) ClosestPointOnPolyBoundary(ref NavMeshPolyRef, pos Vector3f, closest *Vector3f) NavMeshStatus { + Assert(this.m_NavMesh != nil) + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.m_NavMesh.GetOffMeshConnection(ref) + if con == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + + if con.endPoints[0].tileRef == 0 || con.endPoints[1].tileRef == 0 { + return kNavMeshFailure + } + + // TODO: Handle segment + d0 := SqrDistance(con.endPoints[0].mapped[0], pos) + d1 := SqrDistance(con.endPoints[1].mapped[0], pos) + if d0 < d1 { + + *closest = con.endPoints[0].mapped[0] + } else { + *closest = con.endPoints[1].mapped[0] + } + + return kNavMeshSuccess + } + + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusFailed(this.m_NavMesh.GetTileAndPolyByRef(ref, &tile, &poly)) { + return kNavMeshFailure | kNavMeshInvalidParam + } + + localPos := WorldToTile(tile, pos) + var localProjPos Vector3f + ProjectPointToPoly2DLocal(localPos, poly, tile, &localProjPos) + *closest = TileToWorld(tile, localProjPos) + return kNavMeshSuccess +} + +// Project point height to detail triangle and accept immediately if the projected point is inside triangle +func ProjectToPolyDetail(tile *NavMeshTile, poly *NavMeshPoly, pos Vector3f, height *float32) bool { + ip := GetPolyIndex(tile, poly) + pd := &tile.detailMeshes[ip] + for j := uint32(0); j < uint32(pd.triCount); j++ { + t := tile.detailTris[(pd.triBase+j)*4:] + var v [3]Vector3f + for k := 0; k < 3; k++ { + if uint8(t[k]) < poly.vertCount { + v[k] = tile.verts[poly.verts[t[k]]] + + } else { + v[k] = tile.detailVerts[pd.vertBase+(uint32(t[k])-uint32(poly.vertCount))] + } + } + var h float32 + if ClosestHeightPointTriangle(&h, pos, v[0], v[1], v[2]) { + *height = h + return true + } + } + return false +} + +// In the plane of projection find the height of the closest point on the edge of the detail triangles +func ProjectToPolyDetailEdge(tile *NavMeshTile, poly *NavMeshPoly, pos Vector3f) float32 { + ip := GetPolyIndex(tile, poly) + pd := &tile.detailMeshes[ip] + dmin := float32(math.MaxFloat32) + h := float32(math.MaxFloat32) + for j := uint32(0); j < uint32(pd.triCount); j++ { + t := tile.detailTris[(pd.triBase+j)*4:] + var v [3]Vector3f + for k := 0; k < 3; k++ { + if uint8(t[k]) < poly.vertCount { + v[k] = tile.verts[poly.verts[t[k]]] + + } else { + v[k] = tile.detailVerts[pd.vertBase+(uint32(t[k])-uint32(poly.vertCount))] + } + } + + for kp, k := 2, 0; k < 3; kp, k = k, k+1 { + var tt float32 + d := SqrDistancePointSegment2D(&tt, pos, v[kp], v[k]) + if d < dmin { + dmin = d + h = LerpFloat32(v[kp].y, v[k].y, tt) + } + } + } + return h +} + +// Returns height of the polygon at specified location. +// Params: +// ref - (in) ref to the polygon. +// pos[3] - (in) the point where to locate the height. +// height - (out) height at the location. +// Returns: true if over polygon. +func (this *NavMeshQuery) GetPolyHeightLocal(ref NavMeshPolyRef, pos Vector3f, height *float32) NavMeshStatus { + Assert(this.m_NavMesh != nil) + Assert(height != nil) + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.m_NavMesh.GetOffMeshConnection(ref) + if con != nil { + // TODO: handle segment + v0 := con.endPoints[0].mapped[0] + v1 := con.endPoints[1].mapped[0] + d0 := Distance(pos, v0) + d1 := Distance(pos, v1) + u := d0 / (d0 + d1) + *height = LerpFloat32(v0.y, v1.y, u) + return kNavMeshSuccess + } + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusSucceed(this.m_NavMesh.GetTileAndPolyByRef(ref, &tile, &poly)) { + // Most calls should terminate here + if ProjectToPolyDetail(tile, poly, pos, height) { + return kNavMeshSuccess + } + + // Only rarely should this be executed - so we allow a second lookup of triangles + *height = ProjectToPolyDetailEdge(tile, poly, pos) + return kNavMeshSuccess + } + } + + return kNavMeshFailure | kNavMeshInvalidParam +} + +// Project point to polygon along the local up-axis +func (this *NavMeshQuery) ProjectToPoly(projPos *Vector3f, ref NavMeshPolyRef, pos Vector3f) NavMeshStatus { + Assert(this.m_NavMesh != nil) + Assert(projPos != nil) + *projPos = pos + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + con := this.m_NavMesh.GetOffMeshConnection(ref) + if con != nil { + v0 := LerpVector3f(con.endPoints[0].mapped[0], con.endPoints[0].mapped[1], 0.5) + v1 := LerpVector3f(con.endPoints[1].mapped[0], con.endPoints[1].mapped[1], 0.5) + d0 := Distance(pos, v0) + d1 := Distance(pos, v1) + u := d0 / (d0 + d1) + *projPos = LerpVector3f(v0, v1, u) + return kNavMeshSuccess + } + } else { + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusSucceed(this.m_NavMesh.GetTileAndPolyByRef(ref, &tile, &poly)) { + // Most calls should terminate here + var localHeight float32 + localPos := WorldToTile(tile, pos) + if ProjectToPolyDetail(tile, poly, localPos, &localHeight) { + worldPos := TileToWorld(tile, Vector3f{localPos.x, localHeight, localPos.z}) + *projPos = worldPos + return kNavMeshSuccess + } + + // Only rarely should this be executed - so we allow a second lookup of triangles + localHeight = ProjectToPolyDetailEdge(tile, poly, localPos) + worldPos := TileToWorld(tile, Vector3f{localPos.x, localHeight, localPos.z}) + *projPos = worldPos + return kNavMeshSuccess + } + } + + return kNavMeshFailure | kNavMeshInvalidParam +} + +type NearestQuery1 struct { + m_NavMeshMeshQuery *NavMeshQuery + m_Filter *QueryFilter + m_Center Vector3f + + m_DistanceSqr [2]float32 + m_PolyRef [2]NavMeshPolyRef + m_LocalPoint [2]Vector3f +} + +func NewNearestQuery1(navMeshQuery *NavMeshQuery, filter *QueryFilter, center Vector3f) *NearestQuery1 { + query := new(NearestQuery1) + query.m_NavMeshMeshQuery = navMeshQuery + query.m_Filter = filter + query.m_Center = center + query.m_DistanceSqr[0] = math.MaxFloat32 + query.m_DistanceSqr[1] = math.MaxFloat32 + query.m_PolyRef[0] = 0 + query.m_PolyRef[1] = 0 + // It's strictly not necessary to initialise the positions. + // The user should be checking the corresponding polygon reference before reading the position + query.m_LocalPoint[0].SetZero() + query.m_LocalPoint[1].SetZero() + return query +} + +func (this *NearestQuery1) ProcessPolygons(tile *NavMeshTile, polyRefs []NavMeshPolyRef, polys []*NavMeshPoly, itemCount int) { + localPosition := WorldToTile(tile, this.m_Center) + + for item := 0; item < itemCount; item++ { + ref := polyRefs[item] + poly := polys[item] + if !this.m_Filter.PassFilter(poly.flags) { + continue + } + + var closestPtPoly Vector3f + var inside int32 + if this.m_NavMeshMeshQuery.ClosestPointOnPolyInTileLocal(tile, poly, ref, localPosition, &closestPtPoly) { + inside = 1 + } else { + inside = 0 + } + + // Keep track of the closest position. Calculating the squared vertical and 3D distances. + // The 3D distance is used for comparing points projected outside the polygon - otherwise using the vertical distance. + var d [2]float32 + d[0] = SqrMagnitude(localPosition.Sub(closestPtPoly)) + d[1] = Sqr(localPosition.y - closestPtPoly.y) + + if d[inside] < this.m_DistanceSqr[inside] { + this.m_LocalPoint[inside] = closestPtPoly + this.m_DistanceSqr[inside] = d[inside] + this.m_PolyRef[inside] = ref + } + } +} + +// Finds the nearest navigation polygon around the center location. +// Params: +// center[3] - (in) The center of the search box. +// extents[3] - (in) The extents of the search box. +// filter - (in) path polygon filter. +// nearestRef - (out) Reference to the nearest polygon. +// nearestPt[3] - (out, opt) The nearest point on found polygon, null if not needed. +func (this *NavMeshQuery) FindNearestPoly(center Vector3f, extents Vector3f, filter *QueryFilter, + nearestRef *NavMeshPolyRef, nearestPt *Vector3f) { + Assert(this.m_NavMesh != nil) + Assert(nearestRef != nil) + Assert(nearestPt != nil) + + // Get the nearest polygons and projected points + nearest := NewNearestQuery1(this, filter, center) + this.m_NavMesh.QueryPolygons(filter.GetTypeID(), center, extents, nearest) + + // Check if any of the closest points found (outside/inside) is within the query volume + // Prefer inside points (inside == 1) + + bounds := AABB{center, extents} + var point Vector3f + var ref NavMeshPolyRef = 0 + for inside := 0; inside < 2; inside++ { + tile := this.m_NavMesh.GetTileByRef(NavMeshTileRef(nearest.m_PolyRef[inside])) + if tile != nil { + worldPoint := TileToWorld(tile, nearest.m_LocalPoint[inside]) + if bounds.IsInside(worldPoint) { + ref = nearest.m_PolyRef[inside] + point = worldPoint + } + } + } + + if nearestRef != nil { + *nearestRef = ref + } + + if nearestPt != nil && ref != 0 { + *nearestPt = point + } +} + +type PolygonQuery struct { + m_NavMeshMeshQuery *NavMeshQuery + m_Filter *QueryFilter + m_Results []NavMeshPolyRef + m_MaxResults int32 + m_ResultCount int32 +} + +func NewPolygonQuery(query *NavMeshQuery, filter *QueryFilter, polys []NavMeshPolyRef, maxPolys int32) *PolygonQuery { + pQuery := new(PolygonQuery) + pQuery.m_NavMeshMeshQuery = query + pQuery.m_Filter = filter + pQuery.m_Results = polys + pQuery.m_MaxResults = maxPolys + pQuery.m_ResultCount = 0 + return pQuery +} + +func (this *PolygonQuery) ProcessPolygons(title *NavMeshTile, polyRefs []NavMeshPolyRef, polys []*NavMeshPoly, itemCount int) { + // Find nearest polygon amongst the nearby polygons. + for i := 0; i < itemCount; i++ { + if !this.m_Filter.PassFilter(polys[i].flags) { + continue + } + + if this.m_ResultCount < this.m_MaxResults { + + this.m_Results[this.m_ResultCount] = polyRefs[i] + this.m_ResultCount++ + } + } +} + +// Returns polygons which overlap the query box. +// Params: +// center[3] - (in) the center of the search box. +// extents[3] - (in) the extents of the search box. +// filter - (in) path polygon filter. +// polys - (out) array holding the search result. +// polyCount - (out) Number of polygons in search result array. +// maxPolys - (in) The max number of polygons the polys array can hold. +func (this *NavMeshQuery) QueryPolygons(center Vector3f, extents Vector3f, filter *QueryFilter, + polys []NavMeshPolyRef, polyCount *int32, maxPolys int32) { + + polygons := NewPolygonQuery(this, filter, polys, maxPolys) + this.m_NavMesh.QueryPolygons(filter.GetTypeID(), center, extents, polygons) + + if polyCount != nil { + *polyCount = polygons.m_ResultCount + } +} + +func (this *NavMeshQuery) InitSlicedFindPath(startRef NavMeshPolyRef, endRef NavMeshPolyRef, startPos Vector3f, + endPos Vector3f, agentType int32, areaMask int32, costs [kAreaCount]float32) NavMeshStatus { + if this.m_NavMesh == nil { + return kNavMeshFailure + } + filter := NewQueryFilter() + filter.Set(agentType, uint32(areaMask), costs[:]) + return this.InitSlicedFindPath2(startRef, endRef, startPos, endPos, filter) +} + +// Initializes sliced path find query. +// Note 1: calling any other NavMeshQuery method before calling FindPathEnd() +// may results in corrupted data! +// Note 2: The pointer to filter is store, and used in subsequent +// calls to UpdateSlicedFindPath(). +// Params: +// startRef - (in) ref to path start polygon. +// endRef - (in) ref to path end polygon. +// startPos[3] - (in) Path start location. +// endPos[3] - (in) Path end location. +// filter - (in) path polygon filter. +func (this *NavMeshQuery) InitSlicedFindPath2(startRef NavMeshPolyRef, endRef NavMeshPolyRef, startPos Vector3f, + endPos Vector3f, filter *QueryFilter) NavMeshStatus { + Assert(this.m_NavMesh != nil) + Assert(this.m_NodePool != nil) + Assert(this.m_OpenList != nil) + + // Init path state. + this.m_QueryData = NavMeshQueryData{} + this.m_QueryData.status = kNavMeshFailure + this.m_QueryData.startRef = startRef + this.m_QueryData.endRef = endRef + this.m_QueryData.startPos = startPos + this.m_QueryData.endPos = endPos + this.m_QueryData.filter = filter + if startRef == 0 || endRef == 0 { + return kNavMeshFailure | kNavMeshInvalidParam + } + + // Validate input + if !this.m_NavMesh.IsValidPolyRef(startRef) || !this.m_NavMesh.IsValidPolyRef(endRef) { + return kNavMeshFailure | kNavMeshInvalidParam + } + + // Validate first poly + if !this.m_QueryData.filter.PassFilter(this.m_NavMesh.GetPolyFlags(startRef)) { + return kNavMeshFailure + } + if startRef == endRef { + this.m_QueryData.status = kNavMeshSuccess + return kNavMeshSuccess + } + + this.m_NodePool.Clear() + this.m_OpenList.Clear() + var endPosProjStart Vector3f + this.ClosestPointOnPoly(startRef, endPos, &endPosProjStart) + startHeuristic := Distance(endPosProjStart, endPos) * H_SCALE + startNode := this.m_NodePool.GetNode(startRef) + startNode.pos = startPos + startNode.pidx = 0 + startNode.cost = 0 + startNode.total = startHeuristic + startNode.id = startRef + startNode.flags = kOpen + this.m_OpenList.Push(startNode) + this.m_QueryData.status = kNavMeshInProgress + this.m_QueryData.lastBestNode = startNode + this.m_QueryData.lastBestNodeCost = startHeuristic + return this.m_QueryData.status +} + +// Updates sliced path find query. +// Params: +// maxIter - (in) Max number of iterations to update. +// doneIters - (out,opt) Number of iterations done during the update. +// Returns: Path query state. +func (this *NavMeshQuery) UpdateSlicedFindPath(maxIter int32, doneIters *int32) NavMeshStatus { + Assert(this.m_NavMesh != nil) + Assert(this.m_NodePool != nil) + Assert(this.m_OpenList != nil) + if !NavMeshStatusInProgress(this.m_QueryData.status) { + if doneIters != nil { + *doneIters = 0 + } + return this.m_QueryData.status + } + + // Make sure the request is still valid. + if !this.m_NavMesh.IsValidPolyRef(this.m_QueryData.startRef) || !this.m_NavMesh.IsValidPolyRef(this.m_QueryData.endRef) { + this.m_QueryData.status = kNavMeshFailure + if doneIters != nil { + *doneIters = 0 + } + return kNavMeshFailure + } + + iter := int32(0) + for iter < maxIter && !this.m_OpenList.empty() { + iter++ + + // Remove node from open list and put it in closed list. + bestNode := this.m_OpenList.Pop() + bestNode.flags &= ^kOpen + bestNode.flags |= kClosed + + // Reached the goal, stop searching. + if bestNode.id == this.m_QueryData.endRef { + this.m_QueryData.lastBestNode = bestNode + details := this.m_QueryData.status & kNavMeshStatusDetailMask + this.m_QueryData.status = kNavMeshSuccess | details + if doneIters != nil { + *doneIters = iter + } + return this.m_QueryData.status + } + + // Get and verify best poly ref. + bestRef := bestNode.id + if !this.m_NavMesh.IsValidPolyRef(bestRef) { + // Things changed during the sliced query, fail. + this.m_QueryData.status = kNavMeshFailure + if doneIters != nil { + *doneIters = iter + } + return kNavMeshFailure + } + + // Get and verify parent poly ref. + parentRef := NavMeshPolyRef(0) + if bestNode.pidx != 0 { + // Things changed during the sliced query, fail. + parentRef = this.m_NodePool.GetNodeAtIdx(bestNode.pidx).id + if !this.m_NavMesh.IsValidPolyRef(parentRef) { + this.m_QueryData.status = kNavMeshFailure + if doneIters != nil { + *doneIters = iter + } + return kNavMeshFailure + } + } + + for link := this.m_NavMesh.GetFirstLink(bestRef); link != nil; link = this.m_NavMesh.GetNextLink(link) { + this.UpdateNeighbourLink(link, parentRef, bestRef, bestNode) + } + } + + // Exhausted all nodes, but could not find path. + if this.m_OpenList.empty() { + details := this.m_QueryData.status & kNavMeshStatusDetailMask + this.m_QueryData.status = kNavMeshSuccess | details + } + + if doneIters != nil { + *doneIters = iter + } + return this.m_QueryData.status +} + +func (this *NavMeshQuery) UpdateNeighbourLink(link *NavMeshLink, parentRef NavMeshPolyRef, bestRef NavMeshPolyRef, bestNode *NavMeshNode) { + Assert(this.m_OpenList != nil) + Assert(this.m_NodePool != nil) + neighbourRef := link.ref + + // Skip invalid ids and do not expand back to where we came from. + if neighbourRef == 0 || neighbourRef == parentRef { + return + } + + if !this.m_QueryData.filter.PassFilter(this.m_NavMesh.GetPolyFlags(neighbourRef)) { + return + } + + neighbourNode := this.m_NodePool.GetNode(neighbourRef) + if neighbourNode == nil { + this.m_QueryData.status |= kNavMeshOutOfNodes + return + } + + // If the node is visited the first time, calculate node position. + if neighbourNode.flags == kNew { + var left, right Vector3f + if NavMeshStatusFailed(this.GetPortalPoints(bestRef, neighbourRef, &left, &right)) { + return + } + + dl := right.Sub(left) + ddl := DotVector3f(dl, dl) + if ddl > 0.0001 { + dp := bestNode.pos.Sub(left) + pdot := DotVector3f(dl, dp) / ddl + pdot = FloatClamp(pdot, 0.05, 0.95) // Avoid degenerating to vertex + + dp = left.Add(dl.Mulf(pdot)) + neighbourNode.pos = dp + } else { + neighbourNode.pos = left + } + } + + // Calculate cost and heuristic. + heuristic := float32(0.0) + cost := bestNode.cost + Distance(bestNode.pos, neighbourNode.pos)*GetCostModifier(this.m_NavMesh, this.m_QueryData.filter, bestRef) + + // Special case for last node. + if neighbourRef == this.m_QueryData.endRef { + cost += Distance(neighbourNode.pos, this.m_QueryData.endPos) * GetCostModifier(this.m_NavMesh, this.m_QueryData.filter, neighbourRef) + } else { + var endPosProjNeighbour Vector3f + if NavMeshStatusFailed(this.ClosestPointOnPolyBoundary(neighbourRef, this.m_QueryData.endPos, &endPosProjNeighbour)) { + return + } + heuristic = Distance(endPosProjNeighbour, this.m_QueryData.endPos) * H_SCALE + } + + // Update nearest node to target so far. + if heuristic < this.m_QueryData.lastBestNodeCost { + this.m_QueryData.lastBestNodeCost = heuristic + this.m_QueryData.lastBestNode = neighbourNode + } + + total := cost + heuristic + + // The node is already in open list and the new result is worse, skip. + if (neighbourNode.flags&kOpen) != 0 && total >= neighbourNode.total { + return + } + // The node is already visited and process, and the new result is worse, skip. + if (neighbourNode.flags&kClosed) != 0 && total >= neighbourNode.total { + return + } + + // Add or update the node. + neighbourNode.pidx = this.m_NodePool.GetNodeIdx(bestNode) + neighbourNode.id = neighbourRef + neighbourNode.flags &= ^kClosed + neighbourNode.cost = cost + neighbourNode.total = total + if (neighbourNode.flags & kOpen) != 0 { + // Already in open, update node location. + this.m_OpenList.Modify(neighbourNode) + } else { + // Put the node in open list. + neighbourNode.flags |= kOpen + this.m_OpenList.Push(neighbourNode) + } +} + +// Finalizes sliced path find query and returns found path. +// pathCount - (out) Number of polygons in search result. +func (this *NavMeshQuery) FinalizeSlicedFindPath(pathCount *int32) NavMeshStatus { + Assert(this.m_NodePool != nil) + *pathCount = 0 + if NavMeshStatusFailed(this.m_QueryData.status) { + // Reset query. + this.m_QueryData = NavMeshQueryData{} + return kNavMeshFailure + } + + n := int32(0) + if this.m_QueryData.startRef == this.m_QueryData.endRef { + // Special case: the search starts and ends at same poly. + n = 1 + } else { + // Reverse the path. + Assert(this.m_QueryData.lastBestNode != nil) + if this.m_QueryData.lastBestNode.id != this.m_QueryData.endRef { + this.m_QueryData.status |= kNavMeshPartialResult + } + + var prev *NavMeshNode + node := this.m_QueryData.lastBestNode + for { + next := this.m_NodePool.GetNodeAtIdx(node.pidx) + node.pidx = this.m_NodePool.GetNodeIdx(prev) + prev = node + node = next + n++ + if node == nil { + break + } + } + + this.m_QueryData.startNode = prev + } + + details := this.m_QueryData.status & kNavMeshStatusDetailMask + *pathCount = n + return kNavMeshSuccess | details +} + +// Finalizes partial sliced path find query and returns path to the furthest +// polygon on the existing path that was visited during the search. +// existing - (out) Array of polygons in the existing path. +// existingSize - (out) Number of polygons in existing path array. +// pathCount - (out) Number of polygons in search result. +func (this *NavMeshQuery) FinalizeSlicedFindPathPartial(pathCount *int32, existing []NavMeshPolyRef, + existingSize int32) NavMeshStatus { + *pathCount = 0 + if existingSize == 0 { + return kNavMeshFailure + } + + if NavMeshStatusFailed(this.m_QueryData.status) { + // Reset query. + this.m_QueryData = NavMeshQueryData{} + return kNavMeshFailure + } + + n := int32(0) + if this.m_QueryData.startRef == this.m_QueryData.endRef { + // Special case: the search starts and ends at same poly. + n = 1 + } else { + // Find furthest existing node that was visited. + var prev, node *NavMeshNode + for i := existingSize - 1; i >= 0; i-- { + node = this.m_NodePool.FindNavMeshNode(existing[i]) + if node == nil { + break + } + } + + if node == nil { + return kNavMeshFailure + } + + // Reverse the path. + for { + next := this.m_NodePool.GetNodeAtIdx(node.pidx) + node.pidx = this.m_NodePool.GetNodeIdx(prev) + prev = node + node = next + n++ + if node == nil { + break + } + } + + this.m_QueryData.startNode = prev + } + + details := this.m_QueryData.status & kNavMeshStatusDetailMask + *pathCount = n + return kNavMeshSuccess | details +} + +// Returns found path, must call finalizeSlicedFindPath() or finalizeSlicedFindPathPartial() before calling this function. +// path - (out) array holding the search result. +// pathCount - (out) Number of polygons in search result array. +// maxPath - (in) The max number of polygons the path array can hold. +func (this *NavMeshQuery) GetPath(path []NavMeshPolyRef, pathCount *int32, maxPath int32) NavMeshStatus { + if NavMeshStatusFailed(this.m_QueryData.status) { + // Reset query. + this.m_QueryData = NavMeshQueryData{} + return kNavMeshFailure + } + + n := int32(0) + if this.m_QueryData.startRef == this.m_QueryData.endRef { + // Special case: the search starts and ends at same poly. + path[n] = this.m_QueryData.startRef + n++ + } else { + // startNode is updated when the path is reversed, must have it to continue. + if this.m_QueryData.startNode == nil { + return kNavMeshFailure + } + // Store path + node := this.m_QueryData.startNode + for { + path[n] = node.id + n++ + if n >= maxPath { + this.m_QueryData.status |= kNavMeshBufferTooSmall + break + } + node = this.m_NodePool.GetNodeAtIdx(node.pidx) + if node == nil { + break + } + } + } + + details := this.m_QueryData.status & kNavMeshStatusDetailMask + + // Reset query. + this.m_QueryData = NavMeshQueryData{} + *pathCount = n + return kNavMeshSuccess | details +} + +// returns the Closest Point of Approach (CPA) on segment p for two line segments (p,q). +// note: returns segment midpoint in the degenerate case. +func SegmentSegmentCPA(p0 Vector3f, p1 Vector3f, q0 Vector3f, q1 Vector3f) Vector3f { + u := p1.Sub(p0) + v := q1.Sub(q0) + w0 := p0.Sub(q0) + + a := DotVector3f(u, u) + b := DotVector3f(u, v) + c := DotVector3f(v, v) + d := DotVector3f(u, w0) + e := DotVector3f(v, w0) + den := a*c - b*b + if den == 0 { + return p0.Add(p1).Mulf(0.5) + } + + t := (b*e - c*d) / den + return LerpVector3f(p0, p1, FloatClamp(t, 0, 1)) +} + +// Retrace portals between corners register if type of polygon changes +func (this *NavMeshQuery) RetracePortals(startIndex int32, endIndex int32, + path []NavMeshPolyRef, n int32, termPos Vector3f, straightPath []Vector3f, + straightPathFlags []byte, straightPathRefs []NavMeshPolyRef, maxStraightPath int32) int32 { + Assert(n < maxStraightPath) + Assert(startIndex <= endIndex) + for k := startIndex; k < endIndex-1; k++ { + type1 := DecodePolyIdType(path[k]) + type2 := DecodePolyIdType(path[k+1]) + if type1 != type2 { + var l, r Vector3f + status := this.GetPortalPoints(path[k], path[k+1], &l, &r) + Assert(status == kNavMeshSuccess) // Expect path elements k, k+1 to be verified + cpa := SegmentSegmentCPA(l, r, straightPath[n-1], termPos) + straightPath[n] = cpa + straightPathRefs[n] = path[k+1] + if type2 == kPolyTypeOffMeshConnection { + + straightPathFlags[n] = byte(kStraightPathOffMeshConnection) + } else { + + straightPathFlags[n] = 0 + } + n++ + if n == maxStraightPath { + return maxStraightPath + } + } + } + straightPath[n] = termPos + straightPathRefs[n] = path[endIndex] + if DecodePolyIdType(path[endIndex]) == kPolyTypeOffMeshConnection { + + straightPathFlags[n] = byte(kStraightPathOffMeshConnection) + } else { + + straightPathFlags[n] = 0 + } + n++ + return n +} + +func WorldToTileSafe(tile *NavMeshTile, p Vector3f) Vector3f { + if tile != nil { + return WorldToTile(tile, p) + } else { + return p + } +} + +func TileToWorldSafe(tile *NavMeshTile, p Vector3f) Vector3f { + if tile != nil { + return TileToWorld(tile, p) + } else { + return p + } +} + +// Finds a straight path from start to end locations within the corridor +// described by the path polygons. +// Start and end locations will be clamped on the corridor. +// The returned polygon references are point to polygon which was entered when +// a path point was added. For the end point, zero will be returned. This allows +// to match for example off-mesh link points to their representative polygons. +// Params: +// startPos[3] - (in) Path start location. +// endPo[3] - (in) Path end location. +// path - (in) Array of connected polygons describing the corridor. +// pathSize - (in) Number of polygons in path array. +// straightPath - (out) Points describing the straight path. +// straightPathFlags - (out, opt) Flags describing each point type, see NavMeshStraightPathFlags. +// straightPathRefs - (out, opt) References to polygons at point locations. +// straightPathCount - (out) Number of points in the path. +// maxStraightPath - (in) The max number of points the straight path array can hold. Must be at least 1 +func (this *NavMeshQuery) FindStraightPath(startPos Vector3f, endPos Vector3f, + path []NavMeshPolyRef, pathSize int32, straightPath []Vector3f, + straightPathFlags []byte, straightPathRefs []NavMeshPolyRef, + straightPathCount *int32, maxStraightPath int32) NavMeshStatus { + Assert(this.m_NavMesh != nil) + Assert(maxStraightPath > 1) + Assert(pathSize > 0) + Assert(straightPath != nil) + Assert(straightPathRefs != nil) + Assert(straightPathFlags != nil) + if path[0] == 0 || !this.m_NavMesh.IsValidPolyRef(path[0]) { + *straightPathCount = 0 + return kNavMeshFailure | kNavMeshInvalidParam + } + + straightPath[0] = startPos + straightPathRefs[0] = path[0] + straightPathFlags[0] = byte(kStraightPathStart) + apexIndex := int32(0) + n := int32(1) + if pathSize > 1 { + startTile := this.m_NavMesh.GetTileByRef(NavMeshTileRef(path[0])) + apex := WorldToTileSafe(startTile, startPos) + left := Vector3f{0.0, 0.0, 0.0} + right := Vector3f{0.0, 0.0, 0.0} + leftIndex := int32(-1) + rightIndex := int32(-1) + for i := int32(1); i <= pathSize; i++ { + tile := this.m_NavMesh.GetTileByRef(NavMeshTileRef(path[apexIndex])) + var vl, vr Vector3f + if i == pathSize { + vr = WorldToTileSafe(tile, endPos) + vl = vr + } else { + if NavMeshStatusFailed(this.GetPortalPoints(path[i-1], path[i], &vl, &vr)) { + return kNavMeshFailure | kNavMeshInvalidParam + } + Assert(this.m_NavMesh.IsValidPolyRef(path[i-1])) + Assert(this.m_NavMesh.IsValidPolyRef(path[i])) + vl = WorldToTileSafe(tile, vl) + vr = WorldToTileSafe(tile, vr) + } + + vl = vl.Sub(apex) + vr = vr.Sub(apex) + + // Ensure left/right ordering + if Perp2D(vl, vr) < 0 { + vl, vr = vr, vl + } + + // Terminate funnel by turning + if Perp2D(left, vr) < 0 { + termPos := TileToWorldSafe(tile, apex.Add(left)) + n = this.RetracePortals(apexIndex, leftIndex, path, n, termPos, straightPath, straightPathFlags, straightPathRefs, maxStraightPath) + if n == maxStraightPath { + *straightPathCount = n + return kNavMeshBufferTooSmall | kNavMeshSuccess + } + + apex = WorldToTileSafe(tile, termPos) + left.SetZero() + right.SetZero() + i, apexIndex = leftIndex, leftIndex + continue + } + if Perp2D(right, vl) > 0 { + termPos := TileToWorldSafe(tile, apex.Add(right)) + n = this.RetracePortals(apexIndex, rightIndex, path, n, termPos, straightPath, straightPathFlags, straightPathRefs, maxStraightPath) + if n == maxStraightPath { + *straightPathCount = n + return kNavMeshBufferTooSmall | kNavMeshSuccess + } + + apex = WorldToTileSafe(tile, termPos) + left.SetZero() + right.SetZero() + i, apexIndex = rightIndex, rightIndex + continue + } + // Consider: additional termination test - based on changing up-vector in frame of reference + + // Narrow funnel + if Perp2D(left, vl) >= 0 { + left = vl + leftIndex = i + } + if Perp2D(right, vr) <= 0 { + right = vr + rightIndex = i + } + } + } + + // Remove the the next to last if duplicate point - e.g. start and end positions are the same + // (in which case we have get a single point) + if n > 0 && (straightPath[n-1] == endPos) { + n-- + } + n = this.RetracePortals(apexIndex, pathSize-1, path, n, endPos, straightPath, straightPathFlags, straightPathRefs, maxStraightPath) + if n == maxStraightPath { + *straightPathCount = n + return kNavMeshBufferTooSmall | kNavMeshSuccess + } + + // Fix flag for final path point + straightPathFlags[n-1] = byte(kStraightPathEnd) + *straightPathCount = n + return kNavMeshSuccess +} + +// Moves from startPos to endPos constrained to the navmesh. +// If the endPos is reachable, the resultPos will be endPos, +// or else the resultPos will be the nearest point in navmesh. +// Note: The resulting point is not projected to the ground, use GetPolyHeight() to get height. +// Note: The algorithm is optimized for small delta movement and small number of polygons. +// Params: +// startRef - (in) ref to the polygon where startPos lies. +// startPos[3] - (in) start position of the mover. +// endPos[3] - (in) desired end position of the mover. +// filter - (in) path polygon filter. +// resultPos[3] - (out) new position of the mover. +// visited - (out) array of visited polygons. +// visitedCount - (out) Number of entries in the visited array. +// maxVisitedSize - (in) max number of polygons in the visited array. +func (this *NavMeshQuery) MoveAlongSurface(startRef NavMeshPolyRef, startPos Vector3f, + endPos Vector3f, filter *QueryFilter, resultPos *Vector3f, visited []NavMeshPolyRef, + visitedCount *int32, maxVisitedSize int32) NavMeshStatus { + return this.MoveAlongSurface2(startRef, startPos, endPos, filter, resultPos, visited, visitedCount, maxVisitedSize, this.m_TinyNodePool) +} + +const kMaxStack = 48 + +func (this *NavMeshQuery) MoveAlongSurface2(startRef NavMeshPolyRef, startPos Vector3f, + endPos Vector3f, filter *QueryFilter, resultPos *Vector3f, visited []NavMeshPolyRef, + visitedCount *int32, maxVisitedSize int32, nodePool *NavMeshNodePool) NavMeshStatus { + Assert(this.m_NavMesh != nil) + Assert(nodePool != nil) + *visitedCount = 0 + + // Validate input + if startRef == 0 { + return kNavMeshFailure | kNavMeshInvalidParam + } + if !this.m_NavMesh.IsValidPolyRef(startRef) { + return kNavMeshFailure | kNavMeshInvalidParam + } + + // Test start poly vs filter + if !filter.PassFilter(this.m_NavMesh.GetPolyFlags(startRef)) { + return kNavMeshFailure + } + status := kNavMeshSuccess + + // Here we assume all connected tiles are have the same world xform + startTile := this.m_NavMesh.GetTileByRef(NavMeshTileRef(startRef)) + localStart := WorldToTile(startTile, startPos) + localEnd := WorldToTile(startTile, endPos) + var stack [kMaxStack]*NavMeshNode + nstack := int32(0) + nodePool.Clear() + startNode := nodePool.GetNode(startRef) + startNode.pidx = 0 + startNode.cost = 0 + startNode.total = 0 + startNode.id = startRef + startNode.flags = kClosed + stack[nstack] = startNode + nstack++ + + bestPos := localStart + bestDist := float32(math.MaxFloat32) + var bestNode *NavMeshNode + + // Search constraints + searchPos := LerpVector3f(localStart, localEnd, 0.5) + searchRadSqr := Sqr(Distance(localStart, localEnd)/2.0 + 0.001) + var verts [kNavMeshVertsPerPoly]Vector3f + var neighbours [kNavMeshVertsPerPoly * kMaxNeis]NavMeshPolyRef + for nstack != 0 { + // Pop front. + curNode := stack[0] + for i := int32(0); i < nstack-1; i++ { + stack[i] = stack[i+1] + } + nstack-- + + // Get poly and tile. + // The API input has been checked already, skip checking internal data. + curRef := curNode.id + + // Collect vertices. + nverts := this.m_NavMesh.GetPolyGeometry(curRef, verts[:], neighbours[:], kMaxNeis) + if nverts == 0 { + continue + } + + // If target is inside the poly, stop search. + if PointInPolygon2D(localEnd, verts[:], nverts) { + bestNode = curNode + bestDist = 0 + bestPos = localEnd + break + } + + // Find wall edges and find nearest point inside the walls. + var i, j int32 + for j = int32(nverts - 1); i < nverts; i++ { + // Find links to neighbours. + nneis := int32(0) + neis := neighbours[j*kMaxNeis:] + for k := int32(0); k < kMaxNeis; k++ { + neiRef := neis[k] + if neiRef == 0 { + break + } + + // Skip if no node can be allocated. + neighbourNode := nodePool.GetNode(neiRef) + if neighbourNode == nil { + j = i + continue + } + + // Skip if already visited. + if (neighbourNode.flags & kClosed) != 0 { + j = i + continue + } + + // Do not advance if the polygon is excluded by the filter. + if !filter.PassFilter(this.m_NavMesh.GetPolyFlags(neiRef)) { + j = i + continue + } + + // Skip the link if it is too far from search constraint. + // TODO: Maybe should use GetPortalPoints(), but this one is way faster. + vj := verts[j] + vi := verts[i] + var tseg float32 + distSqr := SqrDistancePointSegment2D(&tseg, searchPos, vj, vi) + if distSqr > searchRadSqr { + j = i + continue + } + + // Mark as the node as visited and push to queue. + if nstack < kMaxStack { + neighbourNode.pidx = nodePool.GetNodeIdx(curNode) + neighbourNode.flags |= kClosed + stack[nstack] = neighbourNode + nstack++ + } + nneis++ + } + + if nneis == 0 { + // Wall edge, calculate distance. + vj := verts[j] + vi := verts[i] + var tseg float32 + distSqr := SqrDistancePointSegment2D(&tseg, localEnd, vj, vi) + if distSqr < bestDist { + // Update nearest distance. + bestPos = LerpVector3f(vj, vi, tseg) + bestDist = distSqr + bestNode = curNode + } + } + j = i + } + } + + n := int32(0) + if bestNode != nil { + // Reverse the path. + var prev *NavMeshNode + node := bestNode + for { + next := nodePool.GetNodeAtIdx(node.pidx) + node.pidx = nodePool.GetNodeIdx(prev) + prev = node + node = next + if node == nil { + break + } + } + + // Store result + node = prev + for { + visited[n] = node.id + n++ + if n >= maxVisitedSize { + status |= kNavMeshBufferTooSmall + break + } + node = nodePool.GetNodeAtIdx(node.pidx) + if node == nil { + break + } + } + } + + *resultPos = TileToWorld(startTile, bestPos) + *visitedCount = n + return status +} + +// Returns portal points between two polygons. +func (this *NavMeshQuery) GetPortalPoints(from NavMeshPolyRef, to NavMeshPolyRef, left *Vector3f, right *Vector3f) NavMeshStatus { + Assert(this.m_NavMesh != nil) + + // Handle ground.offmesh and offmesh.ground + fromOffMeshCon := DecodePolyIdType(from) == uint32(kPolyTypeOffMeshConnection) + toOffMeshCon := DecodePolyIdType(to) == uint32(kPolyTypeOffMeshConnection) + if fromOffMeshCon || toOffMeshCon { + for link := this.m_NavMesh.GetFirstLink(from); link != nil; link = this.m_NavMesh.GetNextLink(link) { + if link.ref == to { + iv := link.edge + Assert(link.edge == 0 || link.edge == 1) + var v0, v1 Vector3f + if fromOffMeshCon { + con := this.m_NavMesh.GetOffMeshConnection(from) + v0 = con.endPoints[iv].mapped[0] + v1 = con.endPoints[iv].mapped[1] + } else if toOffMeshCon { + con := this.m_NavMesh.GetOffMeshConnection(to) + v0 = con.endPoints[iv].mapped[0] + v1 = con.endPoints[iv].mapped[1] + } else { + Assert(false) + } + + // Unpack portal limits. + if link.bmin != 0 || link.bmax != 255 { + s := float32(1.0 / 255.0) + tmin := FloatMax(float32(link.bmin)*s, 0.0) + tmax := FloatMin(float32(link.bmax)*s, 1.0) + *left = LerpVector3f(v0, v1, tmin) + *right = LerpVector3f(v0, v1, tmax) + } else { + *left = v0 + *right = v1 + } + + return kNavMeshSuccess + } + } + return kNavMeshFailure + } + + // Handle ground.ground + + var fromTile *NavMeshTile + var fromPoly *NavMeshPoly + if NavMeshStatusFailed(this.m_NavMesh.GetTileAndPolyByRef(from, &fromTile, &fromPoly)) { + return kNavMeshFailure | kNavMeshInvalidParam + } + var toTile *NavMeshTile + var toPoly *NavMeshPoly + if NavMeshStatusFailed(this.m_NavMesh.GetTileAndPolyByRef(to, &toTile, &toPoly)) { + return kNavMeshFailure | kNavMeshInvalidParam + } + ip := GetPolyIndex(fromTile, fromPoly) + firstLink := fromTile.polyLinks[ip] + var link *NavMeshLink + for flink := this.m_NavMesh.GetLink(firstLink); flink != nil; flink = this.m_NavMesh.GetNextLink(flink) { + if flink.ref == to { + link = flink + break + } + } + if link == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + + // Find portal vertices. + Assert(link.edge < fromPoly.vertCount) + var nextEdge int32 + if link.edge+1 == fromPoly.vertCount { + nextEdge = 0 + } else { + nextEdge = int32(link.edge) + 1 + } + v0 := fromPoly.verts[link.edge] + v1 := fromPoly.verts[nextEdge] + *left = fromTile.verts[v0] + *right = fromTile.verts[v1] + + // If the link is at tile boundary, clamp the vertices to + // the link width. + if link.side != 0xff { + // Unpack portal limits. + if link.bmin != 0 || link.bmax != 255 { + s := float32(1.0 / 255.0) + tmin := FloatMax(float32(link.bmin)*s, 0.0) + tmax := FloatMin(float32(link.bmax)*s, 1.0) + *left = LerpVector3f(fromTile.verts[v0], fromTile.verts[v1], tmin) + *right = LerpVector3f(fromTile.verts[v0], fromTile.verts[v1], tmax) + } + } + + *right = TileToWorld(fromTile, *right) + *left = TileToWorld(fromTile, *left) + return kNavMeshSuccess +} + +// Casts 'walkability' ray along the navmesh surface from startPos towards the endPos. +// Params: +// startRef - (in) ref to the polygon where the start lies. +// startPos[3] - (in) start position of the query. +// endPos[3] - (in) end position of the query. +// filter - (in) path polygon filter. +// result - (out) raycast result data. +// path - (out,opt) visited path polygons. +// pathCount - (out,opt) Number of polygons visited. +// maxPath - (in) max number of polygons in the path array. +func (this *NavMeshQuery) Raycast(startRef NavMeshPolyRef, startPos Vector3f, endPos Vector3f, filter *QueryFilter, + result *NavMeshRaycastResult, path []NavMeshPolyRef, pathCount *int32, maxPath int32) NavMeshStatus { + Assert(this.m_NavMesh != nil) + + // Clear output + *result = NavMeshRaycastResult{} + if pathCount != nil { + *pathCount = 0 + } + + // Validate input + startTile := this.m_NavMesh.GetTileByRef(NavMeshTileRef(startRef)) + if startTile == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + localStartPos := WorldToTile(startTile, startPos) + localEndPos := WorldToTile(startTile, endPos) + curRef := startRef + lastPoly := startRef + var verts [kNavMeshVertsPerPoly]Vector3f + t := float32(0) + costScale := float32(0) + n := int32(0) + status := kNavMeshSuccess + for curRef != 0 { + // Cast ray against current polygon. + nverts := this.m_NavMesh.GetPolyGeometry(curRef, verts[:], nil, 0) + if nverts == 0 { + break + } + var tmin, tmax float32 + var segMin, segMax int32 + if !IntersectSegmentPoly2D(&tmin, &tmax, &segMin, &segMax, localStartPos, localEndPos, verts[:], nverts) && segMax != -1 { + // Could not hit the polygon, keep the old t and report hit. + + // In some cases, when 'startPos' is collinear to an edge between two polygons, 'tmax' becomes a tiny + // negative number and we would break here - causing the raycast to terminate prematurely. + // We prevent that by ensuring tmax > 0 for the first polygon. + if curRef != startRef || tmax > 0 { + break + } + } + + // Keep track of furthest t so far. + if tmax > t { + dt := tmax - t + costScale += dt * float32(filter.GetAreaCost(int32(this.m_NavMesh.GetPolyArea(curRef)))) + t = tmax + } + + lastPoly = curRef + + // Store visited polygons. + if n < maxPath { + path[n] = curRef + n++ + + } else { + status |= kNavMeshBufferTooSmall + } + + // Ray end is completely inside the polygon. + if segMax == -1 { + t = 1.0 + break + } + + // Follow neighbours. + var nextRef NavMeshPolyRef + + for link := this.m_NavMesh.GetFirstLink(curRef); link != nil; link = this.m_NavMesh.GetNextLink(link) { + // Skip off-mesh connections. + if DecodePolyIdType(link.ref) == kPolyTypeOffMeshConnection { + continue + } + + // Find link which contains this edge. + if int32(link.edge) != segMax { + continue + } + + // If the link is internal, accept and just return the ref. + if link.side == 0xff { + nextRef = link.ref + break + } + + // If the link is at tile boundary, + // Check if the link spans the whole edge, and accept. + if link.bmin == 0 && link.bmax == 255 { + nextRef = link.ref + break + } + + // Check for partial edge links. + Assert(int32(link.edge) < nverts) + var nextEdge int32 + if int32(link.edge)+1 == nverts { + nextEdge = 0 + } else { + nextEdge = int32(link.edge) + 1 + } + left := verts[link.edge] + right := verts[nextEdge] + + // Check that the intersection lies inside the link portal. + if link.side == 0 || link.side == 4 { + // Calculate link size. + s := float32(1.0 / 255.0) + lmin := left.z + (right.z-left.z)*float32(link.bmin)*s + lmax := left.z + (right.z-left.z)*float32(link.bmax)*s + if lmin > lmax { + lmin, lmax = lmax, lmin + } + + // Find Z intersection. + z := localStartPos.z + (localEndPos.z-localStartPos.z)*tmax + if z >= lmin && z <= lmax { + nextRef = link.ref + break + } + } else if link.side == 2 || link.side == 6 { + // Calculate link size. + s := float32(1.0 / 255.0) + lmin := left.x + (right.x-left.x)*float32(link.bmin)*s + lmax := left.x + (right.x-left.x)*float32(link.bmax)*s + if lmin > lmax { + lmin, lmax = lmax, lmin + } + + // Find X intersection. + x := localStartPos.x + (localEndPos.x-localStartPos.x)*tmax + if x >= lmin && x <= lmax { + nextRef = link.ref + break + } + } + } + + if nextRef == 0 || !filter.PassFilter(this.m_NavMesh.GetPolyFlags(nextRef)) { + // No accessible neighbour, we hit a wall. + + // Calculate hit normal. + a := segMax + b := int32(0) + if segMax+1 < nverts { + b = segMax + 1 + } + va := verts[a] + vb := verts[b] + dx := vb.x - va.x + dz := vb.z - va.z + lenSq := dx*dx + dz*dz + if lenSq > 0 { + s := float32(1.0 / math.Sqrt(float64(lenSq))) + result.normal.x = dz * s + result.normal.y = 0.0 + result.normal.z = -dx * s + } + + // Advance ref - it allows us to obtain the blocking poly ref. + curRef = nextRef + break + } + + // No hit, advance to neighbour polygon. + curRef = nextRef + } + + result.t = t + result.totalCost = costScale * Distance(startPos, endPos) + result.lastPoly = lastPoly + result.hitPoly = curRef + result.normal = TileToWorldVector(startTile, result.normal) + if pathCount != nil { + *pathCount = n + } + return status +} + +// Finds non-overlapping local neighbourhood around center location. +// Note: The algorithm is optimized for small query radius and small number of polygons. +// Params: +// startRef - (in) ref to the polygon where the search starts. +// centerPos[3] - (in) center if the query circle. +// radius - (in) radius of the query circle. +// filter - (in) path polygon filter. +// resultRef - (out) refs to the polygons touched by the circle. +// resultParent - (out, opt) parent of each result polygon. +// resultCount - (out) number of results. +// maxResult - (int) maximum capacity of search results. +func (this *NavMeshQuery) FindLocalNeighbourhood(startRef NavMeshPolyRef, centerPos Vector3f, + radius float32, filter *QueryFilter, resultRef []NavMeshPolyRef, resultParent []NavMeshPolyRef, + resultCount *int32, maxResult int32) NavMeshStatus { + Assert(this.m_NavMesh != nil) + Assert(this.m_TinyNodePool != nil) + *resultCount = 0 + + // Validate input + if startRef == 0 || !this.m_NavMesh.IsValidPolyRef(startRef) { + return kNavMeshFailure | kNavMeshInvalidParam + } + var stack [kMaxStack]*NavMeshNode + nstack := 0 + this.m_TinyNodePool.Clear() + startNode := this.m_TinyNodePool.GetNode(startRef) + startNode.pidx = 0 + startNode.id = startRef + startNode.flags = kClosed + stack[nstack] = startNode + nstack++ + + radiusSqr := Sqr(radius) + var pa [kNavMeshVertsPerPoly]Vector3f + var pb [kNavMeshVertsPerPoly]Vector3f + status := kNavMeshSuccess + n := int32(0) + if n < maxResult { + resultRef[n] = startNode.id + if resultParent != nil { + resultParent[n] = 0 + } + n++ + } else { + status |= kNavMeshBufferTooSmall + } + + for nstack != 0 { + // Pop front. + curNode := stack[0] + for i := 0; i < nstack-1; i++ { + stack[i] = stack[i+1] + } + nstack-- + + // Get poly and tile. + // The API input has been checked already, skip checking internal data. + curRef := curNode.id + for link := this.m_NavMesh.GetFirstLink(curRef); link != nil; link = this.m_NavMesh.GetNextLink(link) { + neighbourRef := link.ref + + // Skip off-mesh connections. + if DecodePolyIdType(neighbourRef) == kPolyTypeOffMeshConnection { + continue + } + + // Skip invalid neighbours. + if neighbourRef == 0 { + continue + } + + // Skip if cannot alloca more nodes. + neighbourNode := this.m_TinyNodePool.GetNode(neighbourRef) + if neighbourNode == nil { + continue + } + // Skip visited. + if (neighbourNode.flags & kClosed) != 0 { + continue + } + + // Expand to neighbour + var neighbourTile *NavMeshTile + var neighbourPoly *NavMeshPoly + this.m_NavMesh.GetTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly) + + // Do not advance if the polygon is excluded by the filter. + if !filter.PassFilter(neighbourPoly.flags) { + continue + } + + // Find edge and calc distance to the edge. + var va, vb Vector3f + if this.GetPortalPoints(curRef, neighbourRef, &va, &vb) == 0 { + continue + } + + // If the circle is not touching the next polygon, skip it. + var tseg float32 + distSqr := SqrDistancePointSegment2D(&tseg, centerPos, va, vb) + if distSqr > radiusSqr { + continue + } + + // Mark node visited, this is done before the overlap test so that + // we will not visit the poly again if the test fails. + neighbourNode.flags |= kClosed + neighbourNode.pidx = this.m_TinyNodePool.GetNodeIdx(curNode) + + // Check that the polygon does not collide with existing polygons. + + // Collect vertices of the neighbour poly. + npa := this.m_NavMesh.GetPolyGeometry(neighbourRef, pa[:], nil, 0) + overlap := false + for j := int32(0); j < n; j++ { + pastRef := resultRef[j] + // Connected polys do not overlap. + connected := false + for clink := this.m_NavMesh.GetFirstLink(curRef); clink != nil; clink = this.m_NavMesh.GetNextLink(clink) { + if clink.ref == pastRef { + connected = true + break + } + } + if connected { + continue + } + // Get vertices and test overlap + npb := this.m_NavMesh.GetPolyGeometry(pastRef, pb[:], nil, 0) + if OverlapPolyPoly2D(pa[:], npa, pb[:], npb) { + overlap = true + break + } + } + if overlap { + continue + } + + // This poly is fine, store and advance to the poly. + if n < maxResult { + resultRef[n] = neighbourRef + if resultParent != nil { + resultParent[n] = curRef + } + n++ + } else { + status |= kNavMeshBufferTooSmall + } + + if nstack < kMaxStack { + stack[nstack] = neighbourNode + nstack++ + } + } + } + + *resultCount = n + return status +} + +type SegInterval struct { + ref NavMeshPolyRef + tmin, tmax int16 +} + +func InsertInterval(ints []SegInterval, nints int32, maxInts int32, tmin int16, tmax int16, ref NavMeshPolyRef) int32 { + if nints+1 > maxInts { + return maxInts + } + // Find insertion point. + idx := int32(0) + for idx < nints { + if tmax <= ints[idx].tmin { + break + } + idx++ + } + // Move current results. + if nints-idx != 0 { + for i := nints - idx - 1; i >= 0; i-- { + ints[nints+idx+1+i] = ints[nints+idx+i] + } + } + // Store + ints[idx].ref = ref + ints[idx].tmin = tmin + ints[idx].tmax = tmax + return nints + 1 +} + +const MAX_INTERVAL = 16 + +// Returns wall segments of specified polygon. +// If 'segmentRefs' is specified, both the wall and portal segments are returned. +// Wall segments will have null (0) polyref, and portal segments store the polygon they lead to. +// Params: +// ref - (in) ref to the polygon. +// filter - (in) path polygon filter. +// segmentVerts[2*maxSegments] - (out) wall segments (2 endpoints per segment). +// segmentRefs[maxSegments] - (out,opt) reference to a neighbour. +// segmentCount - (out) number of wall segments. +// maxSegments - (in) max number of segments that can be stored in 'segments'. +func (this *NavMeshQuery) GetPolyWallSegments(ref NavMeshPolyRef, filter *QueryFilter, + segmentVerts []Vector3f, segmentRefs []NavMeshPolyRef, segmentCount *int32, maxSegments int32) NavMeshStatus { + Assert(this.m_NavMesh != nil) + if DecodePolyIdType(ref) == kPolyTypeOffMeshConnection { + return kNavMeshFailure | kNavMeshInvalidParam + } + var tile *NavMeshTile + var poly *NavMeshPoly + if NavMeshStatusFailed(this.m_NavMesh.GetTileAndPolyByRef(ref, &tile, &poly)) { + return kNavMeshFailure | kNavMeshInvalidParam + } + n := int32(0) + var ints [MAX_INTERVAL]SegInterval + storePortals := segmentRefs != nil + status := kNavMeshSuccess + for i, j := uint8(0), poly.vertCount-1; i < poly.vertCount; j, i = i, i+1 { + // Skip non-solid edges. + nints := int32(0) + if (poly.neis[j] & kNavMeshExtLink) != 0 { + // Tile border. + ip := GetPolyIndex(tile, poly) + firstLink := tile.polyLinks[ip] + for link := this.m_NavMesh.GetLink(firstLink); link != nil; link = this.m_NavMesh.GetNextLink(link) { + if link.edge == j { + if link.ref != 0 { + var neiTile *NavMeshTile + var neiPoly *NavMeshPoly + this.m_NavMesh.GetTileAndPolyByRefUnsafe(link.ref, &neiTile, &neiPoly) + if neiPoly != nil && filter.PassFilter(neiPoly.flags) { + nints = InsertInterval(ints[:], nints, MAX_INTERVAL, int16(link.bmin), int16(link.bmax), link.ref) + } + } + } + } + } else { + // Internal edge + var ref NavMeshPolyRef + if (poly.neis[j]) != 0 { + idx := uint32(poly.neis[j] - 1) + ref = this.m_NavMesh.GetPolyRefBase(tile) | EncodeBasePolyId(kPolyTypeGround, idx) + if !storePortals && !filter.PassFilter(tile.polys[idx].flags) { + ref = 0 + } + } + + // If the edge leads to another polygon and portals are not stored, skip. + if ref != 0 && !storePortals { + continue + } + if n < maxSegments { + vj := tile.verts[poly.verts[j]] + vi := tile.verts[poly.verts[i]] + segmentVerts[2*n+0] = vj + segmentVerts[2*n+1] = vi + if segmentRefs != nil { + segmentRefs[n] = ref + } + n++ + } else { + status |= kNavMeshBufferTooSmall + } + + continue + } + + // Add sentinels + nints = InsertInterval(ints[:], nints, MAX_INTERVAL, -1, 0, 0) + nints = InsertInterval(ints[:], nints, MAX_INTERVAL, 255, 256, 0) + + // Store segments. + vj := tile.verts[poly.verts[j]] + vi := tile.verts[poly.verts[i]] + for k := int32(1); k < nints; k++ { + // Portal segment. + if storePortals && ints[k].ref != 0 { + tmin := float32(ints[k].tmin) / 255.0 + tmax := float32(ints[k].tmax) / 255.0 + if n < maxSegments { + segmentVerts[2*n+0] = LerpVector3f(vj, vi, tmin) + segmentVerts[2*n+1] = LerpVector3f(vj, vi, tmax) + if segmentRefs != nil { + segmentRefs[n] = ints[k].ref + } + n++ + } else { + status |= kNavMeshBufferTooSmall + } + } + + // Wall segment. + imin := ints[k-1].tmax + imax := ints[k].tmin + if imin != imax { + tmin := float32(imin) / 255.0 + tmax := float32(imax) / 255.0 + if n < maxSegments { + segmentVerts[2*n+0] = LerpVector3f(vj, vi, tmin) + segmentVerts[2*n+1] = LerpVector3f(vj, vi, tmax) + if segmentRefs != nil { + segmentRefs[n] = 0 + } + n++ + } else { + status |= kNavMeshBufferTooSmall + } + } + } + } + + *segmentCount = n + return status +} + +// Finds the distance from the specified position to the nearest polygon wall. +// @param[in] startRef The reference id of the polygon containing @p centerPos. +// @param[in] centerPos The center of the search circle. [(x, y, z)] +// @param[in] filter The polygon filter to apply to the query. +// @param[out] hitDist The distance to the nearest wall from @p centerPos. +// @param[out] hitPos The nearest position on the wall that was hit. [(x, y, z)] +// @param[out] hitNormal The normalized ray formed from the wall point to the +// +// source point. [(x, y, z)] +// +// @returns The status flags for the query. +func (this *NavMeshQuery) FindDistanceToWall(startRef NavMeshPolyRef, centerPos Vector3f, + filter *QueryFilter, hitDist *float32, hitPos *Vector3f, hitNormal *Vector3f, + hitFlags *uint32) NavMeshStatus { + Assert(this.m_NavMesh != nil) + Assert(this.m_NodePool != nil) + Assert(this.m_OpenList != nil) + + // Validate input + startTile := this.m_NavMesh.GetTileByRef(NavMeshTileRef(startRef)) + if startTile == nil { + return kNavMeshFailure | kNavMeshInvalidParam + } + localCenterPos := WorldToTile(startTile, centerPos) + this.m_NodePool.Clear() + this.m_OpenList.Clear() + startNode := this.m_NodePool.GetNode(startRef) + startNode.pos = localCenterPos + startNode.pidx = 0 + startNode.cost = 0 + startNode.total = 0 + startNode.id = startRef + startNode.flags = kOpen + this.m_OpenList.Push(startNode) + radiusSqr := float32(math.MaxFloat32) + status := kNavMeshSuccess + var verts [kNavMeshVertsPerPoly]Vector3f + var neighbours [kNavMeshVertsPerPoly * kMaxNeis]NavMeshPolyRef + edgeNormal := Vector3f{0.0, 0.0, 0.0} + for !this.m_OpenList.empty() { + bestNode := this.m_OpenList.Pop() + bestNode.flags &= ^kOpen + bestNode.flags |= kClosed + + // Get poly and tile. + + // The API input has been checked already, skip checking internal data. + bestRef := bestNode.id + + // Get parent poly and tile. + var parentRef NavMeshPolyRef = 0 + if bestNode.pidx != 0 { + parentRef = this.m_NodePool.GetNodeAtIdx(bestNode.pidx).id + } + + // Collect vertices. + nverts := this.m_NavMesh.GetPolyGeometry(bestRef, verts[:], neighbours[:], kMaxNeis) + if nverts == 0 { + continue + } + + // Hit test walls, pruning the search distance too. + for i, j := int32(0), nverts-1; i < nverts; j, i = i, i+1 { + // Skip non-solid edges. + solid := true + neis := neighbours[j*kMaxNeis:] + for k := int32(0); k < kMaxNeis; k++ { + if neis[k] == 0 { + break + } + if filter.PassFilter(this.m_NavMesh.GetPolyFlags(neis[k])) { + // Edge is passable. + solid = false + break + } + } + if !solid { + continue + } + + // Calc distance to the edge. + vj := verts[j] + vi := verts[i] + var tseg float32 + distSqr := SqrDistancePointSegment2D(&tseg, localCenterPos, vj, vi) + + // Edge is too far, skip. + if distSqr > radiusSqr { + continue + } + + // Hit wall, update radius. + radiusSqr = distSqr + if hitFlags != nil { + *hitFlags = this.m_NavMesh.GetPolyFlags(bestRef) + } + + // Calculate hit pos. + *hitPos = LerpVector3f(vj, vi, tseg) + + // Calculate the 2D edge normal + edgeNormal.x = vi.z - vj.z + edgeNormal.z = vj.x - vi.x + } + + // Expand search + for i, j := int32(0), nverts-1; i < nverts; j, i = i, i+1 { + // Skip non-solid edges. + neis := neighbours[j*kMaxNeis:] + for k := int32(0); k < kMaxNeis; k++ { + if neis[k] == 0 { + break + } + neighbourRef := neis[k] + // Skip invalid neighbours and do not follow back to parent. + if neighbourRef == 0 || neighbourRef == parentRef { + continue + } + // Skip off-mesh connections. + if DecodePolyIdType(neighbourRef) == kPolyTypeOffMeshConnection { + continue + } + // Calculate distance to the edge. + va := verts[j] + vb := verts[i] + var tseg float32 + distSqr := SqrDistancePointSegment2D(&tseg, localCenterPos, va, vb) + + // If the circle is not touching the next polygon, skip it. + if distSqr > radiusSqr { + continue + } + if !filter.PassFilter(this.m_NavMesh.GetPolyFlags(neighbourRef)) { + continue + } + neighbourNode := this.m_NodePool.GetNode(neighbourRef) + if neighbourNode == nil { + status |= kNavMeshOutOfNodes + continue + } + + if (neighbourNode.flags & kClosed) != 0 { + continue + } + + // Cost + if neighbourNode.flags == kNew { + neighbourNode.pos = LerpVector3f(va, vb, 0.5) + } + + total := bestNode.total + Distance(bestNode.pos, neighbourNode.pos) + + // The node is already in open list and the new result is worse, skip. + if (neighbourNode.flags&kOpen) != 0 && total >= neighbourNode.total { + continue + } + neighbourNode.id = neighbourRef + neighbourNode.flags = neighbourNode.flags & ^kClosed + neighbourNode.pidx = this.m_NodePool.GetNodeIdx(bestNode) + neighbourNode.total = total + if (neighbourNode.flags & kOpen) != 0 { + this.m_OpenList.Modify(neighbourNode) + } else { + neighbourNode.flags |= kOpen + this.m_OpenList.Push(neighbourNode) + } + } + } + } + + // Calculate the 2D hit normal + // Use the direction to the hit position to ensure smooth behaviour across concave corner points. + // Use the navmesh edge normal when position mapped onto/outside the edge. + direction := localCenterPos.Sub(*hitPos) + dot2d := direction.x*edgeNormal.x + direction.z*edgeNormal.z + if dot2d > 1e-4 { + direction.y = 0.0 + *hitNormal = Normalize(direction) + } else { + *hitNormal = NormalizeSafe(edgeNormal, Vector3f{0, 0, 0}) + } + + *hitDist = Sqrt(radiusSqr) + *hitNormal = TileToWorldVector(startTile, *hitNormal) + *hitPos = TileToWorld(startTile, *hitPos) + return status +} + +// Returns true if poly reference ins in closed list. +func (this *NavMeshQuery) IsInClosedList(ref NavMeshPolyRef) bool { + if this.m_NodePool == nil { + return false + } + + node := this.m_NodePool.FindNavMeshNode(ref) + return node != nil && node.flags&kClosed != 0 +} diff --git a/pkg/navmesh/nav_mesh_query.go b/pkg/navmesh/nav_mesh_query.go new file mode 100644 index 00000000..e9c33ee1 --- /dev/null +++ b/pkg/navmesh/nav_mesh_query.go @@ -0,0 +1,31 @@ +package navmesh + +type NavMeshRaycastResult struct { + t float32 // hit parameter along the segment, 1 if no hit. + normal Vector3f // edge hit normal + totalCost float32 // weighed length of raycast, using filter weights. + lastPoly NavMeshPolyRef // last valid polygon + hitPoly NavMeshPolyRef // last polygon or polygon hit - zero if external edge +} + +type NavMeshQueryData struct { + status NavMeshStatus + lastBestNode *NavMeshNode + startNode *NavMeshNode + lastBestNodeCost float32 + startRef, endRef NavMeshPolyRef + startPos, endPos Vector3f + filter *QueryFilter +} + +type NavMeshQuery struct { + m_NavMesh *NavMesh // Pointer to navmesh data. + m_QueryData NavMeshQueryData // Sliced query state. + m_TinyNodePool *NavMeshNodePool // Pointer to small node pool. + m_NodePool *NavMeshNodePool // Pointer to node pool. + m_OpenList *NavMeshNodeQueue // Pointer to open list queue. +} + +func (this *NavMeshQuery) GetAttachedNavMesh() *NavMesh { + return this.m_NavMesh +} diff --git a/pkg/navmesh/nav_mesh_tile_carving.go b/pkg/navmesh/nav_mesh_tile_carving.go new file mode 100644 index 00000000..a70bdaf7 --- /dev/null +++ b/pkg/navmesh/nav_mesh_tile_carving.go @@ -0,0 +1,1606 @@ +package navmesh + +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)) + polyRegionsSize := Align4(unsafe.Sizeof(NavMeshPolyRegion(0)) * uintptr(header.polyCount)) + + d := headerSize + var verts []Vector3f + sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&(verts))) + sliceHeader.Cap = int(header.vertCount) + sliceHeader.Len = int(header.vertCount) + sliceHeader.Data = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + 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 = 0x00 + if sliceHeader.Len > 0 { + sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d]))) + } + d += bvtreeSize + + var polyRegions []NavMeshPolyRegion + sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(polyRegions))) + sliceHeader.Cap = int(header.polyCount) + sliceHeader.Len = int(header.polyCount) + sliceHeader.Data = 0x00 + if sliceHeader.Len > 0 { + sliceHeader.Data = uintptr(unsafe.Pointer(&(data[d]))) + } + d += polyRegionsSize + + if d != uint32(dataSize) { + return false + } + + tile.verts = verts + tile.polys = polys + tile.detailMeshes = detailMeshes + tile.detailVerts = detailVerts + tile.detailTris = detailTris + tile.bvTree = bvTree + tile.polyRegions = polyRegions + + // 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 { + return DotVector2f(dp, dp) + } + t := DotVector2f(ds, dp) / den + t = FloatClamp(t, 0, 1) + diff := ds.Mulf(t).Sub(dp) + return DotVector2f(diff, diff) +} + +func SimplifyPolyline(hull *Vertex2Array, thr float32) { + i := 0 + count := len(*hull) + for i < count && count > 2 { + pa := (*hull)[PrevIndex(int32(i), int32(count))] + pb := (*hull)[i] + pc := (*hull)[NextIndex(int32(i), int32(count))] + if DistancePointSegmentSqr(pb, pa, pc) < thr*thr { + hull.erase(i) + count-- + } else { + i++ + } + } +} + +func OffsetPolygon(dest *Vertex2Array, poly Vertex2Array, offset float32) { + count := int32(len(poly)) + *dest = make([]Vector2f, 0, count) + for i := int32(0); i < count; i++ { + curr := poly[i] + prev := poly[PrevIndex(i, count)] + next := poly[NextIndex(i, count)] + diffa := NormalizeSafe2(curr.Sub(prev), NewVector2f(0, 0)) + diffb := NormalizeSafe2(next.Sub(curr), NewVector2f(0, 0)) + + // Calculate offset vectors based on neighbor segment directions. + // Scale the offsets to maintain constant line width. + dla := NewVector2f(-diffa.y, diffa.x) + dlb := NewVector2f(-diffb.y, diffb.x) + + // More than 90.1 degree turn, add 2 points. + // Use slack so that about 90 degree corners won't get beveled (common case with box obstacle). + dot := DotVector2f(diffa, diffb) + kCos90p1 := float32(-0.00174542) + if dot < kCos90p1 { + // This is poorman's approximation of a bevel which is offset + // so that it approximates a circle. Consider 2 cases below. + // B._____ A._____.B + // A.´ | | + // | x---- | x | + // | | | | | + // A correct version likely needs asin () & co, not used for speed reasons. + pos := curr.Add(diffa.Mulf(0.25 + FloatAbs(dot)*0.75*offset)) + *dest = append(*dest, pos.Add(dla.Mulf(offset))) + *dest = append(*dest, pos.Add(dlb.Mulf(offset))) + } else { + dm := dla.Add(dlb).Mulf(0.5) + dmr2 := DotVector2f(dm, dm) + if dmr2 > 0.0 { + dm = dm.Mulf(1.0 / dmr2) + } + *dest = append(*dest, curr.Add(dm.Mulf(offset))) + } + } +} + +func CalculateCarveHullFromPoints(carveHull *Hull, localHullBounds *MinMaxAABB, shape *NavMeshCarveShape, + tileOffset Vector3f, carveDepth float32, carveWidth float32, + points []Vector3f, pointCount int32) bool { + // Calculate convex hull of the obstacle on XZ plane + *carveHull = make([]Plane, 0) + var projectedPoints Vertex2Array + var hull Vertex2Array + var hullOffset Vertex2Array + projectedPoints = make([]Vector2f, pointCount) + for i := int32(0); i < pointCount; i++ { + projectedPoints[i] = NewVector2f(points[i].x, points[i].z) + } + + CalculateConvexHull(&hull, &projectedPoints) + SimplifyPolyline(&hull, carveWidth*0.1) + OffsetPolygon(&hullOffset, hull, carveWidth) + + // Bail out if hull has been degenerated. + // It is possible that SimplifyPolyline will simplify the obstacle down to a line, + // OffsetPolygon can take care of that. This is should only happen when the obstacle + // degenerates to a point. + if len(hullOffset) < 3 { + return false + } + + *localHullBounds = shape.bounds + localHullBounds.m_Min = localHullBounds.m_Min.Sub(tileOffset) + localHullBounds.m_Max = localHullBounds.m_Max.Sub(tileOffset) + hullCount := int32(len(hullOffset)) + for i := int32(0); i < hullCount; i++ { + pt := hullOffset[i] + dir := hullOffset[NextIndex(i, hullCount)].Sub(pt) + position := NewVector3f(pt.x, 0, pt.y) + normal := NewVector3f(-dir.y, 0, dir.x) + normal = NormalizeSafe(normal, NewVector3f(0, 0, 0)) + *carveHull = append(*carveHull, Plane{}) + plane := &(*carveHull)[len(*carveHull)-1] + plane.SetNormalAndPosition(normal, position) + localHullBounds.m_Min.x = FloatMin(localHullBounds.m_Min.x, pt.x) + localHullBounds.m_Min.z = FloatMin(localHullBounds.m_Min.z, pt.y) + localHullBounds.m_Max.x = FloatMax(localHullBounds.m_Max.x, pt.x) + localHullBounds.m_Max.z = FloatMax(localHullBounds.m_Max.z, pt.y) + } + + // Calculate approximate up axis. + // The approx normal is chosen so that it is visually plausible, i.e. prefer larger extents. + zero := NewVector3f(0.0, 0.0, 0.0) + yAxis := zero + yAxis = yAxis.Add(shape.xAxis.Mulf(shape.xAxis.y * FloatMax(shape.extents.y, shape.extents.z))) + yAxis = yAxis.Add(shape.yAxis.Mulf(shape.yAxis.y * FloatMax(shape.extents.z, shape.extents.x))) + yAxis = yAxis.Add(shape.zAxis.Mulf(shape.zAxis.y * FloatMax(shape.extents.x, shape.extents.y))) + yAxis = NormalizeSafe(yAxis, zero) + worldYAxis := NewVector3f(0.0, 1.0, 0.0) + if CompareApproximately(yAxis, zero, kEpsilon) { + yAxis = worldYAxis + } + + distMin := float32(math.MaxFloat32) + distMax := float32(-math.MaxFloat32) + for i := int32(0); i < pointCount; i++ { + dist := DotVector3f(points[i], yAxis) + distMin = FloatMin(distMin, dist) + distMax = FloatMax(distMax, dist) + } + + // Add top/bottom caps + *carveHull = append(*carveHull, NewPlane(yAxis.Mulf(-1), yAxis.Mulf(distMin-carveDepth))) + *carveHull = append(*carveHull, NewPlane(yAxis, yAxis.Mulf(distMax))) + + // The aabb top/bottom planes if needed + cosAngleConsiderAxisAligned := float32(0.984807753012208) // Consider colinear if within 10 degrees + isAlmostAxisAlignedY := AreColinear(yAxis, worldYAxis, cosAngleConsiderAxisAligned) + if !isAlmostAxisAlignedY { + min := shape.bounds.m_Min.Sub(tileOffset) + max := shape.bounds.m_Max.Sub(tileOffset) + *carveHull = append(*carveHull, NewPlane(worldYAxis.Mulf(-1), min.Sub(NewVector3f(0, 1, 0).Mulf(carveDepth)))) + *carveHull = append(*carveHull, NewPlane(worldYAxis, max)) + } else { + diagonal2D := localHullBounds.m_Max.Sub(localHullBounds.m_Min) + diagonal2D.y = 0 + halfSpread := 0.5 * Magnitude(diagonal2D) + tanAngleConsiderAxisAligned := float32(0.176326980708464) // Cap slanted up to 10 degrees + maxCapDepth := tanAngleConsiderAxisAligned * halfSpread + localHullBounds.m_Min.y -= maxCapDepth + localHullBounds.m_Max.y += maxCapDepth + } + + localHullBounds.m_Min.y -= carveDepth + return true +} + +// Compute the set of planes defining an extruded bounding box. +// Bounding box is represented by transform and size. +// Extrusion is based on 'carveWidth' horizontally and 'carveDepth' vertically down. +// Everything is translated relative to 'tileOffset'. +func CalculateBoxHull( + carveHull *Hull, localHullBounds *MinMaxAABB, + shape *NavMeshCarveShape, tileOffset Vector3f, + carveDepth, carveWidth float32) bool { + // Calculate obstacle vertices. + var box [8]Vector3f + for i := 0; i < 8; i++ { + box[i] = shape.center.Sub(tileOffset) + x := shape.extents.x + if i&1 == 0 { + x = -shape.extents.x + } + box[i] = box[i].Add(shape.xAxis.Mulf(x)) + y := shape.extents.y + if i&2 == 0 { + y = -shape.extents.y + } + box[i] = box[i].Add(shape.yAxis.Mulf(y)) + z := shape.extents.z + if i&4 == 0 { + z = -shape.extents.z + } + box[i] = box[i].Add(shape.zAxis.Mulf(z)) + } + + return CalculateCarveHullFromPoints(carveHull, localHullBounds, shape, tileOffset, carveDepth, carveWidth, box[:], 8) +} + +const kDivs = 8 + +func CalculateCapsuleHull( + carveHull *Hull, localHullBounds *MinMaxAABB, + shape *NavMeshCarveShape, tileOffset Vector3f, + carveDepth, carveWidth float32) bool { + // TODO: it should be possible to optimize the hull shape a bit more by + // creating the capsule data in 2D, and add min/max points. + // See how a 2D capsule is drawn in NavMeshVisulization.cpp + + var radius float32 = 0 + var height float32 = 0 + FitCapsuleToExtents(&radius, &height, shape.extents) + + // Calculate obstacle vertices. + var cylinder [(kDivs + kDivs + 1) * 2]Vector3f + { + } + var n int32 = 0 + // Scale for "outer" polygon, the polygon is created so that the cylinder circle is inscribing the polygon. + radiusScale := float32(1.0 / math.Cos(math.Pi*2.0/float64(kDivs)*0.5)) + // We have 8 divs effectively in other direction too. + h := float32(0.7071067812) * radius * radiusScale + r := radius * radiusScale + center := shape.center.Sub(tileOffset) + for i := 0; i < kDivs; i++ { + angle := float64(i) / float64(kDivs) * math.Pi * 2.0 + dx := math.Cos(angle) + dz := math.Sin(angle) + ax := shape.xAxis.Mulf(float32(dx)) + az := shape.zAxis.Mulf(float32(dz)) + cylinder[n] = center.Add(ax.Mulf(r)).Add(az.Mulf(r)).Sub(shape.yAxis.Mulf(height)) + n++ + cylinder[n] = center.Add(ax.Mulf(r)).Add(az.Mulf(r)).Add(shape.yAxis.Mulf(height)) + n++ + cylinder[n] = center.Add(ax.Mulf(h)).Add(az.Mulf(h)).Sub(shape.yAxis.Mulf(height + h)) + n++ + cylinder[n] = center.Add(ax.Mulf(h)).Add(az.Mulf(h)).Add(shape.yAxis.Mulf(height + h)) + n++ + } + + // Capsule tips + cylinder[n] = center.Sub(shape.yAxis.Mulf(height + r)) + n++ + cylinder[n] = center.Add(shape.yAxis.Mulf(height + r)) + n++ + + return CalculateCarveHullFromPoints(carveHull, localHullBounds, shape, tileOffset, carveDepth, carveWidth, cylinder[:], n) +} + +// Set flags on polygon edges colinear to tile edges. +// Flagged edges are considered when dynamically stitching neighboring tiles. +func WritePortalFlags(verts []Vector3f, polys []NavMeshPoly, polyCount int32, sourceHeader *NavMeshDataHeader) { + bmax := sourceHeader.bmax + bmin := sourceHeader.bmin + for ip := int32(0); ip < polyCount; ip++ { + poly := &polys[ip] + for iv := uint8(0); iv < poly.vertCount; iv++ { + // Skip already connected edges + if poly.neis[iv] != 0 { + continue + } + + vert := verts[poly.verts[iv]] + ivn := iv + 1 + if iv+1 == poly.vertCount { + ivn = 0 + } + nextVert := verts[poly.verts[ivn]] + + // + // z+ + // o---->o + // ^ | + // x- | | x+ + // | v + // o<----o + // z- + + dx := nextVert.x - vert.x + dz := nextVert.z - vert.z + nei := uint16(0) + if dz < 0.0 && FloatMax(FloatAbs(vert.x-bmax.x), FloatAbs(nextVert.x-bmax.x)) < MAGIC_EDGE_DISTANCE { + nei = kNavMeshExtLink | 0 // x+ portal + } else if dx > 0.0 && FloatMax(FloatAbs(vert.z-bmax.z), FloatAbs(nextVert.z-bmax.z)) < MAGIC_EDGE_DISTANCE { + nei = kNavMeshExtLink | 2 // z+ portal + } else if dz > 0.0 && FloatMax(FloatAbs(vert.x-bmin.x), FloatAbs(nextVert.x-bmin.x)) < MAGIC_EDGE_DISTANCE { + nei = kNavMeshExtLink | 4 // x- portal + } else if dx < 0.0 && FloatMax(FloatAbs(vert.z-bmin.z), FloatAbs(nextVert.z-bmin.z)) < MAGIC_EDGE_DISTANCE { + nei = kNavMeshExtLink | 6 // z- portal + } + poly.neis[iv] = nei + } + } +} + +func SimplePolygonTriangulation(dtl *NavMeshPolyDetail, dtris []NavMeshPolyDetailIndex, detailTriBase int32, polygonVertexCount int32) int32 { + dtl.vertBase = 0 + dtl.vertCount = 0 + dtl.triBase = uint32(detailTriBase) + dtl.triCount = NavMeshPolyDetailIndex(polygonVertexCount - 2) + + // Triangulate polygon (local indices). + for j := int32(2); j < polygonVertexCount; j++ { + t := dtris[4*detailTriBase:] + t[0] = 0 + t[1] = NavMeshPolyDetailIndex(j - 1) + t[2] = NavMeshPolyDetailIndex(j) + // Bit for each edge that belongs to poly boundary. + t[3] = 1 << 2 + if j == 2 { + t[3] |= 1 << 0 + } + if j == polygonVertexCount-1 { + t[3] |= 1 << 4 + } + detailTriBase++ + } + return detailTriBase +} + +func GetEdgeFlags(va Vector3f, poly []Vector3f) byte { + // Return mask indicating which edges the vertex touches. + thrSqr := Sqr(MAGIC_EDGE_DISTANCE) + npoly := len(poly) + var flags byte = 0 + for i, j := 0, npoly-1; i < npoly; i, j = i+1, i { + var t float32 + if SqrDistancePointSegment2D(&t, va, poly[j], poly[i]) < thrSqr { + flags |= 1 << uint8(j) + } + } + return flags +} + +func GetTriFlags(va, vb, vc byte) byte { + var flags byte = 0 + if (va & vb) != 0 { + flags |= 1 << 0 + } + if (vb & vc) != 0 { + flags |= 1 << 2 + } + if (vc & va) != 0 { + flags |= 1 << 4 + } + return flags +} + +func TileToDynamicMesh(tile *NavMeshTile, mesh *DynamicMesh, tileOffset Vector3f) { + + vertCount := tile.header.vertCount + polyCount := tile.header.polyCount + mesh.Reserve(vertCount, polyCount) + for iv := int32(0); iv < vertCount; iv++ { + mesh.AddVertex(tile.verts[iv].Sub(tileOffset)) + } + + for ip := int32(0); ip < polyCount; ip++ { + srcPoly := tile.polys[ip] + mesh.AddPolygon3(srcPoly.verts[:], DataType(ip), int32(srcPoly.vertCount)) + } +} + +func DynamicMeshToTile(dataSize *uint32, mesh *DynamicMesh, clipped []*ClippedDetailMesh, + sourceTile *NavMeshTile, tileOffset Vector3f) []byte { + + // Determine data size + vertCount := mesh.VertCount() + polyCount := mesh.PolyCount() + sourceHeader := sourceTile.header + totVertCount := vertCount + totPolyCount := polyCount + detailVertCount := int32(0) + detailTriCount := int32(0) + RequirementsForDetailMeshMixed(&detailVertCount, &detailTriCount, mesh, sourceTile, clipped) + headSize := Align4(unsafe.Sizeof(NavMeshDataHeader{})) + vertSize := Align4(uintptr(totVertCount) * unsafe.Sizeof(Vector3f{})) + polySize := Align4(uintptr(totPolyCount) * unsafe.Sizeof(NavMeshPoly{})) + detailMeshesSize := Align4(uintptr(polyCount) * unsafe.Sizeof(NavMeshPolyDetail{})) + detailVertsSize := Align4(uintptr(detailVertCount) * unsafe.Sizeof(Vector3f{})) + detailTrisSize := Align4(uintptr(detailTriCount) * 4 * unsafe.Sizeof(NavMeshPolyDetailIndex(0))) + bvTreeSize := uint32(0) + newSize := headSize + vertSize + polySize + + detailTrisSize + detailVertsSize + detailMeshesSize + bvTreeSize + newTile := make([]byte, newSize+1) + if newTile == nil { + *dataSize = 0 + return nil + } + *dataSize = newSize + + // Serialize in the detour recognized format + header := (*NavMeshDataHeader)(unsafe.Pointer(&(newTile[0]))) + d := headSize + var verts []Vector3f + sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&(verts))) + sliceHeader.Cap = int(totVertCount) + sliceHeader.Len = int(totVertCount) + sliceHeader.Data = uintptr(unsafe.Pointer(&(newTile[d]))) + d += vertSize + + var polys []NavMeshPoly + sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(polys))) + sliceHeader.Cap = int(totPolyCount) + sliceHeader.Len = int(totPolyCount) + sliceHeader.Data = uintptr(unsafe.Pointer(&(newTile[d]))) + d += polySize + + var detail []NavMeshPolyDetail + sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(detail))) + sliceHeader.Cap = int(polyCount) + sliceHeader.Len = int(polyCount) + sliceHeader.Data = uintptr(unsafe.Pointer(&(newTile[d]))) + d += detailMeshesSize + + var dverts []Vector3f + sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(dverts))) + sliceHeader.Cap = int(detailVertCount) + sliceHeader.Len = int(detailVertCount) + sliceHeader.Data = uintptr(unsafe.Pointer(&(newTile[d]))) + d += detailVertsSize + + var dtris []NavMeshPolyDetailIndex + sliceHeader = (*reflect.SliceHeader)(unsafe.Pointer(&(dtris))) + sliceHeader.Cap = int(detailTriCount * 4) + sliceHeader.Len = int(detailTriCount * 4) + sliceHeader.Data = uintptr(unsafe.Pointer(&(newTile[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(&(newTile[d]))) + */ + d += bvTreeSize + Assert(d == newSize) + for iv := 0; iv < vertCount; iv++ { + // TODO: apply tile offset earlier, after carving. Now needs to be handled all over the place. + verts[iv] = mesh.GetVertex(iv).Add(tileOffset) + } + + for ip := 0; ip < polyCount; ip++ { + p := mesh.GetPoly(ip) + sourcePolyIndex := *mesh.GetData(ip) + srcPoly := sourceTile.polys[sourcePolyIndex] + poly := &polys[ip] + copy(poly.verts[:], p.m_VertexIDs[:]) + copy(poly.neis[:], p.m_Neighbours[:]) + area := srcPoly.area + poly.flags = 1 << area + poly.area = area + poly.vertCount = p.m_VertexCount + } + + // Set external portal flags + WritePortalFlags(verts, polys, int32(polyCount), sourceHeader) + WriteDetailMeshMixed(detail, dverts, dtris, mesh, sourceTile, tileOffset, clipped, + int32(detailTriCount), int32(detailVertCount)) + + // Copy values from source + *header = *sourceHeader + + // (re)set new tile values + header.polyCount = int32(totPolyCount) + header.vertCount = int32(totVertCount) + header.detailMeshCount = int32(polyCount) + header.detailVertCount = int32(detailVertCount) + header.detailTriCount = int32(detailTriCount) + header.bvNodeCount = 0 // Fixme: bv-tree + + return newTile +} + +func RequirementsForDetailMeshMixed(detailVertCount *int32, detailTriCount *int32, + mesh *DynamicMesh, sourceTile *NavMeshTile, clipped []*ClippedDetailMesh) { + vertCount := NavMeshPolyDetailIndex(0) + triCount := NavMeshPolyDetailIndex(0) + + // Collect sizes needed for detail mesh + polyCount := mesh.PolyCount() + for ip := 0; ip < polyCount; ip++ { + p := mesh.GetPoly(ip) + sourcePolyIndex := *mesh.GetData(ip) + if p.m_Status == kOriginalPolygon { + // When preserving polygon detail mesh just add the source counts + sourceDetail := sourceTile.detailMeshes[sourcePolyIndex] + vertCount += sourceDetail.vertCount + triCount += sourceDetail.triCount + } else { + if clipped[ip] != nil { + vertCount += NavMeshPolyDetailIndex(len(clipped[ip].vertices)) + triCount += NavMeshPolyDetailIndex(len(clipped[ip].triangles)) / 3 + } else { + // Simple triangulation needs n-2 triangles but no extra detail vertices + triCount += NavMeshPolyDetailIndex(p.m_VertexCount) - 2 + } + } + } + *detailVertCount = int32(vertCount) + *detailTriCount = int32(triCount) +} + +func WriteDetailMeshMixed(detail []NavMeshPolyDetail, dverts []Vector3f, dtris []NavMeshPolyDetailIndex, + mesh *DynamicMesh, sourceTile *NavMeshTile, tileOffset Vector3f, + clipped []*ClippedDetailMesh, detailTriCount int32, detailVertCount int32) { + + detailVertBase := uint32(0) + detailTriBase := uint32(0) + var edgeFlags []byte + var poly []Vector3f + + polyCount := mesh.PolyCount() + for ip := 0; ip < polyCount; ip++ { + dtl := &detail[ip] + p := mesh.GetPoly(ip) + if p.m_Status == kOriginalPolygon { + // Fill in the original detail mesh for this polygon + sourcePolyIndex := *mesh.GetData(ip) + sourceDetail := sourceTile.detailMeshes[sourcePolyIndex] + dtl.vertBase = detailVertBase + dtl.vertCount = sourceDetail.vertCount + dtl.triBase = detailTriBase + dtl.triCount = sourceDetail.triCount + + // copy source detail vertices and triangles + size := uint32(sourceDetail.vertCount) + copy(dverts[detailVertBase:detailVertBase+size], sourceTile.detailVerts[sourceDetail.vertBase:sourceDetail.vertBase+size]) + size = uint32(4 * uintptr(sourceDetail.triCount)) + copy(dtris[4*detailTriBase:4*detailTriBase+size], sourceTile.detailTris[4*sourceDetail.triBase:4*sourceDetail.triBase+size]) + + detailVertBase += uint32(sourceDetail.vertCount) + detailTriBase += uint32(sourceDetail.triCount) + } else { + if clipped[ip] != nil { + poly = make([]Vector3f, p.m_VertexCount) + for j := uint8(0); j < p.m_VertexCount; j++ { + poly[j] = tileOffset.Add(mesh.GetVertex(int(p.m_VertexIDs[j]))) + } + + // TODO: check vertex count so that detail vertex index won't overflow. + // TODO: locate and remap polygon vertices to reduce space (now stores poly vertices too). + clip := clipped[ip] + vertCount := len(clip.vertices) + triCount := len(clip.triangles) / 3 + dtl.vertBase = detailVertBase + dtl.vertCount = NavMeshPolyDetailIndex(vertCount) + dtl.triBase = detailTriBase + dtl.triCount = NavMeshPolyDetailIndex(triCount) + + // Copy vertices + for j := uint32(0); j < uint32(vertCount); j++ { + dverts[detailVertBase+j] = clip.vertices[j] + } + + // Calculate edge flags. + edgeFlags = make([]byte, vertCount) + for j := 0; j < vertCount; j++ { + edgeFlags[j] = GetEdgeFlags(clip.vertices[j], poly) + } + + // Copy triangles. + for j := uint32(0); j < uint32(triCount); j++ { + t := dtris[4*(detailTriBase+j):] + t[0] = NavMeshPolyDetailIndex(uint16(p.m_VertexCount) + clip.triangles[j*3+0]) + t[1] = NavMeshPolyDetailIndex(uint16(p.m_VertexCount) + clip.triangles[j*3+1]) + t[2] = NavMeshPolyDetailIndex(uint16(p.m_VertexCount) + clip.triangles[j*3+2]) + t[3] = NavMeshPolyDetailIndex(GetTriFlags(edgeFlags[clip.triangles[j*3+0]], + edgeFlags[clip.triangles[j*3+1]], + edgeFlags[clip.triangles[j*3+2]])) + } + + detailVertBase += uint32(vertCount) + detailTriBase += uint32(triCount) + } else { + detailTriBase = uint32(SimplePolygonTriangulation(dtl, dtris, int32(detailTriBase), int32(p.m_VertexCount))) + } + } + } + Assert(detailTriBase == uint32(detailTriCount)) + Assert(detailVertBase == uint32(detailVertCount)) +} diff --git a/pkg/navmesh/nav_mesh_types.go b/pkg/navmesh/nav_mesh_types.go new file mode 100644 index 00000000..bcc13584 --- /dev/null +++ b/pkg/navmesh/nav_mesh_types.go @@ -0,0 +1,56 @@ +package navmesh + +// Reference to navigation polygon. +type NavMeshPolyRef uint64 + +// Reference to navigation mesh tile. +type NavMeshTileRef uint64 + +const ( + kPolyRefSaltBits NavMeshPolyRef = 16 // Number of salt bits in the poly/tile ID. + kPolyRefTileBits NavMeshPolyRef = 28 // Number of tile bits in the poly/tile ID. + kPolyRefPolyBits NavMeshPolyRef = 16 // Number of poly bits in the poly/tile ID. + kPolyRefTypeBits NavMeshPolyRef = 4 // Number of type bits in the poly/tile ID. + kPolyRefSaltMask NavMeshPolyRef = 1< kMinTargetDistSq { + break + } + } + ncorners -= prune + if prune != 0 && ncorners != 0 { + for i := int32(0); i < ncorners; i++ { + cornerFlags[i] = cornerFlags[i+prune] + cornerPolys[i] = cornerPolys[i+prune] + cornerVerts[i] = cornerVerts[i+prune] + } + } + + // Prune points after an off-mesh connection. + for prune = 0; prune < ncorners; prune++ { + if NavMeshStraightPathFlags(cornerFlags[prune])&kStraightPathOffMeshConnection != 0 { + ncorners = prune + 1 + break + } + } + + *cornerCount = ncorners + if NavMeshStatusDetail(status, kNavMeshPartialResult) { + return kNavMeshSuccess | kNavMeshPartialResult + } + return kNavMeshSuccess +} + +func (this *PathCorridor) OptimizePathVisibility(next Vector3f, navquery *NavMeshQuery, filter *QueryFilter) { + var res [kMaxResults]NavMeshPolyRef + var nres int32 = 0 + var result NavMeshRaycastResult + navquery.Raycast(this.m_path[0], this.m_pos, next, filter, &result, res[:], &nres, kMaxResults) + if nres > 1 && result.t > 0.99 { + ReplacePathStart(&this.m_path, res[:], nres) + } +} + +const kMaxIterations int32 = 8 + +func (this *PathCorridor) OptimizePathTopology(navquery *NavMeshQuery, filter *QueryFilter) bool { + if this.GetPathCount() < 3 { + return false + } + + var res [kMaxResults]NavMeshPolyRef + var nres int32 = 0 + status := navquery.InitSlicedFindPath2(this.m_path[0], this.GetLastPoly(), this.m_pos, this.m_target, filter) + if !NavMeshStatusFailed(status) { + status = navquery.UpdateSlicedFindPath(kMaxIterations, nil) + } + + if !NavMeshStatusSucceed(status) { + // don't accept kNavMeshInProgress + return false + } + + status = navquery.FinalizeSlicedFindPathPartial(&nres, this.m_path, this.GetPathCount()) + if !NavMeshStatusSucceed(status) { + return false + } + + status = navquery.GetPath(res[:], &nres, kMaxResults) + if !NavMeshStatusSucceed(status) { + return false + } + + return ReplacePathStart(&this.m_path, res[:], nres) +} + +func (this *PathCorridor) MoveOverOffmeshConnection(offMeshConRef NavMeshPolyRef, currentPos Vector3f, + startPos Vector3f, endPos Vector3f, navquery *NavMeshQuery) bool { + Assert(navquery != nil) + Assert(this.GetPathCount() != 0) + + // Advance the path up to and over the off-mesh connection. + var prevRef, nextRef NavMeshPolyRef + polyRef := this.m_path[0] + var npos int32 = 0 + npath := this.GetPathCount() + for npos < npath && polyRef != offMeshConRef { + prevRef = polyRef + polyRef = this.m_path[npos] + if npos+1 < npath { + nextRef = this.m_path[npos+1] + } + npos++ + } + if npos == npath { + // Could not find offMeshConRef + return false + } + + // Prune path + this.m_path = this.m_path[npos:] + + nav := navquery.GetAttachedNavMesh() + Assert(nav != nil) + conn := nav.GetOffMeshConnection(polyRef) + if conn == nil { + return false + } + + if conn.width > 0.0 { + // Handle wide link + status := nav.GetNearestOffMeshConnectionEndPoints(prevRef, polyRef, nextRef, currentPos, &startPos, &endPos) + if NavMeshStatusSucceed(status) { + this.m_pos = endPos + return true + } + } else { + status := nav.GetOffMeshConnectionEndPoints(prevRef, polyRef, &startPos, &endPos) + if NavMeshStatusSucceed(status) { + this.m_pos = endPos + return true + } + } + + return false +} + +// TODO : notify callers - return success/failure +const kMaxVisited int32 = 16 + +func (this *PathCorridor) MovePosition(newPos Vector3f, navquery *NavMeshQuery, filter *QueryFilter) bool { + Assert(this.GetPathCount() != 0) + if SqrDistance2D(newPos, this.m_pos) == 0.0 { + return false + } + + // Move along navmesh and update new position. + var result Vector3f + var visited [kMaxVisited]NavMeshPolyRef + var nvisited int32 = 0 + status := navquery.MoveAlongSurface(this.m_path[0], this.m_pos, newPos, filter, + &result, visited[:], &nvisited, kMaxVisited) + + if !NavMeshStatusSucceed(status) { + return false + } + + ReplacePathStartReverse(&this.m_path, visited[:], nvisited) + // Adjust the position to stay on top of the navmesh. + navquery.ProjectToPoly(&this.m_pos, this.m_path[0], result) + return true +} + +func (this *PathCorridor) UpdateTargetPosition(ref NavMeshPolyRef, target Vector3f) bool { + if ref != this.GetLastPoly() { + return false + } + + this.m_target = target + return true +} + +const kExtraCapacity uint32 = 16 + +func (this *PathCorridor) SetCorridor(target Vector3f, navquery *NavMeshQuery, path []NavMeshPolyRef, npath int32, partialPath bool) { + Assert(npath > 0) + + // Reserving room for extra polygons allows us to subsequently extend the path a bit, + // e.g. from a thread/job, without allocating memory and possibly locking. + this.m_path = make([]NavMeshPolyRef, npath) + this.m_target = target + copy(this.m_path, path[:npath]) + + this.m_stateFlags = kPathCorridorValid + this.SetPathPartial(partialPath) + + // Adjust the position to stay on top of the navmesh. + navquery.ProjectToPoly(&this.m_target, this.GetLastPoly(), target) +} + +func (this *PathCorridor) SetStateFlag(setFlag bool, stateFlag PathCorridorState) { + if setFlag { + this.m_stateFlags |= stateFlag + } else { + this.m_stateFlags &= ^stateFlag + } +} + +func (this *PathCorridor) SetPathValid(inbool bool) { + this.SetStateFlag(inbool, kPathCorridorValid) +} + +func (this *PathCorridor) SetPathPartial(inbool bool) { + this.SetStateFlag(inbool, kPathCorridorPartial) +} + +func (this *PathCorridor) SetPathInterrupted(inbool bool) { + this.SetStateFlag(inbool, kPathCorridorInterrupted) +} + +func (this *PathCorridor) GetLastPoly() NavMeshPolyRef { + return this.m_path[this.GetPathCount()-1] +} + +func (this *PathCorridor) GetPath() []NavMeshPolyRef { + return this.m_path +} + +func ReplacePathStart(path *[]NavMeshPolyRef, start []NavMeshPolyRef, nstart int32) bool { + npath := int32(len(*path)) + var ipath, istart int32 + if !FindFurthestIntersectionIndices(*path, start, npath, nstart, &ipath, &istart) { + return false + } + + // the result may only grow before the elements are moved in-place. + tmpath := make([]NavMeshPolyRef, npath) + copy(tmpath, *path) + + nres := istart + (npath - ipath) + if nres > npath { + *path = append(*path, make([]NavMeshPolyRef, nres-npath)...) + } + + // move elements in place + copy((*path)[istart:], tmpath[ipath:npath]) + copy(*path, start[:istart]) + + *path = (*path)[:nres] + // shrink result to fit + return true +} + +func FindFurthestIntersectionIndices(a []NavMeshPolyRef, b []NavMeshPolyRef, na, nb int32, ia, ib *int32) bool { + for i := na - 1; i >= int32(0); i-- { + for j := nb - 1; j >= 0; j-- { + if a[i] == b[j] { + *ia = i + *ib = j + return true + } + } + } + return false +} + +func ReplacePathStartReverse(path *[]NavMeshPolyRef, start []NavMeshPolyRef, nstart int32) bool { + npath := int32(len(*path)) + var ipath, istart int32 + if !FindFurthestIntersectionIndices(*path, start, npath, nstart, &ipath, &istart) { + return false + } + + // the pivot index for the reversed start segment + istartrev := nstart - 1 - istart + + tmpath := make([]NavMeshPolyRef, npath) + copy(tmpath, *path) + nres := istartrev + (npath - ipath) + // the result may only grow before the elements are moved in-place. + if nres > npath { + *path = append(*path, make([]NavMeshPolyRef, nres-npath)...) + } + + // move elements in place + copy((*path)[istartrev:], tmpath[ipath:]) + for i := int32(0); i < istartrev; i++ { + (*path)[i] = start[nstart-1-i] + } + + // shrink result to fit + *path = (*path)[:nres] + return true +} diff --git a/pkg/navmesh/plane.go b/pkg/navmesh/plane.go new file mode 100644 index 00000000..da7871f6 --- /dev/null +++ b/pkg/navmesh/plane.go @@ -0,0 +1,21 @@ +package navmesh + +type Plane struct { + normal Vector3f + distance float32 +} + +func (p *Plane) SetNormalAndPosition(normal Vector3f, position Vector3f) { + p.normal = normal + p.distance = -DotVector3f(normal, position) +} + +func (this *Plane) GetDistanceToPoint(inPt Vector3f) float32 { + return DotVector3f(this.normal, inPt) + this.distance +} + +func NewPlane(normal, position Vector3f) Plane { + plane := Plane{} + plane.SetNormalAndPosition(normal, position) + return plane +} diff --git a/pkg/navmesh/quaternion.go b/pkg/navmesh/quaternion.go new file mode 100644 index 00000000..6f7d9969 --- /dev/null +++ b/pkg/navmesh/quaternion.go @@ -0,0 +1,175 @@ +package navmesh + +import ( + "math" +) + +type Quaternionf struct { + x, y, z, w float32 +} + +func NewQuaternionf(x, y, z, w float32) Quaternionf { + return Quaternionf{x, y, z, w} +} + +func (this *Quaternionf) X() float32 { + return this.x +} + +func (this *Quaternionf) Y() float32 { + return this.y +} + +func (this *Quaternionf) Z() float32 { + return this.z +} + +func (this *Quaternionf) W() float32 { + return this.w +} + +func (this *Quaternionf) Add(that Quaternionf) Quaternionf { + return Quaternionf{ + this.x + that.x, + this.y + that.y, + this.z + that.z, + this.w + that.w, + } +} + +func (this *Quaternionf) Sub(that Quaternionf) Quaternionf { + return Quaternionf{ + this.x - that.x, + this.y - that.y, + this.z - that.z, + this.w - that.w, + } +} + +func (lhs Quaternionf) Mul(rhs Quaternionf) Quaternionf { + return NewQuaternionf( + lhs.w*rhs.x+lhs.x*rhs.w+lhs.y*rhs.z-lhs.z*rhs.y, + lhs.w*rhs.y+lhs.y*rhs.w+lhs.z*rhs.x-lhs.x*rhs.z, + lhs.w*rhs.z+lhs.z*rhs.w+lhs.x*rhs.y-lhs.y*rhs.x, + lhs.w*rhs.w-lhs.x*rhs.x-lhs.y*rhs.y-lhs.z*rhs.z) +} + +func QuaternionToMatrix3(q Quaternionf, m *Matrix3x3f) { + // Precalculate coordinate products + x := q.x * 2.0 + y := q.y * 2.0 + z := q.z * 2.0 + xx := q.x * x + yy := q.y * y + zz := q.z * z + xy := q.x * y + xz := q.x * z + yz := q.y * z + wx := q.w * x + wy := q.w * y + wz := q.w * z + + // Calculate 3x3 matrix from orthonormal basis + m.m_Data[0] = 1.0 - (yy + zz) + m.m_Data[1] = xy + wz + m.m_Data[2] = xz - wy + m.m_Data[3] = xy - wz + m.m_Data[4] = 1.0 - (xx + zz) + m.m_Data[5] = yz + wx + m.m_Data[6] = xz + wy + m.m_Data[7] = yz - wx + m.m_Data[8] = 1.0 - (xx + yy) +} + +func QuaternionToMatrix4(q Quaternionf, m *Matrix4x4f) { + // Precalculate coordinate products + x := q.x * 2.0 + y := q.y * 2.0 + z := q.z * 2.0 + xx := q.x * x + yy := q.y * y + zz := q.z * z + xy := q.x * y + xz := q.x * z + yz := q.y * z + wx := q.w * x + wy := q.w * y + wz := q.w * z + + // Calculate 3x3 matrix from orthonormal basis + m.m_Data[0] = 1.0 - (yy + zz) + m.m_Data[1] = xy + wz + m.m_Data[2] = xz - wy + m.m_Data[3] = 0.0 + m.m_Data[4] = xy - wz + m.m_Data[5] = 1.0 - (xx + zz) + m.m_Data[6] = yz + wx + m.m_Data[7] = 0.0 + m.m_Data[8] = xz + wy + m.m_Data[9] = yz - wx + m.m_Data[10] = 1.0 - (xx + yy) + m.m_Data[11] = 0.0 + m.m_Data[12] = 0.0 + m.m_Data[13] = 0.0 + m.m_Data[14] = 0.0 + m.m_Data[15] = 1.0 +} + +func InverseQuaternion(q Quaternionf) Quaternionf { + var ret Quaternionf + ret.x = -q.x + ret.y = -q.y + ret.z = -q.z + ret.w = q.w + return ret +} + +type RotationOrder int + +const ( + kOrderXYZ RotationOrder = iota + kOrderXZY + kOrderYZX + kOrderYXZ + kOrderZXY + kOrderZYX + OrderUnity = kOrderZXY +) + +func EulerToQuaternionUnity(eulerAngle Vector3f) Quaternionf { + return EulerToQuaternion(eulerAngle.Mulf(math.Pi/180.0), kOrderZXY) +} + +func EulerToQuaternion(someEulerAngles Vector3f, order RotationOrder) Quaternionf { + cX := math.Cos(float64(someEulerAngles.x / 2.0)) + sX := math.Sin(float64(someEulerAngles.x / 2.0)) + cY := math.Cos(float64(someEulerAngles.y / 2.0)) + sY := math.Sin(float64(someEulerAngles.y / 2.0)) + cZ := math.Cos(float64(someEulerAngles.z / 2.0)) + sZ := math.Sin(float64(someEulerAngles.z / 2.0)) + qX := NewQuaternionf(float32(sX), 0.0, 0.0, float32(cX)) + qY := NewQuaternionf(0.0, float32(sY), 0.0, float32(cY)) + qZ := NewQuaternionf(0.0, 0.0, float32(sZ), float32(cZ)) + var ret Quaternionf + + switch order { + case kOrderZYX: + CreateQuaternionFromAxisQuaternions(qX, qY, qZ, &ret) + case kOrderYZX: + CreateQuaternionFromAxisQuaternions(qX, qZ, qY, &ret) + case kOrderXZY: + CreateQuaternionFromAxisQuaternions(qY, qZ, qX, &ret) + case kOrderZXY: + CreateQuaternionFromAxisQuaternions(qY, qX, qZ, &ret) + case kOrderYXZ: + CreateQuaternionFromAxisQuaternions(qZ, qX, qY, &ret) + case kOrderXYZ: + CreateQuaternionFromAxisQuaternions(qZ, qY, qX, &ret) + } + + return ret +} + +func CreateQuaternionFromAxisQuaternions(q1 Quaternionf, q2 Quaternionf, q3 Quaternionf, result *Quaternionf) { + *result = q1.Mul(q2).Mul(q3) +} diff --git a/pkg/navmesh/query_filter.go b/pkg/navmesh/query_filter.go new file mode 100644 index 00000000..3d9467d4 --- /dev/null +++ b/pkg/navmesh/query_filter.go @@ -0,0 +1,63 @@ +package navmesh + +const ( + kMaxAreas int32 = 32 +) + +type QueryFilter struct { + m_AreaCost [kMaxAreas]float32 // Array storing cost per area type, used by default implementation. + m_IncludeFlags uint32 // Include poly flags, used by default implementation. + m_TypeID int32 // Which type of navmesh is considered +} + +func NewQueryFilter() *QueryFilter { + var filter QueryFilter + filter.m_IncludeFlags = 0xffffffff + filter.m_TypeID = -1 + for i := range filter.m_AreaCost { + filter.m_AreaCost[i] = 1.0 + } + return &filter +} + +func (this *QueryFilter) PassFilter(flags uint32) bool { + return (flags & this.m_IncludeFlags) != 0 +} + +func (this *QueryFilter) Set(typeID int32, includeFlags uint32, costs []float32) { + this.m_TypeID = typeID + this.m_IncludeFlags = includeFlags + if costs != nil { + copy(this.m_AreaCost[:], costs) + } +} + +// Getters and setters for the default implementation data. +func (this *QueryFilter) GetAreaCost(i int32) float32 { + Assert(i < kMaxAreas) + return this.m_AreaCost[i] +} + +func (this *QueryFilter) SetAreaCost(i int32, cost float32) { + this.m_AreaCost[i] = cost +} + +func (this *QueryFilter) SetAreaCosts(areaCosts []float32) { + copy(this.m_AreaCost[:], areaCosts) +} + +func (this *QueryFilter) GetIncludeFlags() uint32 { + return this.m_IncludeFlags +} + +func (this *QueryFilter) SetIncludeFlags(flags uint32) { + this.m_IncludeFlags = flags +} + +func (this *QueryFilter) SetTypeID(typeID int32) { + this.m_TypeID = typeID +} + +func (this *QueryFilter) GetTypeID() int32 { + return this.m_TypeID +} diff --git a/pkg/navmesh/util.go b/pkg/navmesh/util.go new file mode 100644 index 00000000..ac560597 --- /dev/null +++ b/pkg/navmesh/util.go @@ -0,0 +1,199 @@ +package navmesh + +import ( + "unsafe" +) + +func Assert(v bool) { + if !v { + panic("Assert failed") + } +} + +var navMeshTileSize = unsafe.Sizeof(NavMeshTile{}) + +func GetTileIndex(begin, end *NavMeshTile) int32 { + a := uintptr(unsafe.Pointer(begin)) + b := uintptr(unsafe.Pointer(end)) + return int32((b - a) / navMeshTileSize) +} + +type TileFreeList struct { + m_Data []NavMeshTile + m_NextFree uint32 +} + +const ( + kNullLinkId uint32 = 0xffffffff +) + +func (this *TileFreeList) Init() { + this.m_NextFree = kNullLinkId +} + +func (this *TileFreeList) Alloc() uint32 { + if this.m_NextFree == kNullLinkId { + s := 2 * this.Capacity() + if s == 0 { + s = 4 + } + this.Grow(s) + } + id := this.m_NextFree + this.m_NextFree = this.m_Data[id].next + this.m_Data[id].next = 0 + return id +} + +func (this *TileFreeList) Grow(s uint32) { + capacity := this.Capacity() + if s < capacity || this.m_NextFree != kNullLinkId { + return + } + + for i := uint32(len(this.m_Data)); i < s; i++ { + this.m_Data = append(this.m_Data, *NewNavMeshTile()) + this.m_Data[i].next = i + 1 + } + this.m_Data[s-1].next = kNullLinkId + this.m_NextFree = capacity +} + +func (this *TileFreeList) Release(id uint32) { + this.m_Data[id].next = this.m_NextFree + this.m_NextFree = id +} + +func (this *TileFreeList) Capacity() uint32 { + return uint32(len(this.m_Data)) +} + +func (this *TileFreeList) Get(i uint32) *NavMeshTile { + return &this.m_Data[i] +} + +type LinkFreeList struct { + m_Data []NavMeshLink + m_NextFree uint32 +} + +func (this *LinkFreeList) Alloc() uint32 { + if this.m_NextFree == kNullLinkId { + s := 2 * this.Capacity() + if s == 0 { + s = 4 + } + this.Grow(s) + } + id := this.m_NextFree + this.m_NextFree = this.m_Data[id].next + this.m_Data[id].next = 0 + return id +} + +func (this *LinkFreeList) Release(id uint32) { + this.m_Data[id].next = this.m_NextFree + this.m_NextFree = id +} + +func (this *LinkFreeList) Capacity() uint32 { + return uint32(len(this.m_Data)) +} + +func (this *LinkFreeList) Get(i uint32) *NavMeshLink { + return &this.m_Data[i] +} + +func (this *LinkFreeList) Init() { + this.m_NextFree = kNullLinkId +} + +func (this *LinkFreeList) Grow(s uint32) { + capacity := this.Capacity() + if s < capacity || this.m_NextFree != kNullLinkId { + return + } + + for i := uint32(len(this.m_Data)); i < s; i++ { + this.m_Data = append(this.m_Data, NavMeshLink{}) + this.m_Data[i].next = i + 1 + } + this.m_Data[s-1].next = kNullLinkId + this.m_NextFree = capacity +} + +type OffMeshFreeList struct { + m_Data []OffMeshConnection + m_NextFree uint32 +} + +func (this *OffMeshFreeList) Alloc() uint32 { + if this.m_NextFree == kNullLinkId { + s := 2 * this.Capacity() + if s == 0 { + s = 4 + } + this.Grow(s) + } + id := this.m_NextFree + this.m_NextFree = this.m_Data[id].next + this.m_Data[id].next = 0 + return id +} + +func (this *OffMeshFreeList) Release(id uint32) { + this.m_Data[id].next = this.m_NextFree + this.m_NextFree = id +} + +func (this *OffMeshFreeList) Capacity() uint32 { + return uint32(len(this.m_Data)) +} + +func (this *OffMeshFreeList) Get(i uint32) *OffMeshConnection { + return &this.m_Data[i] +} + +func (this *OffMeshFreeList) Init() { + this.m_NextFree = kNullLinkId +} + +func (this *OffMeshFreeList) Grow(s uint32) { + capacity := this.Capacity() + if s < capacity || this.m_NextFree != kNullLinkId { + return + } + + for i := uint32(len(this.m_Data)); i < s; i++ { + this.m_Data = append(this.m_Data, *NewOffMeshConnection()) + this.m_Data[i].next = i + 1 + } + this.m_Data[s-1].next = kNullLinkId + this.m_NextFree = capacity +} + +func NextIndex(index, modulus int32) int32 { + Assert(index < modulus) + next := index + 1 + if next == modulus { + return 0 + } else { + return next + } +} + +func PrevIndex(index, modulus int32) int32 { + if index == 0 { + return modulus - 1 + } else { + return index - 1 + } +} + +func TriArea2D(a, b, c Vector3f) float32 { + abx := b.x - a.x + abz := b.z - a.z + acx := c.x - a.x + acz := c.z - a.z + return acx*abz - abx*acz +} diff --git a/pkg/navmesh/vector.go b/pkg/navmesh/vector.go new file mode 100644 index 00000000..4f3e320a --- /dev/null +++ b/pkg/navmesh/vector.go @@ -0,0 +1,206 @@ +package navmesh + +import ( + "fmt" + "math" +) + +type Vector3f struct { + x, y, z float32 +} + +var ( + Vector3_One = Vector3f{1, 1, 1} + Vector2_One = Vector2f{1, 1} +) + +func NewVector3f(x, y, z float32) Vector3f { + var v Vector3f + v.Set(x, y, z) + return v +} + +func (this *Vector3f) Set(x, y, z float32) { + this.x = x + this.y = y + this.z = z +} + +func (this *Vector3f) SetData(i int, data float32) { + switch i { + case 0: + this.x = data + case 1: + this.y = data + case 2: + this.z = data + default: + panic(fmt.Errorf("invalid vector index:%d", i)) + } +} + +func (this *Vector3f) GetData(i int) float32 { + switch i { + case 0: + return this.x + case 1: + return this.y + case 2: + return this.z + default: + panic(fmt.Errorf("invalid vector index:%d", i)) + } +} + +func (this Vector3f) Sub(data Vector3f) Vector3f { + return Vector3f{this.x - data.x, this.y - data.y, this.z - data.z} +} + +func (this Vector3f) Add(data Vector3f) Vector3f { + return Vector3f{this.x + data.x, this.y + data.y, this.z + data.z} +} + +func (this Vector3f) Mulf(data float32) Vector3f { + return Vector3f{this.x * data, this.y * data, this.z * data} +} + +func (this Vector3f) Mulv(data Vector3f) Vector3f { + return Vector3f{this.x * data.x, this.y * data.y, this.z * data.z} +} + +func (this Vector3f) Div(v float32) Vector3f { + return Vector3f{this.x / v, this.y / v, this.z / v} +} + +func (this Vector3f) Neg() Vector3f { + return Vector3f{-this.x, -this.y, -this.z} +} + +func (this *Vector3f) SetZero() { + this.x = 0 + this.y = 0 + this.z = 0 +} + +func ScaleVector3f(l, r Vector3f) Vector3f { + return Vector3f{l.x * r.x, l.y * r.y, l.z * r.z} +} + +func MinVector3f(l, r Vector3f) Vector3f { + return Vector3f{FloatMin(l.x, r.x), FloatMin(l.y, r.y), FloatMin(l.z, r.z)} +} + +func MaxVector3f(l, r Vector3f) Vector3f { + return Vector3f{FloatMax(l.x, r.x), FloatMax(l.y, r.y), FloatMax(l.z, r.z)} +} + +func DotVector3f(l, r Vector3f) float32 { + return l.x*r.x + l.y*r.y + l.z*r.z +} + +func Dot2D(a, b Vector3f) float32 { + return a.x*b.x + a.z*b.z +} + +func DotQuaternionf(l, r Quaternionf) float32 { + return l.x*r.x + l.y*r.y + l.z*r.z + l.w*r.w +} + +func LerpVector3f(from, to Vector3f, t float32) Vector3f { + return to.Mulf(t).Add(from.Mulf(1.0 - t)) +} + +func Perp2D(u, v Vector3f) float32 { + return u.z*v.x - u.x*v.z +} + +func Magnitude(inV Vector3f) float32 { + return float32(math.Sqrt(float64(DotVector3f(inV, inV)))) +} + +func Magnitude2(inV Vector2f) float32 { + return float32(math.Sqrt(float64(DotVector2f(inV, inV)))) +} + +func SqrMagnitude(inV Vector3f) float32 { + return DotVector3f(inV, inV) +} + +func Distance(a, b Vector3f) float32 { + return Magnitude(b.Sub(a)) +} + +func Cross(lhs, rhs Vector3f) Vector3f { + return Vector3f{ + lhs.y*rhs.z - lhs.z*rhs.y, + lhs.z*rhs.x - lhs.x*rhs.z, + lhs.x*rhs.y - lhs.y*rhs.x, + } +} + +func AbsVector3f(v Vector3f) Vector3f { + return NewVector3f(FloatAbs(v.x), FloatAbs(v.y), FloatAbs(v.z)) +} + +func NormalizeSafe(inV, defaultV Vector3f) Vector3f { + mag := Magnitude(inV) + if mag > kEpsilon { + return inV.Div(mag) + } else { + return defaultV + } +} + +func NormalizeSafe2(inV, defaultV Vector2f) Vector2f { + mag := Magnitude2(inV) + if mag > kEpsilon { + return inV.Div(mag) + } else { + return defaultV + } +} + +func CompareApproximately(inV0, inV1 Vector3f, inMaxDist float32) bool { + return SqrMagnitude(inV1.Sub(inV0)) <= inMaxDist*inMaxDist +} + +func Normalize(inV Vector3f) Vector3f { + mag := Magnitude(inV) + return inV.Div(mag) +} + +type Vector2f struct { + x, y float32 +} + +func NewVector2f(x, y float32) Vector2f { + return Vector2f{x, y} +} + +func MinVector2f(l, r Vector2f) Vector2f { + return Vector2f{FloatMin(l.x, r.x), FloatMin(l.y, r.y)} +} + +func DotVector2f(l, r Vector2f) float32 { + return l.x*r.x + l.y*r.y +} + +func MaxVector2f(l, r Vector2f) Vector2f { + return Vector2f{FloatMax(l.x, r.x), FloatMax(l.y, r.y)} +} + +func (this Vector2f) Sub(data Vector2f) Vector2f { + return Vector2f{this.x - data.x, this.y - data.y} +} + +func (this Vector2f) Div(v float32) Vector2f { + return Vector2f{this.x / v, this.y / v} +} + +func (this Vector2f) Mulf(data float32) Vector2f { + return Vector2f{this.x * data, this.y * data} +} + +func (this Vector2f) Add(data Vector2f) Vector2f { + return Vector2f{this.x + data.x, this.y + data.y} +} diff --git a/pkg/navmesh/vertex_welder.go b/pkg/navmesh/vertex_welder.go new file mode 100644 index 00000000..aefe61b2 --- /dev/null +++ b/pkg/navmesh/vertex_welder.go @@ -0,0 +1,104 @@ +package navmesh + +func hash(x, y, z int, BucketCount int) int { + h1 := 0x8da6b343 // Large multiplicative constants; + h2 := 0xd8163841 // here arbitrarily chosen primes + h3 := 0xcb1ab31f + n := h1*x + h2*y + h3*z + return n & (BucketCount - 1) +} + +func NewVertexWelder(BucketCount int, verts *[]Vector3f, weldThr float32) *VertexWelder { + welder := &VertexWelder{ + m_weldThr: weldThr, + m_verts: verts, + m_next: nil, + m_first: make([]int, BucketCount), + BucketCount: BucketCount, + } + + Assert(weldThr > 0.0) + for i := 0; i < BucketCount; i++ { + welder.m_first[i] = -1 + } + return welder +} + +type VertexWelder struct { + m_weldThr float32 + m_verts *[]Vector3f + m_next []int + m_first []int + BucketCount int +} + +func (this *VertexWelder) GetCellSize() float32 { + return this.m_weldThr * 10.0 +} + +func (this *VertexWelder) SetVertexArray(verts *[]Vector3f) { + Assert(len(*verts) == 0) + this.m_verts = verts +} + +func (this *VertexWelder) Reset() { + for i := 0; i < this.BucketCount; i++ { + this.m_first[i] = -1 + } + this.m_next = this.m_next[:0] +} + +func (this *VertexWelder) Push(pt Vector3f) int { + cellSize := this.GetCellSize() + // Add vertex + x := FloorfToInt(pt.x / cellSize) + y := FloorfToInt(pt.y / cellSize) + z := FloorfToInt(pt.z / cellSize) + h := hash(int(x), int(y), int(z), this.BucketCount) + *this.m_verts = append(*this.m_verts, pt) + this.m_next = append(this.m_next, -1) + // The external array must be kept in sync with m_next. + // Only this method should add stuff to verts when using the welder. + Assert(len(*this.m_verts) == len(this.m_next)) + idx := len(*this.m_verts) - 1 + this.m_next[idx] = this.m_first[h] + this.m_first[h] = idx + return idx +} + +func (this *VertexWelder) AddUnique(pt Vector3f) int { + verts := *this.m_verts + + // Try to find vertex + weldThr := this.m_weldThr + cellSize := this.GetCellSize() + minx := FloorfToInt((pt.x - weldThr) / cellSize) + maxx := FloorfToInt((pt.x + weldThr) / cellSize) + miny := FloorfToInt((pt.y - weldThr) / cellSize) + maxy := FloorfToInt((pt.y + weldThr) / cellSize) + minz := FloorfToInt((pt.z - weldThr) / cellSize) + maxz := FloorfToInt((pt.z + weldThr) / cellSize) + bestIndex := -1 + bestDistSq := weldThr * weldThr + for z := minz; z <= maxz; z++ { + for y := miny; y <= maxy; y++ { + for x := minx; x <= maxx; x++ { + h := hash(int(x), int(y), int(z), this.BucketCount) + for i := this.m_first[h]; i != -1; i = this.m_next[i] { + distSq := SqrMagnitude(verts[i].Sub(pt)) + if distSq < bestDistSq { + bestDistSq = distSq + bestIndex = i + } + } + } + } + } + + if bestIndex != -1 { + + return bestIndex + } + + return this.Push(pt) +}