using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using AtriLib3.Interfaces;
namespace AtriLib3.Utility
private List<IWorldObject> _objects;
private Rectangle _bounds;
private QuadTree[] nodes;
public QuadTree(int level, Rectangle bounds)
_objects = new List<IWorldObject>();
for(int i = 0; i < nodes.Length; i++)
int subWidth = _bounds.Width / 2;
int subHeight = _bounds.Height / 2;
nodes[0] = new QuadTree(_level + 1, new Rectangle(x + subWidth, y, subWidth, subHeight));
nodes[1] = new QuadTree(_level + 1, new Rectangle(x, y, subWidth, subHeight));
nodes[2] = new QuadTree(_level + 1, new Rectangle(x, y + subHeight, subWidth, subHeight));
nodes[3] = new QuadTree(_level + 1, new Rectangle(x + subWidth, y + subHeight, subWidth, subHeight));
private int GetIndex(Rectangle rect)
double verticalMidpoint = _bounds.X + (_bounds.Width / 2);
double horizontalMidpoint = _bounds.Y + (_bounds.Height / 2);
bool topQuadrant = (rect.Y < horizontalMidpoint && rect.Y + rect.Height < horizontalMidpoint);
bool bottomQuadrant = (rect.Y > horizontalMidpoint);
if(rect.X < verticalMidpoint && rect.X + rect.Width < verticalMidpoint)
else if(rect.X > verticalMidpoint)
public List<IWorldObject> GetObjects(Rectangle rect)
int index = GetIndex(rect);
List<IWorldObject> _retList = new List<IWorldObject>();
if(index != -1 && nodes[index] != null)
nodes[index].GetObjects(rect);
for(int i = 0; i < _objects.Count; i++)
_retList.Add(_objects[i]);
public void Add(IWorldObject iWorldObj)
int index = GetIndex(iWorldObj.ObjectRectangle);
nodes[index].Add(iWorldObj);
if(_objects.Count > Constants.QUADTREE_MAX_OBJECTS && _level < Constants.QUADTREE_MAX_LEVELS)
while(i < _objects.Count)
int index = GetIndex(_objects[i].ObjectRectangle);