Example #1
0
        /// <summary>
        /// Get the vertex at the given position or, if it does not exist, construct a new vertex
        /// </summary>
        /// <param name="vector2"></param>
        /// <returns></returns>
        public Vertex <TVTag, TETag, TFTag> GetOrConstructVertex(Vector2 vector2)
        {
            Contract.Ensures(Contract.Result <Vertex <TVTag, TETag, TFTag> >() != null);
            Contract.Ensures(!Contract.Result <Vertex <TVTag, TETag, TFTag> >().IsDeleted);

            //Select candidate vertices within range (square query)
            var candidates = _vertices.Intersects(new BoundingRectangle(vector2 - new Vector2(VERTEX_EPSILON / 2), vector2 + new Vector2(VERTEX_EPSILON / 2)));

            //Select best candidate (nearest)
            float bestDistance = float.MaxValue;
            Vertex <TVTag, TETag, TFTag> best = null;

            foreach (var candidate in candidates)
            {
                var d = Vector2.DistanceSquared(candidate.Position, vector2);
                if (d < bestDistance && d < VERTEX_EPSILON * VERTEX_EPSILON)
                {
                    bestDistance = d;
                    best         = candidate;
                }
            }

            //If we found a suitable one, return it
            if (best != null)
            {
                return(best);
            }

            //Otherwise create a new vertex and return that
            var v = new Vertex <TVTag, TETag, TFTag>(this, vector2);

            _vertices.Insert(new BoundingRectangle(v.Position, v.Position).Inflate(0.1f), v);
            return(v);
        }
Example #2
0
File: Map.cs Project: CarimA/jrpg
        public void LoadBoundaryData()
        {
            foreach (var objectLayer in MapData.ObjectLayers)
            {
                foreach (var obj in objectLayer.Objects)
                {
                    if (objectLayer.Name.Contains("collision") && obj is TiledMapRectangleObject)
                    {
                        if (obj is TiledMapPolygonObject)
                        {
                            Point2[] points = (obj as TiledMapPolygonObject).Points;

                            List <Vector2> newPoints = points.Select(point => new Vector2(point.X, point.Y)).ToList();
                            World.Insert(new Polygon(obj.Position, newPoints));
                        }
                        else if (obj is TiledMapRectangleObject)
                        {
                            TiledMapRectangleObject rect = obj as TiledMapRectangleObject;
                            Polygon p = ShapePrimitives.Rectangle(obj.Position, (obj as TiledMapRectangleObject).Size.Width, (obj as TiledMapRectangleObject).Size.Height);
                            World.Insert(p);
                        }
                        else
                        {
                            throw new Exception("uhh something's missing :>");
                        }
                    }

                    if (objectLayer.Name.Contains("scripts") && obj is TiledMapRectangleObject)
                    {
                        Vector2 pos  = (obj as TiledMapRectangleObject).Position;
                        Size2   size = (obj as TiledMapRectangleObject).Size;

                        Rectangle rect = new Rectangle(
                            (int)(pos.X / MapData.TileWidth),
                            (int)(pos.Y / MapData.TileHeight),
                            (int)(size.Width / MapData.TileWidth),
                            (int)(size.Height / MapData.TileHeight));

                        for (int x = rect.Left; x < rect.Right; x++)
                        {
                            for (int y = rect.Top; y < rect.Bottom; y++)
                            {
                                InteractScripts.Add(new MapObject <ScriptData>()
                                {
                                    X    = x,
                                    Y    = y,
                                    Data = new ScriptData()
                                    {
                                        Script = obj.Name
                                    }
                                });
                            }
                        }
                    }

                    // todo: handle scripts, warps, etc etc
                }
            }
        }
Example #3
0
        public void AssertThat_Intersects_FindsItemInBounds()
        {
            _tree.Insert(new BoundingRectangle(new Vector2(10, 10), new Vector2(20, 20)), "A");
            _tree.Insert(new BoundingRectangle(new Vector2(90, 90), new Vector2(80, 80)), "B");

            var results = _tree.Intersects(new BoundingRectangle(new Vector2(0, 0), new Vector2(20, 20))).ToArray();

            Assert.AreEqual(1, results.Length);
            Assert.AreEqual("A", results.Single());
        }
Example #4
0
        public void CreateAndInsertUnderLimit()
        {
            var quadtree = new Quadtree <MockQuadtreeItem>(new RectangleF(0, 0, 100, 100));

            quadtree.Insert(new MockQuadtreeItem(1, new RectangleF(0, 0, 1, 1)));
            quadtree.Insert(new MockQuadtreeItem(2, new RectangleF(1, 1, 2, 2)));

            var allItems = quadtree.FindIntersecting(quadtree.Bounds).ToList();

            Assert.Equal(2, allItems.Count);
        }
Example #5
0
        public void InsertAndRemoveManyOverlapping()
        {
            var items = new List <MockQuadtreeItem>
            {
                new MockQuadtreeItem(1, new RectangleF(0, 0, 1, 1)),
                new MockQuadtreeItem(2, new RectangleF(0, 0, 1.25f, 1.25f)),
                new MockQuadtreeItem(3, new RectangleF(0, 0, 1.5f, 1.5f)),
                new MockQuadtreeItem(4, new RectangleF(0, 0, 1.75f, 1.75f)),
                new MockQuadtreeItem(5, new RectangleF(0, 0, 2f, 2f)),
            };

            var quadtree = new Quadtree <MockQuadtreeItem>(new RectangleF(0, 0, 10, 10));

            foreach (var item in items)
            {
                quadtree.Insert(item);
            }

            Assert.Equal(5, quadtree.FindIntersecting(quadtree.Bounds).Count());

            foreach (var item in items)
            {
                quadtree.Remove(item);
            }

            Assert.Empty(quadtree.FindIntersecting(quadtree.Bounds));
        }
Example #6
0
        internal void insertRoad(Road road)
        {
            if (road == null)
            {
                return;
            }
            if (road.isBeManaged)
            {
                return;
            }

            // Do not insert this road if there's a reversed one.
            var reversedRoad = road.reverse();

            if (reversedRoads.Contains(reversedRoad) ||
                reversedRoads.Contains(road))
            {
                return;
            }

            roads.Insert(road.Bound, road);
            road.isBeManaged = true;
            reversedRoads.Add(reversedRoad);

            insertJunction(road.start, road);
            insertJunction(road.end, road);
        }
Example #7
0
        /// <summary>
        /// Snaps the points to the network coverage, given the tolerance. Existing locations/values will be cleared only
        /// when there are new points mapped to that branch.
        /// </summary>
        /// <param name="pointValuePairs"></param>
        /// <param name="networkCoverage"></param>
        /// <param name="tolerance"></param>
        public static void SnapToCoverage(IEnumerable <Tuple <IPoint, double> > pointValuePairs,
                                          INetworkCoverage networkCoverage, double tolerance)
        {
            var tree = new Quadtree <IBranch>();

            networkCoverage.Network.Branches.ForEach(b => tree.Insert(b.Geometry.EnvelopeInternal, b));

            // match points to branch buffers
            var locations = new List <Tuple <INetworkLocation, double> >();

            foreach (var pointValue in pointValuePairs)
            {
                var envelope = pointValue.Item1.EnvelopeInternal;
                envelope.ExpandBy(tolerance);
                var branches = tree.Query(envelope).Cast <IBranch>();

                var location = MapPointToClosestBranch(pointValue.Item1, branches, tolerance);
                if (location != null)
                {
                    locations.Add(new Tuple <INetworkLocation, double>(location, pointValue.Item2));
                }
            }

            // remove values for all branches that have new values imported
            var branchesToClear = locations.Select(l => l.Item1.Branch).Distinct();

            branchesToClear.ForEach(b => NetworkHelper.ClearLocations(networkCoverage, b));

            // add new values/locations to coverage
            locations.ForEach(l => networkCoverage[l.Item1] = l.Item2);
        }
 internal void AddRange(IEnumerable <GeometryData> sourceData)
 {
     foreach (var data in sourceData)
     {
         Index.Insert(data.Geom.EnvelopeInternal, data);
     }
 }
Example #9
0
 void FillQuadTree()
 {
     for (int i = 0; i < Objects.Count; i++)
     {
         quad.Insert(Objects[i]);
     }
 }
        private void GenerateFaces()
        {
            var xValues = x.Values;
            var yValues = y.Values;

            faces = new MultiDimensionalArray <IGridFace>(new [] { Size1 - 1, Size2 - 1 });

            // build quad tree
            facesIndex = new Quadtree();

            for (var i = 0; i < Size1 - 1; i++)
            {
                for (var j = 0; j < Size2 - 1; j++)
                {
                    var points = new Coordinate[5];
                    points[0] = new Coordinate(xValues[i, j], yValues[i, j]);
                    points[1] = new Coordinate(xValues[i, j + 1], yValues[i, j + 1]);
                    points[2] = new Coordinate(xValues[i + 1, j + 1], yValues[i + 1, j + 1]);
                    points[3] = new Coordinate(xValues[i + 1, j], yValues[i + 1, j]);
                    points[4] = points[0];

                    var face = new Face {
                        Geometry = new Polygon(new LinearRing(points)), I = i, J = j, Index = MultiDimensionalArrayHelper.GetIndex1d(new[] { i, j }, xValues.Stride), Grid = this
                    };
                    Faces[i, j] = face;
                    facesIndex.Insert(face.Geometry.EnvelopeInternal, face);
                }
            }
        }
Example #11
0
        public Test(string name) : base(name)
        {
            Tables   = new List <Table>();
            entities = new List <RelatusObject>();
            Player   = new Player(200, 0);
            entities.Add(Player);

            quad = new Quad(0, 0, WindowManager.PixelWidth * 2, WindowManager.PixelHeight * 2)
            {
                Color = Color.Gray
            };
            quad.ApplyChanges();

            for (int y = 0; y < WindowManager.PixelHeight * 2 / 41; y++)
            {
                for (int x = 0; x < WindowManager.PixelWidth * 2 / 139; x++)
                {
                    if (x % 2 == 0 && y % 3 == 0)
                    {
                        Tables.Add(new Table(139 * x, 41 * y, Tables.Count));
                    }
                }
            }

            TableQuadtree = new Quadtree <Table>(new RectangleF(0, 0, WindowManager.PixelWidth * 2, WindowManager.PixelHeight * 2), 256);

            foreach (Table t in Tables)
            {
                TableQuadtree.Insert(t);
                entities.Add(t);
            }

            entities.Add(new Worker(0, 0, true, true));
        }
Example #12
0
        void BuildQuadtree()
        {
            Quadtree.Clear();
            if (agents.Count > 0)
            {
                //GG
                //Rect bounds = Rect.MinMaxRect(agents[0].position.x, agents[0].position.y, agents[0].position.x, agents[0].position.y);
                VRect bounds = VRect.MinMaxRect(agents[0].position.x, agents[0].position.y, agents[0].position.x, agents[0].position.y);
                for (int i = 1; i < agents.Count; i++)
                {
                    //GG

                    /*Vector2 p = agents[i].position;
                     * bounds = Rect.MinMaxRect(Mathf.Min(bounds.xMin, p.x), Mathf.Min(bounds.yMin, p.y), Mathf.Max(bounds.xMax, p.x), Mathf.Max(bounds.yMax, p.y));*/
                    VInt2 p = agents[i].position;
                    bounds = VRect.MinMaxRect(Mathf.Min(bounds.xMin, p.x), Mathf.Min(bounds.yMin, p.y), Mathf.Max(bounds.xMax, p.x), Mathf.Max(bounds.yMax, p.y));
                }
                Quadtree.SetBounds(bounds);

                for (int i = 0; i < agents.Count; i++)
                {
                    Quadtree.Insert(agents[i]);
                }

                //quadtree.DebugDraw ();
            }

            Quadtree.CalculateSpeeds();
        }
Example #13
0
        static TopoData BuildTopology()
        {
            var polylineIds = CadUtils.FindAllPolylines(Application.DocumentManager.MdiActiveDocument);
            var datebase    = Application.DocumentManager.MdiActiveDocument.Database;

            using (var tr = datebase.TransactionManager.StartTransaction())
            {
                // 读入多边形数据
                var reader   = new DwgReader();
                var polygons = new Dictionary <ObjectId, IPolygon>();
                var quadtree = new Quadtree <IGeometry>();

                // 构建拓扑
                foreach (ObjectId polylineId in polylineIds)
                {
                    var polygon = reader.ReadEntityAsPolygon(tr, polylineId) as IPolygon;
                    if (polygon != null)
                    {
                        polygons.Add(polylineId, polygon);
                        quadtree.Insert(polygon.EnvelopeInternal, polygon);
                    }
                }

                tr.Commit();

                return(new TopoData()
                {
                    Polygons = polygons,
                    Quadtree = quadtree,
                    Reader = reader,
                });
            }
        }
Example #14
0
        private void Awake()
        {
            var boundaries = new Rect(
                0.0f,
                0.0f,
                2000.0f,
                2000.0f
                );

            var tree = new Quadtree <Vector3>(boundaries);

            var positions = new Vector3[1000000];

            // generate random vectors
            for (var index = 0; index < positions.Length; index++)
            {
                positions[index] = new Vector3(
                    Random.value * 2000.0f,
                    Random.value * 2000.0f,
                    Random.value * 2000.0f
                    );
            }

            // fill tree
            Measure.DebugLogTime("Fill", () =>
            {
                for (var index = 0; index < positions.Length; index++)
                {
                    var position = positions[index];
                    tree.Insert(position, position);
                }
            });

            // query tree
            Measure.DebugLogTime("Query", () =>
            {
                for (var index = 0; index < positions.Length; index++)
                {
                    var range = new Rect(
                        Random.value * 2000.0f,
                        Random.value * 2000.0f,
                        10.0f,
                        10.0f
                        );
                    tree.Find(range);
                }
            });

            // empty tree
            Measure.DebugLogTime("Remove", () =>
            {
                for (var index = 0; index < positions.Length; index++)
                {
                    var position = positions[index];
                    tree.Remove(position, position);
                }
            });
        }
        private void Awake()
        {
            var boundaries = new Rect(
                0.0f,
                0.0f,
                2000.0f,
                2000.0f
                );

            var tree = new Quadtree<Vector3>(boundaries);

            var positions = new Vector3[1000000];

            // generate random vectors
            for (var index = 0; index < positions.Length; index++)
            {
                positions[index] = new Vector3(
                    Random.value * 2000.0f,
                    Random.value * 2000.0f,
                    Random.value * 2000.0f
                    );
            }

            // fill tree
            Measure.DebugLogTime("Fill", () =>
            {
                for (var index = 0; index < positions.Length; index++)
                {
                    var position = positions[index];
                    tree.Insert(position, position);
                }
            });

            // query tree
            Measure.DebugLogTime("Query", () =>
            {
                for (var index = 0; index < positions.Length; index++)
                {
                    var range = new Rect(
                        Random.value * 2000.0f,
                        Random.value * 2000.0f,
                        10.0f,
                        10.0f
                        );
                    tree.Find(range);
                }
            });

            // empty tree
            Measure.DebugLogTime("Remove", () =>
            {
                for (var index = 0; index < positions.Length; index++)
                {
                    var position = positions[index];
                    tree.Remove(position, position);
                }
            });
        }
 private void BuildQuadtree()
 {
     _quadtree = new Quadtree();
     for (int i = 0; i < _rings.Count; i++)
     {
         LinearRing ring = (LinearRing)_rings[i];
         Envelope   env  = ring.GetEnvelopeInternal();
         _quadtree.Insert(env, ring);
     }
 }
Example #17
0
 protected override void AddCells_internal()
 {
     foreach (var cell in CellList)
     {
         var cellPos = cell.PositionWithSize;
         //Console.WriteLine(cell.Position);
         NTSQuadTreeCellTree.Insert(new Envelope(cellPos[0].MinVal, cellPos[0].MaxVal,
                                                 cellPos[1].MinVal, cellPos[1].MaxVal), cell);
     }
 }
Example #18
0
        public void InsertAndRemove()
        {
            var quadtree = new Quadtree <MockQuadtreeItem>(new RectangleF(0, 0, 10, 10));

            var item = new MockQuadtreeItem(1, new RectangleF(0.5f, 0.5f, 1, 1));

            quadtree.Insert(item);
            quadtree.Remove(item.Bounds);

            Assert.Empty(quadtree.FindIntersecting(quadtree.Bounds));
        }
Example #19
0
        public void InsertAndRemoveNonExistant()
        {
            var quadtree = new Quadtree <MockQuadtreeItem>(new RectangleF(0, 0, 10, 10));

            var item = new MockQuadtreeItem(1, new RectangleF(8, 8, 2, 2));

            quadtree.Insert(item);
            quadtree.Remove(new RectangleF(0, 0, 1, 1));

            Assert.Equal(new[] { item }, quadtree.FindIntersecting(quadtree.Bounds));
        }
        /// <summary>
        ///
        /// </summary>
        private void BuildQuadtree()
        {
            quadtree = new Quadtree();

            for (int i = 0; i < rings.Count; i++)
            {
                ILinearRing ring = (ILinearRing)rings[i];
                Envelope    env  = (Envelope)ring.EnvelopeInternal;
                quadtree.Insert(env, ring);
            }
        }
Example #21
0
        public void IterationSetup()
        {
            _quadtree = new Quadtree <BenchQuadtreeItem>(_bounds);

            foreach (var item in _items)
            {
                _quadtree.Insert(item);
            }

            _movingItems = _movingItemsOriginal.Select(x => x.Clone()).ToArray();
        }
Example #22
0
        public Quadtree <BenchQuadtreeItem> InsertTest()
        {
            var tree = new Quadtree <BenchQuadtreeItem>(_treeBounds);

            foreach (var item in _items)
            {
                tree.Insert(item);
            }

            return(tree);
        }
        private Quadtree <Side> ConstructSideQuadtree()
        {
            Contract.Ensures(Contract.Result <Quadtree <Side> >() != null);

            var sides = new Quadtree <Side>(Bounds, 4);

            foreach (var side in _shape)
            {
                sides.Insert(new BoundingRectangle(Vector2.Min(side.Start, side.End) - new Vector2(0.01f), Vector2.Max(side.Start, side.End) + new Vector2(0.01f)), side);
            }
            return(sides);
        }
Example #24
0
        // Use this for initialization
        void Start()
        {
            Vector2 minMapPostion = new Vector2(-1000, -1000);
            Vector2 maxMapPostion = new Vector2(1000, 1000);
            Rect    r             = new Rect(minMapPostion, maxMapPostion - minMapPostion);

            junctions = new Quadtree <Junction>(r, 63, 8);

            Junction j = new Junction(1, 0, 1);

            junctions.Insert(j.Bound, j);
        }
Example #25
0
    private void OnDrawGizmos()
    {
        var quadtree = new Quadtree <bool>(this.transform.position, size, depth);

        foreach (var point in points)
        {
            quadtree.Insert(point.position, true);
        }


        DrawNode(quadtree.GetRoot());
    }
Example #26
0
        public void TestNullQuery()
        {
            var qt      = new Quadtree <string>();
            var result1 = qt.Query(null);

            Assert.That(result1.Count, Is.EqualTo(0));

            qt.Insert(new Envelope(0, 10, 0, 10), "some data");
            var result2 = qt.Query(null);

            Assert.That(result2.Count, Is.EqualTo(0));
        }
Example #27
0
    public static void QuadtreeNonAllocTest()
    {
        float topBoundry    = float.MinValue;
        float bottomBoundry = float.MaxValue;
        float leftBoundry   = float.MaxValue;
        float rightBoundry  = float.MinValue;

        foreach (var s in ShapeSystem.shapes)
        {
            if (s.center.x > rightBoundry)
            {
                rightBoundry = s.center.x;
            }
            if (s.center.x < leftBoundry)
            {
                leftBoundry = s.center.x;
            }
            if (s.center.y > topBoundry)
            {
                topBoundry = s.center.y;
            }
            if (s.center.y < bottomBoundry)
            {
                bottomBoundry = s.center.y;
            }
        }

        q.Resize(
            (rightBoundry + leftBoundry) / 2,
            (topBoundry + bottomBoundry) / 2,
            rightBoundry - leftBoundry,
            topBoundry - bottomBoundry);

        q.Clear();

        foreach (var s in ShapeSystem.shapes)
        {
            q.Insert(s);
        }

        q.ClearEmptySubdivisions();

        if (Settings.debugDrawTree)
        {
            q.Draw();
        }

        foreach (var s in ShapeSystem.shapes)
        {
            q.Search(s);
        }
    }
        internal void AddRange(IEnumerable <GeometryData> sourceData)
        {
            foreach (var data in sourceData)
            {
                var item = new PolyLocator
                {
                    Locator = new IndexedPointInAreaLocator(data.Geom),
                    Data    = data
                };

                Index.Insert(data.Geom.EnvelopeInternal, item);
            }
        }
        private void BuildQuadtree()
        {
            quadtree = new Quadtree();

            int nCount = rings.Count;

            for (int i = 0; i < nCount; i++)
            {
                LinearRing ring = (LinearRing)rings[i];
                Envelope   env  = ring.Bounds;
                quadtree.Insert(env, ring);
            }
        }
        private static void InsertPolys(Geometry geom, Quadtree <Geometry> tree)
        {
            if (geom.IsEmpty)
            {
                return;
            }
            var polyList = PolygonExtracter.GetPolygons(geom);

            foreach (var poly in polyList)
            {
                tree.Insert(poly.EnvelopeInternal, poly);
            }
        }
Example #31
0
        public HalfEdge <TVTag, TETag, TFTag> GetOrConstructHalfEdge(Vertex <TVTag, TETag, TFTag> start, Vertex <TVTag, TETag, TFTag> end)
        {
            Contract.Requires(start != null);
            Contract.Requires(start.Mesh == this);
            Contract.Requires(end != null);
            Contract.Requires(end.Mesh == this);
            Contract.Requires(!start.Equals(end));
            Contract.Ensures(Contract.Result <HalfEdge <TVTag, TETag, TFTag> >() != null);
            Contract.Ensures(!Contract.Result <HalfEdge <TVTag, TETag, TFTag> >().IsDeleted);

            //Try to find an edge which already connects these vertices
            var edge = (from e in start.Edges
                        where e.EndVertex.Equals(end)
                        select e).SingleOrDefault();

            //No luck, create a new edge
            if (edge == null)
            {
                //Create edge and pair and associate with one another
                edge = new HalfEdge <TVTag, TETag, TFTag>(start, end);
                var pair = edge.Pair;

                //Add to vertices
                var addedA = start.AddEdge(edge);
                var addedB = end.AddEdge(pair);
                if (!addedA || !addedB)
                {
                    throw new InvalidOperationException("Constructing new half edge found duplicate edge");
                }

                //Add to quadtree
                var bb = edge.Bounds;
                _halfEdges.Insert(bb, edge);
                _halfEdges.Insert(bb, pair);
            }

            Contract.Assume(!edge.IsDeleted);
            return(edge);
        }
 private static Quadtree<IGeometry> BuildQuadtree(IGeometry geom)
 {
     var index = new Quadtree<IGeometry>();
     geom.Apply(new DelegateGeometryFilter()
     {
         DoFilter = delegate(IGeometry tmpGeometry)
         {
             // only insert atomic geometries
             if (tmpGeometry is IGeometryCollection) return;
             index.Insert(tmpGeometry.EnvelopeInternal, tmpGeometry);
         }
     });
     return index;
 }