Beispiel #1
0
 private void GraphicsCircle(Geo g)
 {
     int size = g.begin.X - g.eind.X;
         int x = g.begin.X - size;
         int y = g.begin.Y - size;
         pea.Graphics.DrawEllipse(pen, x, y, size, size);
 }
Beispiel #2
0
 public void Draw(Geo.CompiledModel model)
 {
     device.SetVertexBuffer(model.verticies);
     device.Indices = model.indicies;
     device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, model.verticies.VertexCount,
         0, System.Math.Min(model.primitiveCount, 65535));
 }
        public void OneEntry()
        {
            var zeroZero = new Geo(0, 0);
            //var oneOne = new Geo(1, 1);
            //Geo result;

            _list.Add(zeroZero);
            Assert.AreEqual(1, _list.Count);
            Assert.AreSame(zeroZero, _list[0]);
            Assert.AreSame(zeroZero, _list[0, 0]);
            
            //Assert.IsTrue(_list.TryGetNearestPoint(oneOne, out result));
            //Assert.AreSame(result, zeroZero);
            
            //Assert.IsFalse(_list.TryGetNearestPoint(oneOne, out result, 100));
            //Assert.IsTrue(_list.TryGetNearestPoint(oneOne, out result, 200));
            //Assert.AreSame(result, zeroZero);
            
            //Assert.IsTrue(_list.TryGetExactPoint(zeroZero, out result));
            //Assert.AreSame(result, zeroZero);

            var result = _list.GetExactPointAsync(0, 0).Result;
            Assert.AreSame(result, zeroZero);

            //result = _list.GetNearestPoint(0, 1);
            //Assert.AreSame(result, zeroZero);

            //result = _list.GetNearestPoint(0, 0, 0);
            //Assert.AreSame(result, zeroZero);
        }
        public static float SoundSpeed(Geo location, float depth, float temperature, float salinity)
        {
            var tempSq = temperature * temperature;
            var tempCu = tempSq * temperature;
            var tempQuad = tempCu * temperature;
            var tempQuin = tempQuad * temperature;

            var pressure = DepthToPressure(location.LatitudeRadians, depth);
            var pressSq = pressure * pressure;
            var pressCu = pressSq * pressure;

            var result = (( 
                          // computes sound speed of pure water
                          ((C00 + C01 * temperature + C02 * tempSq + C03 * tempCu + C04 * tempQuad + C05 * tempQuin)) + ((C10 + C11 * temperature + C12 * tempSq + C13 * tempCu + C14 * tempQuad) * pressure) + ((C20 + C21 * temperature + C22 * tempSq + C23 * tempCu + C24 * tempQuad) * pressSq) + ((C30 + C31 * temperature + C32 * tempSq) * pressCu)) -
                          // compute correction
                          (((LI11 + LI12 * temperature + LI13 * tempSq) * pressure) + ((LI21 + LI22 * temperature + LI23 * tempSq) * pressSq) + ((LI31) * pressCu))) +
                          // compute a
                         (((A00 + A01 * temperature + A02 * tempSq + A03 * tempCu + A04 * tempQuad)) + ((A10 + A11 * temperature + A12 * tempSq + A13 * tempCu + A14 * tempQuad) * pressure) + ((A20 + A21 * temperature + A22 * tempSq + A23 * tempCu) * pressSq) + ((A30 + A31 * temperature + A32 * tempSq) * pressCu)) * salinity +
                         // compute b
                         (((B00 + B01 * temperature)) + ((B10 + B11 * temperature) * pressure)) * Math.Pow(salinity, 3.0 / 2.0) +
                         // compute d
                         (((D00 + D10 * pressure))) * salinity * salinity;

            return (float) result;
        }
 /// <summary>
 /// Find the intersection of the great circle described by segment and the great circle normal 
 /// to it that passes through r. We assume the segment subtends less than 180 degrees.  If the
 /// segment happens to subtend exactly 180 degrees, the antipode of the returned point is also
 /// a valid intersection. Note that the returned point may not actually lie on the segment, if 
 /// the intersection point lies at a different location along the great circle than that 
 /// subtended by the segment. To check if the returned point is actually on the segment, use
 /// the Intersection extension method for the segment.
 /// </summary>
 /// <param name="segment"></param>
 /// <param name="r"></param>
 /// <returns></returns>
 public static Geo GreatCircleIntersection(this GeoSegment segment, Geo r)
 {
     var a = segment[0].Dot(r);
     var b = segment[1].Dot(r);
     var x = -b / (a - b);
     return segment[0].Scale(x) + segment[1].Scale(1.0 - x).Normalized;
 }
        /// <summary>
        /// Rotates geo2 counterclockwise about geo1 through the specified angle
        /// </summary>
        /// <param name="geo1"></param>
        /// <param name="angle"></param>
        /// <param name="geo2"></param>
        /// <param name="isDegrees"> </param>
        /// <returns></returns>
        public static Geo Rotate(Geo geo1, Geo geo2, double angle, bool isDegrees)
        {
            var x = geo1.X;
            var y = geo1.Y;
            var z = geo1.Z;
            var c = Math.Cos(isDegrees ? MoreMath.DegreesToRadians(angle) : angle);
            var s = Math.Sin(isDegrees ? MoreMath.DegreesToRadians(angle) : angle);
            var b = 1.0 - c;
            var bx = b * x;
            var by = b * y;
            var bz = b * z;
            var bxx = bx * x;
            var bxy = bx * y;
            var bxz = bx * z;
            var byy = by * y;
            var byz = by * z;
            var bzz = bz * z;
            var sx = s * x;
            var sy = s * y;
            var sz = s * z;
            var m00 = c + bxx;
            var m11 = c + byy;
            var m22 = c + bzz;
            var m01 = (-sz) + bxy;
            var m10 = sz + bxy;
            var m12 = (-sx) + byz;
            var m21 = sx + byz;
            var m02 = sy + bxz;
            var m20 = (-sy) + bxz;

            return new Geo(m00 * geo2.X + m01 * geo2.Y + m02 * geo2.Z, m10 * geo2.X + m11 * geo2.Y + m12 * geo2.Z, m20 * geo2.X + m21 * geo2.Y + m22 * geo2.Z);
        }
Beispiel #7
0
        private void DoUpdateNodesAndLinks()
        {
            VerifyAccess();
            this.UpdateNodesAndLinksNeeded = false;

            Diagram observed = this.Observed;

            if (observed == null)
            {
                return;
            }
            PartManager obmgr = observed.PartManager;

            if (obmgr == null)
            {
                return;
            }

            // make sure each Node and Link have the same locations and routes and visibility as those in the Observed diagram
            bool usevis = this.UsesObservedPartVisible;

            if (this.UsesObservedNodeLocation)
            {
                foreach (Node overviewnode in this.Nodes)
                {
                    Node observednode = obmgr.FindNodeForData(overviewnode.Data, this.Model);
                    if (observednode != null)
                    {
                        Point ovloc = overviewnode.Location;
                        Point obloc = observednode.Location;
                        if (!Geo.IsApprox(ovloc, obloc))
                        {
                            overviewnode.Location = obloc;
                        }
                        if (usevis)
                        {
                            overviewnode.Visible = observednode.Visible;
                        }
                    }
                }
            }
            if (this.UsesObservedLinkRoute)
            {
                foreach (Link overviewlink in this.Links)
                {
                    Link observedlink = obmgr.FindLinkForData(overviewlink.Data, this.Model);
                    if (observedlink != null)
                    {
                        overviewlink.Route.Points = observedlink.Route.Points;
                        if (usevis)
                        {
                            overviewlink.Visible = observedlink.Visible;
                        }
                    }
                }
            }
            // afterwards, Node.Location is updated dynamically in Overview.ObservedPanel_PartBoundsChanged
            // and Part.Visible is updated dynamically in Overview.ObservedPanel_PartVisibleChanged
        }
Beispiel #8
0
        /// <summary>
        /// Dynamically compute the desired angle of an element along a segment of the route.
        /// </summary>
        /// <param name="elt">the <c>UIElement</c> being rotated</param>
        /// <param name="orient">the <see cref="LabelOrientation"/> declared for the element</param>
        /// <param name="angle">the angle of the segment of the route where the element is attached</param>
        /// <returns>the intended angle for the element</returns>
        /// <remarks>
        /// This method is not called unless the <see cref="GetOrientation"/> attached property value is
        /// not <see cref="LabelOrientation.None"/>.
        /// </remarks>
        protected virtual double ComputeAngle(UIElement elt, LabelOrientation orient, double angle)
        {
            double a;

            switch (orient)
            {
            default:
            case LabelOrientation.None: a = 0; break;

            case LabelOrientation.Along: a = angle; break;

            case LabelOrientation.Plus90: a = angle + 90; break;

            case LabelOrientation.Minus90: a = angle - 90; break;

            case LabelOrientation.Opposite: a = angle + 180; break;

            case LabelOrientation.Upright: // like Along
                a = Geo.NormalizeAngle(angle);
                if (a > 90 && a < 270)
                {
                    a -= 180;               // make sure never upside-down
                }
                break;

            case LabelOrientation.Plus90Upright: // like Plus90
                a = Geo.NormalizeAngle(angle + 90);
                if (a > 90 && a < 270)
                {
                    a -= 180;               // make sure never upside-down
                }
                break;

            case LabelOrientation.Minus90Upright: // like Minus90
                a = Geo.NormalizeAngle(angle - 90);
                if (a > 90 && a < 270)
                {
                    a -= 180;               // make sure never upside-down
                }
                break;

            case LabelOrientation.Upright45: // like Along
                a = Geo.NormalizeAngle(angle);
                if (a > 45 && a < 135)
                {
                    return(0);              // make sure never angled too much
                }
                if (a > 225 && a < 315)
                {
                    return(0);
                }
                if (a > 90 && a < 270)
                {
                    a -= 180;               // make sure never upside-down
                }
                break;
            }
            return(Geo.NormalizeAngle(a));
        }
        //
        // GET: /Geo/Create
        public ActionResult Create(Guid?parentID)
        {
            Geo e = new Geo();

            e.ParentID = parentID;

            return(View(e));
        }
        public void TestItAddsGeo()
        {
            Geo geo = GeoFactory.Make();

            collection.Add(geo);

            Assert.Equal(geo, collection.GeoElements[0]);
        }
Beispiel #11
0
        public JsonResult ListGeo2(string parentFullName)
        {
            GeoRepository geoRepository = new GeoRepository();

            Geo e = geoRepository.GetByFullname(parentFullName);

            return(Json(e.Children.Select(r => new { r.ID, r.FullName }).OrderBy(r => r.FullName)));
        }
 public void ShouldStayAsInitialized(
     [Random(-90.0, 90.0, 50)] double lat, 
     [Random(-180.0, 180.0, 50)] double lon)
 {
     var geo = new Geo(lat, lon);
     Assert.That(geo.Latitude, Is.EqualTo(lat).Within(0.000001));
     Assert.That(geo.Longitude, Is.EqualTo(lon).Within(0.000001));
 }
Beispiel #13
0
        public void TestItAddsGeoDataWithMultipleSegment()
        {
            RunParserOnLines(
                new List <string>(new[]
            {
                "TestGeo                     N050.57.00.000 W001.21.24.490 BCN BCN test ;comment",
                "                            N051.57.00.000 W002.21.24.490 BHD BHD test2 ;comment1",
                "                            N053.57.00.000 W003.21.24.490 LAM LAM test3 ;comment2"
            })
                );

            Geo result = sectorElementCollection.GeoElements[0];

            Assert.Equal(
                new Point(new Coordinate("N050.57.00.000", "W001.21.24.490")),
                result.FirstPoint
                );
            Assert.Equal(
                new Point("BCN"),
                result.SecondPoint
                );
            Assert.Equal(
                "test",
                result.Colour
                );
            AssertExpectedMetadata(result);

            // Segment 1
            Assert.Equal(2, result.AdditionalSegments.Count);
            Assert.Equal(
                new Point(new Coordinate("N051.57.00.000", "W002.21.24.490")),
                result.AdditionalSegments[0].FirstPoint
                );
            Assert.Equal(
                new Point("BHD"),
                result.AdditionalSegments[0].SecondPoint
                );
            Assert.Equal(
                "test2",
                result.AdditionalSegments[0].Colour
                );
            AssertExpectedMetadata(result.AdditionalSegments[0], 2, "comment1");

            // Segment 2
            Assert.Equal(
                new Point(new Coordinate("N053.57.00.000", "W003.21.24.490")),
                result.AdditionalSegments[1].FirstPoint
                );
            Assert.Equal(
                new Point("LAM"),
                result.AdditionalSegments[1].SecondPoint
                );
            Assert.Equal(
                "test3",
                result.AdditionalSegments[1].Colour
                );
            AssertExpectedMetadata(result.AdditionalSegments[1], 3, "comment2");
        }
 private static void ValidateBaseGeo(Geo geo, SectorElementCollection sectorElements, IEventLogger events)
 {
     if (!ColourValid(geo.Colour, sectorElements))
     {
         string errorMessage =
             $"Invalid colour value {geo.Colour} in GEO declaration {geo.GetCompileData(sectorElements)}";
         events.AddEvent(new ValidationRuleFailure(errorMessage, geo));
     }
 }
Beispiel #15
0
        public override bool Update(BasicEnemy enemy)
        {
            Vector2 dir = enemy.GetDirection();

            float ang = Geo.ToAng(dir);

            enemy.transform.eulerAngles = new Vector3(0, 0, ang - 90);
            return((Vector2)enemy.transform.up == dir);
        }
 public void CreateAnalysisPoints()
 {
     IMasterDatabaseService database;
     EnvironmentalCacheService cache;
     PluginManagerService plugins;
     var location = TestLocation.LoadOrCreate("Jacksonville", OverlayFile, _databaseDirectory, PluginDirectory, out database, out cache, out plugins);
     var scenario = TestScenario.LoadOrCreate(database, location, SimAreaDirectory, NemoFile);
     var center = new Geo((location.GeoRect.North + location.GeoRect.South) / 2, (location.GeoRect.East + location.GeoRect.West) / 2);
 }
Beispiel #17
0
        //ITU Org

        /* This utility will be used to develop track files for vessels within a specific AIS file */

        static void Main(string[] args)
        {
            var vessels = new Dictionary <int, List <Geo> >();
            var idx     = 0;

            var lines = System.IO.File.ReadLines(inputFile);

            foreach (var line in lines)
            {
                if (idx > 1)
                {
                    var parts = line.Split(",");
                    var mmsi  = Convert.ToInt32(parts[0]);
                    var geo   = new Geo();
                    geo.TimeStamp = parts[1];
                    geo.Lat       = parts[2];
                    geo.Lon       = parts[3];
                    geo.Status    = parts[10];

                    if (vessels.ContainsKey(mmsi))
                    {
                        vessels[mmsi].Add(geo);
                    }
                    else
                    {
                        vessels.Add(mmsi, new List <Geo>()
                        {
                            geo
                        });
                    }

                    if (idx % 1000 == 0)
                    {
                        Console.WriteLine(idx);
                    }
                }

                ++idx;
            }

            Console.WriteLine("Writing Vessels");

            foreach (var key in vessels.Keys)
            {
                var vessel = vessels[key];
                var bldr   = new StringBuilder();
                foreach (var points in vessel)
                {
                    bldr.AppendLine($"{points.TimeStamp},{points.Lat},{points.Lon},{points.Status}");
                }

                System.IO.File.WriteAllText($@"S:\Zone17\{key}.csv", bldr.ToString());
            }

            Console.WriteLine("Done");
            Console.ReadKey();
        }
 internal int Insert(Geo model)
 {
     using (var db = new ApplicationDbContext())
     {
         db.Geo.Add(model);
         db.SaveChanges();
         return(model.Id);
     }
 }
 public GetGameStateResult(GameState state, int score, string lastGameMessage, PlayerDescription[] players, ClientApple[] apples, Geo[] gameBorderPoints)
 {
     State = state;
     Score = score;
     LastGameMessage = lastGameMessage;
     Players = players;
     Apples = apples;
     GameBorderPoints = gameBorderPoints;
 }
 public Transect(string name, Geo startPoint, double bearing, double length) : base(startPoint)
 {
     Name = name;
     Length = length;
     EndPoint = Offset(KilometersToRadians(Length / 1000), DegreesToRadians(Bearing));
     Bearing = bearing;
     MidPoint = new Geo(startPoint);
     MidPoint = Offset(KilometersToRadians(Length / 2000), DegreesToRadians(Bearing));
 }
Beispiel #21
0
 private void Panel_ViewportBoundsChanged(Object sender, RoutedPropertyChangedEventArgs <Rect> e)
 {
     // only call LayoutDiagram when the size of the viewport has changed (in model coordinates),
     // because the panel changed size or because the panel.Scale changed
     if (!Geo.IsApprox(e.OldValue.Width, e.NewValue.Width) || !Geo.IsApprox(e.OldValue.Height, e.NewValue.Height))
     {
         LayoutDiagram();
     }
 }
        public void Test_02()
        {
// vcard[1].geo.latitude
            string test      = nodes.GetNameByPosition("vcard", 1).Nodes["geo"].Nodes["latitude"].Value;
            string testGeo   = new Geo(test).ToString();
            string resultGeo = new Geo("37.77").ToString();

            Assert.That(testGeo, Is.EqualTo(resultGeo), "Should extract latitude value from paired value");
        }
 public Transect(string name, Geo startPoint, Geo endPoint)
     : base(startPoint)
 {
     Name = name;
     EndPoint = endPoint;
     Length = DistanceKilometers(EndPoint) * 1000;
     Bearing = RadiansToDegrees(Azimuth(EndPoint));
     MidPoint = Offset(KilometersToRadians(Length / 2000), DegreesToRadians(Bearing));
 }
Beispiel #24
0
 public override void ToStream(Stream output)
 {
     output.Write(TLUtils.SignatureToBytes(Signature));
     Geo.ToStream(output);
     Title.ToStream(output);
     Address.ToStream(output);
     Provider.ToStream(output);
     VenueId.ToStream(output);
 }
        public void Test_05()
        {
// vcard[4].geo.latitude
            string test      = nodes.GetNameByPosition("vcard", 4).Nodes["geo"].Nodes["latitude"].Value;
            string testGeo   = new Geo(test).ToString();
            string resultGeo = new Geo("0").ToString();

            Assert.That(testGeo, Is.EqualTo(resultGeo), "Should find latitude value from single element");
        }
Beispiel #26
0
        public static Rect calcolaDimensioni(Fascia qualeFascia, float ratioCarta, Geo imageGeo)
        {
            double l = calcolaDimensione(qualeFascia, Dimensione.Left, ratioCarta, imageGeo, imageGeo);
            double t = calcolaDimensione(qualeFascia, Dimensione.Top, ratioCarta, imageGeo, imageGeo);
            double w = calcolaDimensione(qualeFascia, Dimensione.Width, ratioCarta, imageGeo, imageGeo);
            double h = calcolaDimensione(qualeFascia, Dimensione.Height, ratioCarta, imageGeo, imageGeo);

            return(new Rect(l, t, w, h));
        }
 public void Extend(Geo<float> deepestPoint)
 {
     lock (_lockObject)
     {
         if (_isExtended) return;
         foreach (var soundSpeedField in SoundSpeedFields) soundSpeedField.ExtendProfiles(deepestPoint);
         _isExtended = true;
     }
 }
        public OverlayLineSegment(Geo p1, Geo p2, Color color, float width, LineStyle lineStyle)
            : base(color, width, lineStyle)
        {
            Add(p1);
            Add(p2);

            Course = new Course(p1, p2);
            ComputeCoefficients();
        }
Beispiel #29
0
        public bool Collide(AttackableUnit target)
        {
            var   unitCoords     = target.Position;
            var   targetDistance = Vector2.Distance(Begin, unitCoords);
            float targetAngle    = Geo.GetAngleDegrees(Begin, unitCoords);
            bool  result         = targetDistance <= Radius && targetAngle >= BeginAngle && targetAngle <= EndAngle;

            return(result);
        }
Beispiel #30
0
    ///////////////////////////////////////////

    public static async Task RequestHeight(string apiKey, BoundingBox regionBounds, Action <Tex, Vec3, Vec2> OnReceivedHeight)
    {
        // Here's an elevation request! This doesn't provide an image, rather,
        // it gives us a grid of height values. It's limited to a maximum of
        // 1024 values per request, so we're only asking for a grid of 32x32
        // elevations.
        // However! This request does work exactly within the bounds provided,
        // so we're getting what we expect from the results of this request.
        // Details about the request can be found here:
        // https://github.com/microsoft/BingMapsRESTToolkit/blob/master/Docs/API%20Reference.md#ElevationRequest
        ElevationRequest request = new ElevationRequest()
        {
            Bounds      = regionBounds,
            Row         = 32,
            Col         = 32,
            BingMapsKey = apiKey
        };
        Response response = await ServiceManager.GetResponseAsync(request);

        // StatusCode is a web response status code, where 200-299 means
        // success. Details here:
        // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
        if (response.StatusCode < 200 || response.StatusCode >= 300)
        {
            Log.Warn("Bing Maps API error:\n" + string.Join('\n', response.ErrorDetails));
            return;
        }

        // Convert the elevation data we've received into a grayscale heightmap texture!
        ElevationData data = response.ResourceSets[0].Resources[0] as ElevationData;

        Color[] heights = new Color[32 * 32];
        for (int y = 0; y < 32; y++)
        {
            for (int x = 0; x < 32; x++)
            {
                float height = data.Elevations[x + y * 32] / Geo.EarthTallest;
                // Height data is provided upside-down, so we're flipping it with
                // this index on the Y axis.
                heights[x + (31 - y) * 32] = Color.White * height;
            }
        }

        // Create a texture from the elevation data! We're storing it as
        // Rgba128 to preserve floating point precision in the height values.
        Tex texture = new Tex(TexType.ImageNomips, TexFormat.Rgba128);

        texture.SetColors(32, 32, heights);
        texture.AddressMode = TexAddress.Clamp;

        // Our bounds should be correct, but we still need it in StereoKit
        // units, so convert!
        Geo.BoundsToWorld(regionBounds, regionBounds, out Vec3 size, out Vec2 center);

        // Done! Pass the results back.
        OnReceivedHeight(texture, size, center);
    }
 private static void ValidateBaseGeo(Geo geo, SectorElementCollection sectorElements, IEventLogger events)
 {
     if (!PointsValid(geo.FirstPoint, geo.SecondPoint, sectorElements))
     {
         string message = $"Invalid waypoint on GEO declaration: {geo.GetCompileData(sectorElements)}";
         events.AddEvent(
             new ValidationRuleFailure(message, geo)
             );
     }
 }
Beispiel #32
0
    public virtual void FaceTarget()
    {
        Vector2 dir = GetDirection();

        if ((Vector2)transform.up != dir)
        {
            float ang = Geo.ToAng(dir);
            transform.eulerAngles = new Vector3(0, 0, ang - 90);
        }
    }
Beispiel #33
0
        public void UpdateFullnameRecursive(Geo e)
        {
            SetFullname(e);
            e.FullNameNoDiacritics = e.FullName.RemoveDiacritics();

            foreach (var item in e.Children)
            {
                UpdateFullnameRecursive(item);
            }
        }
 public void ShouldHaveConsistentDistance(
     [Random(-1000, 1000.0, 5)] double lat,
     [Random(-1000.0, 1000.0, 5)] double lon,
     [Random(-360.0, 360.0, 10)] double bearing,
     [Random(0.0, 1000.0, 10)] double distance)
 {
     var sourceGeo = new Geo(lat, lon);
     var destGeo = sourceGeo.Offset(Geo.KilometersToRadians(distance), Geo.DegreesToRadians(bearing));
     Assert.That(sourceGeo.DistanceKilometers(destGeo), Is.EqualTo(distance).Within(0.0003));
 }
Beispiel #35
0
 void Hit(Vector2 bulletDir)
 {
     ManagerScript.me.scoreInt++;
     if (blood != null)
     {
         Instantiate(blood, transform.position, Quaternion.Euler(new Vector3(-Geo.ToAng(bulletDir), 90, 0)));
         blood.Play();
     }
     Destroy(gameObject);
 }
Beispiel #36
0
 public override void ToStream(Stream output)
 {
     output.Write(TLUtils.SignatureToBytes(Signature));
     output.Write(Id.ToBytes());
     output.Write(AccessHash.ToBytes());
     output.Write(UserId.ToBytes());
     output.Write(Date.ToBytes());
     Geo.ToStream(output);
     Sizes.ToStream(output);
 }
Beispiel #37
0
 public void OnLocationChanged(Android.Locations.Location location)
 {
     if (location != null)
     {
         Geo g = new Geo {
             latitude = location.Latitude, longitud = location.Longitude
         };
         LatLonUpd(g);
     }
 }
 public PollAndGetAllMapDataResult(ClientEntity[] players, ClientApple[] apples, Geo[] gameBorderPoints, GameState gameState, int score, int pacMenLeft, string lastGameMessage)
 {
     Players = players;
     Apples = apples;
     GameBorderPoints = gameBorderPoints;
     GameState = gameState;
     Score = score;
     PacMenLeft = pacMenLeft;
     LastGameMessage = lastGameMessage;
 }
        public void Read(BinaryReader reader)
        {
            int num1 = reader.ReadInt32();

            if (num1 >= 1)
            {
                this._attachmentType       = (AttachmentType)reader.ReadInt32();
                this.ResourceUri           = reader.ReadString();
                this._resourceDescription  = reader.ReadString();
                this._latitude             = reader.ReadDouble();
                this._longitude            = reader.ReadDouble();
                this._mediaDurationSeconds = reader.ReadInt32();
                this.MediaId         = reader.ReadInt64();
                this.MediaOwnerId    = reader.ReadInt64();
                this.VideoUri        = reader.ReadString();
                this.IsExternalVideo = reader.ReadBoolean();
                this.Artist          = reader.ReadString();
                this.UniqueId        = reader.ReadString();
                this.Audio           = reader.ReadGeneric <AudioObj>();
                this.AccessKey       = reader.ReadString();
                this.Photo           = reader.ReadGeneric <Photo>();
                this._wallPost       = reader.ReadGeneric <WallPost>();
                if (this._attachmentType == AttachmentType.Geo && string.IsNullOrEmpty(this._resourceDescription))
                {
                    this.InitializeUIPropertiesForGeoAttachment();
                }
            }
            if (num1 >= 2)
            {
                this._stickerDimension = reader.ReadDouble();
                this._stickerAlignment = (HorizontalAlignment)reader.ReadInt32();
            }
            if (num1 >= 3)
            {
                this._documentImageUri = reader.ReadString();
            }
            if (num1 >= 4)
            {
                this._attachment = reader.ReadGeneric <Attachment>();
                this._geo        = reader.ReadGeneric <Geo>();
            }
            if (num1 >= 5)
            {
                this._comment = reader.ReadGeneric <Comment>();
            }
            if (num1 >= 6)
            {
                this.ParentPostId = reader.ReadString();
            }
            if (num1 < 7)
            {
                return;
            }
            this.AudioContentRestricted = reader.ReadInt32();
        }
        /// <summary>
        /// Updates user in the database
        /// </summary>
        /// <param name="id">Guid</param>
        /// <param name="user">User</param>
        /// <returns>A boolean if the user is updated correctly from the database</returns>
        public Task <bool> UpdateUser(Guid id, User user)
        {
            Task <bool> task = Task.Run(() =>
            {
                int rows;
                using (SqlConnection conn = new SqlConnection(_connString))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(_updateUser, conn))
                    {
                        cmd.Parameters.AddWithValue("@id", id);
                        cmd.Parameters.AddWithValue("@name", user.Name);
                        cmd.Parameters.AddWithValue("@surname", user.Surname);
                        cmd.Parameters.AddWithValue("@email", user.Email);
                        cmd.Parameters.AddWithValue("@phonenumber", user.Phonenumber);
                        cmd.Parameters.AddWithValue("@usertype", user.UserType);
                        cmd.Parameters.AddWithValue("@password", user.Password);

                        rows = cmd.ExecuteNonQuery();
                        if (rows == 0)
                        {
                            return(false);

                            throw new AggregateException("The User object was not valid");
                        }
                        cmd.Dispose();
                    }
                    using var client = new HttpClient();
                    var content      = client.GetStringAsync("https://maps.googleapis.com/maps/api/geocode/json?address=" + user.AddressList[0].StreetName + "+" + user.AddressList[0].StreetNumber + "+" + user.AddressList[0].Postalcode + "&key=AIzaSyC2t8TFM7VJY_gUpk45PYxbxqqxPcasVho").Result;
                    Geo geoData      = JsonConvert.DeserializeObject <Geo>(content);

                    user.AddressList[0].Latitude   = double.Parse(geoData.results[0].geometry.location.lat, new CultureInfo("en-UK"));
                    user.AddressList[0].Longtitude = double.Parse(geoData.results[0].geometry.location.lng, new CultureInfo("en-UK"));
                    using (SqlCommand cmd = new SqlCommand(_updateUserAddress, conn))
                    {
                        cmd.Parameters.AddWithValue("@id", user.Id);
                        cmd.Parameters.AddWithValue("@streetname", user.AddressList[0].StreetName);
                        cmd.Parameters.AddWithValue("@streetnr", user.AddressList[0].StreetNumber);
                        cmd.Parameters.AddWithValue("@postalcode", user.AddressList[0].Postalcode);
                        cmd.Parameters.AddWithValue("@lat", user.AddressList[0].Latitude);
                        cmd.Parameters.AddWithValue("@long", user.AddressList[0].Longtitude);
                        rows = cmd.ExecuteNonQuery();
                        if (rows == 0)
                        {
                            return(false);

                            throw new AggregateException("The Address object was not valid");
                        }
                    }
                    return(true);
                }
            });

            return(task);
        }
Beispiel #41
0
        public void TestScalarGeoWithin()
        {
            List <IpGeopoint> list;

            using (var conn = TestCrateConnection())
            {
                conn.Open();
                list = conn.Where <IpGeopoint>(t => Geo.Within(t.Pin, new GeoPolygon(new GeoPoint(40, 20), new GeoPoint(49, 20), new GeoPoint(49, 30), new GeoPoint(40, 30), new GeoPoint(40, 20))));
            }
            Assert.GreaterOrEqual(list.Count, 1);
        }
        public void TwoByTwoSquare()
        {
            var zeroZero = new Geo(0, 0);
            var zeroOne = new Geo(0, 1);
            var oneZero = new Geo(1, 0);
            var oneOne = new Geo(1, 1);

            _list.Add(oneOne);
            _list.Add(oneZero);
            _list.Add(zeroOne);
            _list.Add(zeroZero);
            Assert.AreEqual(4, _list.Count);
            
            Assert.AreSame(oneOne, _list[0]);
            Assert.AreSame(oneZero, _list[1]);
            Assert.AreSame(zeroOne, _list[2]);
            Assert.AreSame(zeroZero, _list[3]);

            Assert.IsFalse(_list.IsSorted);
            _list.Sort();
            Assert.IsTrue(_list.IsSorted);

            Assert.AreSame(zeroZero, _list[0]);
            Assert.AreSame(zeroOne, _list[1]);
            Assert.AreSame(oneZero, _list[2]);
            Assert.AreSame(oneOne, _list[3]);

            Assert.AreSame(zeroZero, _list[0, 0]);
            Assert.AreSame(zeroOne, _list[1, 0]);
            Assert.AreSame(oneOne, _list[1, 1]);
            Assert.AreSame(oneZero, _list[0, 1]);

            TestNearestAndExact(zeroZero, 0, -1);
            TestNearestAndExact(zeroZero, -1, -1);
            TestNearestAndExact(zeroZero, -1, 0);
            TestNearestAndExact(zeroZero, 0.4, 0.4);

            TestNearestAndExact(oneZero, 1, -1);
            TestNearestAndExact(oneZero, 2, -1);
            TestNearestAndExact(oneZero, 2, 0);
            TestNearestAndExact(oneZero, 0.6, 0.4);

            TestNearestAndExact(oneOne, 2, 1);
            TestNearestAndExact(oneOne, 2, 2);
            TestNearestAndExact(oneOne, 1, 2);
            TestNearestAndExact(oneOne, 0.6, 0.6);

            TestNearestAndExact(zeroOne, 0, 2);
            TestNearestAndExact(zeroOne, -1, 2);
            TestNearestAndExact(zeroOne, -1, 1);
            TestNearestAndExact(zeroOne, 0.4, 0.6);

            TestNearestAndExact(oneOne, 0.5, 0.5);
        }
 public override void ToStream(Stream output)
 {
     output.Write(TLUtils.SignatureToBytes(Signature));
     Flags.ToStream(output);
     Geo.ToStream(output);
     Title.ToStream(output);
     Address.ToStream(output);
     Provider.ToStream(output);
     VenueId.ToStream(output);
     ToStream(output, ReplyMarkup, Flags, (int)InputBotInlineMessageFlags.ReplyMarkup);
 }
 public OverlayLineSegments(Geo[] points, Color color, float size = 1f, LineStyle lineStyle = LineStyle.Solid)
     : base(color, size, lineStyle)
 {
     Segments = new List<OverlayLineSegment>();
     Add(points);
     if (points.Length < 2) return;
     CreateSegments();
     ComputeBoundingBox();
     CheckForClosure();
     CheckCrossingSegments();
 }
 public void PropertyChangedTest()
 {
     var geoRect = new GeoRect(44, 41, -69, -72);
     Post.Cast<GeoRect, INotifyPropertyChanged>(geoRect).PropertyChanged += (s, e) => Console.WriteLine("PropertyChanged: {0}", e.PropertyName);
     var insideGeo = new Geo(42, -70);
     var outsideGeo = new Geo(0, 0);
     Assert.IsTrue(geoRect.Contains(insideGeo));
     Assert.IsFalse(geoRect.Contains(outsideGeo));
     Console.WriteLine("Setting North to 45");
     geoRect.North = 45;
 }
Beispiel #46
0
        public Cone(Vector2 begin, Vector2 end, float angleDeg)
        {
            Radius = Vector2.Distance(begin, end);

            float middlePointAngle = Geo.GetAngleDegrees(begin, end);

            Begin      = begin;
            End        = end;
            BeginAngle = middlePointAngle - angleDeg;
            EndAngle   = middlePointAngle + angleDeg;
        }
 // Update is called once per frame
 void LateUpdate()
 {
     //rb.MoveRotation(Geo.ToAng(rb.velocity));
     //rb.AddTorque(100f);
     if (!inWall)
     {
         transform.eulerAngles = new Vector3(0, 0, Geo.ToAng(rb.velocity));
     }
     //transform.rotation = Quaternion.AngleAxis(180 + Time.timeSinceLevelLoad, Vector3.forward);
     //print(Geo.ToAng(rb.velocity));
 }
Beispiel #48
0
        public void TestScalarGeoPointDistance()
        {
            List <IpGeopoint> list;

            using (var conn = TestCrateConnection())
            {
                conn.Open();
                list = conn.Where <IpGeopoint>(t => Geo.Distance(t.Pin, new GeoPoint(21, 2)) > 1);
            }
            Assert.GreaterOrEqual(list.Count, 1);
        }
        public void UnionGeo()
        {
            var baseRect = new GeoRect(43, 41, -69, -71);
            var containedWithin = new Geo(42, -70);
            var onWesternEdge = new Geo(42, -71);
            var onCorner = new Geo(43, -69);
            var outside = new Geo(44, -60);

            Assert.IsTrue(GeoRect.Union(baseRect,containedWithin).Equals(baseRect));
            Assert.IsTrue(GeoRect.Union(baseRect, onWesternEdge).Equals(baseRect));
            Assert.IsTrue(GeoRect.Union(baseRect, onCorner).Equals(baseRect));
            Assert.IsFalse(GeoRect.Union(baseRect,outside).Equals(baseRect));
            Assert.IsTrue(GeoRect.Union(baseRect,outside).Equals(new GeoRect(44,41,-60,-71)));
        }
 public void ShouldWrapOutOfRangeValues(
     [Random(-1000, 1000.0, 50)] double lat,
     [Random(-1000.0, 1000.0, 50)] double lon)
 {
     var wrappedLat = lat;
     while (wrappedLat < -90) wrappedLat += 180.0;
     while (wrappedLat > 90.0) wrappedLat -= 180.0;
     var wrappedLon = lon;
     while (wrappedLon < -180) wrappedLon += 360.0;
     while (wrappedLon > 180.0) wrappedLon -= 360.0;
     var geo = new Geo(lat, lon);
     Assert.That(geo.Latitude, Is.EqualTo(wrappedLat).Within(0.000001));
     Assert.That(geo.Longitude, Is.EqualTo(wrappedLon).Within(0.000001));
 }
 /// <summary>
 /// Returns a random location that is within the specified perimeter
 /// </summary>
 /// <param name="perimeter"></param>
 /// <returns></returns>
 public static Geo RandomLocationWithinPerimeter(this GeoArray perimeter)
 {
     if (!perimeter.IsClosed) throw new InvalidPerimeterException("Perimeter is not closed");
     if (perimeter.HasCrossingSegments) throw new InvalidPerimeterException("Perimeter is not a simple polygon (segments cross each other)");
     Geo location = null;
     while ((location == null) || (!location.IsInside(perimeter)))
     {
         location = new Geo(perimeter.BoundingBox.South + (perimeter.BoundingBox.Height * Random.NextDouble()), perimeter.BoundingBox.West + (perimeter.BoundingBox.Width * Random.NextDouble()));
         //var distance = Random.NextDouble() * perimeter.BoundingCircle.Radius;
         //var azimuth = Random.NextDouble() * MoreMath.TwoPi;
         //location = perimeter.Center.Offset(distance, azimuth);
     }
     return location;
 }
Beispiel #52
0
        public GuiSceneNode(Geo.Mesh Mesh, GraphicsDevice device, int width, int height, Euler Euler = null)
        {
            this.Device = device;
            this.Mesh = Mesh;

            this.Orientation = Euler;
            if (this.Orientation == null) this.Orientation = new Euler();

            uiCamera = new Render.OrthographicCamera(new Viewport(0, 0, width, height));
            uiRoot = new UIItem("ROOT", new QuadShape(0, 0, width, height), null);

            uiCamera.focus = new Vector2(width / 2, height / 2);

            renderTarget = new RenderTarget2D(device, uiCamera.Viewport.Width, uiCamera.Viewport.Height);
        }
 /// <summary>
 /// Describes a circular arc on the surface of a sphere
 /// </summary>
 /// <param name="location">Location of the center of the circle we're describing an arc of</param>
 /// <param name="centerAzimuth">Azimuth of the center of the slice, in radians from true north</param>
 /// <param name="horizontalWidth">Width of the slice in radians</param>
 /// <param name="radius">Radius of the circle in radians (relative to the center of the sphere)</param>
 public GeoArc(Geo location, double centerAzimuth, double horizontalWidth, double radius)
 {
     Location = location;
     Radius = radius;
     // Force the center azimuth to be between -2pi and 2pi
     centerAzimuth = Math.Sign(centerAzimuth) * (Math.Abs(centerAzimuth) % MoreMath.TwoPi);
     if (horizontalWidth < 0)
     {
         SliceStartAzimuth = centerAzimuth + (horizontalWidth / 2);
         SliceEndAzimuth = centerAzimuth - (horizontalWidth / 2);
     }
     else
     {
         SliceStartAzimuth = centerAzimuth - (horizontalWidth / 2);
         SliceEndAzimuth = centerAzimuth + (horizontalWidth / 2);
     }
     SliceWidth = Math.Min(Math.Abs(horizontalWidth), MoreMath.TwoPi);
 }
 /// <summary>
 /// Bounce a platform around inside a given perimeter
 /// </summary>
 /// <param name="perimeter">A GeoArray of points in the perimeter, which must satisfy certain conditions (no segments may cross and the polygon 
 /// must be closed)</param>
 /// <param name="startPoint">A Geo containing the starting point.  If this is null, a point inside the perimeter is chosen randomly</param>
 /// <param name="initialCourse">The initial course, in radians from true north.  If startPoint is null, or if initialCourse is NaN, this is 
 /// chosen randomly</param>
 /// <param name="minimumCourseLength">The minimum length of the returned course, in meters</param>
 /// <returns>A GeoArray containing the start location and each point where the course bounces off the perimeter</returns>
 public static GeoArray PerimeterBounce(this GeoArray perimeter, Geo startPoint, double initialCourse, double minimumCourseLength)
 {
     if (!perimeter.IsClosed) throw new InvalidPerimeterException("Perimeter is not closed");
     if (perimeter.HasCrossingSegments) throw new InvalidPerimeterException("Perimeter is not a simple polygon (segments cross each other)");
     var points = new List<Geo>();
     while ((startPoint == null) || (!startPoint.IsInside(perimeter)))
     {
         var distance = Random.NextDouble() * perimeter.BoundingCircle.Radius;
         var azimuth = Random.NextDouble() * MoreMath.TwoPi;
         startPoint = perimeter.Center.Offset(distance, azimuth);
     }
     points.Add(startPoint);
     if (double.IsNaN(initialCourse)) initialCourse = Random.NextDouble()*MoreMath.TwoPi;
     var courseSegment = new GeoSegment(startPoint, startPoint.Offset(Geo.KilometersToRadians(0.001), initialCourse)).Scale(1000 * Geo.RadiansToKilometers(MoreMath.PiOverTwo));
     var bounceCount = 1;
     while (minimumCourseLength > 0)
     {
         var minIntersectionRange = double.MaxValue;
         GeoSegment firstIntersectingSegment = null;
         Geo firstIntersection = null;
         foreach (var segment in perimeter.Segments)
         {
             var intersection = courseSegment.Intersection(segment);
             if (intersection == null) continue;
             var curIntersectionRange = startPoint.DistanceRadians(intersection);
             if (curIntersectionRange < Geo.KilometersToRadians(0.001) || curIntersectionRange >= minIntersectionRange) continue;
             minIntersectionRange = curIntersectionRange;
             firstIntersectingSegment = segment;
             firstIntersection = intersection;
         }
         if (firstIntersection == null) throw new PerimeterBounceException(string.Format("Course segment failed to intersect the perimeter on bounce {0}", bounceCount));
         var actualCourseSegment = new GeoSegment(points.Last(), firstIntersection);
         minimumCourseLength -= Geo.RadiansToKilometers(actualCourseSegment.LengthRadians) * 1000;
         points.Add(firstIntersection);
         var reflectedSegment = courseSegment.Reflect(firstIntersectingSegment);
         var reflectionAzimuth = reflectedSegment[0].Azimuth(reflectedSegment[1]);
         courseSegment = new GeoSegment(reflectedSegment[1], 1000 * Geo.RadiansToKilometers(MoreMath.PiOverTwo), Geo.RadiansToDegrees(reflectionAzimuth));
         bounceCount++;
     }
     return new GeoArray(points);
 }
 public void CreateTestDatabase()
 {
     if (Directory.Exists(_databaseDirectory))
     {
         Console.WriteLine("Deleting database directory {0}", _databaseDirectory);
         foreach (var file in Directory.EnumerateFiles(_databaseDirectory, "*.*", SearchOption.AllDirectories))
             File.Delete(file);
         Directory.Delete(_databaseDirectory, true);
         var retry = 10;
         while (Directory.Exists(_databaseDirectory) && retry > 0)
         {
             Thread.Sleep(100);
             retry--;
         }
     }
     IMasterDatabaseService database;
     EnvironmentalCacheService cache;
     PluginManagerService plugins;
     var location = TestLocation.LoadOrCreate("Jacksonville", OverlayFile, _databaseDirectory, PluginDirectory, out database, out cache, out plugins);
     var scenario = TestScenario.LoadOrCreate(database, location, SimAreaDirectory, NemoFile);
     var center = new Geo((location.GeoRect.North + location.GeoRect.South) / 2, (location.GeoRect.East + location.GeoRect.West) / 2);
 }
 /// <summary>
 /// Write a Geo to the stream
 /// </summary>
 /// <param name="writer"></param>
 /// <param name="geo"></param>
 public static void Write(this BinaryWriter writer, Geo geo)
 {
     geo.Write(writer);
 }
 private static int IsLeft(Geo p0, Geo p1, Geo p2)
 {
     var calc = ((p1.Longitude - p0.Longitude)*(p2.Latitude - p0.Latitude) -
                 (p2.Longitude - p0.Longitude)*(p1.Latitude - p0.Latitude));
     if (calc > 0) return 1;
     if (calc < 0) return -1;
     return 0;
 }
 void Copy(AnalysisPoint analysisPoint)
 {
     Geo = new Geo(analysisPoint.Geo);
     LayerSettings = new LayerSettings(analysisPoint.LayerSettings);
 }
 public OverlayLineSegment(Geo p1, Geo p2)
     : this(p1, p2, Colors.Black, 1f, LineStyle.Solid)
 {
 }
        public override bool Contains(Geo pointToTest)
        {
            var verticalMatch = false;
            var horizontalMatch = false;
            // We don't know or care if this line segment is drawn west to east in longitude, so we will test for both possibilities.
            // The same thing goes for north and south with respect to latitude.

            // If one or the other is true, then the test is deemed to have succeeded.  If neither are true, the test fails.

            // If the point's longitude is within the span of longitudes covered by this line segment
            if (IsVertical)
            {
                var deltaLon = Math.Abs(this[0].Longitude - pointToTest.Longitude);
                if (deltaLon < 1e-6) verticalMatch = true;
            }
            else
            {
                if (((this[0].Longitude <= pointToTest.Longitude) && (pointToTest.Longitude <= this[1].Longitude)) ||
                    ((this[1].Longitude <= pointToTest.Longitude) && (pointToTest.Longitude <= this[0].Longitude))) 
                    verticalMatch = true;
            }
            if (IsHorizontal)
            {
                var deltaLat = Math.Abs(this[0].Latitude - pointToTest.Latitude);
                if (deltaLat < 1e-6) horizontalMatch = true;
            }
            else
            {
                // If the point's latitude is within the span of latitudes covered by this line segment
                if (((this[0].Latitude <= pointToTest.Latitude) && (pointToTest.Latitude <= this[1].Latitude)) || 
                    ((this[1].Latitude <= pointToTest.Latitude) && (pointToTest.Latitude <= this[0].Latitude))) 
                    horizontalMatch = true;
            }
            return verticalMatch && horizontalMatch; // The line segment does not contain the point
        }