/// <summary> /// Creates a QuadTree of SkyBoT objects for quick lookup. /// </summary> /// <param name="NamesList">List of SkyBoT objects.</param> public static QuadTree <SkybotObject> CreateTreeFromList(IEnumerable <SkybotObject> NamesList) { double T = double.MaxValue, B = double.MinValue, L = double.MaxValue, R = double.MinValue; foreach (SkybotObject obj in NamesList) { if (obj.Position.Dec < T) { T = obj.Position.Dec; } if (obj.Position.Dec > B) { B = obj.Position.Dec; } if (obj.Position.RA > R) { R = obj.Position.RA; } if (obj.Position.RA < L) { L = obj.Position.RA; } } QuadTree <SkybotObject> Tree = new QuadTree <SkybotObject>(8, T, B, L, R); foreach (SkybotObject obj in NamesList) { Tree.Add(obj, obj.Position.RA, obj.Position.Dec); } return(Tree); }
/// <summary> /// Adds the point into the corrent quad /// </summary> /// <param name="northWest"></param> /// <param name="northEast"></param> /// <param name="southWest"></param> /// <param name="southEast"></param> /// <param name="point2Int"></param> /// <param name="center"></param> private static void AddPoint(QuadTree northWest, QuadTree northEast, QuadTree southWest, QuadTree southEast, Point2Int point2Int, Point2Int center) { // is point on east side if (point2Int.X > center.X) { // Is point on north if (point2Int.Y > center.Y) { northEast.Add(point2Int); } else { southEast.Add(point2Int); } } else { // Is point on north if (point2Int.Y > center.Y) { northWest.Add(point2Int); } else { southWest.Add(point2Int); } } }
public void Load() { _tileMntTexture = Engine.AssetLoader.Get <TextureAsset>("Image/mnt.png"); _tileGrs1Texture = Engine.AssetLoader.Get <TextureAsset>("Image/grs1.png"); _tileGrs2Texture = Engine.AssetLoader.Get <TextureAsset>("Image/grs2.png"); // _ubuntuFontAsset = Engine.AssetLoader.Get<FontAsset>("font/UbuntuMono-R.ttf").GetAtlas(16f); GenHeightMap(); GetTileMap(); Rectangle boundsOfMap = Rectangle.BoundsFromPolygonPoints(new[] { tiles[0, 0].Vertex0, tiles[MAP_WIDTH - 1, 0].Vertex1, tiles[MAP_WIDTH - 1, MAP_HEIGHT - 1].Vertex2, tiles[0, MAP_HEIGHT - 1].Vertex3, }); quadTree = new QuadTree <TileQuadrilateral>(boundsOfMap, 100); foreach (var tile in tiles) { quadTree.Add(tile); } GLThread.ExecuteGLThread(() => { _frameBuffer = new FrameBuffer(new Texture(Engine.Renderer.DrawBuffer.Size)); }); }
public void OnNodesReset() { SpatiallyOrderedNodes = new QuadTree <TNode>(RectangleF.FromLTRB(0, 0, 2048, 2048)); SpatiallyOrderedConnections = new QuadTree <Tuple <UnorderedTuple2 <Output>, RectangleF> >(RectangleF.FromLTRB(0, 0, 2048, 2048)); foreach (var list in m_connectionDeregisterActions.Values) { foreach (var deregister in list) { deregister(); } } m_connectionDeregisterActions.Clear(); foreach (var node in CurrentFile.Nodes) { node.Renderer.UpdateArea(); } foreach (var node in CurrentFile.Nodes) { SpatiallyOrderedNodes.Add(node, node.Renderer.Area); AddNodeMovedCallbacks(node); StoreConnections(node, true); } }
public void AddPointOutsideOfBoundary() { var ut = new QuadTree(new Bounding2DBox(new Point2Int(-1, -1), new Point2Int(1, 1)), 10, new SimpleQuadTreeDivisionStrategy()); var point = new Point2Int(10, 10); Assert.Throws <ArgumentOutOfRangeException>(() => ut.Add(point)); }
/// <summary> /// Calibrates an input image using VizieR stars catalogs. /// </summary> /// <param name="VizieRStars">List of VizieR stars.</param> /// <param name="DetectedStars">List of locally detected stars.</param> /// <param name="PositionError">Maximum position error of stars. Value in arcseconds.</param> /// <returns>The Zero Point magnitude.</returns> public static double Calibrate(List <StarInfo> VizieRStars, List <Star> DetectedStars, double PositionError) { double T = double.MaxValue, B = double.MinValue, L = double.MaxValue, R = double.MinValue; List <Tuple <Star, StarInfo> > Pairs = new List <Tuple <Star, StarInfo> >(); foreach (Star s in DetectedStars) { if (s.EqCenter.Dec < T) { T = s.EqCenter.Dec; } if (s.EqCenter.Dec > B) { B = s.EqCenter.Dec; } if (s.EqCenter.RA > R) { R = s.EqCenter.RA; } if (s.EqCenter.RA < L) { L = s.EqCenter.RA; } } QuadTree <Star> Tree = new QuadTree <Star>(10, T, B, L, R); foreach (Star s in DetectedStars) { Tree.Add(s, s.EqCenter.RA, s.EqCenter.Dec); } foreach (StarInfo si in VizieRStars) { var Stars = Tree.Query(si.Coordinate.RA, si.Coordinate.Dec, Arc1Sec * PositionError); var St2 = Tree.Query(si.Coordinate.RA, si.Coordinate.Dec, Arc1Sec * PositionError * 5); if (St2.Count == 1 & Stars.Count == 1) { Pairs.Add(new Tuple <Star, StarInfo>(Stars[0], si)); } } if (Pairs.Count < 5) { throw new IndexOutOfRangeException("Could not find enough pairs for calibration."); } var Rpairs1 = Pairs.ToArray(); var ZPSet = Pairs.Select((x) => x.Item2.Magnitude + 2.5 * Math.Log10(x.Item1.Flux)).ToArray(); Array.Sort(ZPSet, Rpairs1); var Rpairs2 = Rpairs1.Skip(Rpairs1.Length / 4).Take(Rpairs1.Length / 2).ToList(); LinearRegression.LinearRegressionParameters LRP = LinearRegression.ComputeLinearRegression(Rpairs2.Select((x) => Math.Log10(x.Item1.Flux)).ToArray(), Rpairs2.Select((x) => x.Item2.Magnitude).ToArray()); if (LRP.PearsonR * LRP.PearsonR < CalibMinR * CalibMinR) { throw new ArgumentOutOfRangeException("Could not calibrate the fluxes with enough accuracy."); } return(ZPSet[ZPSet.Length / 2]); }
/// <summary> /// Initializes a new instance of the <see cref="QueueManager"/> class. /// </summary> /// <param name="queueWaypoint">The queue way point.</param> /// <param name="queue">The queue.</param> /// <param name="pathManager">The path manager.</param> public QueueManager(Waypoint queueWaypoint, List <Waypoint> queue, PathManager pathManager) { QueueWaypoint = queueWaypoint; Queue = queue; _queueWaypointIndices = new Dictionary <Waypoint, int>(); for (int i = 0; i < Queue.Count; i++) { _queueWaypointIndices[Queue[i]] = i; Queue[i].QueueManager = this; } Queue.RemoveAll(w => w == null); LockedWaypoints = new Dictionary <Waypoint, Bot>(); _pathManager = pathManager; // Init storage _managedBots = new List <BotNormal>(); _botsInQueue = new HashSet <BotNormal>(); _placeInQueue = new Dictionary <BotNormal, Waypoint>(); _queueCruisePaths = new Dictionary <BotNormal, List <Waypoint> >(); // Define a loos queue area for some asserting double minArcLength = Queue.Min(firstWP => Queue.Where(wp => wp != firstWP).Min(secondWP => firstWP.GetDistance(secondWP))); _queueAreaXMin = Queue.Min(w => w.X) - minArcLength; _queueAreaXMax = Queue.Max(w => w.X) + minArcLength; _queueAreaYMin = Queue.Min(w => w.Y) - minArcLength; _queueAreaYMax = Queue.Max(w => w.Y) + minArcLength; // Get a quad tree to lookup real waypoints faster _queueNodeTree = new QuadTree <Waypoint>(2, 1, _queueAreaXMin, _queueAreaXMax, _queueAreaYMin, _queueAreaYMax); foreach (var wp in Queue) { _queueNodeTree.Add(wp); } // Obtain maximal edge length _maxEdgeLength = Queue.ToDictionary(wp => wp, wp => wp.Paths.Max(otherWP => wp.GetDistance(otherWP))); }
public void RemoveTest() { Rect bounds = new Rect(8, 8); QuadTree <Actor> tree = new QuadTree <Actor>(bounds, 2, 3); List <Actor> actors = new List <Actor> { new Goblin(0, 0), new Goblin(1, 1), new Goblin(2, 2), new Goblin(5, 5), new Goblin(6, 6), new Goblin(7, 7) }; foreach (var item in actors) { if (!tree.Add(item)) { Assert.Inconclusive(); } } Assert.IsTrue(tree.Remove(actors[5])); Assert.IsTrue(tree.Remove(actors[2])); Assert.AreEqual(actors.Count - 2, tree.Count); }
public void BulkCreationTest() { QuadTree <TestObject> individualTree = new QuadTree <TestObject>(m_Bounds); QuadTree <TestObject> bulkTree = new QuadTree <TestObject>(m_Bounds); Random random = new Random(0); List <TestObject> objects = new List <TestObject>(); for (int i = 0; i < 500; i++) { objects.Add(new TestObject( new Vector2f((float)random.NextDouble(), (float)random.NextDouble()) * 1000)); individualTree.Add(objects[objects.Count - 1]); bulkTree.Add(objects[objects.Count - 1]); individualTree.Update(); } bulkTree.Update(); List <FloatRect> regions1 = new List <FloatRect>(); List <FloatRect> regions2 = new List <FloatRect>(); individualTree.GetAllRegions(regions1); bulkTree.GetAllRegions(regions2); HashSet <FloatRect> remaining = new HashSet <FloatRect>(regions1); remaining.ExceptWith(regions2); Assert.AreEqual(0, remaining.Count); }
public static void TestAddDepth0() { var test = new QuadTree <object> .Element(RectangleF.FromLTRB(0, 0, 1, 1)); var element1 = new object(); var element2 = new object(); Assert.That(test.Add(element1, RectangleF.FromLTRB(0.1f, 0.1f, 0.9f, 0.9f)), Is.EqualTo(test)); Assert.That(test, Contains.Item(element1)); Assert.That(test.Count(), Is.EqualTo(1)); Assert.That(test.Add(element2, RectangleF.FromLTRB(0.1f, 0.1f, 0.9f, 0.9f)), Is.EqualTo(test)); Assert.That(test, Contains.Item(element1)); Assert.That(test, Contains.Item(element2)); Assert.That(test.Count(), Is.EqualTo(2)); }
public void AddAPointAssertExists() { var ut = new QuadTree(Bounding2DBox.Max, 10, new SimpleQuadTreeDivisionStrategy()); ut.Add(Point2Int.Zero); Assert.IsTrue(ut.Contains(Point2Int.Zero)); }
public void Size() { var q = new QuadTree <CustomData, QuadNode <CustomData> >(); Assert.AreEqual(0, q.Size); q.Add(new CustomData { X = 0, Y = 0 }); Assert.AreEqual(1, q.Size); q.Add(new CustomData { X = 1, Y = 1 }) .Add(new CustomData { X = 3, Y = 3 }); Assert.AreEqual(3, q.Size); }
internal void AddPod(Pod pod) { Instance.Compound.PodCurrentTier[pod] = this; lock (this) Pods.Add(pod); PodQuadTree.Add(pod); PodQuadTree.UpdateTree(); pod.Tier = this; }
public Node CreateNode(Vector3 position) { var node = createNode(position); nodes.Add(node); node.NotifyOfCreation(); return(node); }
void AddItem(Vector3 position) { GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube); go.transform.parent = itemParent.transform; go.transform.position = position; quadTree.Add(go); }
public void TestRemoveBug() { var tree = new QuadTree <TreeItem>(new Rectangle(0, 0, 10, 10), 1); var i = new TreeItem(new Rectangle(0, 0, 3, 3)); var j = new TreeItem(new Rectangle(0, 0, 2, 2)); tree.Add(i); tree.Add(j); var success = tree.Remove(j); Assert.IsTrue(success); Assert.AreEqual(1, tree.Count); Assert.IsTrue(tree.Contains(i)); Assert.IsFalse(tree.Contains(j)); }
/// <summary>Generates the search structures.</summary> public void GeneratePool() { DetectionPool = new QuadTree <ImageDetection>(PoolDepth, Topmost, Lowermost, Leftmost, Rightmost); foreach (ImageDetection md in PoolList) { DetectionPool.Add(md, md.Barycenter.EP.RA, md.Barycenter.EP.Dec); } }
internal void AddBot(Bot bot) { Instance.Compound.BotCurrentTier[bot] = this; lock (this) Bots.Add(bot); BotQuadTree.Add(bot); BotQuadTree.UpdateTree(); bot.Tier = this; }
/// <summary>Generates the search structures.</summary> public void GeneratePool() { DetectionPool = new QuadTree <Star>(PoolDepth, Topmost, Lowermost, Leftmost, Rightmost); foreach (Star md in PoolList) { DetectionPool.Add(md, md.EqCenter.RA, md.EqCenter.Dec); } }
public static void TestNegativeY() { QuadTree <object> tree = new QuadTree <object>(RectangleF.FromLTRB(0, 0, 1, 1)); var element1 = new object(); var rect = new RectangleF(new PointF(0.25f, -1), new SizeF(0.1f, 0.1f)); tree.Add(element1, rect); tree.Remove(element1); }
public void AddDeleteQT() { var obj = m_Objects[m_Random.Next(0, m_Objects.Count)]; m_Tree.Remove(obj); m_Tree.Update(); m_Tree.Add(obj); m_Tree.Update(); }
private void GraphicalTestUpdate(float dt) { m_Tree.Update(); m_TestRefreshCounter += dt; if (m_TestRefreshCounter > m_TestRefreshRate) { m_TestRefreshCounter = 0f; //RefreshTest(); } var mousePos = GetMousePos(); foreach (var testObject in m_TestObjects) { var toMouse = (mousePos - testObject.Key.Position).Normalized(); testObject.Key.Position += (testObject.Value + toMouse) * dt * m_SpeedMultiplier; testObject.Key.FillColor = Color.Blue; WrapPosition(testObject.Key); } var kClosest = m_Tree.GetKClosestObjects(GetMousePos(), 30, m_QueeryRange); foreach (var circle in kClosest.Cast <CircleShape>()) { circle.FillColor = Color.Green; } if (kClosest.Length > 1) { ((CircleShape)kClosest[0]).FillColor = Color.Red; } while (m_NumCircles > m_TestObjects.Count) { var obj = new CircleShape(2f) { FillColor = Color.Blue, Position = GetRandomPos() }; m_TestObjects.Add(obj, RandomVelocity()); m_Tree.Add(obj); } while (m_NumCircles < m_TestObjects.Count) { var obj = m_TestObjects.Keys.First(); m_TestObjects.Remove(obj); m_Tree.Remove(obj); } for (int i = 0; i < 10; i++) { var removedObj = m_TestObjects.Keys.ToArray()[Random.Next(0, m_TestObjects.Count)]; //m_TestObjects.Remove(removedObj); //m_Tree.Remove(removedObj); } }
public void Remove() { QuadTree <byte> tree = new QuadTree <byte>(5, Vector2.zero, new Vector2(10, 10)); tree.Add(new Vector2(3, 7), 8); tree.Add(new Vector2(-3.423f, 73), 205); tree.Add(new Vector2(1302, 53e5f), 125); byte[] data = tree.GetAll(); Debug.Assert(data.Length == 3); tree.Remove(125); data = tree.GetAll(); Debug.Assert(data.Length == 2); Debug.Assert(data[0] == 8); Debug.Assert(data[1] == 205); }
public void AddTest1() { // Lets break it c: QuadTree <double, int> quadTree = new QuadTree <double, int>(); Assert.IsNotNull(quadTree); Assert.AreEqual(0, QuadTree <double, int> .QTNodeCount); double range = 5; int index = 0; int[] dataToAdd = new int[] { 0, 1, 2, 4, 3, 5, 6, 7, 8, 9, 10 }; quadTree.Add(new QTPoint { X = 0.0, Y = 0.0 }, range, dataToAdd[index++]); // Lets not make the range smaller and see what happens... range *= 0.5; quadTree.Add(new QTPoint { X = 1.0, Y = 1.0 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 3.0, Y = 1.0 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 3.0, Y = 3.0 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 1.0, Y = 3.0 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 0.5, Y = 3.5 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 0.5, Y = 3.5 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 0.000001, Y = 0.000001 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 0.0000001, Y = 0.0000001 }, range, dataToAdd[index++]); Trace.WriteLine(quadTree.ToString()); }
public void Setup() { m_Tree = new QuadTree <TestObject>(new FloatRect(0, 0, 1000, 1000)); m_Objects = new List <TestObject>(N); for (int i = 0; i < N; i++) { var obj = new TestObject(RandomPosition()); m_Objects.Add(obj); m_Tree.Add(obj); } }
public void TestFindInAreaEdgeMiss() { var tree = new QuadTree <TreeItem>(new Rectangle(0, 0, 50, 50)); var i = new TreeItem(new Rectangle(5, 5, 10, 10)); tree.Add(i); var result = tree.FindInArea(new Rectangle(10, 15, 3, 3)).ToList(); Assert.AreEqual(0, result.Count); }
public void EnumerationTests() { var tree = new QuadTree <TestObject>(m_Bounds); var one = new TestObject(1, 1); var two = new TestObject(2, 2); var three = new TestObject(3, 3); tree.Add(one); tree.Add(two); tree.Add(three); tree.Update(); HashSet <TestObject> enumerated = new HashSet <TestObject>(tree); Assert.IsTrue(enumerated.Contains(one)); Assert.IsTrue(enumerated.Contains(two)); Assert.IsTrue(enumerated.Contains(three)); Assert.AreEqual(3, enumerated.Count); }
public void TestFindAtPoint2() { var tree = new QuadTree <TreeItem>(new Rectangle(0, 0, 50, 50)); var i = new TreeItem(new Rectangle(3, 3, 7, 8)); tree.Add(i); var result = tree.FindAtPoint(new Point(2, 20)).ToList(); Assert.AreEqual(0, result.Count); }
public void QueryTest() { QuadTree <double, int> quadTree = new QuadTree <double, int>(); Assert.IsNotNull(quadTree); Assert.AreEqual(0, QuadTree <double, int> .QTNodeCount); double range = 5; int index = 0; int[] dataToAdd = new int[] { 0, 1, 2, 4, 3, 5 }; quadTree.Add(new QTPoint { X = 0.0, Y = 0.0 }, range, dataToAdd[index++]); range *= 0.5; quadTree.Add(new QTPoint { X = 1.0, Y = 1.0 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 3.0, Y = 1.0 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 3.0, Y = 3.0 }, range, dataToAdd[index++]); quadTree.Add(new QTPoint { X = 1.0, Y = 3.0 }, range, dataToAdd[index++]); range *= 0.5; quadTree.Add(new QTPoint { X = 0.5, Y = 3.5 }, range, dataToAdd[index++]); Trace.WriteLine(quadTree.ToString()); List <int> data = new List <int>(); quadTree.Query(new QTPoint { X = 0, Y = 0 }, 2, ref data); for (int i = 0; i < 2; ++i) { Assert.AreEqual(dataToAdd[i], data.IndexOf(i)); } quadTree.Add(new QTPoint { X = 0, Y = 0 }, range, -1); data = new List <int>(); dataToAdd = new int[] { -1, 1, 2, 4, 3, 5 }; quadTree.Query(new QTPoint { X = 0, Y = 0 }, 5, ref data); for (int i = 0; i < 2; ++i) { Assert.AreEqual(dataToAdd[i], data.IndexOf(i)); } }
public void TestFindInAreaLots() { var tree = new QuadTree <TreeItem>(new Rectangle(0, 0, 10, 10), 2); var i = new TreeItem(new Rectangle(2, 2, 2, 2)); var j = new TreeItem(new Rectangle(6, 6, 3, 2)); var k = new TreeItem(new Rectangle(1, 6, 2, 2)); var l = new TreeItem(new Rectangle(7, 0, 2, 2)); var m = new TreeItem(new Rectangle(0, 0, 4, 4)); var n = new TreeItem(new Rectangle(4, 3, 6, 6)); tree.Add(i); tree.Add(j); tree.Add(k); tree.Add(l); tree.Add(m); tree.Add(n); var result = tree.FindInArea(new Rectangle(1, 7, 8, 3)).ToList(); Assert.IsFalse(result.Contains(i)); Assert.IsTrue(result.Contains(j)); Assert.IsTrue(result.Contains(k)); Assert.IsFalse(result.Contains(l)); Assert.IsFalse(result.Contains(m)); Assert.IsTrue(result.Contains(n)); }
/// <summary> /// Merges objects from the given scene for the given zoom level. /// </summary> /// <param name="target"></param> /// <param name="source"></param> /// <param name="idx"></param> private void MergeObjects(Scene2D target, Scene2D source, int idx) { var lines = new Dictionary<Scene2D.ScenePoints, Scene2DStylesSet>(); var linesIndex = new QuadTree<PointF2D, Scene2D.ScenePoints>(); var polygons = new Dictionary<Scene2D.ScenePoints, Scene2DStylesSet>(); //var polygonsIndex = new QuadTree<PointF2D, Scene2D.ScenePoints>(); Dictionary<uint, SceneObject> sceneObjects = source.GetSceneObjectsAt(idx); float zoomFactor = source.GetMaximumZoomFactorAt(idx); float epsilon = source.CalculateSimplificationEpsilon(zoomFactor); foreach (var sceneObject in sceneObjects) { if (sceneObject.Value.Enum == SceneObjectType.LineObject) { // the scene object is a line object. var sceneLineObject = sceneObject.Value as SceneLineObject; Scene2D.ScenePoints scenePoints = source.GetPoints(sceneLineObject.GeoId); Scene2DStylesSet stylesSet = null; if (!lines.TryGetValue(scenePoints, out stylesSet)) { // create styles set. stylesSet = new Scene2DStylesSet(); lines.Add(scenePoints, stylesSet); // add scenePoints to the index. linesIndex.Add(new PointF2D(scenePoints.X[0], scenePoints.Y[0]), scenePoints); linesIndex.Add(new PointF2D(scenePoints.X[scenePoints.X.Length - 1], scenePoints.Y[scenePoints.Y.Length - 1]), scenePoints); } stylesSet.AddStyleLine(sceneLineObject.StyleId); } else if (sceneObject.Value.Enum == SceneObjectType.LineTextObject) { var sceneLineTextObject = sceneObject.Value as SceneLineTextObject; Scene2D.ScenePoints scenePoints = source.GetPoints(sceneLineTextObject.GeoId); Scene2DStylesSet stylesSet = null; if (!lines.TryGetValue(scenePoints, out stylesSet)) { // create styles set. stylesSet = new Scene2DStylesSet(); lines.Add(scenePoints, stylesSet); // add scenePoints to the index. linesIndex.Add(new PointF2D(scenePoints.X[0], scenePoints.Y[0]), scenePoints); linesIndex.Add(new PointF2D(scenePoints.X[scenePoints.X.Length - 1], scenePoints.Y[scenePoints.Y.Length - 1]), scenePoints); } stylesSet.AddStyleLineText(sceneLineTextObject.StyleId, sceneLineTextObject.TextId); } else if (sceneObject.Value.Enum == SceneObjectType.IconObject) { throw new NotSupportedException("Icons not yet supported!"); //var sceneIconObject = (sceneObject.Value as SceneIconObject); //Scene2D.ScenePoint scenePoint = source.GetPoint(sceneIconObject.GeoId); //source.GetStyleIcon( //target.AddIcon(target.AddPoint(scenePoint.X, scenePoint.Y); } else if (sceneObject.Value.Enum == SceneObjectType.PointObject) { var scenePointObject = (sceneObject.Value as ScenePointObject); Scene2D.ScenePoint scenePoint = source.GetPoint(scenePointObject.GeoId); StylePoint stylePoint = source.GetStylePoint(scenePointObject.StyleId); target.AddStylePoint(target.AddPoint(scenePoint.X, scenePoint.Y), stylePoint.Layer, stylePoint.MinZoom, stylePoint.MaxZoom, stylePoint.Color, stylePoint.Size); } else if (sceneObject.Value.Enum == SceneObjectType.PolygonObject) { // the scene object is a polygon. var scenePolygonObject = (sceneObject.Value as ScenePolygonObject); Scene2D.ScenePoints scenePoints = source.GetPoints(sceneObject.Value.GeoId); Scene2DStylesSet stylesSet = null; if (!polygons.TryGetValue(scenePoints, out stylesSet)) { // create styles set. stylesSet = new Scene2DStylesSet(); polygons.Add(scenePoints, stylesSet); //// add scenePoints to the index. //polygonsIndex.Add(new PointF2D(scenePoints.X[0], scenePoints.Y[0]), scenePoints); //polygonsIndex.Add(new PointF2D(scenePoints.X[scenePoints.X.Length - 1], scenePoints.Y[scenePoints.Y.Length - 1]), scenePoints); } stylesSet.AddStylePolygon(scenePolygonObject.StyleId); //var scenePolygonObject = (sceneObject.Value as ScenePolygonObject); //Scene2D.ScenePoints scenePoints = source.GetPoints(sceneObject.Value.GeoId); //StylePolygon stylePolygon = source.GetStylePolygon(sceneObject.Value.StyleId); //uint? pointsId = target.AddPoints(scenePoints.X, scenePoints.Y); //if (pointsId.HasValue) //{ // target.AddStylePolygon(pointsId.Value, stylePolygon.Layer, stylePolygon.MinZoom, stylePolygon.MaxZoom, // stylePolygon.Color, stylePolygon.Width, stylePolygon.Fill); //} } else if (sceneObject.Value.Enum == SceneObjectType.TextObject) { var sceneTextObject = (sceneObject.Value as SceneTextObject); Scene2D.ScenePoint scenePoint = source.GetPoint(sceneObject.Value.GeoId); StyleText styleText = source.GetStyleText(sceneTextObject.StyleId); string text = source.GetText(sceneTextObject.TextId); target.AddText(target.AddPoint(scenePoint.X, scenePoint.Y), styleText.Layer, styleText.MinZoom, styleText.MaxZoom, styleText.Size, text, styleText.Color, styleText.HaloColor, styleText.HaloRadius, styleText.Font); } } // loop until there are no more candidates. int totalLines = lines.Count; float latestProgress = 0; while (lines.Count > 0) { var line = lines.First(); lines.Remove(line.Key); // report progress. float progress = (float)System.Math.Round((((double)(totalLines - lines.Count) / (double)totalLines) * 100)); if (progress != latestProgress) { OsmSharp.Logging.Log.TraceEvent("SceneSerializer", OsmSharp.Logging.TraceEventType.Information, "Merging lines @z{3}e{4} ({1}/{2})... {0}%", progress, totalLines - lines.Count, totalLines, zoomFactor, epsilon); latestProgress = progress; } // copy the coordinates to lists. double[] x = line.Key.X.Clone() as double[]; double[] y = line.Key.Y.Clone() as double[]; // find a matching line. int mergeCount = 1; Scene2D.ScenePoints found; MatchPosition foundPosition = this.FindMatch(linesIndex, lines, x, y, line.Value, epsilon, out found); while (found != null) { // TODO: keep expanding and duplicating until not possible anymore. // remove the found line. lines.Remove(found); // report progress. progress = (float)System.Math.Round((((double)(totalLines - lines.Count) / (double)totalLines) * 100)); if (progress != latestProgress) { OsmSharp.Logging.Log.TraceEvent("SceneSerializer", OsmSharp.Logging.TraceEventType.Information, "Merging lines @z{3}e{4} ({1}/{2})... {0}%", progress, totalLines - lines.Count, totalLines, zoomFactor, epsilon); latestProgress = progress; } // add the line. int lengthBefore = x.Length; Array.Resize(ref x, x.Length + found.X.Length - 1); Array.Resize(ref y, y.Length + found.Y.Length - 1); switch (foundPosition) { case MatchPosition.FirstFirst: found.X.InsertToReverse(1, x, 0, found.X.Length - 1); found.Y.InsertToReverse(1, y, 0, found.Y.Length - 1); break; case MatchPosition.FirstLast: found.X.InsertTo(0, x, 0, found.X.Length - 1); found.Y.InsertTo(0, y, 0, found.Y.Length - 1); break; case MatchPosition.LastFirst: found.X.CopyTo(x, lengthBefore - 1); found.Y.CopyTo(y, lengthBefore - 1); break; case MatchPosition.LastLast: found.X.CopyToReverse(x, lengthBefore - 1); found.Y.CopyToReverse(y, lengthBefore - 1); break; } // select a new line. foundPosition = this.FindMatch(linesIndex, lines, x, y, line.Value, epsilon, out found); mergeCount++; } // simplify first. double[][] simplified = OsmSharp.Math.Algorithms.SimplifyCurve.Simplify(new double[][] { x, y }, epsilon); // add the new points. uint? pointsId = target.AddPoints(simplified[0], simplified[1]); // add points again with appropriate styles. if (pointsId.HasValue) { foreach (var style in line.Value) { var scene2DStyleLine = (style as Scene2DStyleLine); if (scene2DStyleLine != null) { StyleLine styleLine = source.GetStyleLine(scene2DStyleLine.StyleLineId); target.AddStyleLine(pointsId.Value, styleLine.Layer, styleLine.MinZoom, styleLine.MaxZoom, styleLine.Color, styleLine.Width, styleLine.LineJoin, styleLine.Dashes); continue; } var scene2DStyleLineText = (style as Scene2DStyleLineText); if (scene2DStyleLineText != null) { StyleText styleText = source.GetStyleLineText(scene2DStyleLineText.StyleLineTextId); string text = source.GetText(scene2DStyleLineText.TextId); target.AddStyleLineText(pointsId.Value, styleText.Layer, styleText.MinZoom, styleText.MaxZoom, styleText.Color, styleText.Size, text, styleText.Font, styleText.HaloColor, styleText.HaloRadius); continue; } } } } // loop until there are no more candidates. totalLines = polygons.Count; latestProgress = 0; while (polygons.Count > 0) { var polygon = polygons.First(); polygons.Remove(polygon.Key); // report progress. float progress = (float)System.Math.Round((((double)(totalLines - polygons.Count) / (double)totalLines) * 100)); if (progress != latestProgress) { OsmSharp.Logging.Log.TraceEvent("SceneSerializer", OsmSharp.Logging.TraceEventType.Information, "Merging polygons @z{3}e{4} ({1}/{2})... {0}%", progress, totalLines - polygons.Count, totalLines, zoomFactor, epsilon); latestProgress = progress; } // copy the coordinates to lists. double[] x = polygon.Key.X.Clone() as double[]; double[] y = polygon.Key.Y.Clone() as double[]; //// find a matching line. //int mergeCount = 1; //Scene2D.ScenePoints found; //MatchPosition foundPosition = this.FindMatch(linesIndex, lines, x, y, line.Value, epsilon, out found); //while (found != null) //{ // TODO: keep expanding and duplicating until not possible anymore. // // remove the found line. // lines.Remove(found); // // report progress. // progress = (float)System.Math.Round((((double)(totalLines - lines.Count) / (double)totalLines) * 100)); // if (progress != latestProgress) // { // OsmSharp.Logging.Log.TraceEvent("SceneSerializer", OsmSharp.Logging.TraceEventType.Information, // "Merging lines @z{3}e{4} ({1}/{2})... {0}%", progress, totalLines - lines.Count, totalLines, zoomFactor, epsilon); // latestProgress = progress; // } // // add the line. // int lengthBefore = x.Length; // Array.Resize(ref x, x.Length + found.X.Length - 1); // Array.Resize(ref y, y.Length + found.Y.Length - 1); // switch (foundPosition) // { // case MatchPosition.FirstFirst: // found.X.InsertToReverse(1, x, 0, found.X.Length - 1); // found.Y.InsertToReverse(1, y, 0, found.Y.Length - 1); // break; // case MatchPosition.FirstLast: // found.X.InsertTo(0, x, 0, found.X.Length - 1); // found.Y.InsertTo(0, y, 0, found.Y.Length - 1); // break; // case MatchPosition.LastFirst: // found.X.CopyTo(x, lengthBefore - 1); // found.Y.CopyTo(y, lengthBefore - 1); // break; // case MatchPosition.LastLast: // found.X.CopyToReverse(x, lengthBefore - 1); // found.Y.CopyToReverse(y, lengthBefore - 1); // break; // } // // select a new line. // foundPosition = this.FindMatch(linesIndex, lines, x, y, line.Value, epsilon, out found); // mergeCount++; //} // simplify first. double[][] simplified = OsmSharp.Math.Algorithms.SimplifyCurve.Simplify(new double[][] { x, y }, epsilon); // add the new points. uint? pointsId = target.AddPoints(simplified[0], simplified[1]); // add points again with appropriate styles. if (pointsId.HasValue) { foreach (var style in polygon.Value) { var scene2DStylePolygon = (style as Scene2DStylePolygon); if (scene2DStylePolygon != null) { StylePolygon stylePolygon = source.GetStylePolygon(scene2DStylePolygon.StylePolygonId); target.AddStylePolygon(pointsId.Value, stylePolygon.Layer, stylePolygon.MinZoom, stylePolygon.MaxZoom, stylePolygon.Color, stylePolygon.Width, stylePolygon.Fill); continue; } } } } }
public void QuadTreeTestTwo() { int numPoints = 1000; double BoundarySize = 1000; int seed = 0; Random RandGen = new Random(seed); QuadTree<int> Tree = new QuadTree<int>(new GridRectangle(-BoundarySize, BoundarySize, -BoundarySize, BoundarySize)); GridVector2[] points = new GridVector2[numPoints]; //Create the QuadTree for (int i = 0; i < numPoints; i++) { points[i] = new GridVector2(RandGen.NextDouble() * BoundarySize, RandGen.NextDouble() * BoundarySize); Tree.Add(points[i], i); } double distance; //Check to see we can find every item in the quad tree for (int i = 0; i < numPoints; i++) { int iFound = Tree.FindNearest(points[i], out distance); Debug.Assert(iFound == i, "Could not find previously inserted point"); } //Remove half the points for (int i = 0; i < numPoints / 2; i++) { Tree.Remove(i); //Make sure if we look for the removed point we get an index higher than the ones we've already removed int iFound = Tree.FindNearest(points[i], out distance); Debug.Assert(iFound > i, "Found previously deleted point"); } //Look for the remaining points for (int i = numPoints / 2; i < numPoints; i++) { //Make sure if we look for the removed point we get an index higher than the ones we've already removed int iFound = Tree.FindNearest(points[i], out distance); Debug.Assert(iFound == i, "Could not find previously inserted point after deletes"); } //Re-insert the removed points for (int i = 0; i < numPoints / 2; i++) { Tree.Add(points[i], i); //Make sure if we look for the removed point we get an index higher than the ones we've already removed int iFound = Tree.FindNearest(points[i], out distance); Debug.Assert(iFound == i, "Could not find newly inserted point after deletes"); } //Look for the remaining points for (int i = numPoints / 2; i < numPoints; i++) { //Make sure if we look for the removed point we get an index higher than the ones we've already removed int iFound = Tree.FindNearest(points[i], out distance); Debug.Assert(iFound == i, "Could not find previously inserted point after delete and insert"); } //Delete all the points for (int i = 0; i < numPoints; i++) { Tree.Remove(i); //Make sure if we look for the removed point we get an index higher than the ones we've already removed if (i < numPoints - 1) { int iFound = Tree.FindNearest(points[i], out distance); Debug.Assert(iFound > i, "Found previously deleted point"); } } //Insert some points into the empty tree to make sure we still can for (int i = 0; i < numPoints; i++) { points[i] = new GridVector2(RandGen.NextDouble() * BoundarySize, RandGen.NextDouble() * BoundarySize); Tree.Add(points[i], i); } //Check to see we can find every item in the quad tree for (int i = 0; i < numPoints; i++) { int iFound = Tree.FindNearest(points[i], out distance); Debug.Assert(iFound == i, "Could not find previously inserted point"); } //The end }