/* osgEarth - Geospatial SDK for OpenSceneGraph
* Copyright 2018 Pelican Mapping
* MIT License
*/
#ifndef OSGEARTH_DRIVERS_MP_TERRAIN_ENGINE_HFCACHE
#define OSGEARTH_DRIVERS_MP_TERRAIN_ENGINE_HFCACHE 1

#include "Common"
#include "TileNode"
#include "TileNodeRegistry"
#include "MPTerrainEngineOptions"
#include <osgEarth/Map>
#include <osgEarth/Progress>
#include <osgEarth/Threading>
#include <osgEarth/Containers>
#include <osgEarth/HeightFieldUtils>
#include "MapFrame"
#include <osgEarth/MapInfo>

namespace osgEarth { namespace Drivers { namespace MPTerrainEngine
{
    using namespace osgEarth;

    /** Key into the height field cache */
    struct HFKey 
    {
        TileKey               _key;
        Revision              _revision;
        ElevationSamplePolicy _samplePolicy;

        bool operator < (const HFKey& rhs) const {
            if ( _key < rhs._key ) return true;
            if ( rhs._key < _key ) return false;
            if ( _revision < rhs._revision ) return true;
            if ( _revision > rhs._revision ) return false;
            return _samplePolicy < rhs._samplePolicy;
        }
    };

    /** value in the height field cache */
    struct HFValue
    {
        osg::ref_ptr<osg::HeightField> _hf;
        bool                           _isFallback;
    };        

    /** caches hightfields for fast neighor lookup */
    class HeightFieldCache : public osg::Referenced //, public Revisioned
    {
    public:
        HeightFieldCache(const MPTerrainEngineOptions& options);

        void setTileSize(int tileSize)
        {
            _tileSize = tileSize;
        }

        bool getOrCreateHeightField( 
                const MapFrame&                 frame,
                const TileKey&                  key,
                const osg::HeightField*         parent_hf,
                osg::ref_ptr<osg::HeightField>& out_hf,
                bool&                           out_isFallback,
                ElevationSamplePolicy           samplePolicy,
                RasterInterpolation          interp,
                ProgressCallback*               progress );

        void clear()
        {
            _cache.clear();
        }

    private:
        bool                            _enabled;
        mutable LRUCache<HFKey,HFValue> _cache;
        int                             _tileSize;
        bool                            _useParentAsReferenceHF;
    };

} } } // namespace osgEarth::Drivers::MPTerrainEngine

#endif // OSGEARTH_DRIVERS_MP_TERRAIN_ENGINE_HFCACHE
