Example #1
0
 public static void LogPath(NavPoint[] points)
 {
     string message = "Path: ";
     foreach(NavPoint np in points) {
         message += " " + np.position;
     }
     Debug.Log(message);
 }
Example #2
0
 public void AddItem(NavPoint pt)
 {
     if (items.Contains(pt)) return;
     items.Add(pt);
     this.IsReadOnly = false;
     this.AppendText(pt.ToString());
     this.AppendText(Environment.NewLine);
     this.IsReadOnly = true;
 }
Example #3
0
 public static void Register(string id, NavPoint area)
 {
     if (NavPoint.database == null) NavPoint.database = new Dictionary<string, NavPoint>();
     if (!NavPoint.database.ContainsKey(id)) {
         NavPoint.database[id] = area;
     } else {
         throw new System.Exception("A NavPoint with id `" + id + "` is already registered");
     }
 }
Example #4
0
 public void AddItem(NavPoint pt)
 {
     if (items.Contains(pt))
     {
         return;
     }
     items.Add(pt);
     this.IsReadOnly = false;
     this.AppendText(pt.ToString());
     this.AppendText(Environment.NewLine);
     this.IsReadOnly = true;
 }
 public void AddPatrolPoint(ref NavPoint newPoint)
 {
     if (newPoint == null)
     {
         Debug.LogWarning("New NavPoint is null");
         return;
     }
     _currentDestination = newPoint;
     if (enabled == false)
     {
         enabled = true;
     }
 }
Example #6
0
        public bool retrace_navpoint()
        {
            directionWeight = -1;

            if (_debug_)
            {
                Console.Out.WriteLine("in retrace_navpoint");
            }

            if (__closestNavpointID__ == "")
            {
                return(false);
            }

            string mostVisitedNav = "";
            int    count          = -10;

            foreach (NavPoint.Neighbor neigh in navPoints[__closestNavpointID__].NGP)
            {
                if (mostVisitedNav == "")
                {
                    mostVisitedNav = neigh.Id;
                    if (navPointHistory.ContainsKey(neigh.Id))
                    {
                        count = navPointHistory[neigh.Id];
                    }
                }
                else
                {
                    if (navPointHistory.ContainsKey(neigh.Id) && navPointHistory [neigh.Id] > count)
                    {
                        mostVisitedNav = neigh.Id;
                        count          = navPointHistory [neigh.Id];
                    }
                }
            }

            if (mostVisitedNav == "")
            {
                __selectedNavpoint__ = null;
                return(false);
            }

            __selectedNavpoint__ = navPoints [mostVisitedNav];
            if (_debug_)
            {
                Console.Out.WriteLine("retrace: select " + __selectedNavpoint__.Id);
            }

            return(true);
        }
Example #7
0
    public NavPoint[] GetShortestPath(NavPoint start, NavPoint target)
    {
        HashSet<NavPoint> visited = new HashSet<NavPoint>();
        SortedDictionary<float,NavPoint> pq = new SortedDictionary<float, NavPoint>();
        Dictionary<NavPoint,NavPoint> cameFrom = new Dictionary<NavPoint, NavPoint>();
        Dictionary<NavPoint,float> scores = new Dictionary<NavPoint, float>();

        pq.Add(Vector3.Distance(target.position,start.position),start);
        scores.Add(start,Vector3.Distance(target.position,start.position));

        while(pq.Count > 0)
        {
            SortedDictionary<float,NavPoint>.KeyCollection.Enumerator keyEnumer = pq.Keys.GetEnumerator();
            keyEnumer.MoveNext();
            NavPoint np = pq[keyEnumer.Current];
            pq.Remove(keyEnumer.Current);

            if(IsGoal(np, target))
                return ReconstructPath(cameFrom,np);

            visited.Add(np);
            foreach(NavPoint neighbour in np.neighbours)
            {
                if(neighbour.gameObject.activeInHierarchy)
                {
                    if(visited.Contains(neighbour))
                        continue;
                    float estimate = scores[np] + Vector3.Distance(np.position,neighbour.position);
                    //if this is the first time we've seen this node
                    //or if we have a found a shorter path to it
                    if(!pq.ContainsValue(neighbour) || (scores.ContainsKey(neighbour) && estimate < scores[neighbour])) {
                        cameFrom[neighbour] = np;
                        scores[neighbour] = estimate;
                        try
                        {
                            pq.Add(estimate + Vector3.Distance(neighbour.position,target.position),neighbour);
                        } catch (System.ArgumentException e) {
                            //this means the key already exists i.e. there is already a distance that is this value
                            //this is real bad for A* that we can't have two things of the same priority but I'm just going
                            //to ignore it because GAME JAM
                            pq.Add(estimate + Vector3.Distance(neighbour.position,target.position)+Random.value/100,neighbour);
                        }
                    }
                }
            }
        }

        return null;
    }
Example #8
0
        public async Task LoadContentAsync(NavPoint navPoint)
        {
            var fileName     = Path.GetFileName(navPoint.ContentPath);
            var manifestItem = Source.Manifest.FirstOrDefault(a =>
            {
                var itemFileName = Path.GetFileName(a.Value.ContentLocation);
                return(itemFileName == fileName);
            });

            _currentSpineItem = Source.Spine.FirstOrDefault(a => a.IdRef == manifestItem.Key);
            var contents = Source.GetContents(navPoint, true, true);

            // var stylesheetLocations = GetStylesheetLocations(contents, navPoint.ContentPath);
            await LoadContentAsync(contents, new string[0]);
        }
Example #9
0
 private void PopulateTreeView(NavPoint nav, TreeNode parentNode)
 {
     if (nav.Children != null && nav.Children.Count != 0)
     {
         for (Int32 i = 0; i < nav.Children.Count; i++)
         {
             NavPoint n       = nav.Children[i];
             TreeNode curNode = parentNode.Nodes.Add(n.Title);
             try
             {
                 book_content.Add(curNode.FullPath, n.ContentData.Content);
             }
             catch { }
             PopulateTreeView(n, curNode);
         }
     }
 }
Example #10
0
    public static float CalCulatePathLength(NavPoint source, NavMeshAgent agent)
    {
        NavMeshPath navMeshPath = new NavMeshPath();

        agent.CalculatePath(source.Position, navMeshPath);

        //foreach (var item in navMeshPath.corners)
        //{
        //    GameObject tp = NavMeshHelper.CreatePoint(item, "" + item, 0.1f, Color.black);
        //    testPoints.Add(tp);
        //}

        float sum = GetPathDistance(navMeshPath);

        Debug.Log(string.Format("{0},{1},{2},{3},{4}", source.Name, navMeshPath.status, navMeshPath.corners.Length, source.Position, sum));
        return(sum);
    }
Example #11
0
        bool select_flag(bool ourFlag)
        {
            if (GetMovement().info == null)
            {
                return(false);
            }

            string flagID = "";

            if (ourFlag && GetMovement().info.ourFlagInfo.ContainsKey("Id"))
            {
                flagID = GetMovement().info.ourFlagInfo ["Id"];
            }
            else if (!ourFlag && GetMovement().info.enemyFlagInfo.ContainsKey("Id"))
            {
                flagID = GetMovement().info.enemyFlagInfo ["Id"];
            }
            else
            {
                return(false);
            }

            if (navPoints.ContainsKey(__closestNavpointID__))
            {
                foreach (string navid in navPoints.Keys)
                {
                    if (navid.Contains(flagID))
                    {
                        foreach (NavPoint.Neighbor neigh in navPoints[__closestNavpointID__].NGP)
                        {
                            if (neigh.Id == navid)
                            {
                                __selectedNavpoint__ = navPoints [navid];
                                break;
                            }
                        }
                        if (__selectedNavpoint__ != navPoints [navid])
                        {
                            select_navpoint();
                        }
                        break;
                    }
                }
            }
            return(true);
        }
    List <NavPoint> CalculateRouteMain(NavPoint target)
    {
        // Resets Search Stack from previous Nav
        bool found = false;

        searchStack.Clear();
        searchStack.TrimExcess();

        // Adds This object as the first NavPoint in the search stack.
        searchStack.Add(this.gameObject.GetComponent <NavPoint>());

        // Loops until a route is found or search stack is empty
        while (!found && searchStack.Count > 0)
        {
            // Checks if it can reach the target and adds follow up points
            found = CalculateRouteRecursion(target, searchStack[0]);

            // Sorts list by fCost (Cost to point on current route + As the crow flies to Target)
            searchStack.Sort(delegate(NavPoint a, NavPoint b)
            {
                return((a.fCost).CompareTo(b.fCost));
            });
        }

        // This loop runs if there is absolutly no route to target. In this case it rams headlong into a wall.
        // Under all normal circumstances this should never run. Unless a ball is spawned ontop of a wall or enclosed by obstacles there will be a way
        // If there's a will there's a way
        if (!found)
        {
            List <NavPoint> crashRoute = new List <NavPoint>();
            crashRoute.Add(target);
            return(crashRoute);
        }

        // Goes back along the route from the target to This Object using NavPoint.from
        NavPoint        backTrack = target;
        List <NavPoint> route     = new List <NavPoint>();

        do
        {
            route.Add(backTrack);
            backTrack = backTrack.from;
        } while (backTrack != this.gameObject.GetComponent <NavPoint>());
        return(route);
    }
Example #13
0
        public void MovedToNavpoint(NavPoint nav)
        {
            Console.Out.WriteLine("in MovedToNavpoint");

            if (nav != null)
            {
                __lastVisitedNavpoint__           = __closestNavpointID__;
                closestNavPointReachable [nav.Id] = false;
            }
            if (navPointHistory.ContainsKey(nav.Id))
            {
                navPointHistory [nav.Id] += directionWeight;
            }
            else
            {
                navPointHistory [nav.Id] = 1;
            }
        }
    private void GetNextPatrolPoint()
    {
        NavPoint[] possibleToTravel = _currentDestination?.NeighbourNavPoints;

        if (possibleToTravel == null || possibleToTravel.Length == 0)
        {
            Debug.LogError("Couldn't get new NavPoints");
            enabled = false;
            return;
        }
        _currentDestination = possibleToTravel[Random.Range(0, (int)possibleToTravel.Length)];
        if (_currentDestination == null)
        {
            Debug.LogError("Current destination is null");
            enabled = false;
            return;
        }
        _agent.destination = _currentDestination.transform.position;
    }
Example #15
0
        private void FormSettingsButtonClick(object sender, EventArgs e)
        {
            openFileDialog1.Title  = "Select EPUB";
            openFileDialog1.Filter = "EPUB|*.epub";
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                if (treeView1.Nodes != null && treeView1.Nodes.Count != 0)
                {
                    treeView1.Nodes.Clear();
                }
                if (book_content != null && book_content.Count != 0)
                {
                    book_content.Clear();
                }
                if (navPoints != null && navPoints.Count != 0)
                {
                    navPoints.Clear();
                }


                fileLocation = openFileDialog1.FileName;

                book      = new Epub(fileLocation);
                bookName  = book.Title[0];
                author    = book.Creator[0];
                navPoints = book.TOC;


                for (Int32 i = 0; i < navPoints.Count; i++)
                {
                    NavPoint n       = navPoints[i];
                    TreeNode curNode = treeView1.Nodes.Add(n.Title);
                    try
                    {
                        book_content.Add(curNode.FullPath, n.ContentData.Content);
                    }
                    catch { }
                    PopulateTreeView(n, curNode);
                }

                selectNode(treeView1.Nodes[0]);
            }
        }
Example #16
0
        /// <summary>
        /// not well optimised because it also checks each duplicate
        /// </summary>
        /// <param name="navPoints"></param>
        /// <returns></returns>
        internal NavPoint GetLeastOftenVisitedNavPoint(List <NavPoint> navPoints)
        {
            // FIX: corrected mistake in the original implementation which should have faulted the code

            int      currentMin   = info.visitedNavPoints.Count(g => g == navPoints[0].Id);
            NavPoint currentMinNP = navPoints[0];

            foreach (NavPoint point in navPoints)
            {
                int currentCount = info.visitedNavPoints.Count(g => g == point.Id);
                if (currentCount < currentMin)
                {
                    currentMin   = currentCount;
                    currentMinNP = point;
                }
            }

            return(currentMinNP);
        }
Example #17
0
    // Use this for initialization
    void Start()
    {
        gc = GameObject.FindWithTag("GameController").GetComponent<GameController>();
        //cache this for later
        firstPoint = startPoint.startingNavPoint;
        dfs = new DFS(firstPoint);
        //pops the top off the stack which is just the first point
        nextPoint = dfs.GetNextNavPoint();
        //put us at the start point if we're not
        if (Vector3.Distance(transform.position, nextPoint.position) > 0.05f)
            transform.position = nextPoint.position;
        //find our actual next point
        nextPoint = dfs.GetNextNavPoint();

        agent = GetComponent<NavMeshAgent>();
        agent.updateRotation = false;
        SetDestination(nextPoint.position);
        foundTribute = false;
    }
Example #18
0
        /// <summary>
        /// Examine polygons in the NavMeshQuery and add polygon edges
        /// </summary>
        /// <param name="reference">The starting polygon reference</param>
        /// <param name="pos">Current position</param>
        /// <param name="collisionQueryRange">Range to query</param>
        /// <param name="navquery">The NavMeshQuery</param>
        public void Update(NavPolyId reference, Vector3 pos, float collisionQueryRange, NavMeshQuery navquery)
        {
            const int MAX_SEGS_PER_POLY = PathfindingCommon.VERTS_PER_POLYGON;

            if (reference == NavPolyId.Null)
            {
                this.center   = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
                this.segCount = 0;
                this.numPolys = 0;
                return;
            }

            this.center = pos;

            //first query non-overlapping polygons
            NavPolyId[] tempArray   = new NavPolyId[polys.Length];
            NavPoint    centerPoint = new NavPoint(reference, pos);

            navquery.FindLocalNeighborhood(ref centerPoint, collisionQueryRange, polys, tempArray, ref numPolys, MaxLocalPolys);

            //secondly, store all polygon edges
            this.segCount = 0;
            Segment[] segs    = new Segment[MAX_SEGS_PER_POLY];
            int       numSegs = 0;

            for (int j = 0; j < numPolys; j++)
            {
                tempArray = new NavPolyId[segs.Length];
                navquery.GetPolyWallSegments(polys[j], segs, tempArray, ref numSegs, MAX_SEGS_PER_POLY);
                for (int k = 0; k < numSegs; k++)
                {
                    //skip too distant segments
                    float tseg;
                    float distSqr = Distance.PointToSegment2DSquared(ref pos, ref segs[k].Start, ref segs[k].End, out tseg);
                    if (distSqr > collisionQueryRange * collisionQueryRange)
                    {
                        continue;
                    }
                    AddSegment(distSqr, segs[k]);
                }
            }
        }
Example #19
0
        public async Task LoadContentAsync(NavPoint navPoint)
        {
            var manifestItem = Source.Manifest.FirstOrDefault(a => Path.GetFileName(a.Value.ContentLocation) == Path.GetFileName(navPoint.ContentPath));

            _currentSpineItem = Source.Spine.FirstOrDefault(a => a.IdRef == manifestItem.Key);

            var contents = await Source.GetContentsAsync(navPoint);

            var stylesheetLocations = GetStylesheetLocations(contents, navPoint.ContentPath);
            var css = string.Empty;

            foreach (var location in stylesheetLocations)
            {
                var file = await Source.GetFileAsync(location);

                css += $"\r{await FileIO.ReadTextAsync(file)}";
            }

            _converter.Convert(contents, css);
        }
Example #20
0
 public NavPoint TryGetRandomDifferentPoint(NavPoint notThis)
 {
     if (neighbours.Count == 1)
         return neighbours[0];
     else if(neighbours.Count == 2)
     {
         return neighbours.Find( (np) => {
             return !np.Equals(notThis);
         });
     }
     else
     {
         NavPoint point;
         do
         {
             point = GetRandomNeighbour();
         } while (point.Equals(notThis));
         return point;
     }
 }
Example #21
0
    private NavPoint GetMinDistancePoint(List <NavPoint> ps, Vector3 target)
    {
        NavPoint r   = null;
        float    dis = float.MaxValue;

        foreach (NavPoint i in ps)
        {
            if (i == null)
            {
                continue;
            }
            float d = Vector3.Distance(i.Position, target) + i.distanceOffset;
            if (d < dis)
            {
                dis = d;
                r   = i;
            }
        }
        return(r);
    }
Example #22
0
        /// <summary>
        /// Request an empty slot in the path queue
        /// </summary>
        /// <param name="start">Start position</param>
        /// <param name="end">End position</param>
        /// <returns>Index of empty slot</returns>
        public int Request(NavPoint start, NavPoint end)
        {
            //find empty slot
            int slot = -1;

            for (int i = 0; i < MaxQueue; i++)
            {
                if (queue[i].Index == 0)
                {
                    slot = i;
                    break;
                }
            }

            //could not find slot
            if (slot == -1)
            {
                return(PathQueue.Invalid);
            }

            int index = nextHandle++;

            if (nextHandle == 0)
            {
                nextHandle++;
            }

            PathQuery q = queue[slot];

            q.Index = index;
            q.Start = start;
            q.End   = end;

            q.Status    = 0;
            q.PathCount = 0;
            q.KeepAlive = 0;

            queue[slot] = q;

            return(index);
        }
 void TossingAI()
 {
     if ((FollowRoute() && !justGrabbed) || movingBack)
     {
         Vector3 relativePos = targetPos.point - GetComponent <NavPoint>().point;
         float   distance    = relativePos.magnitude;
         if (distance < 11.669f)
         {
             movingBack = true;
             Vector3 neededMove = (targetPos.point - GetComponent <NavPoint>().point).normalized * -1f * (11.71f - distance);
             Move(GetComponent <NavPoint>().point + neededMove, 5, .040f, true);
             return;
         }
         // Checks if the robot is pointing at the target Taken from Robot Movement as Move can only turn and move and it might just need to turn
         float relativeAngle       = Vector3.SignedAngle(relativePos, this.transform.forward, this.transform.up);
         float relativeRotationDir = relativeAngle / (Mathf.Abs(relativeAngle));
         if (Mathf.Abs(relativeAngle) > 7.5f)
         {
             // Rotates the robot towards the target
             if (relativeAngle * relativeRotationDir > gameObject.GetComponent <RobotMovement>().rotateSpeed *Time.deltaTime)
             {
                 this.transform.Rotate(0, gameObject.GetComponent <RobotMovement>().rotateSpeed *Time.deltaTime *relativeRotationDir * -1, 0);
             }
             else
             {
                 // If movement is greater then needed only do needed
                 this.transform.Rotate(0, relativeAngle * -1, 0);
             }
             return;
         }
         movingBack = false;
         Toss();
         justReleased = true;
     }
     else if (FindNearest(baskets).GetComponent <NavPoint>() != targetPos)
     {
         targetPos     = FindNearest(baskets).GetComponent <NavPoint>();
         targetChanged = true;
         justGrabbed   = false;
     }
 }
Example #24
0
        /*
         *
         * internal methods
         *
         */

        /// <summary>
        /// updates the flag positions in PositionsInfo
        /// also updates details of bases, if relevant info sent
        /// the position of a flag is how we determine where the bases are
        /// </summary>
        /// <param name="values">Dictionary containing the Flag details</param>
        override internal void ReceiveFlagDetails(Dictionary <string, string> values)
        {
            // TODO: fix the mix of information in this method it should just contain relevant info


            if (GetBot().info == null || GetBot().info.Count < 1)
            {
                return;
            }
            // set flag stuff
            if (values["Team"] == GetBot().info["Team"])
            {
                if (info.ourFlagInfo != null && info.ourFlagInfo.ContainsKey("Location"))
                {
                    return;
                }
                info.ourFlagInfo = values;
            }
            else
            {
                if (info.enemyFlagInfo != null && info.enemyFlagInfo.ContainsKey("Location"))
                {
                    return;
                }
                info.enemyFlagInfo = values;
            }

            if (values["State"] == "home")
            {
                if (values["Team"] == GetBot().info["Team"])
                {
                    info.ownBasePos = NavPoint.ConvertToNavPoint(values);
                }
                else
                {
                    info.enemyBasePos = NavPoint.ConvertToNavPoint(values);
                }
            }
        }
Example #25
0
        private void FillTocRecursively(eBdb.EpubReader.NavPoint tocEntry, NavPoint parent)
        {
            NavPoint navPoint;

            if (parent != null)
            {
                navPoint = parent.AddNavPoint(tocEntry.Title, tocEntry.Source, tocEntry.Order);
            }
            else
            {
                navPoint = parsedEpub.AddNavPoint(tocEntry.Title, tocEntry.Source, tocEntry.Order);
            }

            if (tocEntry.Children == null)
            {
                return;
            }

            foreach (eBdb.EpubReader.NavPoint nestedEntry in tocEntry.Children)
            {
                FillTocRecursively(nestedEntry, navPoint);
            }
        }
Example #26
0
    public void FindNeighbours()
    {
        var nearby = Physics.OverlapSphere(this.transform.position, MAX_DISTANCE);

        if (nearby != null)
        {
            foreach (var obj in nearby)
            {
                if (obj != SelfCollider)
                {
                    NavPoint potentialNeighbour = obj.GetComponent <NavPoint>();
                    if (potentialNeighbour)
                    {
                        if (!Neighbours.Contains(potentialNeighbour) && ClearRaycastToNeighbour(potentialNeighbour.transform))
                        {
                            AddNeighbour(potentialNeighbour);
                            potentialNeighbour.AddNeighbour(this);
                        }
                    }
                }
            }
        }
    }
Example #27
0
    // Update is called once per frame
    void Update()
    {
        foreach (var target in fov.visibleTargets)
        {
            var player = target.gameObject.GetComponent <PlayerController>();

            if (player != null)
            {
                if (player.inNaughtyZone)
                {
                    hunted = player;
                    agent.SetDestination(hunted.transform.position);
                }
            }
        }

        if (hunted == null)
        {
            float dist = agent.remainingDistance;
            if (agent.pathStatus == UnityEngine.AI.NavMeshPathStatus.PathComplete && agent.remainingDistance == 0)
            {
                if (currentPoint.next)
                {
                    currentPoint = currentPoint.next;
                    agent.SetDestination(currentPoint.transform.position);
                }
            }
        }
        else
        {
            float dist = agent.remainingDistance;
            if (dist < .4f)
            {
                hunted.gameObject.SetActive(false);
            }
        }
    }
Example #28
0
    private static NavPointList GetSampleAndEdgeEx(Vector3 target, NavMeshAgent agent)
    {
        NavPointList psList = new NavPointList();
        NavMeshHit   hitInfo;

        if (NavMesh.FindClosestEdge(target, out hitInfo, -1))
        {
            NavPoint navP = new NavPoint("Edge", hitInfo.position, target, Color.green, agent);
            //psList.Add(navP);
            psList.Edge = navP;

            GetDownCast(hitInfo.position, "Edge");
        }
        else
        {
            //Debug.LogError("GetClosetPoint No FindClosestEdge ");
        }

        if (NavMesh.SamplePosition(target, out hitInfo, 100, -1))
        {
            var dis = Vector3.Distance(hitInfo.position, target);
            if (dis < MaxDistance)
            {
                NavPoint navP = new NavPoint("Sample", hitInfo.position, target, Color.blue, agent);
                //psList.Add(navP);
                psList.Sample = navP;

                GetDownCast(hitInfo.position, "Sample");
            }
        }
        else
        {
            //Debug.LogError("GetClosetPoint No SamplePosition ");
        }

        return(psList);
    }
    void FixedUpdate()
    {
        if (_waiting > 0f)
        {
            _waiting -= Time.fixedDeltaTime;
            return;
        }

        if (NextNavPoint == null)
        {
            return;
        }

        if (Vector3.Distance(transform.position, NextNavPoint.transform.position) <= Distance)
        {
            _waiting = NextNavPoint.Wait;
            NextNavPoint.OnEnterPoint.Invoke();
            NextNavPoint = NextNavPoint.NextPoint;

            return;
        }

        transform.SetPositionAndRotation(Vector3.Lerp(transform.position, NextNavPoint.transform.position, Speed * Time.fixedDeltaTime), transform.rotation);
    }
Example #30
0
        private void GeneratePathfinding()
        {
            if (!hasGenerated)
            {
                return;
            }

            NavQueryFilter filter = new NavQueryFilter();

            buildData = new NavMeshBuilder(polyMesh, polyMeshDetail, new SharpNav.Pathfinding.OffMeshConnection[0], settings);

            tiledNavMesh = new TiledNavMesh(buildData);

            for (int i = 0; i < tiledNavMesh.Tiles.Count; ++i)
            {
                for (int j = 0; j < tiledNavMesh.Tiles[i].Verts.Length; ++j)
                {
                    //if (j < tiledNavMesh.Tiles[i].Verts.Length - 1)
                    //    Debug.DrawLine(ExportNavMeshToObj.ToUnityVector(tiledNavMesh.Tiles[i].Verts[j]), ExportNavMeshToObj.ToUnityVector(tiledNavMesh.Tiles[i].Verts[j + 1]), Color.blue, 99);
                }
            }

            navMeshQuery = new NavMeshQuery(tiledNavMesh, 2048);

            //Find random start and end points on the poly mesh

            /*int startRef;
             * navMeshQuery.FindRandomPoint(out startRef, out startPos);*/

            //SVector3 c = new SVector3(10, 0, 0);
            //SVector3 e = new SVector3(5, 5, 5);
            //navMeshQuery.FindNearestPoly(ref c, ref e, out startPt);

            //navMeshQuery.FindRandomPointAroundCircle(ref startPt, 1000, out endPt);

            startPt = navMeshQuery.FindRandomPoint();
            endPt   = navMeshQuery.FindRandomPoint();

            //calculate the overall path, which contains an array of polygon references
            int MAX_POLYS = 256;

            path = new Path();
            navMeshQuery.FindPath(ref startPt, ref endPt, filter, path);

            //find a smooth path over the mesh surface
            int      npolys    = path.Count;
            SVector3 iterPos   = new SVector3();
            SVector3 targetPos = new SVector3();

            navMeshQuery.ClosestPointOnPoly(startPt.Polygon, startPt.Position, ref iterPos);
            navMeshQuery.ClosestPointOnPoly(path[npolys - 1], endPt.Position, ref targetPos);

            smoothPath = new List <SVector3>(2048);
            smoothPath.Add(iterPos);

            float STEP_SIZE = 0.5f;
            float SLOP      = 0.01f;

            while (npolys > 0 && smoothPath.Count < smoothPath.Capacity)
            {
                //find location to steer towards
                SVector3          steerPos     = new SVector3();
                StraightPathFlags steerPosFlag = 0;
                NavPolyId         steerPosRef  = NavPolyId.Null;

                if (!GetSteerTarget(navMeshQuery, iterPos, targetPos, SLOP, path, ref steerPos, ref steerPosFlag, ref steerPosRef))
                {
                    break;
                }

                bool endOfPath         = (steerPosFlag & StraightPathFlags.End) != 0 ? true : false;
                bool offMeshConnection = (steerPosFlag & StraightPathFlags.OffMeshConnection) != 0 ? true : false;

                //find movement delta
                SVector3 delta = steerPos - iterPos;
                float    len   = (float)Math.Sqrt(SVector3.Dot(delta, delta));

                //if steer target is at end of path or off-mesh link
                //don't move past location
                if ((endOfPath || offMeshConnection) && len < STEP_SIZE)
                {
                    len = 1;
                }
                else
                {
                    len = STEP_SIZE / len;
                }

                SVector3 moveTgt = new SVector3();
                VMad(ref moveTgt, iterPos, delta, len);

                //move
                SVector3         result     = new SVector3();
                List <NavPolyId> visited    = new List <NavPolyId>(16);
                NavPoint         startPoint = new NavPoint(path[0], iterPos);
                navMeshQuery.MoveAlongSurface(ref startPoint, ref moveTgt, out result, visited);
                path.FixupCorridor(visited);
                npolys = path.Count;
                float h = 0;
                navMeshQuery.GetPolyHeight(path[0], result, ref h);
                result.Y = h;
                iterPos  = result;

                //handle end of path when close enough
                if (endOfPath && InRange(iterPos, steerPos, SLOP, 1.0f))
                {
                    //reached end of path
                    iterPos = targetPos;
                    if (smoothPath.Count < smoothPath.Capacity)
                    {
                        smoothPath.Add(iterPos);
                    }
                    break;
                }

                //store results
                if (smoothPath.Count < smoothPath.Capacity)
                {
                    smoothPath.Add(iterPos);
                }
            }

            for (int i = 0; i < smoothPath.Count; i++)
            {
                //if (i < smoothPath.Count - 1)
                //    Debug.DrawLine(ExportNavMeshToObj.ToUnityVector(smoothPath[i]), ExportNavMeshToObj.ToUnityVector(smoothPath[i + 1]), Color.red, 99);
            }
        }
        public Vector2[] GetPath(Vector2 start, Vector2 end)
        {
            NavPoint startPt = navMeshQuery.FindNearestPoly(new SVector3(-start.X, 0, start.Y), new SharpNav.Geometry.Vector3(2f, 2f, 2f));
            NavPoint endPt   = navMeshQuery.FindNearestPoly(new SVector3(-end.X, 0, end.Y), new SharpNav.Geometry.Vector3(2f, 2f, 2f));
            Path     path    = new Path();

            navMeshQuery.FindPath(ref startPt, ref endPt, new NavQueryFilter(), path);

            List <SVector3> smoothPath;

            //find a smooth path over the mesh surface
            int      npolys    = path.Count;
            SVector3 iterPos   = new SVector3();
            SVector3 targetPos = new SVector3();

            navMeshQuery.ClosestPointOnPoly(startPt.Polygon, startPt.Position, ref iterPos);
            navMeshQuery.ClosestPointOnPoly(path[npolys - 1], endPt.Position, ref targetPos);

            smoothPath = new List <SVector3>(2048);
            smoothPath.Add(iterPos);

            float STEP_SIZE = 0.5f;
            float SLOP      = 0.01f;

            while (npolys > 0 && smoothPath.Count < smoothPath.Capacity)
            {
                //find location to steer towards
                SVector3          steerPos     = new SVector3();
                StraightPathFlags steerPosFlag = 0;
                NavPolyId         steerPosRef  = NavPolyId.Null;

                if (!GetSteerTarget(navMeshQuery, iterPos, targetPos, SLOP, path, ref steerPos, ref steerPosFlag, ref steerPosRef))
                {
                    break;
                }

                bool endOfPath         = (steerPosFlag & StraightPathFlags.End) != 0 ? true : false;
                bool offMeshConnection = (steerPosFlag & StraightPathFlags.OffMeshConnection) != 0 ? true : false;

                //find movement delta
                SVector3 delta = steerPos - iterPos;
                float    len   = (float)Math.Sqrt(SVector3.Dot(delta, delta));

                //if steer target is at end of path or off-mesh link
                //don't move past location
                if ((endOfPath || offMeshConnection) && len < STEP_SIZE)
                {
                    len = 1;
                }
                else
                {
                    len = STEP_SIZE / len;
                }

                SVector3 moveTgt = new SVector3();
                VMad(ref moveTgt, iterPos, delta, len);

                //move
                SVector3         result     = new SVector3();
                List <NavPolyId> visited    = new List <NavPolyId>(16);
                NavPoint         startPoint = new NavPoint(path[0], iterPos);
                navMeshQuery.MoveAlongSurface(ref startPoint, ref moveTgt, out result, visited);
                path.FixupCorridor(visited);
                npolys = path.Count;
                float h = 0;
                navMeshQuery.GetPolyHeight(path[0], result, ref h);
                result.Y = h;
                iterPos  = result;

                //handle end of path when close enough
                if (endOfPath && InRange(iterPos, steerPos, SLOP, 1.0f))
                {
                    //reached end of path
                    iterPos = targetPos;
                    if (smoothPath.Count < smoothPath.Capacity)
                    {
                        smoothPath.Add(iterPos);
                    }
                    break;
                }

                //store results
                if (smoothPath.Count < smoothPath.Capacity)
                {
                    smoothPath.Add(iterPos);
                }
            }

            return(smoothPath.Select(x => new Vector2(-x.X, x.Z)).ToArray());
        }
Example #32
0
 public void AddNavPoint(NavPoint argNavPoint)
 {
     myNavPoints.Add(argNavPoint);
 }
Example #33
0
        public void DoNext(Player _player)
        {
            player = _player;

            if (first)
            {
                foreach (Entity e in player.Tissue.GetEntitiesByType(EntityEnum.AZN))
                {
                    aznPoint.Add(new Point(e.X, e.Y));
                }
                foreach (NavigationStruct node in MyAI.listNavColObj)
                {
                    foreach (NavNode n in node.Nodes)
                    {
                        allNodes.Add(n);
                    }
                }
                allNodes.Sort(new NavNodeComparer());
                first = false;
            }

            HandleStockKosong();
            HandleEnemies();

            if (this.State == NanoBotState.Moving)
            {
                foreach (NavNode node in allNodes)
                {
                    if (node.NavPt.Location == this.PointInfo)
                    {
                        node.Bot  = this;
                        node.Done = false;
                    }
                }
            }

            //cek apakah sudah selesai
            if (this.State == NanoBotState.WaitingOrders)
            {
                bool selesai = true;
                foreach (BaseObjective b in player.Mission.Objectives)
                {
                    if ((b is NavigationObjective) && (b.Status == ObjectiveStatus.ToBeDone))
                    {
                        selesai = false;
                        break;
                    }
                }
                if (selesai)
                {
                    if (this.player.NanoBots.Count < Utils.NbrMaxBots)
                    {
                        //this.MoveTo(player.PierreTeamInjectionPoint);
                        //HandleFreeRoam();
                        this.MoveTo(Global.PF.FindWay(this.Location, Global.MYAI.PierreTeamInjectionPoint).Points);
                        return;
                    }
                    else
                    {
                        this.ForceAutoDestruction();
                    }
                }
                else
                {
                    //set destination
                    if (dest == null)
                    {
                        dest = FindNextDest();
                    }

                    //move to destination and wait
                    if (dest != null)
                    {
                        if ((this.Location != dest.Location) || (player.CurrentTurn < dest.StartTurn))
                        {
                            //this.MoveTo(dest.Location);
                            this.MoveTo(Global.PF.FindWay(this.Location, dest.Location).Points);
                            return;
                        }
                        else
                        {
                            dest = null;
                            foreach (NavNode node in allNodes)
                            {
                                if (node.Bot.Equals(this))
                                {
                                    node.Bot  = null;
                                    node.Done = true;
                                }
                            }
                            return;
                        }
                    }
                }
            }
        }
Example #34
0
 public NavNode(NavPoint p)
 {
     pt         = p;
     isAssigned = false;
     isDone     = false;
 }
Example #35
0
 //a navpoint is the goal if we can see the target from it
 bool IsGoal(NavPoint np, NavPoint target)
 {
     return np.GetInstanceID() == target.GetInstanceID();
 }
        // Copyright (c) 2013-2016 Robert Rouhani <*****@*****.**> and other contributors (see CONTRIBUTORS file).
        // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE

        public static List <Vector3> GetPath(actors.area.Zone zone, Vector3 startVec, Vector3 endVec, float stepSize = 0.70f, int pathSize = 45, float polyRadius = 0.0f, bool skipToTarget = false)
        {
            var navMesh      = zone.tiledNavMesh;
            var navMeshQuery = zone.navMeshQuery;

            // no navmesh loaded, run straight to player
            if (navMesh == null)
            {
                return(new List <Vector3>()
                {
                    endVec
                });
            }

            // no need to waste cycles finding path to same point
            if (startVec.X == endVec.X && startVec.Y == endVec.Y && startVec.Z == endVec.Z && polyRadius == 0.0f)
            {
                return(null);
            }

            var smoothPath = new List <Vector3>(pathSize)
            {
            };

            NavQueryFilter filter = new NavQueryFilter();

            NavPoint startPt, endPt;

            try
            {
                SharpNav.Geometry.Vector3 c  = new SharpNav.Geometry.Vector3(startVec.X, startVec.Y, startVec.Z);
                SharpNav.Geometry.Vector3 ep = new SharpNav.Geometry.Vector3(endVec.X, endVec.Y, endVec.Z);

                SharpNav.Geometry.Vector3 e = new SharpNav.Geometry.Vector3(5, 5, 5);
                navMeshQuery.FindNearestPoly(ref c, ref e, out startPt);
                navMeshQuery.FindNearestPoly(ref ep, ref e, out endPt);

                //calculate the overall path, which contains an array of polygon references
                int MAX_POLYS = 256;
                var path      = new SharpNav.Pathfinding.Path();

                navMeshQuery.FindPath(ref startPt, ref endPt, filter, path);

                //find a smooth path over the mesh surface
                int npolys = path.Count;
                SharpNav.Geometry.Vector3 iterPos   = new SharpNav.Geometry.Vector3();
                SharpNav.Geometry.Vector3 targetPos = new SharpNav.Geometry.Vector3();
                navMeshQuery.ClosestPointOnPoly(startPt.Polygon, startPt.Position, ref iterPos);
                navMeshQuery.ClosestPointOnPoly(path[npolys - 1], endPt.Position, ref targetPos);

                // set target to random point at end of path
                if (polyRadius != 0.0f)
                {
                    var randPoly = navMeshQuery.FindRandomPointAroundCircle(endPt, polyRadius);
                    targetPos = randPoly.Position;
                }

                if (skipToTarget)
                {
                    return(new List <Vector3>()
                    {
                        new Vector3(targetPos.X, targetPos.Y, targetPos.Z)
                    });
                }
                smoothPath.Add(new Vector3(iterPos.X, iterPos.Y, iterPos.Z));

                //float STEP_SIZE = 0.70f;
                float SLOP = 0.15f;
                while (npolys > 0 && smoothPath.Count < smoothPath.Capacity)
                {
                    //find location to steer towards
                    SharpNav.Geometry.Vector3 steerPos     = new SharpNav.Geometry.Vector3();
                    StraightPathFlags         steerPosFlag = 0;
                    NavPolyId steerPosRef = NavPolyId.Null;

                    if (!GetSteerTarget(navMeshQuery, iterPos, targetPos, SLOP, path, ref steerPos, ref steerPosFlag, ref steerPosRef))
                    {
                        break;
                    }

                    bool endOfPath         = (steerPosFlag & StraightPathFlags.End) != 0 ? true : false;
                    bool offMeshConnection = (steerPosFlag & StraightPathFlags.OffMeshConnection) != 0 ? true : false;

                    //find movement delta
                    SharpNav.Geometry.Vector3 delta = steerPos - iterPos;
                    float len = (float)Math.Sqrt(SharpNav.Geometry.Vector3.Dot(delta, delta));

                    //if steer target is at end of path or off-mesh link
                    //don't move past location
                    if ((endOfPath || offMeshConnection) && len < stepSize)
                    {
                        len = 1;
                    }
                    else
                    {
                        len = stepSize / len;
                    }

                    SharpNav.Geometry.Vector3 moveTgt = new SharpNav.Geometry.Vector3();
                    VMad(ref moveTgt, iterPos, delta, len);

                    //move
                    SharpNav.Geometry.Vector3 result  = new SharpNav.Geometry.Vector3();
                    List <NavPolyId>          visited = new List <NavPolyId>(pathSize);
                    NavPoint startPoint = new NavPoint(path[0], iterPos);
                    navMeshQuery.MoveAlongSurface(ref startPoint, ref moveTgt, out result, visited);
                    path.FixupCorridor(visited);
                    npolys = path.Count;
                    float h = 0;
                    navMeshQuery.GetPolyHeight(path[0], result, ref h);
                    result.Y = h;
                    iterPos  = result;

                    //handle end of path when close enough
                    if (endOfPath && InRange(iterPos, steerPos, SLOP, 1000.0f))
                    {
                        //reached end of path
                        iterPos = targetPos;
                        if (smoothPath.Count < smoothPath.Capacity)
                        {
                            smoothPath.Add(new Vector3(iterPos.X, iterPos.Y, iterPos.Z));
                        }
                        break;
                    }

                    //store results
                    if (smoothPath.Count < smoothPath.Capacity)
                    {
                        smoothPath.Add(new Vector3(iterPos.X, iterPos.Y, iterPos.Z));
                    }
                }
            }
            catch (Exception e)
            {
                Program.Log.Error(e.Message);
                Program.Log.Error("Start pos {0} {1} {2} end pos {3} {4} {5}", startVec.X, startVec.Y, startVec.Z, endVec.X, endVec.Y, endVec.Z);
                // todo: probably log this
                return(new List <Vector3>()
                {
                    endVec
                });
            }
            return(smoothPath);
        }
Example #37
0
 NavPoint[] ReconstructPath(Dictionary<NavPoint,NavPoint> cameFrom, NavPoint current)
 {
     Stack<NavPoint> path = new Stack<NavPoint>();
     path.Push(current);
     while(cameFrom.ContainsKey(current)) {
         current = cameFrom[current];
         path.Push(current);
     }
     return path.ToArray();
 }
Example #38
0
        /*
         *
         * internal methods
         *
         */


        override internal void ReceiveDeathDetails(Dictionary <string, string> value)
        {
            __selectedNavpoint__     = null;
            closestNavPointReachable = new Dictionary <string, bool>();
        }
        public void DoNext(Player _player)
        {
            player = _player;

            if (first)
            {
                foreach (Entity e in player.Tissue.GetEntitiesByType(EntityEnum.AZN))
                {
                    aznPoint.Add(new Point(e.X, e.Y));
                }
                foreach (NavigationStruct node in MyAI.listNavColObj)
                {
                    foreach (NavNode n in node.Nodes)
                    {
                        allNodes.Add(n);
                    }
                }
                allNodes.Sort(new NavNodeComparer());
                first = false;
            }

            HandleStockKosong();
            HandleEnemies();

            if (this.State == NanoBotState.Moving)
            {
                foreach (NavNode node in allNodes)
                {
                    if (node.NavPt.Location == this.PointInfo)
                    {
                        node.Bot = this;
                        node.Done = false;
                    }
                }
            }

            //cek apakah sudah selesai
            if (this.State == NanoBotState.WaitingOrders)
            {
                bool selesai = true;
                foreach (BaseObjective b in player.Mission.Objectives)
                {
                    if ((b is NavigationObjective) && (b.Status == ObjectiveStatus.ToBeDone))
                    {
                        selesai = false;
                        break;
                    }
                }
                if (selesai)
                {
                    if (this.player.NanoBots.Count < Utils.NbrMaxBots)
                    {
                        //this.MoveTo(player.PierreTeamInjectionPoint);
                        //HandleFreeRoam();
                        this.MoveTo(Global.PF.FindWay(this.Location, Global.MYAI.PierreTeamInjectionPoint).Points);
                        return;
                    }
                    else
                    {
                        this.ForceAutoDestruction();
                    }
                }
                else
                {
                    //set destination
                    if (dest == null)
                    {
                        dest = FindNextDest();
                    }

                    //move to destination and wait
                    if (dest != null)
                    {
                        if ((this.Location != dest.Location) || (player.CurrentTurn < dest.StartTurn))
                        {
                            //this.MoveTo(dest.Location);
                            this.MoveTo(Global.PF.FindWay(this.Location, dest.Location).Points);
                            return;
                        }
                        else
                        {
                            dest = null;
                            foreach (NavNode node in allNodes)
                            {
                                if (node.Bot.Equals(this))
                                {
                                    node.Bot = null;
                                    node.Done = true;
                                }
                            }
                            return;
                        }
                    }
                }
            }
        }
Example #40
0
        public bool select_navpoint(string navID)
        {
            string leastVisitedNav = "";

            directionWeight = 1;
            Console.Out.WriteLine("in select_navpoint");

            if (navID != "" && navPoints.ContainsKey(navID))
            {
                __selectedNavpoint__ = navPoints [navID];
                return(true);
            }

            if (__closestNavpointID__ == null)
            {
                return(false);
            }

            int count = 0;

            foreach (NavPoint.Neighbor nei in navPoints[__closestNavpointID__].NGP)
            {
                if (leastVisitedNav == "")
                {
                    leastVisitedNav = nei.Id;
                    if (navPointHistory.ContainsKey(leastVisitedNav))
                    {
                        count = navPointHistory [leastVisitedNav];
                    }
                    else
                    {
                        break;
                    }
                }
                else if (navPointHistory.ContainsKey(nei.Id))
                {
                    if (navPointHistory [nei.Id] < count)
                    {
                        leastVisitedNav = nei.Id;
                        count           = navPointHistory [nei.Id];
                    }
                }
                else
                {
                    leastVisitedNav = nei.Id;
                    break;
                }
            }
            if (leastVisitedNav == "")
            {
                __selectedNavpoint__ = null;
                return(false);
            }

            __selectedNavpoint__ = navPoints [leastVisitedNav];

            if (_debug_)
            {
                Console.Out.WriteLine("selected Navpoint: " + leastVisitedNav);
            }

            return(true);
        }
Example #41
0
 public NavNode(NavPoint p)
 {
     pt = p;
     isAssigned = false;
     isDone = false;
 }
Example #42
0
 public DFS(NavPoint startPt)
 {
     this.stack = new Stack<NavPoint>();
     stack.Push(startPt);
 }
        public void DoNext(Player _player)
        {
            player = _player;

            if (first)
            {
                foreach (NavigationStruct node in MyAI.listNavExpObj)
                {
                    foreach (NavNode n in node.Nodes)
                    {
                        allNodes.Add(n);
                    }
                }
                //allNodes.Sort(new NavNodeComparer());
                first = false;
            }

            /*int numBot = 0;
            foreach (NanoBot bot in _player.NanoBots)
            {
                if (bot is NavigationExplorerBot)
                    numBot++;
            }
            if (Global.NBNAVEXPTOBUILD < numBot)
            {
                // pertama kali atau bot sudah ada yang mati
                foreach (NavNode node in allNodes)
                {
                    node.Bot = null;
                    node.Done = false;
                    return;
                }
            }*/

            if (this.State == NanoBotState.Moving)
            {
                foreach (NavNode node in allNodes)
                {
                    if (node.NavPt.Location == this.PointInfo)
                    {
                        node.Bot = this;
                        node.Done = false;
                    }
                }
            }

            //cek apakah sudah selesai
            if (this.State == NanoBotState.WaitingOrders)
            {
                bool selesai = true;
                foreach (BaseObjective b in player.Mission.Objectives)
                {
                    if ((b is NavigationObjective) && (b.Status == ObjectiveStatus.ToBeDone))
                    {
                        selesai = false;
                        break;
                    }
                }
                if (selesai)
                {
                    HandleFreeRoam();
                    //this.MoveTo(Global.SPF.FindWay(this.Location, Global.MYAI.PierreTeamInjectionPoint).Points);
                    return;
                }
                else
                {
                    //set destination
                    if (dest == null)
                    {
                        dest = FindNextDest();
                    }

                    //move to destination and wait
                    if (dest != null)
                    {
                        if ((this.Location != dest.Location) || (player.CurrentTurn < dest.StartTurn))
                        {
                            this.MoveTo(Global.SPF.FindWay(this.Location, dest.Location).Points);
                            return;
                        }
                        else
                        {
                            dest = null;
                            foreach (NavNode node in allNodes)
                            {
                                if (node.Bot.Equals(this))
                                {
                                    node.Bot = null;
                                    node.Done = true;
                                }
                            }
                            return;
                        }
                    }
                }
            }
        }
Example #44
0
 public bool RemovePoint(NavPoint p)
 {
     return this.pointsToVisit.Remove(p);
 }