1 // Copyright (C) 2008 Tim Moore
3 // This program is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU General Public License as
5 // published by the Free Software Foundation; either version 2 of the
6 // License, or (at your option) any later version.
8 // This program is distributed in the hope that it will be useful, but
9 // WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 #include <osg/BoundingBox>
19 #include <simgear/scene/util/SGNodeMasks.hxx>
21 #include "QuadTreeBuilder.hxx"
28 QuadTreeBuilder::QuadTreeBuilder(const Vec2& min, const Vec2& max) :
29 _root(new osg::Group), _min(min), _max(max)
31 for (int i = 0; i < QUAD_TREE_LEAVES; ++i) {
32 Group* interior = new osg::Group;
33 _root->addChild(interior);
34 for (int j = 0; j < QUAD_TREE_LEAVES; ++j) {
35 LOD* lod = new osg::LOD;
36 interior->addChild(lod);
42 void QuadTreeBuilder::addNode(Node* node, int lod, const Matrix& transform)
44 Vec3 center = node->getBound().center() * transform;
46 int x = (int)(QUAD_TREE_LEAVES * (center.x() - _min.x()) / (_max.x() - _min.x()));
47 x = clampTo(x, 0, (QUAD_TREE_LEAVES - 1));
48 int y = (int)(QUAD_TREE_LEAVES * (center.y() - _min.y()) / (_max.y() - _min.y()));
49 y = clampTo(y, 0, (QUAD_TREE_LEAVES -1));
51 _leaves[y][x]->addChild(node, 0, lod);
54 osg::Group* QuadTreeBuilder::makeQuadTree(LodMap& models,
55 const Matrix& transform)
57 typedef vector<ref_ptr<Node> > NodeList;
59 for (LodMap::iterator iter = models.begin(); iter != models.end(); ++iter) {
60 const Vec3 center = (*iter).first->getBound().center() * transform;
61 extents.expandBy(center);
63 const Vec2 quadMin(extents.xMin(), extents.yMin());
64 const Vec2 quadMax(extents.xMax(), extents.yMax());
65 ref_ptr<Group> result;
67 QuadTreeBuilder quadTree(quadMin, quadMax);
68 for (LodMap::iterator iter = models.begin();
71 quadTree.addNode(iter->first.get(), iter->second, transform);
73 result = quadTree.getRoot();
75 return result.release();