/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2013 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
*/
#ifndef OSGEARTH_ENGINE_MP_TILE_GROUP
#define OSGEARTH_ENGINE_MP_TILE_GROUP 1

#include "Common"
#include "TileNode"
#include <osg/Group>
#include <osgDB/Options>

using namespace osgEarth;

namespace osgEarth_engine_mp
{
    class TileNodeRegistry;

    /**
     * A TileGroup parents a TileNode (which contains the geometry for a
     * TileKey) and four TilePagedLODs (each of which is responsible for
     * loading one of the four subtiles).
     */
    class TileGroup : public osg::Group
    {
    public:
        TileGroup(
            TileNode*         tilenode,
            const UID&        engineUID, 
            TileNodeRegistry* liveTiles,
            TileNodeRegistry* deadTiles,
            osgDB::Options*   dbOptions);

        /** Range at which subtiles should start paging in. */
        void setSubtileRange(float range);

        /** The TilePagedLOD nodes under this group call this method to
          * notify the Group that a subtile is ready. */
        unsigned& numSubtilesLoaded() { return _numSubtilesLoaded; }

        /** A TilePagedLOD node under this group bumps this counter
          * when it tries to fall back on an upsampled tile */
        unsigned& numSubtilesUpsampling() { return _numSubtilesUpsampling; }

        /** TilePagedLOD will call this if it fails to load a subtile.
         *  If any one subtile fails to load, we cannot display any */
        void cancelSubtiles() { _traverseSubtiles = false; }

        /** The TileNode holding the geometry for this group. */
        TileNode* getTileNode() const { return _tilenode; }

    public: // osg::Node

        /** custom traversal. */
        void traverse(osg::NodeVisitor& nv);
        
        /** Bound is equivalent to the bound of the tilenode. */
        osg::BoundingSphere computeBound() const { return _tilenode->computeBound(); }

    protected:
        virtual ~TileGroup() { }

    private:
        TileKey   _key;
        unsigned  _numSubtilesLoaded;
        unsigned  _numSubtilesUpsampling;
        TileNode* _tilenode;
        float     _subtileRange;
        bool      _traverseSubtiles;
    };

} // namespace osgEarth_engine_mp

#endif // OSGEARTH_ENGINE_MP_TILE_GROUP
