a simple quadtree implementation in c# - codeproject

Upload: dhiresh-das

Post on 01-Jun-2018

247 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    1/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 1/13

    10,798,674 members

    Sign in

    home quick answers discussions

    features community helpSearch for articles, questions, tips

    Articles General Programming Algorithms & Recipes Computational Geometry

    Michael Coyle , 29 Oct 2008

    Rate this:

    A Simple QuadTree

    Implementation in C#

    A QuadTree is a spatialindexing method wel l suited to 2 dimensional spatial problems

    Download demo project - 10.81 KB

    Download source - 19.82 KB

    4.70 (21 votes)

    articles

    http://www.codeproject.com/script/Membership/View.aspx?mid=30332http://www.codeproject.com/script/Articles/Latest.aspxhttp://www.codeproject.com/KB/recipes/QuadTree/QuadTree_src.ziphttp://www.codeproject.com/KB/recipes/QuadTree/QuadTree_demo.ziphttp://www.codeproject.com/script/Membership/View.aspx?mid=30332http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C?display=Printhttp://www.codeproject.com/script/Bookmarks/Add.aspx?obid=30535&obtid=2&action=AddBookmark&bio=true&bis=mediumhttp://www.codeproject.com/KB/recipes/#Computational+Geometryhttp://www.codeproject.com/KB/recipes/http://www.codeproject.com/Chapters/6/General-Programming.aspxhttp://www.codeproject.com/script/Content/SiteMap.aspxhttp://www.codeproject.com/KB/FAQs/http://www.codeproject.com/Lounge.aspxhttp://www.codeproject.com/Feature/http://www.codeproject.com/script/Forums/List.aspxhttp://www.codeproject.com/script/Answers/List.aspx?tab=activehttp://www.codeproject.com/https://www.codeproject.com/script/Membership/LogOn.aspx?rp=%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-Chttp://www.codeproject.com/
  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    2/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 2/13

    IntroductionA QuadTree is a spatial partitioning strategy used to makequeries on relationships between 2D spatial data such ascoordinates in a Geographic Information System (GIS), or thelocation of objects in a video game. For instance, you mayneed to know all of the objects within a region on a map, testwhether objects are visible by a camera, or optimize a collisiondetection algorithm.

    The QuadTree is so named because it recursively partitions

    http://en.wikipedia.org/wiki/Quadtree
  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    3/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 3/13

    regions into four parts, with leaf nodes containing referencesto the spatial objects. Querying the QuadTree is a function of traversing the tree nodes that intersect the query area.

    The OctTree is the analogous structure used for 3 dimensionalproblems.

    For a masterful collection of demos and variations on the

    QuadTree and other spatial indexing methods, see FrantisekBrabec and Hanan Samet's site, or use the references at theend of this article.

    BackgroundThere are many spatial partitioning methods, each with thegoal of providing an efficient way of determining the positionof an item in a spatial domain. For example, a database querycan be considered as a graphical problem. Consider a query ona database containing date of birth and income: a queryagainst all people between 35 and 50 years of age andincomes between 30,000 and 60,000 per year is the same as aquery for all restaurants in the city of Vancouver: they are 2dimensional spatial queries.

    Several spatial indexing methods are more efficient in time andspace, and are easily generalizable to higher dimensions.However, the QuadTree is specialized to the 2D domain, and it

    is easy to implement.

    Algorithm

    The general strategy of the QuadTree is to build a treestructure that partitions a region recursively into four parts, orQuads. Each Quad can further partition itself as necessary. Apre-requisite is that you must know the bounds of the area tobe encompassed; the basic algorithm does not lend itself tothe addition or removal of areas under consideration withoutrebuilding the index.

    Insertion

    When an item is inserted into the tree, it is inserted into aQuad that encompasses the item's position (or spatial index).Each Quad has a maximum capacity. When that capacity isexceeded, the Quad splits into four sub-quads that becomechild nodes of the parent Quad, and the items are

    http://en.wikipedia.org/wiki/Spatial_indexhttp://donar.umiacs.umd.edu/quadtree/index.html
  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    4/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 4/13

    redistributed into the new leaves of the QuadTree. Somevariations set the maximum capacity to one, and subdivideuntil each leaf contains at most a single item ( AdaptiveQuadTree ).

    Querying

    To query a QuadTree for items that are inside a particularrectangle, the tree is traversed. Each Quad is tested forintersection with the query area.

    1. Quads that do not intersect are not traversed, allowinglarge regions of the spatial index to be rejected rapidly.

    2. Quads that are wholly contained by the query regionhave their sub-trees added to the result set withoutfurther spatial tests: this allows large regions to becovered without further expensive operations.

    3. Quads that intersect are traversed, with each sub-Quadtested for intersection recursively.

  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    5/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 5/13

    4. When a Quad is found with no sub-Quads, its contentsare individually tested for intersection with the queryrectangle.

    Other Operations

    Other operations on the QuadTree could include:

    1. Deletion: An object is removed from the QuadTree,empty quads are removed

    2. Merge: Two quadtrees are merged, indexes are rebuilt3. Nearest Neighbour: Common to more advanced spatial

    indexes, a Query could ask for the nearest neighboursto a given object. A simple implementation would be to

    take the object's bounding rect and inflate it by anamount based on the neighbor proximity. Objects in theresult set would be sorted by increasing distance.

    These operations are not demonstrated in this code.

    Variation

    This implementation of the QuadTree has the followingvariations:

    The QuadTree has been changed to index items withrectangular bounds rather than points. This allows it to beused with lines, and polygons.

    On insertion, new quads are created until there are noQuads able to contain an item's rectangle. IE: the item isinserted into the smallest quad that will contain it.There is no maximum number of items in a Quad, thereis a minimum Quad size (necessary to avoid massivetree growth if an item happens to have a very small

  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    6/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 6/13

    area).Because the Quad an item is stored in is related to thesize of the item, both leaf nodes and parent nodes storeitems.The QuadTree's performance will be severely impacted if there are many large items.The Quadtree's performance will be best when the sizeof most items are close to the minimum quad size.

    After writing this code, I find that this particular variation bearsa striking resemblance to the " MX-CIF QuadTree".

    Note: There are other operations on QuadTrees such asdeleting a node, or find the nearest neighbour. These are notsupported in this implementation.

    The following two diagrams show the spatial relationship of the QuadTree with the tree structure. The coloured regionsrepresent objects in the spatial domain. Those that are entirelywithin a quad are shown in the tree structure in their smallestenclosing quad. You can see that the green shape, since itintersects two of the highest level Quads and does not fit intoeither is placed in the root quad. The red and purple shapesare placed in child nodes at level one since they are the largestenclosing Quads. The blue shape is at level three along withthe orange shape. The Yellow shape is at level four. This tree isadaptive in that it does not create quads until insertion isrequested.

    http://donar.umiacs.umd.edu/quadtree/rectangles/cifquad.html
  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    7/13

  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    8/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 8/13

    Run the demo application, and left click anywhere in the clientrectangle: an object is inserted at the click point with a randomsize. Right-click and drag: a selection rectangle is created.Release the mouse button: the QuadTree is queried with theselection rectangle. The QuadTree renderer draws theQuadTree nodes and the objects in the QuadTree in randomcolours. It also draws the selection region and highlights theselected nodes.

    PerformanceThere are two components of QuadTree performance:insertion and query. Insertion can be very expensive because itinvolves several intersection tests per item to be inserted. Thenumber of tests depends on the size of the region (the root of the QuadTree ) and on the minimum Quad size configured.

    These two numbers have to be tuned per application. Loadingmany items into the QuadTree (bulk load, or indexing) tendsto be very CPU intensive. This overhead may not beacceptable; consider storing the QuadTree structure on disk(not covered in this article).

    The QuadTree is designed to be faster at querying the spatialdomain than iteration, but the performance of the indexdepends on the distribution of objects in the domain. If itemsare clustered together, the tree tends to have many items inone branch which defeats the strategy of being able to culllarge regions, and reduce the number of intersection tests. Theworst case performance happens when all objects are in onesmall cluster that is the same size as the smallest Quad; in thiscase the performance of the QuadTree will be slightly worsethan just iterating through all objects.

    If items are uniformly distributed across the spatial domain,performance is approximately O(n*log n).

    Points of InterestGeneric implementation; allows you to use it with anyclass that implements IHasRect interface.Colour used to draw the node is stored in an hashtable;allows the colour of the Quad on screen to be constantover the life of the QuadTree .In the QuadTreeRenderer class, note the anonymousdelegate used to draw the QuadTreeNodes ; allows theQuadTree to be tested, and visualized, without adding

  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    9/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 9/13

    specific code to the class to do so.

    ReferencesH. Samet, The Design and Analysis of Spatial DataStructures , Addison-Wesley, Reading, MA, 1990. ISBN

    0-201-50255-0H. Samet, Applications of Spatial Data Structures:Computer Graphics, Image Processing, and GIS ,Addison-Wesley, Reading, MA, 1990. ISBN 0-201-50300-0 .Mark de Berg, Marc van Kreveld, Mark Overmars,Otfried Schwarzkopf, Computational Geometry:

    Algorithms and Applications , 2nd Edition, Springer-Verlag 2000 ISBN: 3-540-65620-0

    HistoryInitial version with regions and simple Insert and Queryoperations, demo application

    LicenseThis article, along with any associated source code and files, islicensed under The Code Project Open License (CPOL)

    Share

    About the Author

    EMAIL

    http://pinterest.com/pin/create/button/?url=http%3a%2f%2fwww.codeproject.com%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-C&media=http://kurtnoble.com/labs/rrssb/media/facebook-share.jpg&description=A%20Simple%20QuadTree%20Implementation%20in%20C#%20-%20CodeProjecthttps://plus.google.com/share?url=Check%20out%20A%20Simple%20QuadTree%20Implementation%20in%20C#%20-%20CodeProject%20http%3a%2f%2fwww.codeproject.com%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-Chttp://www.reddit.com/submit?url=http%3a%2f%2fwww.codeproject.com%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-Chttp://www.linkedin.com/shareArticle?mini=true&url=http%3a%2f%2fwww.codeproject.com%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-C&title=A%20Simple%20QuadTree%20Implementation%20in%20C#%20-%20CodeProjecthttps://www.facebook.com/sharer/sharer.php?u=http%3a%2f%2fwww.codeproject.com%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-Chttp://twitter.com/home?status=A%20Simple%20QuadTree%20Implementation%20in%20C#%20-%20CodeProject%20http%3a%2f%2fwww.codeproject.com%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-Cmailto:?subject=A%20Simple%20QuadTree%20Implementation%20in%20C%23%20-%20CodeProject&body=http%3a%2f%2fwww.codeproject.com%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-Chttp://www.codeproject.com/info/cpol10.aspxhttp://books.google.ca/books?id=C8zaAWuOIOcC&pg=PT1&lpg=PT1&dq=isbn+3-540-65620-0&source=web&ots=ynTlRf4DPW&sig=Ofgb9FpP-eHr9d4yRq_rx9GYy5M&hl=en&sa=X&oi=book_result&resnum=2&ct=resulthttp://www.cs.umd.edu/~hjs/pubs/bookform.pdfhttp://www.cs.umd.edu/~hjs/pubs/bookform.pdf
  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    10/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 10/13

    Article

    Browse Code

    Stats

    Revisions (2)

    Alternatives

    Comments (45)

    Tagged as

    .NET2.0

    C#2.0

    C#3.0

    C#

    .NET

    Dev

    Intermediate

    Michael CoyleArchitect Blue Toque SoftwareCanada

    I've been lead architect in several software companies. I'veworked in the Justice and Public Safety area for the last 7years, writing facial recognition, arrest and booking softwareand emergency management/GIS software. Prior to that Iworked in the games industry with 3D animation. Currently I'm working on some GIS/mapping software foroutdoor enthusiasts. I intend to spin off portions of this intothe open source community as time permits.

    Follow on Twitter Google LinkedIn

    Search Comments Go

    Article Top

    Comments and Discussions

    You must Sign In to use this message board.

    Profile popups Spacing Relaxed Noise Medium

    https://www.codeproject.com/script/Membership/LogOn.aspx?rp=%2fArticles%2f30535%2fA-Simple-QuadTree-Implementation-in-C%3ffid%3d1529493%26df%3d90%26mpp%3d25%26noise%3d3%26prof%3dTrue%26sort%3dPosition%26view%3dNormal%26spc%3dRelaxedhttp://-/?-http://www.linkedin.com/profile/view?id=11655972http://www.linkedin.com/profile/view?id=11655972https://plus.google.com/104341695922990705557?rel=authorhttps://plus.google.com/104341695922990705557http://www.twitter.com/bluetoque_ca?rel=authorhttp://www.twitter.com/bluetoque_cahttp://www.codeproject.com/Members/Michael-Coylehttp://www.codeproject.com/Tags/Intermediatehttp://www.codeproject.com/Tags/Devhttp://www.codeproject.com/Tags/.NEThttp://www.codeproject.com/Tags/C--hash--http://www.codeproject.com/Tags/C--hash--3.0http://www.codeproject.com/Tags/C--hash--2.0http://www.codeproject.com/Tags/.NET2.0http://www.codeproject.com/Articles/30535/WebControls/#_commentshttp://www.codeproject.com/script/Articles/ListAlternatives.aspx?aid=30535http://www.codeproject.com/script/Articles/ListVersions.aspx?aid=30535http://www.codeproject.com/script/Articles/Statistics.aspx?aid=30535http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=30535
  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    11/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C 11/13

    Layout Normal Per page 25 Update

    First Prev Next

    Member 10665902 23-Mar-14 21:37

    Lowrenz 1-Mar-14 5:22

    Member 10357716 4-Nov-13 4:24

    Michael Coyle 4-Nov-13 6:04

    Member 10357716 4-Nov-13 7:25

    sleekFish 10-Aug-13 22:42

    Michael Coyle 6-Sep-13 7:27

    Thomas Schmidt 2-Apr-12 21:15

    Michael Coyle 4-Apr-12 11:12

    Thomas Schmidt 4-Apr-12 11:20

    delete aitem

    My voteof 5

    Count

    Re:Count

    Re:Count

    Traversingthroughall thenodespresent inaQuadTree

    Re:Traversingthroughall thenodespresent inaQuadTree

    Pointvariant?

    Re:Pointvariant?

    Re:Point

    http://www.codeproject.com/Messages/4212498/Re-Point-variant.aspxhttp://www.codeproject.com/Messages/4212494/Re-Point-variant.aspxhttp://www.codeproject.com/Messages/4210718/Point-variant.aspxhttp://www.codeproject.com/Messages/4654502/Re-Traversing-through-all-the-nodes-present-in-a-Q.aspxhttp://www.codeproject.com/Messages/4633546/Traversing-through-all-the-nodes-present-in-a-Quad.aspxhttp://www.codeproject.com/Messages/4693680/Re-Count.aspxhttp://www.codeproject.com/Messages/4693620/Re-Count.aspxhttp://www.codeproject.com/Messages/4693513/Count.aspxhttp://www.codeproject.com/Messages/4769918/My-vote-of.aspxhttp://www.codeproject.com/Messages/4784814/delete-a-item.aspxhttp://www.codeproject.com/script/Membership/View.aspx?mid=48935http://www.codeproject.com/script/Membership/View.aspx?mid=30332http://www.codeproject.com/script/Membership/View.aspx?mid=48935http://www.codeproject.com/script/Membership/View.aspx?mid=30332http://www.codeproject.com/script/Membership/View.aspx?mid=10186517http://www.codeproject.com/script/Membership/View.aspx?mid=10357716http://www.codeproject.com/script/Membership/View.aspx?mid=30332http://www.codeproject.com/script/Membership/View.aspx?mid=10357716http://www.codeproject.com/script/Membership/View.aspx?mid=7597769http://www.codeproject.com/script/Membership/View.aspx?mid=10665902http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C?fid=1529493&df=90&mpp=25&noise=3&prof=True&sort=Position&view=Normal&spc=Relaxed&fr=26#xx0xx
  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    12/13

  • 8/9/2019 A Simple QuadTree Implementation in C# - CodeProject

    13/13

    16/8/2014 A Simple QuadTree Implementation in C# - CodeProject

    Permalink | Advertise | Privacy | Mobile Web04 | 2.8.140814.1 | Last Updated 30 Oct 2008

    Article Copyright 2008 by Michael CoyleEverything else Copyright CodeProject , 1999-2014

    Terms of Service

    Layout: fixed | fluid

    Michael Coyle 13-Oct-10 12:19

    chengiz5 26-Aug-10 5:40

    ralstogj 9-Sep-09 11:10

    Michael Coyle 9-Sep-09 12:50

    ralstogj 9-Sep-09 12:59

    Last Visit: 31-Dec-99 18:00 Last Update: 15-Aug-14 4:45

    Refresh 1 2 Next

    General News Suggestion Question BugAnswer Joke Rant Admin

    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switchthreads, Ctrl+Shift+Left/Right to switch pages.

    Re: File-basedsolution[modified]

    My vote

    of 2 Access C#dll fromvb.net

    Re:AccessC# dllfromvb.net

    Re:AccessC# dllfromvb.net

    http://www.codeproject.com/Messages/3191591/Re-Access-Csharp-dll-from-vb-net.aspxhttp://www.codeproject.com/Messages/3191581/Re-Access-Csharp-dll-from-vb-net.aspxhttp://www.codeproject.com/Messages/3191507/Access-Csharp-dll-from-vb-net.aspxhttp://www.codeproject.com/Messages/3578404/My-vote-of.aspxhttp://www.codeproject.com/Messages/3631028/Re-File-based-solution-modified.aspxhttp://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C?fid=1529493&df=90&mpp=25&noise=3&prof=True&sort=Position&view=Normal&spc=Relaxed&fr=26#xx0xxhttp://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C?fid=1529493&df=90&mpp=25&noise=3&prof=True&sort=Position&view=Normal&spc=Relaxed&fr=26#xx0xxhttp://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C?fid=1529493&df=90&mpp=25&noise=3&prof=True&sort=Position&view=Normal&spc=Relaxedhttp://www.codeproject.com/script/Membership/View.aspx?mid=6544303http://www.codeproject.com/script/Membership/View.aspx?mid=30332http://www.codeproject.com/script/Membership/View.aspx?mid=6544303http://www.codeproject.com/script/Membership/View.aspx?mid=5971104http://www.codeproject.com/script/Membership/View.aspx?mid=30332http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C?PageFlow=Fluidhttp://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C?PageFlow=FixedWidthhttp://www.codeproject.com/info/TermsOfUse.aspxmailto:[email protected]://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C?display=Mobilehttp://www.codeproject.com/info/privacy.aspxhttp://developermedia.com/http://www.codeproject.com/Articles/30535/A-Simple-QuadTree-Implementation-in-C