private async void BuildTheRoute_Click(object sender, RoutedEventArgs e)
        {
            if (_mapPoints.Count < 2)
            {
                return;
            }
            CheckRouteServicePreffer();
            if (_mapPoints.Count > 47 && !_manualRoute)
            {
                MessageBox.Show(
                    "Too many waypoints, try to reduce them to 47, or wait for next releases, where that limit will be increased!",
                    "Routing Error", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            BuildingProgressBar.Value = 0;
            BotWindowData bot;
            var           route = GetWorkingRouting(out bot);

            if (route == "error" && !_manualRoute)
            {
                MessageBox.Show(
                    "You have to enter Google Direction API or Mapzen Valhalla API to any of your bots, before creating a route",
                    "API Key Error", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var start = _mapPoints.FirstOrDefault(x => x.IsStart) ?? _mapPoints.First();

            BuildingProgressBar.Value = 10;

            RoutingResponse response = null;
            var             cycleWp  = _mapPoints.Where(x => !x.IsStart).Select(x => x.Location).ToList();

            cycleWp.Add(start.Location);
            List <GeoCoordinate> routePoints;

            if (!_manualRoute)
            {
                if (route == "google")
                {
                    response = GoogleRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                }
                else if (route == "mapzen")
                {
                    response = MapzenRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                }
                if (response?.Coordinates == null || response.Coordinates.Count == 0)
                {
                    return;
                }
                routePoints = response.Coordinates.Select(wp => new GeoCoordinate(wp[0], wp[1])).ToList();
            }
            else
            {
                cycleWp.Insert(0, start.Location);
                routePoints = new List <GeoCoordinate>(cycleWp);
            }
            BuildingProgressBar.Value = 60;
            _currentRoute?.Points?.Clear();
            if (_currentRoute == null)
            {
                _currentRoute = new GMapRoute(new List <PointLatLng>());
                RouteCreatorMap.Markers.Add(_currentRoute);
            }
            BuildingProgressBar.Value = 70;
            _buildedRoute             = new List <GeoCoordinate>(routePoints);

            foreach (var item in routePoints)
            {
                _currentRoute.Points?.Add(new PointLatLng(item.Latitude, item.Longitude));
            }

            _currentRoute?.RegenerateShape(RouteCreatorMap);
            var path = _currentRoute?.Shape as Path;

            if (path != null)
            {
                path.Stroke = new SolidColorBrush(Color.FromRgb(255, 0, 0));
            }


            bot = MainWindow.BotsCollection.FirstOrDefault(
                x => !string.IsNullOrEmpty(x.GlobalSettings.LocationSettings.MapzenApiElevationKey));
            if (bot != null)
            {
                await bot.Session.MapzenApi.FillAltitude(_buildedRoute.ToList());
            }
            BuildingProgressBar.Value = 100;
            _builded = true;
        }
        private async Task BuildTheRouteTask(CancellationToken token)
        {
            try
            {
                token.ThrowIfCancellationRequested();
                if (_mapPoints.Count < 2)
                {
                    return;
                }
                await Dispatcher.BeginInvoke(new ThreadStart(CheckRouteServicePrefer));

                if (_mapPoints.Count > 47 && !_manualRoute)
                {
                    Dispatcher.Invoke(new ThreadStart(delegate
                    {
                        MessageBox.Show(
                            TranslationEngine.GetDynamicTranslationString("%TOO_MANY_ROUTE_POINTS%",
                                                                          "Too many waypoints, try to reduce them to 47, or wait for next releases, where that limit will be increased!"),
                            "Routing Error", MessageBoxButton.OK, MessageBoxImage.Information);
                    }));
                    return;
                }
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_2%", "Started!..."), 0);
                BotWindowData bot;
                var           route = GetWorkingRouting(out bot);
                if (route == "error" && !_manualRoute)
                {
                    MessageBox.Show(
                        TranslationEngine.GetDynamicTranslationString("%NO_ROUTE_API_FOUND%",
                                                                      "You have to enter Google Direction API or Mapzen Valhalla API to any of your bots, before creating a route"),
                        "API Key Error", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var start = _mapPoints.FirstOrDefault(x => x.IsStart) ?? _mapPoints.First();
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_3%", "Started!..."), 10);
                RoutingResponse response = null;
                var             cycleWp  = _mapPoints.Where(x => !x.IsStart).Select(x => x.Location).ToList();
                cycleWp.Add(start.Location);
                List <GeoCoordinate> routePoints;
                token.ThrowIfCancellationRequested();
                if (!_manualRoute)
                {
                    if (route == "google")
                    {
                        response = GoogleRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                    }
                    else if (route == "mapzen")
                    {
                        response = MapzenRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                    }
                    if (response?.Coordinates == null || response.Coordinates.Count == 0)
                    {
                        return;
                    }
                    routePoints = response.Coordinates.Select(wp => new GeoCoordinate(wp[0], wp[1])).ToList();
                }
                else
                {
                    cycleWp.Insert(0, start.Location);
                    routePoints = new List <GeoCoordinate>(cycleWp);
                }
                token.ThrowIfCancellationRequested();
                UpdateProgress(
                    TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_4%", "Handling result..."), 60);
                _currentRoute?.Points?.Clear();
                if (_currentRoute == null)
                {
                    _currentRoute = new GMapRoute(new List <PointLatLng>());
                }

                await RouteCreatorMap.Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    RouteCreatorMap.Markers.Add(_currentRoute);
                }));

                token.ThrowIfCancellationRequested();
                UpdateProgress(
                    TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_5%", "Requesting altitude..."), 70);
                _buildedRoute = new List <GeoCoordinate>(routePoints);
                token.ThrowIfCancellationRequested();
                foreach (var item in routePoints)
                {
                    _currentRoute.Points?.Add(new PointLatLng(item.Latitude, item.Longitude));
                }
                await Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    try
                    {
                        _currentRoute.RegenerateShape(RouteCreatorMap);
                    }
                    catch (Exception)
                    {
                        //ignore
                    }
                }));

                var path = _currentRoute?.Shape as Path;
                await Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    if (path != null)
                    {
                        path.Stroke = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                    }
                }));


                bot = MainWindow.BotsCollection.FirstOrDefault(
                    x => !string.IsNullOrEmpty(x.GlobalSettings.LocationSettings.MapzenApiKey));
                if (bot != null)
                {
                    await bot.Session.MapzenApi.FillAltitude(_buildedRoute.ToList(), token : token);
                }
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_6%", "Done!"), 100);
                _builded = true;
            }
            catch (OperationCanceledException)
            {
                //ignore
            }
        }
示例#3
0
        private static async Task <List <GeoCoordinate> > CreateHumanRoute(GeoCoordinate destination, CancellationToken cancellationToken, ISession session,
                                                                           bool direct, List <GeoCoordinate> waypointsToVisit, GeoCoordinate currentLocation)
        {
            var waypoints = new List <GeoCoordinate>();

            if (!direct)
            {
                RoutingResponse routingResponse = null;
                try
                {
                    switch (session.LogicSettings.RoutingService)
                    {
                    case RoutingService.OpenLs:
                        routingResponse = OsmRouting.GetRoute(currentLocation, destination, session);
                        break;

                    case RoutingService.GoogleDirections:
                        routingResponse = GoogleRouting.GetRoute(currentLocation, destination, session,
                                                                 waypointsToVisit);
                        break;

                    case RoutingService.MapzenValhalla:
                        routingResponse = MapzenRouting.GetRoute(currentLocation, destination, session,
                                                                 waypointsToVisit);
                        break;
                    }
                }
                catch (NullReferenceException ex)
                {
                    session.EventDispatcher.Send(new DebugEvent
                    {
                        Message = ex.ToString()
                    });
                    routingResponse = new RoutingResponse();
                }

                if (routingResponse?.Coordinates == null)
                {
                    return(waypoints);
                }
                foreach (var item in routingResponse.Coordinates)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    //0 = lat, 1 = long (MAYBE NOT THO?)
                    switch (session.LogicSettings.RoutingService)
                    {
                    case RoutingService.OpenLs:
                        waypoints.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], item.ToArray()[2]));
                        break;

                    case RoutingService.GoogleDirections:
                        waypoints.Add(new GeoCoordinate(item[0], item[1]));
                        break;

                    case RoutingService.MapzenValhalla:
                        waypoints.Add(new GeoCoordinate(item[0], item[1]));
                        break;
                    }
                }
                if ((session.LogicSettings.RoutingService == RoutingService.GoogleDirections ||
                     session.LogicSettings.RoutingService == RoutingService.MapzenValhalla) &&
                    session.LogicSettings.UseMapzenApiElevation)
                {
                    return(await session.MapzenApi.FillAltitude(waypoints, token : cancellationToken));
                }
                return(waypoints);
            }
            waypoints.Add(destination);
            return(waypoints);
        }
示例#4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="destination">Desired location to move</param>
        /// <param name="walkingSpeedMin">Minimal walking speed during the move</param>
        /// <param name="walkingSpeedMax">Maximal walking speed during the move</param>
        /// <param name="functionExecutedWhileWalking">Functions #1 to be exec while walking, like task or smth</param>
        /// <param name="functionExecutedWhileWalking2">Functions #1 to be exec while walking, like task or smth</param>
        /// <param name="cancellationToken">regular session cancelation token</param>
        /// <param name="session">ISession param of the bot, to detect which bot started it</param>
        /// <param name="direct">Directly move to the point, skip routing services</param>
        /// <param name="waypointsToVisit">Waypoints to visit during the move, required to redure Google Directions API usage</param>
        /// <param name="eggWalker"></param>
        /// <returns></returns>
        internal async Task <PlayerUpdateResponse> Move(GeoCoordinate destination, double walkingSpeedMin, double walkingSpeedMax, Func <Task <bool> > functionExecutedWhileWalking, Func <Task <bool> > functionExecutedWhileWalking2,
                                                        CancellationToken cancellationToken, ISession session, bool direct = false, List <GeoCoordinate> waypointsToVisit = null, EggWalker eggWalker = null)
        {
            var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude);
            var result          = new PlayerUpdateResponse();

            if (session.LogicSettings.UseHumanPathing)
            {
                var waypoints = new List <GeoCoordinate>();

                if (!direct)
                {
                    RoutingResponse routingResponse = null;
                    try
                    {
                        switch (session.LogicSettings.RoutingService)
                        {
                        case RoutingService.MobBot:
                            routingResponse = Routing.GetRoute(currentLocation, destination, session);
                            break;

                        case RoutingService.OpenLs:
                            routingResponse = OsmRouting.GetRoute(currentLocation, destination, session);
                            break;

                        case RoutingService.GoogleDirections:
                            routingResponse = GoogleRouting.GetRoute(currentLocation, destination, session,
                                                                     waypointsToVisit);
                            break;

                        case RoutingService.MapzenValhalla:
                            routingResponse = MapzenRouting.GetRoute(currentLocation, destination, session,
                                                                     waypointsToVisit);
                            break;
                        }
                    }
                    catch (NullReferenceException ex)
                    {
                        session.EventDispatcher.Send(new DebugEvent
                        {
                            Message = ex.ToString()
                        });
                        routingResponse = new RoutingResponse();
                    }

                    if (routingResponse?.Coordinates != null)
                    {
                        foreach (var item in routingResponse.Coordinates)
                        {
                            if (item == null)
                            {
                                continue;
                            }
                            //0 = lat, 1 = long (MAYBE NOT THO?)
                            switch (session.LogicSettings.RoutingService)
                            {
                            case RoutingService.MobBot:
                                waypoints.Add(new GeoCoordinate(item[1], item[0]));
                                break;

                            case RoutingService.OpenLs:
                                waypoints.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], item.ToArray()[2]));
                                break;

                            case RoutingService.GoogleDirections:
                                waypoints.Add(new GeoCoordinate(item[0], item[1]));
                                break;

                            case RoutingService.MapzenValhalla:
                                waypoints.Add(new GeoCoordinate(item[0], item[1]));
                                break;
                            }
                        }
                        if ((session.LogicSettings.RoutingService == RoutingService.GoogleDirections || session.LogicSettings.RoutingService == RoutingService.MobBot || session.LogicSettings.RoutingService == RoutingService.MapzenValhalla) && session.LogicSettings.UseMapzenApiElevation)
                        {
                            waypoints = await session.MapzenApi.FillAltitude(waypoints);
                        }
                    }
                }

                if (waypoints.Count == 0)
                {
                    waypoints.Add(destination);
                }
                else if (waypoints.Count > 1)
                {
                    var nextPath = waypoints.Select(item => Tuple.Create(item.Latitude, item.Longitude)).ToList();
                    session.EventDispatcher.Send(new NextRouteEvent
                    {
                        Coords = nextPath
                    });
                    destination = waypoints.Last();
                }

                var  navi               = new Navigation(_client, UpdatePositionEvent);
                var  waypointsArr       = waypoints.ToArray();
                long nextMaintenceStamp = 0;
                //MILD REWRITE TO USE HUMANPATHWALKING;
                foreach (var t in waypointsArr)
                {
                    if (session.ForceMoveTo != null)
                    {
                        return(await ForceMoveTask.Execute(session, cancellationToken));
                    }
                    // skip waypoints under 5 meters
                    var sourceLocation   = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
                    var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, t);
                    if (distanceToTarget <= 5)
                    {
                        continue;
                    }

                    var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor;
                    session.State = BotState.Walk;
                    result        = await navi.HumanPathWalking(session, t, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken);

                    if (session.Runtime.BreakOutOfPathing)
                    {
                        return(result);
                    }
                    UpdatePositionEvent?.Invoke(t.Latitude, t.Longitude, t.Altitude);

                    if (nextMaintenceStamp < DateTime.UtcNow.ToUnixTime())
                    {
                        await MaintenanceTask.Execute(session, cancellationToken);

                        nextMaintenceStamp = DateTime.UtcNow.AddMinutes(3).ToUnixTime();
                    }
                    if (eggWalker != null)
                    {
                        await eggWalker.ApplyDistance(distanceToTarget, cancellationToken);
                    }
                }
                session.State = BotState.Idle;
                var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude);
                if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40)
                {
                    var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor;

                    result = await navi.HumanPathWalking(session, destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken);
                }
                await MaintenanceTask.Execute(session, cancellationToken);
            }
            else
            {
                if (destination.Latitude.Equals(session.Runtime.lastPokeStopCoordinate.Latitude) && destination.Longitude.Equals(session.Runtime.lastPokeStopCoordinate.Longitude))
                {
                    session.Runtime.BreakOutOfPathing = true;
                }

                if (session.Runtime.BreakOutOfPathing)
                {
                    await MaintenanceTask.Execute(session, cancellationToken);

                    return(result);
                }
                var navi     = new Navigation(_client, UpdatePositionEvent);
                var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude);
                if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40)
                {
                    var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor;

                    result = await navi.HumanPathWalking(session, destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken);
                }
            }
            session.State = BotState.Idle;
            await MaintenanceTask.Execute(session, cancellationToken);

            return(result);
        }