Question

I want to be able to inspect all elements in a quadtree that are contained in nodes that are intersected by a region. The problem though is if I call Query on a section that is as small as only having a height of 2 a stack overflow occurs.

What is a more efficient (and less wrong) way to do the following?

//Call
query_area = new a2de::Rectangle(_mouse->GetX(), _mouse->GetY(), 100.0, 100.0, a2de::YELLOW, false);
_selected_elements = _qt->Query(*query_area);

//...
//Definitions
template<typename T>
std::vector<T> QuadTree<T>::Query(a2de::Rectangle& area) {
    return QueryNode(this, area);
}

template<typename T>
std::vector<T> QuadTree<T>::QueryNode(QuadTree<T>* node, a2de::Rectangle& area) {
    std::vector<T> contained_elements;
    if(node->_bounds.Intersects(area)) {
        if(IsLeaf(node) == false) {
            std::vector<T> child_results;
            for(std::size_t i = 0; i < 4; ++i) {
                child_results = QueryNode(_children[i], area);
                for(std::vector<T>::iterator _iter = child_results.begin(); _iter != child_results.end(); ++_iter) {
                    contained_elements.push_back(*_iter);
                }
                child_results.clear();
            }
        } else {
            for(std::vector<T>::iterator _iter = _elements.begin(); _iter != _elements.end(); ++_iter) {
                contained_elements.push_back(*_iter);
            }
        }
    }
    return contained_elements;
}
Was it helpful?

Solution

Fixed. It had to do with calling QueryNode and Leaf with a this pointer instead of the passed in node values.

//Call
query_area = new a2de::Rectangle(_mouse->GetX(), _mouse->GetY(), 100.0, 100.0, a2de::YELLOW, false);
_selected_elements = _qt->Query(*query_area);

//...
//Definitions
template<typename T>
std::vector<T> QuadTree<T>::Query(const a2de::Shape& area) {
    std::vector<T> selected_elements;
    QueryNode(this, area, selected_elements);
    return selected_elements;
}

template<typename T>
void QuadTree<T>::QueryNode(QuadTree<T>* node, const a2de::Shape& area, std::vector<T>& selected_elements) {

    if(node == nullptr) return;

    if(node->_bounds.Intersects(area) == false) return;

    if(IsLeaf(node)) {
        for(std::vector<T>::iterator _iter = node->_elements.begin(); _iter != node->_elements.end(); ++_iter) {
            selected_elements.push_back(*_iter);
        }
        return;
    }
    for(std::size_t i = 0; i < MAX_CHILDREN; ++i) {
        QueryNode(node->_children[i], area, selected_elements);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top