[Category(TestCategory.Jira)] //TOOLS-7021 public void GetFeaturesInRangeShouldNotThrowForGeometryNull() { var features = GeometryHelper.GetFeaturesInRange(new Coordinate(0, 0), new[] { new Feature { Geometry = null }, new Feature { Geometry = null }, new Feature { Geometry = null } }, 5).ToArray(); Assert.IsEmpty(features); var feature1 = new Feature { Geometry = new Point(0.2, 1) }; var feature2 = new Feature { Geometry = new Point(1, 0, 2) }; features = GeometryHelper.GetFeaturesInRange(new Coordinate(0, 0), new[] { feature1, new Feature { Geometry = null }, feature2 }, 5).ToArray(); Assert.AreEqual(2, features.Count()); Assert.Contains(feature1, features); Assert.Contains(feature2, features); }
/// <summary> /// Draws the content of a <see cref="T:System.Windows.Media.DrawingContext" /> object during the render pass of a <see cref="T:System.Windows.Controls.Panel" /> element. /// </summary> /// <param name="dc">The <see cref="T:System.Windows.Media.DrawingContext" /> object to draw.</param> protected override void OnRender(DrawingContext dc) { base.OnRender(dc); var children = GetCurrentChildren(); if (children.Count < 1) { return; } _hitZones.Clear(); var headerHeight = GetHeaderHeight() + 5; var currentLeft = HorizontalHeaderRenderingOffset; var index = SelectedIndex; // Our "first" element is the element that is selected again var isFirst = true; foreach (var child in children) { var title = SimpleView.GetTitle(child.Child); if (string.IsNullOrEmpty(title)) { title = "Item"; } var ft = isFirst ? new FormattedText(title, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(HeaderFontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal), HeaderFontSize, SelectedHeaderForeground) : new FormattedText(title, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(HeaderFontFamily, FontStyles.Normal, FontWeights.Light, FontStretches.Normal), HeaderFontSize, UnselectedHeaderForeground); dc.DrawText(ft, new Point(currentLeft, 0d)); if (index > Children.Count - 1) { index = 0; // We wrap back to item 0 when we shoot out the back } _hitZones.Add(new PanoramaHeaderHitZone { Index = child.ActualChildIndex, Rect = GeometryHelper.NewRect(currentLeft - 10, 0d, ft.Width + 15, headerHeight) }); currentLeft += ft.Width + 25; index++; isFirst = false; } }
///// <summary> ///// Gets the items that touch the given leaf node. ///// </summary> ///// <param name="leaf">The axis-aligned bounding box.</param> ///// <returns>All items that touch the given AABB.</returns> ///// <remarks> ///// Filtering (see <see cref="BasePartition{T}.Filter"/>) is not applied. ///// </remarks> //private IEnumerable<T> GetOverlaps(Node leaf) //{ // // Note: This method is the same as GetOverlaps(Aabb), except that before checking // // the AABBs we compare the nodes. This removes some unnecessary AABB checks when // // computing self-overlaps. // Debug.Assert(leaf.IsLeaf); // Update(false); // if (_root == null) // yield break; // var stack = DigitalRune.ResourcePools<Node>.Stacks.Obtain(); // stack.Push(_root); // while (stack.Count > 0) // { // Node node = stack.Pop(); // node.IsActive = true; // if (node != leaf && GeometryHelper.HaveContact(node.Aabb, leaf.Aabb)) // { // if (node.IsLeaf) // { // yield return node.Item; // } // else // { // SplitIfNecessary(node); // stack.Push(node.RightChild); // stack.Push(node.LeftChild); // } // } // } // DigitalRune.ResourcePools<Node>.Stacks.Recycle(stack); //} /// <summary> /// Gets the leaf nodes that touch the given AABB. (Same as <see cref="GetOverlaps(Aabb)"/> /// except we directly return the AABB tree node.) /// </summary> /// <param name="aabb">The axis-aligned bounding box.</param> /// <returns>All leaf nodes that touch the given AABB.</returns> /// <remarks> /// Filtering (see <see cref="BasePartition{T}.Filter"/>) is not applied. /// </remarks> private IEnumerable<Node> GetLeafNodes(Aabb aabb) { // Note: This methods is the same as GetOverlaps(Aabb), but instead of returning items we // return the nodes directly. This is used in tree vs. tree tests, so we do not have to // recompute the AABBs of each leaf node. UpdateInternal(); if (_root == null) yield break; var stack = DigitalRune.ResourcePools<Node>.Stacks.Obtain(); stack.Push(_root); while (stack.Count > 0) { Node node = stack.Pop(); node.IsActive = true; if (GeometryHelper.HaveContact(node.Aabb, aabb)) { if (node.IsLeaf) { yield return node; } else { SplitIfNecessary(node); stack.Push(node.RightChild); stack.Push(node.LeftChild); } } } DigitalRune.ResourcePools<Node>.Stacks.Recycle(stack); #else // Avoiding garbage: return GetLeafNodesWork.Create(this, ref aabb); }
private void HandleScrollBarVisibility(double totalHeight, Size availableSize = new Size()) { if (availableSize.Height < .1d && availableSize.Width < .1d) { availableSize = GeometryHelper.NewSize(ActualWidth, ActualHeight); } if (!IsVisible) { if (_scrollVertical.Visibility == Visibility.Visible) { _scrollVertical.Visibility = Visibility.Collapsed; InvalidateMeasure(); InvalidateArrange(); InvalidateVisual(); } return; } if (double.IsInfinity(availableSize.Height)) { _scrollVertical.Visibility = Visibility.Collapsed; } else if (totalHeight > availableSize.Height) { if (_scrollVertical.Visibility != Visibility.Visible) { _scrollVertical.Visibility = Visibility.Visible; InvalidateMeasure(); InvalidateArrange(); InvalidateVisual(); } _scrollVertical.Maximum = totalHeight - availableSize.Height; _scrollVertical.ViewportSize = availableSize.Height; } else { _scrollVertical.Visibility = Visibility.Collapsed; } }
/// <summary> /// Draws the content of a <see cref="T:System.Windows.Media.DrawingContext" /> object during the render pass of a <see cref="T:System.Windows.Controls.Panel" /> element. /// </summary> /// <param name="dc">The <see cref="T:System.Windows.Media.DrawingContext" /> object to draw.</param> protected override void OnRender(DrawingContext dc) { base.OnRender(dc); if (_detailAreaFound) { var iconWidth = ExpandIconWidth - 10; if (iconWidth > _mainRowHeight - 10) { iconWidth = _mainRowHeight - 10; } Brush iconBrush = null; if (DetailIsExpanded) { if (CollapseIcon == null) { if (!string.IsNullOrEmpty(CollapseIconBrushResourceKey)) { CollapseIcon = FindResource(CollapseIconBrushResourceKey) as Brush; } } iconBrush = CollapseIcon; } else { if (ExpandIcon == null) { if (!string.IsNullOrEmpty(ExpandIconBrushResourceKey)) { ExpandIcon = FindResource(ExpandIconBrushResourceKey) as Brush; } } iconBrush = ExpandIcon; } if (iconBrush != null) { dc.DrawRectangle(iconBrush, null, GeometryHelper.NewRect(5, (int)((_mainRowHeight - iconWidth) / 2), iconWidth, iconWidth)); } } }
// Update is called once per frame void Update() { if (m_objectToFollow != null) { // drawing just finished, set camera to look at center of drawing if (!m_clockActive && (m_lineDrawerComp.currentState == LineDrawerComponent.DrawState.Complete)) { m_clockActive = true; //transform.position = new Vector3(m_objectToFollow.transform.position.x, m_objectToFollow.transform.position.y + 10, m_objectToFollow.transform.position.z); // get center of polygon //transform.position = m_lineDrawerComp.m_bezierSplineComponent.GetPoint(0); Vector3[] points = m_lineDrawerComp.m_bezierSplineComponent.GetPoints(); float start = m_lineDrawerComp.getClosedLoopStartPoint(); int startIndex = (int)(start * points.Length); closedLoop = new Vector3[points.Length - startIndex]; int j = 0; for (int i = startIndex; i < points.Length; i++) { closedLoop[j] = points[i]; j++; } Vector3 centroid = GeometryHelper.calculateCentroidPosition(closedLoop); float dist = GeometryHelper.getLongestDistanceInPoly(closedLoop); transform.position = new Vector3(centroid.x, dist, centroid.z); } // drawing deactivated if (m_clockActive && !(m_lineDrawerComp.currentState == LineDrawerComponent.DrawState.Complete)) { transform.position = new Vector3(0, -10, 0); m_clockActive = false; } //transform.position = new Vector3(m_objectToFollow.transform.position.x, m_objectToFollow.transform.position.y + 10, m_objectToFollow.transform.position.z); } }
public IEnumerable <Int32Point> GenFilledRegion(IEnumerable <PrimitivePath> paths, Int32Rect bounds) { var region = new List <Int32Point>(); if (_fillColor != null) { var curx = bounds.X; var cury = bounds.Y; var right = curx + bounds.Width; var bottom = cury + bounds.Height; switch (_shape) { case Shape.Rect: for (int i = curx + 1; i < right; i++) { for (int j = cury + 1; j < bottom; j++) { region.Add(new Int32Point(i, j)); } } break; default: var primitives = GeometryHelper._GetCustomGeometryPrimitives(this); for (int i = curx + 1; i < right; i++) { for (int j = cury + 1; j < bottom; j++) { var p = new Int32Point(i, j); if (GeometryHelper.Contains(primitives, p)) { region.Add(p); } } } break; } } return(region); }
public void SplitTest() { var first = LucidLine.Create(new IPoint[] { new LucidPoint(0, 0), new LucidPoint(5, 5), new LucidPoint(10, 9) }); var second = LucidLine.Create(new IPoint[] { new LucidPoint(-1, 4), new LucidPoint(5, 0) }); var parts = GeometryHelper.Split(first, second); Assert.AreEqual(2, parts.Count()); Assert.AreEqual(2, parts.First().Vertices.Count()); Assert.AreEqual(3, parts.ElementAt(1).Vertices.Count()); second.Translate(-10, -10); parts = GeometryHelper.Split(first, second); Assert.AreEqual(1, parts.Count()); Assert.AreEqual(3, parts.First().Vertices.Count()); }
public void SerializationBinary() { // Create a dummy mesh. var randomPoints = Enumerable.Range(0, 100) .Select(i => RandomHelper.Random.NextVector3F(-100, 100)); var mesh = GeometryHelper.CreateConvexHull(randomPoints); VertexAdjacency vertexAdjacency = new VertexAdjacency(mesh); // Serialize object. var stream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(stream, vertexAdjacency); // Deserialize object. stream.Position = 0; var deserializer = new BinaryFormatter(); var vertexAdjacency2 = (VertexAdjacency)deserializer.Deserialize(stream); Assert.That(vertexAdjacency2.ListIndices, Is.EqualTo(vertexAdjacency.ListIndices)); Assert.That(vertexAdjacency2.Lists, Is.EqualTo(vertexAdjacency.Lists)); }
public static void SetDx(Edge edge) { edge.Delta = new IntPoint( edge.Top.X - edge.Bottom.X, edge.Top.Y - edge.Bottom.Y); // Is the edge horizontal? if (edge.Delta.Y == 0) { edge.Dx = GeometryHelper.GetDxSignedLength(edge.Bottom, edge.Top); edge.IsHorizontal = true; edge.IsVertical = false; } else { edge.Dx = (double)edge.Delta.X / edge.Delta.Y; edge.IsHorizontal = false; edge.IsVertical = edge.Delta.X == 0; } }
public void GetClosestPointsSegmentPlane() { Vector3 p0, p1; bool haveContact; haveContact = GeometryHelper.GetClosestPoints(new Plane(new Vector3(0, 1, 0), 1), new LineSegment(new Vector3(0, 0, 0), new Vector3(1, 0, 0)), out p0, out p1); Assert.AreEqual(false, haveContact); // Plane is really a plane - no half space. Assert.AreEqual(0, p1.Y); Assert.AreEqual(0, p1.Z); Assert.AreEqual(1, p0.Y); Assert.AreEqual(p0.X, p1.X); Assert.AreEqual(p0.Z, p1.Z); Assert.IsTrue(p1.X >= 0 && p1.X <= 1); haveContact = GeometryHelper.GetClosestPoints(new Plane(new Vector3(0, 1, 0), 1), new LineSegment(new Vector3(2, 2, 0), new Vector3(3, 4, 0)), out p0, out p1); Assert.AreEqual(false, haveContact); Assert.AreEqual(new Vector3(2, 2, 0), p1); Assert.AreEqual(new Vector3(2, 1, 0), p0); haveContact = GeometryHelper.GetClosestPoints(new Plane(new Vector3(0, 1, 0), 1), new LineSegment(new Vector3(2, 4, 0), new Vector3(3, 2, 0)), out p0, out p1); Assert.AreEqual(false, haveContact); Assert.AreEqual(new Vector3(3, 2, 0), p1); Assert.AreEqual(new Vector3(3, 1, 0), p0); haveContact = GeometryHelper.GetClosestPoints(new Plane(new Vector3(0, 1, 0), 1), new LineSegment(new Vector3(2, 2, 0), new Vector3(3, 1, 0)), out p0, out p1); Assert.AreEqual(true, haveContact); Assert.AreEqual(new Vector3(3, 1, 0), p1); Assert.AreEqual(new Vector3(3, 1, 0), p0); haveContact = GeometryHelper.GetClosestPoints(new Plane(new Vector3(0, 1, 0), 1), new LineSegment(new Vector3(2, 2, 0), new Vector3(4, 0, 0)), out p0, out p1); Assert.AreEqual(true, haveContact); Assert.AreEqual(new Vector3(3, 1, 0), p0); Assert.AreEqual(new Vector3(3, 1, 0), p1); }
public bool TryPutNextRectangle(Size rectangleSize) { try { if (rectangleSize.Width > Width || rectangleSize.Height > Height) { throw new ArgumentException(); } if (Rectangles.Count == 0) { var rectangleCenter = new Point(rectangleSize.Width / 2, rectangleSize.Height / 2); var rectangleLocation = new Point(CenterPoint.X - rectangleCenter.X, CenterPoint.Y - rectangleCenter.Y); var firstRectangle = new Rectangle(rectangleLocation, rectangleSize); Rectangles.Add(firstRectangle); return(true); } while (true) { var nextPoint = Spiral.GetNextPoint(); if (GeometryHelper.IsIncorrectPoint(nextPoint, Width, Height)) { continue; } var currentRectangle = new Rectangle(nextPoint, rectangleSize); if (IsPossiblePutRectangle(currentRectangle)) { currentRectangle = ShiftRectangleToCenter(currentRectangle); Rectangles.Add(currentRectangle); return(true); } } } catch { return(false); } }
/// <summary> /// Removes duplicate vertices. /// </summary> /// <param name="vertexPositionTolerance"> /// The vertex position tolerance. If the distance between two vertices is less than this value, /// the vertices are merged. /// </param> /// <returns>The number of removed vertices.</returns> /// <remarks> /// <para> /// Vertex welding is also called vertex shifting or vertex merging. Vertices near each other /// are merged to a single vertex to remove duplicate, redundant vertices. /// </para> /// </remarks> /// <example> /// The following examples shows how to apply vertex welding when building a complex mesh. /// <code lang="csharp"> /// <![CDATA[ /// // Building a complex triangle mesh using vertex welding. /// TriangleMesh mesh = new TriangleMesh(); /// /// // Add triangles: /// mesh.AddTriangle(new Triangle(v0, v1, v2), false); /// mesh.AddTriangle(new Triangle(v4, v1, v0), false); /// ... /// /// // After all vertices are added, remove duplicates. /// mesh.WeldVertices(0.001f); /// ]]> /// </code> /// </example> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="vertexPositionTolerance"/> is negative or 0. /// </exception> public int WeldVertices(float vertexPositionTolerance) { if (Vertices == null || Indices == null) { return(0); } int[] vertexRemap; int numberOfMergedVertices = GeometryHelper.MergeDuplicatePositions(Vertices, vertexPositionTolerance, out vertexRemap); if (numberOfMergedVertices > 0) { // Remap Indices. int numberOfIndices = Indices.Count; for (int i = 0; i < numberOfIndices; i++) { Indices[i] = vertexRemap[Indices[i]]; } } return(numberOfMergedVertices); }
private void BuildLookupTable() { // Compute center and radius of the sphere where points are sampled. float polyhedronRadius; Vector3F center; GeometryHelper.ComputeBoundingSphere(_vertices, out polyhedronRadius, out center); float radius = polyhedronRadius * RadiusFactor; // Create directional lookup table. (The poles are excluded.) _directionLookupTable = new DirectionalLookupTableUInt16F(LookupTableWidth); // Sample points on the sphere and determine the indices of the closest vertices on the // convex polyhedron. The indices of the closest vertices are the entries in the lookup // table. foreach (Vector3F direction in _directionLookupTable.GetSampleDirections()) { direction.Normalize(); Vector3F samplePoint = direction * radius; _directionLookupTable[direction] = GetClosestVertex(samplePoint); } }
public double Calculate() { if (description.UpSpine == null || description.DownSpine == null || description.storage == null) { throw new ArgumentNullException("Fill all properties"); } if (!description.storage.ContainDescription(description.UpSpine) || !description.storage.ContainDescription(description.DownSpine)) { throw new ArgumentException("Spine not in storage"); } var upspine = description.storage.GetDescription(description.UpSpine); var downspine = description.storage.GetDescription(description.DownSpine); var up_point = new PointF(upspine.DownLeft.X, upspine.DownLeft.Y); var down_point = new PointF(downspine.UpLeft.X, downspine.UpLeft.Y); var upline = GeometryHelper.GetLineFromPoints(up_point, down_point); var downline = downspine.UpperLine; return(GeometryHelper.AngleBetweenLines(upline, downline)); }
public override void Update(GameTime gameTime) { // Left mouse button --> Add vertex. if (InputService.IsPressed(MouseButtons.Left, false)) { // Add vertex. Vector2F position = InputService.MousePosition; _mesh.Vertices.Add(new Vector3F(position.X, position.Y, 0)); // Use GeometryHelper to compute indices of triangulated polygon. _mesh.Indices.Clear(); int numberOfTriangles = GeometryHelper.Triangulate(_mesh.Vertices, _mesh.Indices); #if !WINDOWS_PHONE && !XBOX Trace.WriteLine("Number of triangles: " + numberOfTriangles); #endif var debugRenderer = GraphicsScreen.DebugRenderer2D; debugRenderer.Clear(); for (int i = 0; i < _mesh.Vertices.Count; i++) { debugRenderer.DrawPoint(_mesh.Vertices[i], Color.Black, true); } for (int i = 0; i < _mesh.Vertices.Count - 1; i++) { debugRenderer.DrawLine(_mesh.Vertices[i], _mesh.Vertices[i + 1], Color.Black, false); } if (numberOfTriangles > 0) { // Draw fill triangles. debugRenderer.DrawTriangles(_mesh, Pose.Identity, Vector3F.One, new Color(1.0f, 0.0f, 0.0f, 0.25f), false, false); // Draw wireframe. debugRenderer.DrawTriangles(_mesh, Pose.Identity, Vector3F.One, new Color(1.0f, 0.0f, 0.0f, 1.0f), true, false); } } }
/// <summary> /// Winding number test for a point in a polygon. /// </summary> /// See more info about the algorithm here: http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm /// <param name="polygon">The polygon.</param> /// <param name="point">The point to be tested.</param> /// <returns>-1 if the winding number is zero and the point is outside /// the polygon, 1 if the point is inside the polygon, and 0 if the point /// is on the polygons edge.</returns> public static int PointInPolygon(Polygon polygon, Point point) { // Winding number int wn = 0; Vertices polyVertices = polygon.Vertices; // Iterate through polygon's edges for (int i = 0; i < polyVertices.Count; i++) { // Get points Point p1 = polyVertices[i]; Point p2 = polyVertices[polyVertices.NextIndex(i)]; // Test if a point is directly on the edge Point edge = p2 - p1; double area = GeometryHelper.Area(ref p1, ref p2, ref point); if (Math.Abs(area - 0f) < MathHelper.EpsilonD && Point.Dot(point - p1, edge) >= 0 && Point.Dot(point - p2, edge) <= 0) { return(0); } // Test edge for intersection with ray from point if (p1.Y <= point.Y) { if (p2.Y > point.Y && area > 0) { ++wn; } } else { if (p2.Y <= point.Y && area < 0) { --wn; } } } return(wn); }
/// <summary> /// Clones points and parts but allows to set different geometry type. /// The method doesn't check if the result geometry is valid. /// </summary> public IGeometry Clone(GeometryType type, ZValueType zValue = ZValueType.None) { var shapeType = GeometryHelper.GeometryType2ShpType(type, zValue); var shp = new Shape(); shp.Create(shapeType); for (int i = 0; i < _shape.NumParts; i++) { int pointIndex = _shape.Part[i]; shp.InsertPart(i, ref pointIndex); } var g = new Geometry(shp); foreach (var pnt in Points) { g.Points.Add(pnt.Clone()); } return(g); }
protected override bool OnNext(out T current) { while (_stack.Count > 0) { var node = _stack.Pop(); if (GeometryHelper.HaveContact(node.Aabb, _ray.Origin, _rayDirectionInverse, _ray.Length, _epsilon)) { if (node.IsLeaf) { current = node.Item; return(true); } else { _stack.Push(node.RightChild); _stack.Push(node.LeftChild); } } } current = default(T); return(false); }
protected override bool OnNext(out Node current) { while (_stack.Count > 0) { Node node = _stack.Pop(); if (GeometryHelper.HaveContact(node.Aabb, _aabb)) { if (node.IsLeaf) { current = node; return(true); } else { _stack.Push(node.RightChild); _stack.Push(node.LeftChild); } } } current = default(Node); return(false); }
public void NormalizePolygon() { var polygonWithRedundantPoints = new Polygon( new LinearRing(new[] { new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(3, 1), new Coordinate(4, 0), new Coordinate(2, 0), new Coordinate(2, 0), new Coordinate(0, 0) })); var expectedPolygon = new Polygon( new LinearRing(new[] { new Coordinate(0, 0), new Coordinate(2, 2), new Coordinate(4, 0), new Coordinate(0, 0) })); var actualPolygon = GeometryHelper.NormalizeGeometry(polygonWithRedundantPoints); Assert.AreEqual(expectedPolygon.Coordinates.Length, actualPolygon.Coordinates.Length); Assert.AreEqual(expectedPolygon, actualPolygon); }
private void TestGetOverlaps2(ISpatialPartition <int> partition) { var aabb = GetRandomAabb(); var ray = new Ray(aabb.Minimum, aabb.Extent.Normalized, aabb.Extent.Length); ray.Direction = RandomHelper.Random.NextVector3(-1, 1).Normalized; // Compute desired result. var desiredResults = new List <int>(); foreach (var testObject in _testObjects) { if (GeometryHelper.HaveContact(testObject.Aabb, ray)) { desiredResults.Add(testObject.Id); } } var results = partition.GetOverlaps(ray).ToList(); CompareResults(desiredResults, results, "GetOverlaps(Ray) returns different number of results."); }
protected override bool OnNext(out T current) { while (_stack.Count > 0) { Node node = _stack.Pop(); if (node != _leaf && GeometryHelper.HaveContact(node.Aabb, _leaf.Aabb)) { if (node.IsLeaf) { current = node.Item; return true; } else { _stack.Push(node.RightChild); _stack.Push(node.LeftChild); } } } current = default(T); return false; }
public _Arc(PointF center, float radius, float startRadian, float endRadian, PenF pen, Color?fillColor = null, bool isReverse = false) { _pen = pen; _fillColor = fillColor; _bounds = RectF.Empty; Center = center; Radius = radius; StartRadian = startRadian; EndRadian = endRadian; _isReverse = isReverse; if (IsCicle) { _bounds = new RectF(new PointF(center.X - radius, center.Y - radius), new PointF(center.X + radius, center.Y + radius)); } else { _bounds = GeometryHelper.CalcBounds(this); } }
/// <inheritdoc/> public override IEnumerable <T> GetOverlaps(Aabb aabb) { UpdateInternal(); #if !POOL_ENUMERABLES if (_root == null) { yield break; } var stack = DigitalRune.ResourcePools <Node> .Stacks.Obtain(); stack.Push(_root); while (stack.Count > 0) { Node node = stack.Pop(); node.IsActive = true; if (GeometryHelper.HaveContact(node.Aabb, aabb)) { if (node.IsLeaf) { yield return(node.Item); } else { SplitIfNecessary(node); stack.Push(node.RightChild); stack.Push(node.LeftChild); } } } DigitalRune.ResourcePools <Node> .Stacks.Recycle(stack); #else // Avoiding garbage: return(GetOverlapsWork.Create(this, ref aabb)); #endif }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { //1 divide the brep by the Z components of the grid (get Z values on plane of the grid //2 intersect the grid for reach Z value -> planar surface the results //3 check for each pixel if it is closer than the var geometry = DA.FetchList <IGH_GeometricGoo>(0); var pg = DA.Fetch <PixelGrid2D>(1); pg = (PixelGrid2D)pg.Clone(); if (pg == null || !pg.IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The (input) voxelgrid was invalid"); return; } var geometryIndex = new Dictionary <int, IGH_GeometricGoo>(); for (int i = 0, count = geometry.Count; i < count; i++) { geometryIndex.Add(i, geometry[i]); } var ptList = GeometryHelper.TryCastGeometry <Point3d>(geometryIndex, false); var curveList = GeometryHelper.TryCastGeometry <Curve>(geometryIndex, false); foreach (var pt in ptList.Values) { AddPoint3d(pg, pt); } foreach (var c in curveList.Values) { AddCurve(pg, c); } DA.SetData(0, new GH_PixelGrid((PixelGrid2D)pg.Clone())); }
private IEnumerable<int> GetOverlapsImpl(Aabb aabb) { // This method avoids the Update() call! if (_numberOfItems == 0) yield break; // ----- Stackless traversal of tree: // The AABB tree nodes are stored in preorder traversal order. We can visit them in linear // order. The EscapeOffset of each node can be used to skip a subtree. int index = 0; while (index < _nodes.Length) { Node node = _nodes[index]; bool haveContact = GeometryHelper.HaveContact(GetAabb(node), aabb); if (haveContact && node.IsLeaf) yield return node.Item; if (haveContact || node.IsLeaf) { // Given AABB intersects the internal AABB tree node or the node is a leaf. // Continue with next item in preorder traversal order. index++; } else { // Given AABB does not touch the internal AABB tree node. // --> Skip the subtree. index += node.EscapeOffset; } } #else // Avoiding garbage: return GetOverlapsWork.Create(this, ref aabb); }
public void DrawArc(PenF pen, PointF center, float radius, float startAngle, float endAngle, bool isClockwise) { if (startAngle == endAngle) { return; } if (!isClockwise) { MathUtil.Switch(ref startAngle, ref endAngle); } pen.Color = _transform.Transform(pen.Color); GeometryHelper.FormatAngle(ref startAngle); GeometryHelper.FormatAngle(ref endAngle); var startRadian = GeometryHelper.GetRadian(startAngle); var endRadian = GeometryHelper.GetRadian(endAngle); if (!_transform.IsIdentity) { var start = new PointF(center.X + radius * (float)Math.Cos(startRadian), center.Y + radius * (float)Math.Sin(startRadian)); var end = new PointF(center.X + radius * (float)Math.Cos(endRadian), center.Y + radius * (float)Math.Sin(endRadian)); start = _transform.Transform(start); end = _transform.Transform(end); center = _transform.Transform(center); radius = (start - center).Length; startRadian = (float)Math.Atan2(start.Y - center.Y, start.X - center.X); endRadian = (float)Math.Atan2(end.Y - center.Y, end.X - center.X); GeometryHelper.FormatRadian(ref startRadian); GeometryHelper.FormatRadian(ref endRadian); } _primitives.Add(new _Arc(center, radius, startRadian, endRadian, pen, null, !isClockwise)); }
private void TestGetOverlaps3(ISpatialPartition <int> partition) { if (!partition.EnableSelfOverlaps) { return; } // Compute desired result. var desiredResults = new List <Pair <int> >(); for (int i = 0; i < _testObjects.Count; i++) { var a = _testObjects[i]; for (int j = i + 1; j < _testObjects.Count; j++) { var b = _testObjects[j]; if (a != b) { if (partition.Filter == null || partition.Filter.Filter(new Pair <int>(a.Id, b.Id))) { if (GeometryHelper.HaveContact(a.Aabb, b.Aabb)) { desiredResults.Add(new Pair <int>(a.Id, b.Id)); } } } } } var results = partition.GetOverlaps().ToList(); if (desiredResults.Count != results.Count) { var distinct = results.Except(desiredResults).ToList(); } CompareResults(desiredResults, results, "GetOverlaps() returns different number of results."); }
/// <summary> /// Draws the given reference line onto the mat /// </summary> public void DrawReferenceLine(Mat image, DetectedItemArguments refLineArgs, out double lengthOfCoordinate) { // Calculate distance and length of coordinate first! var distance = GeometryHelper.Distance( new System.Windows.Point(refLineArgs.X, refLineArgs.Y), new System.Windows.Point(refLineArgs.Width, refLineArgs.Height)); lengthOfCoordinate = refLineArgs.ActualLength / distance; coordinateLength = lengthOfCoordinate; // Draw the image ref line onto a every frame! var widthRatio = (double)image.Width / (double)refLineArgs.CanvasSize.X; var heightRatio = (double)image.Height / (double)refLineArgs.CanvasSize.Y; var refPoint1 = new OpenCvSharp.Point(refLineArgs.X * widthRatio, refLineArgs.Y * heightRatio); var refPoint2 = new OpenCvSharp.Point(refLineArgs.Width * widthRatio, refLineArgs.Height * heightRatio); Cv2.Line(image, refPoint1, refPoint2, Scalar.Lime, 2); _referenceLine = new Line() { X1 = refPoint1.X, Y1 = refPoint1.Y, X2 = refPoint2.X, Y2 = refPoint2.Y }; // Get the center of the line and draw the actual length into the center. var center = GeometryHelper.GetCenterOfLine( new System.Windows.Point(refPoint1.X, refPoint1.Y), new System.Windows.Point(refPoint2.X, refPoint2.Y)); DrawTextblockWithBackground( image, center, $"{string.Format("{0:0.00}", refLineArgs.ActualLength)}m", Scalar.Lime ); }
public void Setup() { _geometryHelper = new GeometryHelper(); }