Esempio n. 1
0
            public override Widget build(BuildContext buildContext)
            {
                var margin = Painting.EdgeInsets.all(0.0f);

                if (!widget._isFirst)
                {
                    margin = Painting.EdgeInsets.only(left: 16.0f);
                }

                return(new Clickable(
                           onTap: () => LocationUtil.Go(widget._link),
                           hoverChanged: hover =>
                {
                    if (mounted)
                    {
                        setState(() => _hover = hover);
                    }
                },
                           child: new Container(
                               color: new Color(0x00000000),
                               margin: margin,
                               padding: Painting.EdgeInsets.symmetric(horizontal: 8f),
                               child: new Center(
                                   child: new Text(
                                       widget._text,
                                       style: _hover ? HoverStyle : NormalStyle
                                       )
                                   )
                               )
                           ));
            }
Esempio n. 2
0
        public override Widget build(BuildContext context)
        {
            return(new Wrap(
                       runSpacing: 8f,
                       children: _breadcrumbs?
                       .Skip(1) // Maybe the first one is not so reasonable to display on the page?
                       .Select <Breadcrumb, Widget>(
                           breadcrumb => new ClickableText(
                               text: breadcrumb.content,
                               normalStyle: _normalBreadcrumbStyle,
                               hoverStyle: _hoverBreadCrumbStyle,
                               onTap: () => LocationUtil.Go($"/Manual/{breadcrumb.link}")
                               )
                           ).SelectMany <Widget, Widget>((widget, i) =>
            {
                if (i == 0)
                {
                    return new[] { widget };
                }

                return new[]
                {
                    new Container(
                        margin: EdgeInsets.symmetric(horizontal: 8f),
                        child: new Text(
                            _splitter,
                            style: _splitterStyle
                            )
                        ),
                    widget,
                };
            }).ToList()
                       ));
        }
            private void GoToSearch()
            {
                _focusNode.unfocus();
                var encodedKeyword = Uri.EscapeDataString(_textEditingController.value.text);

                LocationUtil.Go($"/Search/{_filterType}/{encodedKeyword}");
            }
Esempio n. 4
0
        public double CheckCustomerLocations(string customerId, int bookingId)
        {
            var booking = _bookingRepository.GetAll()
                          .Where(b => b.Id == bookingId)
                          .Include(b => b.Barber)
                          .First();
            var bookedTime  = booking.BookedTime;
            var currentTime = DateTimeUtil.GetTimeNow();

            if (currentTime < bookedTime.AddMinutes(booking.DurationMinute * BookingConstants.BarberLatencyPercentage))
            {
                return(0);
            }

            var barber    = booking.Barber;
            var locations = GetCustomerLocations(customerId, bookingId)
                            .Where(l => bookedTime <= l.Time && l.Time <= currentTime)
                            .ToList();
            double customerInPlaceCount = 0;

            foreach (var location in locations)
            {
                var distance = LocationUtil.CalculateDistance(location.GpsLong, location.GpsLat,
                                                              barber.Longitude.GetValueOrDefault(), barber.Latitude.GetValueOrDefault());
                if (distance <= LocationUtil.AcceptableDistance)
                {
                    customerInPlaceCount += 1;
                }
            }

            return(customerInPlaceCount / locations.Count);
        }
Esempio n. 5
0
            private void GoToSearch()
            {
                _focusNode.unfocus();
                var encodedKeyword = HttpUtility.UrlEncode(_textEditingController.value.text);

                LocationUtil.Go($"/Search/{_filterType}/{encodedKeyword}");
            }
Esempio n. 6
0
        /// <summary>
        /// GET: /Home/GetDistrictByCity
        /// </summary>
        /// <param name="cityId">City ID</param>
        /// <returns>Task[ActionResult] with JSON contains list of Districts</returns>
        public async Task <ActionResult> GetDistrictByCity(string cityId)
        {
            try
            {
                int tempCityId = 0;
                // Check if city ID is null or not
                if (!String.IsNullOrEmpty(cityId) && Int32.TryParse(cityId, out tempCityId))
                {
                    districtList = await LocationUtil.LoadDistrictInCityAsync(tempCityId);

                    var result = (from d in districtList
                                  select new
                    {
                        id = d.District_ID,
                        name = d.Type + Constants.WhiteSpace + d.District_Name
                    });
                    return(Json(result, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    // Return default value
                    districtList = new List <District>();
                    return(Json(districtList, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception exception)
            {
                LoggingUtil.LogException(exception);
                return(RedirectToAction(Constants.SystemFailureHomeAction, Constants.ErrorController));
            }
        }
        public override void InvokeAction()
        {
            double   alt   = altitude + LocationUtil.TerrainHeight(latitude, longitude, FlightGlobals.currentMainBody);
            Vector3d pos   = FlightGlobals.currentMainBody.GetWorldSurfacePosition(latitude, longitude, alt);
            Actor    actor = cutSceneDefinition.actor(actorName);

            actor.Transform.position = pos;
        }
Esempio n. 8
0
 public override void initState()
 {
     base.initState();
     _scriptingSectionRecognizer = new TapGestureRecognizer
     {
         onTap = () => { LocationUtil.Go("/Manual/ScriptingSection"); }
     };
 }
Esempio n. 9
0
 private static float DistanceTo(TreeBehavior thisTree, TreeBehavior thatTree)
 {
     if (thisTree.Equals(thatTree))
     {
         return(float.MaxValue);
     }
     return(LocationUtil.GetDistance(thatTree.transform.position, thisTree.transform.position));
 }
Esempio n. 10
0
        async void InitializeData()
        {
            Coordinate coords = await LocationUtil.GetCurrentLocation();

            Entry = new PointEntry {
                Title = "Test Entry", Id = Guid.NewGuid().ToString(), Latitude = coords.Latitude, Longitude = coords.Longitude, Category = "Café"
            };
        }
Esempio n. 11
0
            private void OnTap()
            {
                if (widget._language != Language.zhCn)
                {
                    LocationUtil.HrefTo(widget._language.Link());
                }

                widget._parentState.Dismiss();
            }
        public override void MakeActive()
        {
            LoggingUtil.LogVerbose(this, "CutScene: camera '{0}' active", name);

            double   alt = altitude + LocationUtil.TerrainHeight(latitude, longitude, FlightGlobals.currentMainBody);
            Vector3d pos = FlightGlobals.currentMainBody.GetWorldSurfacePosition(latitude, longitude, alt);

            FlightCamera.fetch.SetCamCoordsFromPosition(pos);
        }
Esempio n. 13
0
        /// <summary>
        /// 添加客户的地址
        /// </summary>
        /// <param name="cstmrAddr"></param>
        /// <returns></returns>
        public ActionResult Add(CustomerAddr cstmrAddr)
        {
            CustomerAddr retVal = null;

            ISession     s     = null;
            ITransaction trans = null;

            try
            {
                s     = HibernateOper.GetCurrentSession();
                trans = s.BeginTransaction();

                //查找客户ID
                if (cstmrAddr.AddrCode != null && !cstmrAddr.AddrCode.Equals(""))
                {
                    cstmrAddr.Addr = PojoUtil.GetAddrForCode(s, cstmrAddr.AddrCode);

                    LocationUtil.Location loc = LocationUtil.GetLocation(cstmrAddr.Addr + cstmrAddr.Location);
                    if (loc != null)
                    {
                        cstmrAddr.Lat = loc.lat;
                        cstmrAddr.Lng = loc.lng;
                    }
                }
                string openId = cstmrAddr.Cstmr.OpenId;
                cstmrAddr.Cstmr = PojoUtil.GetCust(s, openId);
                if (cstmrAddr.Cstmr == null)
                {
                    if (openId == null || openId.Equals(""))
                    {
                        //客户不存在
                        throw new Exceptions.CstmrIsNotExistsException();
                    }

                    Customer cstmr = new Customer();
                    cstmr.OpenId = openId;
                    s.Save(cstmr);
                    cstmrAddr.Cstmr = cstmr;
                }

                s.Save(cstmrAddr);

                trans.Commit();

                retVal = cstmrAddr;
            }
            catch (Exception e)
            {
                if (trans != null)
                {
                    trans.Rollback();
                }
                throw e;
            }

            return(Json(retVal));
        }
Esempio n. 14
0
        protected async override void OnAppearing()
        {
            base.OnAppearing();


            Coordinate location = await LocationUtil.GetCurrentLocation();

            Item.Latitude  = location.Latitude;
            Item.Longitude = location.Longitude;
        }
Esempio n. 15
0
        protected override void OnAccepted()
        {
            // Actually spawn the kerbals in the game world!
            foreach (KerbalData kerbal in kerbals)
            {
                LoggingUtil.LogVerbose(this, "Spawning a Kerbal named " + kerbal.name);

                if (kerbal.altitude == null)
                {
                    kerbal.altitude = LocationUtil.TerrainHeight(kerbal.latitude, kerbal.longitude, kerbal.body);
                }

                // Set additional info for landed kerbals
                if (kerbal.landed)
                {
                    Vector3d pos = kerbal.body.GetWorldSurfacePosition(kerbal.latitude, kerbal.longitude, kerbal.altitude.Value);

                    kerbal.orbit = new Orbit(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, kerbal.body);
                    kerbal.orbit.UpdateFromStateVectors(pos, kerbal.body.getRFrmVel(pos), kerbal.body, Planetarium.GetUniversalTime());
                    LoggingUtil.LogVerbose(typeof(SpawnKerbal), "kerbal generated, orbit = " + kerbal.orbit);
                }

                uint flightId = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);

                // Create crew member array
                ProtoCrewMember[] crewArray = new ProtoCrewMember[1];
                crewArray[0] = kerbal.crewMember;

                // Create part nodes
                ConfigNode[] partNodes = new ConfigNode[1];
                partNodes[0] = ProtoVessel.CreatePartNode("kerbalEVA", flightId, crewArray);

                // Create additional nodes
                ConfigNode[]    additionalNodes = new ConfigNode[1];
                DiscoveryLevels discoveryLevel  = kerbal.owned ? DiscoveryLevels.Owned : DiscoveryLevels.Unowned;
                additionalNodes[0] = ProtoVessel.CreateDiscoveryNode(discoveryLevel, UntrackedObjectClass.A, contract.TimeDeadline, contract.TimeDeadline);

                // Create the config node representation of the ProtoVessel
                ConfigNode protoVesselNode = ProtoVessel.CreateVesselNode(kerbal.name, VesselType.EVA, kerbal.orbit, 0, partNodes, additionalNodes);

                // Additional seetings for a landed Kerbal
                if (kerbal.landed)
                {
                    // Create the config node representation of the ProtoVessel
                    protoVesselNode.SetValue("sit", Vessel.Situations.LANDED.ToString());
                    protoVesselNode.SetValue("landed", true.ToString());
                    protoVesselNode.SetValue("lat", kerbal.latitude.ToString());
                    protoVesselNode.SetValue("lon", kerbal.longitude.ToString());
                    protoVesselNode.SetValue("alt", kerbal.altitude.ToString());
                }

                // Add vessel to the game
                HighLogic.CurrentGame.AddVessel(protoVesselNode);
            }
        }
Esempio n. 16
0
    IEnumerator Transition(int finalRoll)
    {
        yield return(new WaitForSeconds(1F));

        Vector3 startPos = rollBox.transform.position;
        Vector3 endPos   = rollCornerPos.transform.position;

        yield return(LocationUtil.SlerpVector(rollBox.transform, endPos, ROLL_TRANSITION_TIME));

        DisplayChoices(finalRoll);
    }
Esempio n. 17
0
 private void OnTap()
 {
     if (string.IsNullOrEmpty(widget._bind.link) || "null".Equals(widget._bind.link))
     {
         OnExpandTap();
     }
     else
     {
         var link = $"{widget._parent.widget._type.PageUrlPrefix()}/{widget._bind.link}";
         LocationUtil.Go(link);
     }
 }
Esempio n. 18
0
 public ActionResult Update(Garden garden)
 {
     //根据地址码获取地址
     garden.Addr = PojoUtil.GetAddrForCode(HibernateOper, garden.AddrCode);
     LocationUtil.Location loc = LocationUtil.GetLocation(garden.Addr + garden.Location);
     if (loc != null)
     {
         garden.Lat = loc.lat;
         garden.Lng = loc.lng;
     }
     return(Json(gardenOper.Update(garden)));
 }
Esempio n. 19
0
 public ActionResult Update(Company company)
 {
     //根据地址码获取地址
     company.Addr = PojoUtil.GetAddrForCode(HibernateOper, company.AddrCode);
     LocationUtil.Location loc = LocationUtil.GetLocation(company.Addr + company.Location);
     if (loc != null)
     {
         company.Lat = loc.lat;
         company.Lng = loc.lng;
     }
     return(Json(companyOper.Update(company)));
 }
        public override void OnDraw()
        {
            string val;
            double dVal;

            GUILayout.BeginHorizontal();
            GUILayout.Label("Latitude", GUILayout.Width(CutSceneConfigurator.CutSceneConfigurator.DETAIL_LABEL_WIDTH));
            val = GUILayout.TextField(latitude.ToString(), GUILayout.Width(CutSceneConfigurator.CutSceneConfigurator.DETAIL_ENTRY_WIDTH));
            if (double.TryParse(val, out dVal))
            {
                latitude = dVal;
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Longitude", GUILayout.Width(CutSceneConfigurator.CutSceneConfigurator.DETAIL_LABEL_WIDTH));
            val = GUILayout.TextField(longitude.ToString(), GUILayout.Width(CutSceneConfigurator.CutSceneConfigurator.DETAIL_ENTRY_WIDTH));
            if (double.TryParse(val, out dVal))
            {
                longitude = dVal;
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label(new GUIContent("Altitude", "Enter the altitude above the terrain."), GUILayout.Width(CutSceneConfigurator.CutSceneConfigurator.DETAIL_LABEL_WIDTH));
            val = GUILayout.TextField(altitude.ToString(), GUILayout.Width(CutSceneConfigurator.CutSceneConfigurator.DETAIL_ENTRY_WIDTH));
            if (double.TryParse(val, out dVal))
            {
                altitude = dVal;
            }
            GUILayout.EndHorizontal();

            GUILayout.FlexibleSpace();

            GUILayout.BeginHorizontal();

            if (GUILayout.Button("Set Position to Current"))
            {
                latitude  = FlightGlobals.currentMainBody.GetLatitude(FlightCamera.fetch.transform.position);
                longitude = FlightGlobals.currentMainBody.GetLongitude(FlightCamera.fetch.transform.position);
                double   terrainHeight = LocationUtil.TerrainHeight(latitude, longitude, FlightGlobals.currentMainBody);
                Vector3d ground        = FlightGlobals.currentMainBody.GetWorldSurfacePosition(latitude, longitude, terrainHeight);
                altitude = (ground - FlightCamera.fetch.transform.position).magnitude;
            }
            if (GUILayout.Button("Jump to Camera Position"))
            {
                MakeActive();
            }

            GUILayout.EndHorizontal();
        }
            private static Widget ProcessLinkOpen(Token token, BuilderContext ctx)
            {
                var uriString = token.attrs[0][1];

                ctx.spanRecognizers.Add(new TapGestureRecognizer
                {
                    onTap = () =>
                    {
                        var uri = new Uri(uriString);
                        switch (uri.Scheme.ToLower())
                        {
                        case "manual":
                            LocationUtil.Go($"/Manual/{uri.LocalPath}");
                            break;

                        case "http":
                        case "https":
                        case "mailto":
                            LocationUtil.HrefTo(uriString);
                            break;

                        case "scripting":
                            LocationUtil.Go($"/Scripting/{uri.LocalPath}");
                            break;

                        case "attachment":
                            LocationUtil.Download(
                                $"{Configuration.Instance.apiHost}/api/documentation/resource/v/2018.1/t/manual_static/f/{uri.LocalPath}",
                                uri.LocalPath
                                );
                            break;

                        default:
                            Debug.Log($"Unrecognized scheme of uri {uriString}");
                            break;
                        }
                    }
                });
                var span = new TextSpan(
                    children: new List <TextSpan>(),
                    style: new TextStyle(
                        color: new Color(0xffe91e63),
                        decoration: TextDecoration.underline
                        )
                    );

                ctx.inline.Push(span);
                ctx.useRecognizer = true;
                return(null);
            }
        public void DownloadAndExtractLatestVersion(FFNxUpdateChannelOptions channel)
        {
            DownloadItem download = new DownloadItem()
            {
                Links = new List <string>()
                {
                    LocationUtil.FormatHttpUrl(GetUpdateChannel(channel))
                },
                SaveFilePath = GetUpdateInfoPath(),
                Category     = DownloadCategory.AppUpdate,
                ItemName     = $"Fetching the latest FFNx version using channel {Sys.Settings.FFNxUpdateChannel.ToString()}..."
            };

            download.IProc = new Install.InstallProcedureCallback(e =>
            {
                bool success = (e.Error == null && e.Cancelled == false);

                if (success)
                {
                    try
                    {
                        StreamReader file = File.OpenText(download.SaveFilePath);
                        dynamic release   = JValue.Parse(file.ReadToEnd());
                        file.Close();
                        File.Delete(download.SaveFilePath);

                        Version newVersion = new Version(GetUpdateVersion(release.name.Value));
                        DownloadAndExtract(GetUpdateReleaseUrl(release.assets), newVersion.ToString());
                    }
                    catch (Exception)
                    {
                        MessageDialogWindow.Show("Something went wrong while checking for FFNx updates. Please try again later.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                        Sys.Message(new WMessage()
                        {
                            Text = $"Could not parse the FFNx release json at {GetUpdateChannel(channel)}", LoggedException = e.Error
                        });
                    }
                }
                else
                {
                    MessageDialogWindow.Show("Something went wrong while checking for FFNx updates. Please try again later.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    Sys.Message(new WMessage()
                    {
                        Text = $"Could not fetch for FFNx updates at {GetUpdateChannel(channel)}", LoggedException = e.Error
                    });
                }
            });

            Sys.Downloads.AddToDownloadQueue(download);
        }
Esempio n. 23
0
        /// <summary>
        /// Downloads the file at <see cref="linkToVersionXml"/> and attempts to deserialize it into <see cref="Sys.LastCheckedVersion"/>.
        /// Uses the download queue so this happens asynchronously. <see cref="UpdateCheckCompleted"/> is raised when the download is complete.
        /// </summary>
        public void CheckForUpdates()
        {
            string path = Path.Combine(Sys.PathToTempFolder, "version.xml");

            Directory.CreateDirectory(Sys.PathToTempFolder);

            DownloadItem download = new DownloadItem()
            {
                Links = new List <string>()
                {
                    LocationUtil.FormatHttpUrl(linkToVersionXml)
                },
                SaveFilePath = path,
                Category     = DownloadCategory.AppUpdate,
                ItemName     = $"{ResourceHelper.Get(StringKey.CheckingForUpdatesAt)} {linkToVersionXml}"
            };

            download.IProc = new Install.InstallProcedureCallback(e =>
            {
                bool success = (e.Error == null && e.Cancelled == false);

                if (success)
                {
                    try
                    {
                        Sys.LastCheckedVersion = Util.Deserialize <AvailableUpdate>(path);
                    }
                    catch (Exception ex)
                    {
                        Sys.LastCheckedVersion = Sys.LastCheckedVersion ?? new AvailableUpdate(); // if currently null then initialize new instance
                        Sys.Message(new WMessage()
                        {
                            Text = $"{ResourceHelper.Get(StringKey.FailedToCheckForUpdatesAt)} {linkToVersionXml}: {ex.Message}", LoggedException = ex
                        });
                    }
                }
                else
                {
                    Sys.LastCheckedVersion = Sys.LastCheckedVersion ?? new AvailableUpdate();
                    Sys.Message(new WMessage()
                    {
                        Text = $"{ResourceHelper.Get(StringKey.FailedToCheckForUpdatesAt)} {linkToVersionXml}", LoggedException = e.Error
                    });
                }

                UpdateCheckCompleted?.Invoke(success);
            });

            Sys.Downloads.AddToDownloadQueue(download);
        }
Esempio n. 24
0
    private void Germinate()
    {
        if (genes == null || LocationUtil.IsInShade(transform.position))
        {
            isSterile = true;
            return;
        }

        GameObject newGameObject = Instantiate(treePrefab, transform.position, transform.rotation);

        ReproductionUtil.GerminateTree(genes, transform.position, newGameObject, fruitPrefab);

        Destroy(this.gameObject);
        Destroy(this);
    }
Esempio n. 25
0
    public static FruitBehavior MakeFruit(Vector3 spawnPosition, GameObject fruitPrefab)
    {
        if (!LocationUtil.IsOnMap(spawnPosition))
        {
            return(null);
        }

        spawnPosition = new Vector3(spawnPosition.x, LocationUtil.groundHeight, spawnPosition.z);
        Vector3 randomSpawnRotation = Vector3.up * Random.Range(0, 360);
        var     fruit = Instantiate(fruitPrefab, spawnPosition, Quaternion.Euler(randomSpawnRotation));

        fruit.name = "Fruit";

        return(fruit.GetComponent <FruitBehavior>());
    }
Esempio n. 26
0
        /// <summary>
        /// Generates a few random <see cref="LocationFix"/>es to act like a real GPS sensor.
        /// </summary>
        /// <param name="requestEnvelope">The <see cref="RequestEnvelope"/> these <see cref="LocationFix"/>es are used for.</param>
        /// <param name="timestampSinceStart">The milliseconds passed since starting the <see cref="Session"/> used by the current <see cref="RequestEnvelope"/>.</param>
        /// <returns></returns>
        private List <LocationFix> BuildLocationFixes(RequestEnvelope requestEnvelope, long timestampSinceStart)
        {
            var locationFixes = new List <LocationFix>();

            if (requestEnvelope.Requests.Count == 0 || requestEnvelope.Requests[0] == null)
            {
                return(locationFixes);
            }

            var providerCount = _session.Random.Next(4, 10);

            for (var i = 0; i < providerCount; i++)
            {
                var timestampSnapshot = timestampSinceStart + (150 * (i + 1) + _session.Random.Next(250 * (i + 1) - 150 * (i + 1)));
                if (timestampSnapshot >= timestampSinceStart)
                {
                    if (locationFixes.Count != 0)
                    {
                        break;
                    }

                    timestampSnapshot = timestampSinceStart - _session.Random.Next(20, 50);

                    if (timestampSnapshot < 0)
                    {
                        timestampSnapshot = 0;
                    }
                }

                locationFixes.Insert(0, new LocationFix
                {
                    TimestampSnapshot  = (ulong)timestampSnapshot,
                    Latitude           = LocationUtil.OffsetLatitudeLongitude(_session.Player.Coordinate.Latitude, _session.Random.Next(100) + 10),
                    Longitude          = LocationUtil.OffsetLatitudeLongitude(_session.Player.Coordinate.Longitude, _session.Random.Next(100) + 10),
                    HorizontalAccuracy = (float)_session.Random.NextDouble(5.0, 25.0),
                    VerticalAccuracy   = (float)_session.Random.NextDouble(5.0, 25.0),
                    Altitude           = (float)_session.Random.NextDouble(10.0, 30.0),
                    Provider           = "fused",
                    ProviderStatus     = 3,
                    LocationType       = 1,
                    // Speed = ?,
                    Course = -1,
                    // Floor = 0
                });
            }

            return(locationFixes);
        }
        /// <summary>
        /// Set message shown to user when opening external link to reflect mod failing to download or only alowing external downloads for it
        /// </summary>
        private void SetExternalUrlDownloadMessage()
        {
            Download.ExternalUrlDownloadMessage = ResourceHelper.Get(StringKey.ExternalUrlDownloadMessage2);

            if (Download.IsModOrPatchDownload && Download.Links.Count == 1)
            {
                // check that the only link available is external url and set message accordingly
                if (LocationUtil.TryParse(Download.Links[0], out LocationType downloadType, out string url))
                {
                    if (downloadType == LocationType.ExternalUrl)
                    {
                        Download.ExternalUrlDownloadMessage = ResourceHelper.Get(StringKey.ExternalUrlDownloadMessage1);
                    }
                }
            }
        }
Esempio n. 28
0
        public override void Entry(IModHelper helper)
        {
            this.Config       = helper.ReadConfig <ModConfig>();
            this.Pointer      = helper.Content.Load <Texture2D>("assets/locator.png"); // Load pointer tex
            this.Constants    = helper.Data.ReadJsonFile <ModData>("assets/constants.json") ?? new ModData();
            this.LocationUtil = new(this.Monitor);

            helper.Events.GameLoop.SaveLoaded            += this.GameLoop_SaveLoaded;
            helper.Events.GameLoop.DayStarted            += this.GameLoop_DayStarted;
            helper.Events.World.LocationListChanged      += this.World_LocationListChanged;
            helper.Events.Multiplayer.ModMessageReceived += this.Multiplayer_ModMessageReceived;
            helper.Events.GameLoop.UpdateTicked          += this.GameLoop_UpdateTicked;
            helper.Events.Input.ButtonPressed            += this.Input_ButtonPressed;
            helper.Events.Input.ButtonReleased           += this.Input_ButtonReleased;
            helper.Events.Display.Rendered += this.Display_Rendered;
        }
Esempio n. 29
0
        /// <summary>Handle the console command.</summary>
        /// <param name="monitor">The monitor with which to write output..</param>
        /// <param name="locationUtil">Scans and maps locations in the game world.</param>
        /// <param name="customizations">Manages customized map recolors, NPCs, sprites, names, etc.</param>
        /// <param name="mapVectors">The in-world tile coordinates and map pixels which represent the same position for each location name.</param>
        /// <param name="npcMarkers">The tracked NPC markers.</param>
        /// <param name="locationsWithoutMapVectors">The outdoor location contexts which don't have any map vectors.</param>
        public static void Handle(IMonitor monitor, LocationUtil locationUtil, ModCustomizations customizations, IDictionary <string, MapVector[]> mapVectors, Dictionary <string, NpcMarker> npcMarkers, IEnumerable <LocationContext> locationsWithoutMapVectors)
        {
            if (!Context.IsWorldReady)
            {
                monitor.Log("You must load a save to use this command.", LogLevel.Error);
                return;
            }

            StringBuilder output = new();

            output.AppendLine();

            // current player
            {
                // collect info
                var             player       = Game1.player;
                var             location     = player.currentLocation;
                string          locationName = locationUtil.GetLocationNameFromLevel(location.NameOrUniqueName) ?? location?.NameOrUniqueName;
                LocationContext context      = locationUtil.TryGetContext(locationName, mapGeneratedLevels: false);
                Vector2         mapPixel     = ModEntry.LocationToMap(locationName, player.getTileX(), player.getTileY(), customizations.MapVectors, customizations.LocationExclusions);

                // collect alternate location names
                List <string> altNames = new();
                if (location.NameOrUniqueName != location.Name)
                {
                    altNames.Add($"unique: {location.NameOrUniqueName}");
                }
                if (location.NameOrUniqueName != locationName)
                {
                    output.Append($"context: {locationName}");
                }

                // build output
                output.AppendLine();
                output.AppendLine("======================");
                output.AppendLine("==  Current player  ==");
                output.AppendLine("======================");
                output.AppendLine($"Player: {player.Name} ({player.UniqueMultiplayerID})");
                output.AppendLine($"Location: {location.Name}{(altNames.Any() ? $" ({string.Join(", ", altNames)})" : "")}");
                output.AppendLine($"Tile: ({player.getTileX()}, {player.getTileY()})");
                output.AppendLine($"Excluded: {customizations.LocationExclusions.Contains(locationName)}");
                output.AppendLine($"Map pixel: {(mapPixel != ModEntry.Unknown ? $"({mapPixel.X}, {mapPixel.Y})" : "unknown")}");
                output.AppendLine();

                output.AppendLine("Configured vectors:");
                if (customizations.MapVectors.TryGetValue(locationName, out MapVector[] vectors) && vectors.Any())
Esempio n. 30
0
        async void AddItem_Clicked(object sender, EventArgs e)
        {
            await Navigation.PushModalAsync(new NavigationPage(new ItemDetailPage()));

            Coordinate location = await LocationUtil.GetCurrentLocation();



            PointEntry item = new PointEntry
            {
                Title     = "Test",
                Category  = "Café",
                Latitude  = location.Latitude,
                Longitude = location.Longitude
            };

            //MessagingCenter.Send(this, "AddItem", item);
        }