public void Polygons() { LineGeometry line = new LineGeometry( new[] { new GeometryPosition(0, 0), new GeometryPosition(0, 1), new GeometryPosition(1, 1), new GeometryPosition(0, 0), }); Assert.AreEqual( "geo.intersects(Foo, geography'POLYGON((0 0,0 1,1 1,0 0))')", SearchFilter.Create($"geo.intersects(Foo, {line})")); PolygonGeometry polygon = new PolygonGeometry(new[] { line }); Assert.AreEqual( "geo.intersects(Foo, geography'POLYGON((0 0,0 1,1 1,0 0))')", SearchFilter.Create($"geo.intersects(Foo, {polygon})")); Assert.Throws<ArgumentException>(() => SearchFilter.Create( $"{new LineGeometry(new[] { new GeometryPosition(0, 0) })}")); Assert.Throws<ArgumentException>(() => SearchFilter.Create( $"{new LineGeometry(new[] { new GeometryPosition(0, 0), new GeometryPosition(0, 0), new GeometryPosition(0, 0), new GeometryPosition(1, 1) })}")); Assert.Throws<ArgumentException>(() => SearchFilter.Create( $"{new PolygonGeometry(new[] { line, line })}")); }
protected override void OnCreate() { base.OnCreate(); _tileColliderArchetype = EntityManager.CreateArchetype( typeof(TileColliderTag), typeof(FixTranslation), typeof(PhysicsColliderBlob)); // Create tile collider BoxGeometry boxGeometry = new BoxGeometry() { Size = float2(1, 1) }; PolygonGeometry triangleGeometry = new PolygonGeometry() { Vertices = new NativeArray <float2>(new float2[] { new float2(-.5f, -.5f), new float2(-.5f, .5f), new float2(.5f, -0.5f), }, Allocator.Temp) }; CollisionFilter filter = CollisionFilter.FromLayer(SimulationGameConstants.Physics.LAYER_TERRAIN); PhysicsMaterial material = PhysicsMaterial.Default; _fullTileCollider = Collider.Create(boxGeometry, filter, material); _cornerTileCollider = Collider.Create(triangleGeometry); }
/// <summary> /// 图形的内缩小 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ElasticityTestBtn_Click(object sender, RoutedEventArgs e) { List <Geometry2D> gss = this.drawingKernel.GeometryShapes; List <Line2D> lines = new List <Line2D>(); foreach (var g in gss) { if (g is DrawingKernel.Geometries.Primitives.LineGeometry) { DrawingKernel.Geometries.Primitives.LineGeometry line = g as DrawingKernel.Geometries.Primitives.LineGeometry; lines.Add(Line2D.Create(line.Start, line.End)); } if (g.GeometryId == "tp") { this.drawingKernel.RemoveGeometryShape(g); } } //查找封闭区域 List <List <Line2D> > nn = GraphicAlgorithm.ClosedLookup(lines, true, true); if (nn != null && nn.Count > 0) { List <Line2D> nt = nn[0]; List <Line2D> wtn = GraphicAlgorithm.Elastic(nt, -20); PolygonGeometry pg = new PolygonGeometry(); wtn.ForEach(y => { pg.PPoints.Add(y.Start); }); pg.FillColor = KernelProperty.GetRandomColor(); pg.GeometryId = "tp"; this.drawingKernel.AddShape(pg); } }
private void ClosetTestBtn2_Click(object sender, RoutedEventArgs e) { //封闭区域测试 List <Geometry2D> gss = this.drawingKernel.GeometryShapes; List <Line2D> lines = new List <Line2D>(); //转换图形 foreach (var g in gss) { if (g is DrawingKernel.Geometries.Primitives.LineGeometry) { DrawingKernel.Geometries.Primitives.LineGeometry line = g as DrawingKernel.Geometries.Primitives.LineGeometry; lines.Add(Line2D.Create(line.Start, line.End)); } if (g.GeometryId == "tp") { this.drawingKernel.RemoveGeometryShape(g); } } //查找封闭区域 List <List <Line2D> > nn = GraphicAlgorithm.ClosedLookup(lines, false, true); if (nn != null) { nn.ForEach(x => { PolygonGeometry pg = new PolygonGeometry(); x.ForEach(y => { pg.PPoints.Add(y.Start); }); pg.FillColor = KernelProperty.GetRandomColor(); pg.GeometryId = "tp"; this.drawingKernel.AddShape(pg); }); } }
public void PhysicsBodyCalculateAabb_PolygonColliderTest() { var vertices = new NativeArray <float2>( new float2[] { new float2(-1f, -2f), new float2(2f, -3f), new float2(4f, 5f), new float2(-6f, 7f) }, Allocator.Temp ); var geometry = new PolygonGeometry { Vertices = vertices, BevelRadius = 3.0f }; var collider1 = PhysicsPolygonCollider.Create(geometry); var collider2 = PhysicsPolygonCollider.Create(geometry); var physicsBody = new PhysicsBody(collider1); var aabb = physicsBody.CalculateAabb(); Assert.IsTrue(aabb.Equals(collider2.Value.CalculateAabb())); vertices.Dispose(); collider1.Dispose(); collider2.Dispose(); }
private void ribbonButton53_Click(object sender, EventArgs e) { if (featurePolygon == null) { Vec3d vec1 = new Vec3d(); vec1.set(0, 40, 0); Vec3d vec2 = new Vec3d(); vec2.set(-60, 40, 0); Vec3d vec3 = new Vec3d(); vec3.set(-60, 60, 0); Vec3d vec4 = new Vec3d(); vec4.set(0, 60, 0); PolygonGeometry polygon = new PolygonGeometry(); polygon.push_back(vec1); polygon.push_back(vec2); polygon.push_back(vec3); polygon.push_back(vec4); Feature feature = new Feature(); feature.setGeometry(polygon); featurePolygon = new FeaturePrimitive(); featurePolygon.setFeature(feature); m_earthRoot.addChild(featurePolygon); } }
/// <summary> /// 一个多边形和另外一个多边形之间的关系 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PolygonInsideTestBtn_Click(object sender, RoutedEventArgs e) { List <Geometry2D> gss = this.drawingKernel.GeometryShapes; List <List <Line2D> > lines = new List <List <Line2D> >(); foreach (var g in gss) { if (g is PolygonGeometry) { List <Line2D> nlines = new List <Line2D>(); PolygonGeometry poly = g as DrawingKernel.Geometries.Primitives.PolygonGeometry; g.FillColor = Colors.Azure; g.Opacity = 0.3; poly.Update(); nlines.AddRange(poly.Lines); lines.Add(nlines); } if (g.GeometryId == "tp") { this.drawingKernel.RemoveGeometryShape(g); } } //计算多边形和多边形之间的关系 if (lines.Count == 2) { List <List <Line2D> > ins = new List <List <Line2D> >(); var result = GraphicAlgorithm.PolygonInsideOfRegion(lines[0], lines[1], ins); if (result == 1) { ins.ForEach(x => { PolygonGeometry pg = new PolygonGeometry(); x.ForEach(y => { pg.PPoints.Add(y.Start); }); pg.FillColor = Colors.Green; pg.GeometryId = "tp"; this.drawingKernel.AddShape(pg); }); } else if (result == 0) { ins.ForEach(x => { PolygonGeometry pg = new PolygonGeometry(); x.ForEach(y => { pg.PPoints.Add(y.Start); }); pg.FillColor = Colors.Red; pg.GeometryId = "tp"; this.drawingKernel.AddShape(pg); }); } else { MessageBox.Show("相离"); } } else { MessageBox.Show("不表现多个多边形的情况"); } }
public void TestSerialization() { var polygon = new PolygonGeometry { Points = new []{new Point(1.5, 2), new Point(3, 4.2), new Point(4.5, 6.4), } }; var writer = new StringWriter(); _serializer.Serialize(writer, polygon); var reader = new StringReader(writer.ToString()); Assert.AreEqual(polygon, _serializer.Deserialize(reader)); }
private LaserBullet(double mass, double angularMass, double power, TimeSpan timeToLive) : base( mass, angularMass, PolygonGeometry.FromRectangle(new Rect(Vector.Zero, new Size(0.35, 0.35))), new ReferenceArea(0.0), power, timeToLive) { }
/// <summary> /// Convert a <see cref="PolygonGeometry"/> to an OData value. A /// PolygonGeometry must have exactly one <see cref="PolygonGeometry.Rings"/> /// to form a searchable polygon. /// </summary> /// <param name="polygon">The polygon.</param> /// <returns>The OData representation of the polygon.</returns> private static string EncodeGeometry(PolygonGeometry polygon) { Argument.AssertNotNull(polygon, nameof(polygon)); Argument.AssertNotNull(polygon.Rings, $"{nameof(polygon)}.{nameof(polygon.Rings)}"); if (polygon.Rings.Count != 1) { throw new ArgumentException( $"A {nameof(PolygonGeometry)} must have exactly one {nameof(PolygonGeometry.Rings)} to form a searchable polygon.", $"{nameof(polygon)}.{nameof(polygon.Rings)}"); } return(EncodeGeometry(polygon.Rings[0])); }
public HomingRocket(Plane target) : base( 20, 50, PolygonGeometry.FromRectangle(new Rect(Vector.Zero, new Size(2, 6.4))), null, 200, TimeSpan.FromSeconds(30)) { Target = target; m_maxRotationVelocity = 10; }
protected override void Setup() { base.Setup(); m_BoxGeometry = new BoxGeometry { Size = new float2(0.01f, 120.40f), Center = new float2(-10.10f, 10.12f), }; m_CapsuleGeometry = new CapsuleGeometry { Vertex0 = new float2(0f, 3f), Vertex1 = new float2(0f, -2f), Radius = 1.5f }; m_CircleGeometry = new CircleGeometry { Center = new float2(-10.10f, 10.12f), Radius = 3.0f }; m_Vertices = new NativeArray <float2>( new float2[] { new float2(-1f, -2f), new float2(2f, -3f), new float2(4f, 5f), new float2(-6f, 7f) }, Allocator.Persistent ); m_GiftWrappedIndices = new NativeArray <int>( new int[] { 2, 3, 0, 1 }, Allocator.Persistent ); Assert.IsTrue(m_Vertices.Length >= 3, "Test array must contain at least 3 points."); Assert.AreEqual(m_Vertices.Length, m_GiftWrappedIndices.Length, "Test array lengths do not match."); m_PolygonGeometry = new PolygonGeometry { Vertices = m_Vertices, BevelRadius = 0.0f }; }
public void Setup() { m_Vertices = new NativeArray <float2>( new [] { new float2(-1f, -2f), new float2(2f, -3f), new float2(4f, 5f), new float2(-6f, 7f) }, Allocator.Persistent ); m_PolygonGeometry = new PolygonGeometry { Vertices = m_Vertices, BevelRadius = 0.0f }; }
private void DrawDebugInfo() { GeometryDrawer debugGeomertyDrawer = new GeometryDrawer( //Game.Content.Load<Texture2D>("Debug/line"), Game.Content.Load <Texture2D>("Debug/pixel"), Game.Content.Load <Texture2D>("Debug/point2"), Game.Content.Load <SpriteFont>("Fonts/debug")); using (var handle = m_safeDrawableGameComponents.SafeRead()) { foreach (var drawableObj in handle.Items) { if (drawableObj is DrawableGameObject) { GameObject gameObject = ((DrawableGameObject)drawableObj).GameObject; debugGeomertyDrawer.Draw(m_spriteBatch, m_coordinatesTransformer, gameObject.CalculateAbsoluteGeometry()); if (gameObject is Plane && gameObject is IHaveEquipment <PlaneEquipment> ) { foreach (var equipment in ((IHaveEquipment <PlaneEquipment>)gameObject).AllEquipment) { var equipmentGeometry = PolygonGeometry.FromRectangle(new Rect(Vector.Zero, equipment.Size)); equipmentGeometry.Rotate(equipment.GetAbsoluteRotation()); equipmentGeometry.Translate(equipment.GetAbsolutePosition()); debugGeomertyDrawer.Draw(m_spriteBatch, m_coordinatesTransformer, equipmentGeometry, drawCenter: false); } } } else if (drawableObj is DrawableStaticObject) { StaticObject staticObject = ((DrawableStaticObject)drawableObj).StaticObject; debugGeomertyDrawer.Draw(m_spriteBatch, m_coordinatesTransformer, staticObject.AbsoluteGeometry); } } } }
private void A_DrawEraseEvent(ActionEventArgs gs) { PolygonGeometry polygon = this.action.Geometry as PolygonGeometry; if (polygon.Lines.Count > 0) { Line2D last = null; if (polygon.Lines.Count == 1) { last = polygon.Lines[0]; } else { last = polygon.Lines[polygon.Lines.Count - 2]; } sublineGeometry.Start = last.Start; sublineGeometry.End = last.End; sublineGeometry.Update(); this.Tip.SetText(sublineGeometry.TextValue, sublineGeometry.TextPosition, sublineGeometry.TextAngle); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return(null); } reader.Read(); // startobject //we should be at geometry type property now if ((string)reader.Value != "geometryType") { throw new InvalidOperationException(); } reader.Read(); //propertyName var type = (string)reader.Value; Geometry value; switch (type) { case "esriGeometryPolygon": value = new PolygonGeometry(); break; case "esriGeometryOther": value = new OtherGeometry(); break; default: throw new NotSupportedException(); } reader.Read(); // move to inner object property //should probably confirm name here reader.Read(); //move to inner object serializer.Populate(reader, value); reader.Read(); //move outside container (should be end object) return(value); }
public async Task <ArcGISAreaLengthResponse> CalculateAreasAndLengths(string token, string sr, EsriGeometryCalcType calculationType, EsriAreaUnit areaUnit, PolygonGeometry geometry, string lengthUnit = "") { string queryUrl = $"{getRestServiceEndpoint()}/areasAndLengths"; var areaUnitParam = new ArcGISCalculateAreasAndLengthAreaParam(areaUnit); PolygonGeometry[] polygonPayload = { geometry }; var encodedContent = new ArcGISEncodedContent { { "f", responseFormat }, { "token", token }, { "sr", sr }, { "lengthUnit", lengthUnit }, { "calculationType", calculationType.ToString() }, { "areaUnit", JsonConvert.SerializeObject(areaUnitParam).TrimJsonRequest() }, { "polygons", JsonConvert.SerializeObject(polygonPayload).TrimJsonRequest() } }; var resp = await ArcGISHttpClient.PostAsync(queryUrl, encodedContent.ToStringUrlEncodedContent()); var respStr = await resp.Content.ReadAsStringAsync(); if (resp.StatusCode != HttpStatusCode.OK) { throw new ArcGISInvalidResponseException($"Unsuccessfull. \n" + $"Response Code: {resp.StatusCode}\n" + $"Response: {respStr}" + $"Query String: {queryUrl}"); } var model = JsonConvert.DeserializeObject <ArcGISCalculateAreasAndLengthsResponse>(respStr); if (model.areas.Count > 1 || model.lengths.Count > 1) { throw new ArcGISUnexpectedResponseException("Returned response count greater than 1 or equal to 0"); } return(new ArcGISAreaLengthResponse(model.areas.FirstOrDefault(), model.lengths.FirstOrDefault())); }
public async Task <PolygonGeometry> ProjectPolygon(string token, string inSR, string outSR, PolygonGeometry geometry) { var queryUrl = $"{getRestServiceEndpoint()}/project"; var payLoadModel = new ArcGISProjectPolygonGeometryParam(new PolygonGeometry[] { geometry }); var encodedContent = new ArcGISEncodedContent { { "f", responseFormat }, { "token", token }, { "inSR", inSR }, { "outSR", outSR }, { "geometries", JsonConvert.SerializeObject(payLoadModel).TrimJsonRequest() } }; var resp = await ArcGISHttpClient.PostAsync(queryUrl, encodedContent.ToStringUrlEncodedContent()); var respStr = await resp.Content.ReadAsStringAsync(); if (resp.StatusCode != HttpStatusCode.OK) { throw new ArcGISInvalidResponseException($"Unsuccessfull. \n" + $"Response Code: {resp.StatusCode}\n" + $"Response: {respStr}" + $"Query String: {queryUrl}"); } var model = JsonConvert.DeserializeObject <ArcGISProjectPolygonResponse>(respStr); return(model.geometries.FirstOrDefault()); }
public void generateFrontJsonFiles(string frontDataFilepath, string DataFilePath) { var frontFileNames = ConfigurationManager.AppSettings["FrontDataFileNames"]; var paths = Directory.GetFiles(DataFilePath, frontFileNames); List <Feature> mainListFeatures = new List <Feature>(); foreach (string path in paths) { var stringData = new List <string>(); var featureType = ""; using (var reader = new StreamReader(path)) { for (int z = 0; z < 2; ++z) { //skip the first 2 lines of the file var skipLine = reader.ReadLine().Trim(); } while (!reader.EndOfStream) { List <string> propertiesLineList = new List <string>(); List <string> propertiesCoorrdinates = new List <string>(); var line = reader.ReadLine().Trim(); if (!string.IsNullOrEmpty(line)) { string[] tempLine = line.Split(','); int numLatLongPairs = Int16.Parse(tempLine[2]); int endIndex = ((numLatLongPairs * 2) + 3 - 1); var text = ""; var width = ""; int[] strokeDash; if (tempLine[0] == "symbol_lowp") { text = "L"; } else if (tempLine[0] == "symbol_high") { text = "H"; } else { if (tempLine[endIndex + 2].Contains("$$")) { //replacing the '$$' with \n for later in the javascrip var tempLineText = tempLine[endIndex + 2].Replace("$$", "\n"); text = tempLineText; } else { //use the tet thats included in the file text = tempLine[endIndex + 2]; } } if (tempLine[endIndex + 3] == "") { width = "3"; } else { width = tempLine[endIndex + 3]; } if (tempLine[0] == "front_trof_strng") { strokeDash = new int[] { 10, 10 }; } else { //create empty array strokeDash = new int[] { }; } PointGeometry geometryPoint = new PointGeometry(); PolygonGeometry geometryPoly = new PolygonGeometry(); var allCoordinates = new List <List <double> >(); Feature feature = new Feature(); if (numLatLongPairs <= 1) { feature.geometry = new PointGeometry() { coordinates = new List <double> { double.Parse(tempLine[4]), double.Parse(tempLine[3]) } }; featureType = "Point"; } else { List <List <double> > coordinates = new List <List <double> >(); for (int i = 3; i < endIndex; i += 2) { coordinates.Add(new List <double> { double.Parse(tempLine[i + 1]), double.Parse(tempLine[i]) }); } //**************NEW MODEL********************* feature.geometry = new LineStringGeometry() { coordinates = coordinates }; featureType = "LineString"; } feature.properties = new FrontsDataProperties { ObjectType = tempLine[0], strokeColor = "#" + tempLine[1].Substring(4), Num_LatLongPairs = tempLine[2], ObjectSize = tempLine[endIndex + 1], Text = text, Width = width, Smoothing = tempLine[endIndex + 4], ClosedLineFlag = tempLine[endIndex + 5], FilledLineFlag = tempLine[endIndex + 6], PipDirection = tempLine[endIndex + 7], Identifier = featureType }; mainListFeatures.Add(feature); } } reader.Close(); } } using (StreamWriter file = File.CreateText(frontDataFilepath + "FrontsGeoJson.json")) { JsonSerializer serializer = new JsonSerializer(); serializer.Formatting = Formatting.None; serializer.Serialize(file, new FeatureCollection { name = "Fronts", features = mainListFeatures }); } }
public void SetGeometry(Vertices vertices) { Geometry = new PolygonGeometry(vertices); }
protected override void OnUpdate() { Entities.ForEach((UnityEngine.PolygonCollider2D collider) => { // Convert the collider if it's valid. if (ConversionUtilities.CanConvertCollider(collider)) { try { // Only single paths with no more than the maximum allowed vertex allowed. // NOTE: Until we implement a convex polygon decomposition, only the convex hull of these points will be used. var colliderPointCount = collider.GetTotalPointCount(); if (collider.pathCount != 1 || colliderPointCount > PhysicsPolygonCollider.Constants.MaxVertexCount) { return; } var lossyScale = new float3(collider.transform.lossyScale).xy; if (math.any(!math.isfinite(lossyScale)) || math.any(lossyScale <= 0.0f)) { throw new ArgumentException("Transform XY scale cannot be zero or Infinite/NaN.", "Transform XY scale."); } var localToWorld = ConversionUtilities.GetColliderLocalToWorld(collider); UnityEngine.Vector3 offset = collider.offset; collider.GetPath(0, m_PolygonVertices); var vertices = new NativeArray <float2>(colliderPointCount, Allocator.Temp, NativeArrayOptions.UninitializedMemory); for (var i = 0; i < colliderPointCount; ++i) { var vertex = localToWorld.MultiplyPoint(offset + (UnityEngine.Vector3)m_PolygonVertices[i]); vertices[i] = new float2(vertex.x, vertex.y); } var geometry = new PolygonGeometry { Vertices = vertices, BevelRadius = PhysicsSettings.Constants.MinimumConvexRadius, }; var colliderBlob = PhysicsPolygonCollider.Create( geometry, ConversionUtilities.GetCollisionFilterFromCollider(collider), ConversionUtilities.GetPhysicsMaterialFromCollider(collider) ); // We finished with the points. vertices.Dispose(); // Submit the collider for conversion. m_ColliderConversionSystem.SubmitCollider(collider, ref colliderBlob); } catch (ArgumentException exception) { UnityEngine.Debug.LogWarning($"{collider.name}: {exception.Message}", collider); } } }); m_PolygonVertices.Clear(); }
public void generateWinterJsonFiles(string winterDataFilepath, string DataFilePath) { var winterFileNames = ConfigurationManager.AppSettings["WinterFileNames"]; var paths = Directory.GetFiles(DataFilePath, winterFileNames); List <WinterJsonModel> fipData = _providerCreateBoundsJson.getWinterJson(winterDataFilepath, DataFilePath); var stringData = new List <string>(); var features = new List <Feature>(); foreach (string path in paths) { using (var reader = new StreamReader(path)) { while (!reader.EndOfStream) { var data = reader.ReadLine().Trim(); if (!string.IsNullOrEmpty(data)) { stringData.Add(data); } } reader.Close(); } } if (stringData.Count > 0) { List <string> propertiesLineList = new List <string>(); foreach (string line in stringData) { if (line.StartsWith("|")) { propertiesLineList = line.Split('|').ToList(); /* * Here we were doing tempProperites = ... * that was the issue we needed to move it inside the else statement * because while looping we were setting variables within tempProperties * AND multiple items in the array were pointing to the SAME REFERENCE of tempProperties * so when feature.properties.State = state; was called you were actually setting that * for each item in the main list which had a reference to that samew tempProperties * therefore we made a dumb mistake like i said */ } else { string[] tempLine = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string fip = tempLine[1]; string state = tempLine[3]; string city = tempLine[2]; string center = tempLine[9]; WinterDataProperties properties = new WinterDataProperties { type = propertiesLineList[1], strokeColor = GetBorderColor(propertiesLineList[1], types.WINTER), strokeThickness = GetPolyBorderThickness(propertiesLineList[0], types.WINTER), StartDateTime = ParseDateTime(propertiesLineList[2]), EndDateTime = ParseDateTime(propertiesLineList[3]), InfoboxTitle = GetInfoboxTitle(propertiesLineList[1], types.WINTER), State = state, Center = center, Fips = fip, City = city, }; Feature feature = new Feature() { properties = properties }; PolygonGeometry geometry = new PolygonGeometry(); var coordinates = fipData.Where(x => x.FIPS == fip).Select(s => { return(s.LatLongPrs.Select(q => new List <double> { (double)q.longitude, (double)q.latitude }).ToList()); }).ToList(); var allCoordinates = new List <List <double> >(); coordinates.ForEach(item => { allCoordinates.AddRange(item); }); geometry.coordinates.Add(allCoordinates); feature.geometry = geometry; if (features.Exists(x => ((WinterDataProperties)x.properties).Fips.Equals(fip))) { features.Remove(features.Find(x => ((WinterDataProperties)x.properties).Fips.Equals(fip))); } features.Add(feature); } } ; List <DateTime> dates = getListOfDates(DataFilePath); for (int i = 0; i < dates.Count; i++) { DateTime currentDate = dates[i]; List <Feature> dateFilteredFeatures = new List <Feature>(); if (i == dates.Count - 1) { dateFilteredFeatures = features.Where(x => { return(Convert.ToDateTime(((WinterDataProperties)x.properties).EndDateTime) >= currentDate); }).ToList(); } else { DateTime nextDate = dates[i + 1]; dateFilteredFeatures = features.Where(x => { /* * Check if endDate is after or equal to current date * ALSO * check if startDate is BEFORE the next date * */ return(Convert.ToDateTime(((WinterDataProperties)x.properties).EndDateTime) >= currentDate && Convert.ToDateTime(((WinterDataProperties)x.properties).StartDateTime) < nextDate); }).ToList(); } using (StreamWriter file = File.CreateText(winterDataFilepath + "winterWarnings_" + i + ".json")) { JsonSerializer serializer = new JsonSerializer(); serializer.Formatting = Formatting.None; serializer.Serialize(file, new FeatureCollection { name = "winterWarnings_" + i, features = dateFilteredFeatures }); } } } }
/// <summary> /// 检测一个点是否在一个多边形内部 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void InsideTestBtn_Click(object sender, RoutedEventArgs e) { List <Geometry2D> gss = this.drawingKernel.GeometryShapes; List <Line2D> lines = new List <Line2D>(); List <Vector2D> vts = new List <Vector2D>(); foreach (var g in gss) { if (g is PolygonGeometry) { PolygonGeometry poly = g as DrawingKernel.Geometries.Primitives.PolygonGeometry; g.FillColor = Colors.Azure; g.Opacity = 0.3; poly.Update(); lines.AddRange(poly.Lines); } if (g is DrawingKernel.Geometries.Primitives.LineGeometry) { DrawingKernel.Geometries.Primitives.LineGeometry l = g as DrawingKernel.Geometries.Primitives.LineGeometry; vts.Add(l.Start); vts.Add(l.End); } if (g.GeometryId == "tp") { this.drawingKernel.RemoveGeometryShape(g); } } if (vts != null) { int resultP = 0; for (int i = 0; i < vts.Count; i++) { resultP = GraphicAlgorithm.InsideOfRegion(vts[i], lines); if (resultP == 0) { CircleGeometry c = new DrawingKernel.Geometries.Primitives.CircleGeometry(); c.FillColor = Colors.Red; c.Start = vts[i]; c.End = Vector2D.Create(vts[i].X + 5, vts[i].Y); c.GeometryId = "tp"; this.drawingKernel.AddShape(c); } else if (resultP == 1) { CircleGeometry c = new DrawingKernel.Geometries.Primitives.CircleGeometry(); c.FillColor = Colors.Green; c.Start = vts[i]; c.End = Vector2D.Create(vts[i].X + 5, vts[i].Y); c.GeometryId = "tp"; this.drawingKernel.AddShape(c); } else { CircleGeometry c = new DrawingKernel.Geometries.Primitives.CircleGeometry(); c.FillColor = Colors.Yellow; c.Start = vts[i]; c.End = Vector2D.Create(vts[i].X + 5, vts[i].Y); c.GeometryId = "tp"; this.drawingKernel.AddShape(c); } } } }
public void TearDown() { m_Vertices.Dispose(); m_PolygonGeometry = default; }
/// <summary> /// 解析指定的XML对象 /// </summary> /// <param name="messageXML"></param> private void ParseXML(XmlReader xmlReader) { Geometry2D shape = null; switch (xmlReader.Name) { case "ArcGeometry": shape = new ArcGeometry(); break; case "BeamGeometry": shape = new BeamGeometry(); break; case "CircleGeometry": shape = new CircleGeometry(); break; case "CSectionGeometry": shape = new CSectionGeometry(); break; case "EllipseGeometry": shape = new EllipseGeometry(); break; case "FloorGeometry": shape = new FloorGeometry(); break; case "LineGeometry": shape = new LineGeometry(); break; case "MeasureGeometry": shape = new MeasureGeometry(); break; case "MemberGeometry": shape = new MemberGeometry(); break; case "OSBGeometry": shape = new OSBGeometry(); break; case "PointGeometry": shape = new PointGeometry(); break; case "PolygonGeometry": shape = new PolygonGeometry(); break; case "PolylineGeometry": shape = new PolylineGeometry(); break; case "RectangleGeometry": shape = new RectangleGeometry(); break; case "SteelBeamGeometry": shape = new SteelBeamGeometry(); break; case "TextGeometry": shape = new TextGeometry(); break; case "WallGeometry": shape = new WallGeometry(); break; } if (shape != null) { //将信息写入数据流中 shape.ReadXML(xmlReader); //将图形添加都界面上 this.drawingKernel.AddShape(shape); } }
public void Draw(SpriteBatch spriteBatch, CoordinatesTransformer coordinatesTransformer, Geometry geometry, bool drawCenter = true) { if (drawCenter) { spriteBatch.DrawString( m_font, geometry.Center.ToString(), coordinatesTransformer.Transform(geometry.Center).Round(), Color.Yellow); spriteBatch.Draw( m_point, coordinatesTransformer.Transform(geometry.Center), null, Color.White, 0, new Vector2(m_point.Width / 2.0f, m_point.Height / 2.0f), 1.0f, SpriteEffects.None, 0f); } foreach (var segment in PolygonGeometry.FromRectangle(geometry.BoundingRectangle).Segments) { Vector centerSegment = (segment.Start + segment.End) / 2.0; double rotation = segment.Offset.Angle(); Vector2 scale = coordinatesTransformer.CreateScaleVector(new Size(1.0, segment.Length), new Size(m_line.Width, m_line.Height)); Vector2 origin = new Vector2(m_line.Width / 2.0f, m_line.Height / 2.0f); spriteBatch.Draw( m_line, coordinatesTransformer.Transform(centerSegment), null, Color.White * 0.8f, (float)Helper.ToRadians(rotation), origin, new Vector2(1, scale.Y), SpriteEffects.None, 0); } if (geometry is PolygonGeometry) { var polygon = geometry as PolygonGeometry; foreach (var segment in polygon.Segments) { Vector centerSegment = (segment.Start + segment.End) / 2.0; double rotation = segment.Offset.Angle(); Vector2 scale = coordinatesTransformer.CreateScaleVector(new Size(1.0, segment.Length), new Size(m_line.Width, m_line.Height)); Vector2 origin = new Vector2(m_line.Width / 2.0f, m_line.Height / 2.0f); spriteBatch.Draw( m_line, coordinatesTransformer.Transform(centerSegment), null, Color.White * 0.8f, (float)Helper.ToRadians(rotation), origin, new Vector2(1, scale.Y), SpriteEffects.None, 0); } } }
/// <summary> /// Create an OData filter expression from an interpolated string. The /// interpolated values will be quoted and escaped as necessary. /// </summary> /// <param name="filter">An interpolated filter string.</param> /// <param name="formatProvider"> /// Format provider used to convert values to strings. /// <see cref="CultureInfo.InvariantCulture"/> is used as a default. /// </param> /// <returns>A valid OData filter expression.</returns> public static string Create(FormattableString filter, IFormatProvider formatProvider) { if (filter == null) { return(null); } formatProvider ??= CultureInfo.InvariantCulture; string[] args = new string[filter.ArgumentCount]; for (int i = 0; i < filter.ArgumentCount; i++) { args[i] = filter.GetArgument(i) switch { // Null null => "null", // Boolean bool x => x.ToString(formatProvider).ToLowerInvariant(), // Numeric sbyte x => x.ToString(formatProvider), byte x => x.ToString(formatProvider), short x => x.ToString(formatProvider), ushort x => x.ToString(formatProvider), int x => x.ToString(formatProvider), uint x => x.ToString(formatProvider), long x => x.ToString(formatProvider), ulong x => x.ToString(formatProvider), decimal x => x.ToString(formatProvider), // Floating point float x => JsonSerialization.Float(x, formatProvider), double x => JsonSerialization.Double(x, formatProvider), // Dates as 8601 with a time zone DateTimeOffset x => JsonSerialization.Date(x, formatProvider), DateTime x => JsonSerialization.Date(x, formatProvider), #if EXPERIMENTAL_SPATIAL // Points GeometryPosition x => EncodeGeometry(x), PointGeometry x => EncodeGeometry(x), // Polygons LineGeometry x => EncodeGeometry(x), PolygonGeometry x => EncodeGeometry(x), #endif // Text string x => Quote(x), char x => Quote(x.ToString(formatProvider)), StringBuilder x => Quote(x.ToString()), // Everything else object x => throw new ArgumentException( $"Unable to convert argument {i} from type {x.GetType()} to an OData literal.") }; } string text = string.Format(formatProvider, filter.Format, args); return(text); }
private void ribbonButton53_Click(object sender, EventArgs e) { if (featurePolygon == null) { Vec3d vec1 = new Vec3d(); vec1.set(0, 40, 0); Vec3d vec2 = new Vec3d(); vec2.set(-60, 40, 0); Vec3d vec3 = new Vec3d(); vec3.set(-60, 60, 0); Vec3d vec4 = new Vec3d(); vec4.set( 0, 60, 0 ); PolygonGeometry polygon = new PolygonGeometry(); polygon.push_back( vec1 ); polygon.push_back( vec2 ); polygon.push_back( vec3 ); polygon.push_back( vec4 ); Feature feature = new Feature(); feature.setGeometry(polygon); featurePolygon = new FeaturePrimitive(); featurePolygon.setFeature( feature ); m_earthRoot.addChild( featurePolygon ); } }
/// <summary> /// 线和多边形的关系 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PInsideTestBtn_Click(object sender, RoutedEventArgs e) { List <Geometry2D> gss = this.drawingKernel.GeometryShapes; List <Line2D> lines = new List <Line2D>(); List <Line2D> vts = new List <Line2D>(); foreach (var g in gss) { if (g is PolygonGeometry) { PolygonGeometry poly = g as DrawingKernel.Geometries.Primitives.PolygonGeometry; g.FillColor = Colors.Azure; g.Opacity = 0.3; poly.Update(); lines.AddRange(poly.Lines); } if (g is DrawingKernel.Geometries.Primitives.LineGeometry) { DrawingKernel.Geometries.Primitives.LineGeometry l = g as DrawingKernel.Geometries.Primitives.LineGeometry; vts.Add(Line2D.Create(l.Start, l.End)); } if (g.GeometryId == "tp") { this.drawingKernel.RemoveGeometryShape(g); } } if (vts != null) { for (int i = 0; i < vts.Count; i++) { var rs = GraphicAlgorithm.LineInsideOfRegion(vts[i], lines, null); if (rs == 1) { DrawingKernel.Geometries.Primitives.LineGeometry lg = new DrawingKernel.Geometries.Primitives.LineGeometry(); lg.Start = vts[i].Start; lg.End = vts[i].End; lg.PenColor = Colors.Blue; lg.GeometryId = "tp"; this.drawingKernel.AddShape(lg); } else if (rs == 0) { DrawingKernel.Geometries.Primitives.LineGeometry lg = new DrawingKernel.Geometries.Primitives.LineGeometry(); lg.PenColor = Colors.Red; lg.Start = vts[i].Start; lg.End = vts[i].End; lg.GeometryId = "tp"; this.drawingKernel.AddShape(lg); } else { DrawingKernel.Geometries.Primitives.LineGeometry lg = new DrawingKernel.Geometries.Primitives.LineGeometry(); lg.PenColor = Colors.Black; lg.Start = vts[i].Start; lg.End = vts[i].End; lg.GeometryId = "tp"; this.drawingKernel.AddShape(lg); } } } }