/* osgEarth
 * Copyright 2025 Pelican Mapping
 * MIT License
 */
#ifndef OSGEARTH_TRITON_DRAWABLE_H
#define OSGEARTH_TRITON_DRAWABLE_H

#include "Common"
#include <osg/Drawable>
#include <osg/RenderInfo>
#include <osg/TextureCubeMap>
#include <osg/Version>
#include <osg/Texture2D>
#include <osg/buffered_value>

#include <osgEarth/Terrain>
#include <osgEarth/NativeProgramAdapter>
#include <osgEarth/ImageLayer>
#include <osgEarth/VerticalDatum>

const unsigned int TRITON_OCEAN_MASK = 0x4; // 0100

namespace osgEarth { namespace Triton
{
    class TritonContext;
    class TritonHeightMap;

    /**
     * Custom drawable for rendering the Triton ocean effects
     */
    class OSGEARTHTRITON_EXPORT TritonDrawable : public osg::Drawable
    {
    public:
        TritonDrawable(TritonContext* TRITON);

        //! Layer to use as an ocean rendering mask
        void setMaskLayer(const osgEarth::ImageLayer* maskLayer);

        //! Height map generator to use to mask out the ocean where the
        //! terrain has positive elevation
        void setHeightMapGenerator(TritonHeightMap* heightMap);

        //! Vertical datum to use to calculate sea level
        void setVerticalDatum(VerticalDatum* value) {
            _verticalDatum = value;
        }

        //! Gets the Triton Camera associated with an osg Camera
        ::Triton::Camera* getTritonCam(const osg::Camera* cam) {
            return _local.get(cam)._tritonCam;
        }

        void setPlanarReflectionMap(osg::Texture2D* map);

        void setPlanarReflectionProjection(osg::RefMatrix* proj);

    public: // osg::Drawable

        void drawImplementation(osg::RenderInfo& ri) const override;

        osg::BoundingBox computeBoundingBox() const override;

    protected:
        virtual ~TritonDrawable();

        osg::observer_ptr<TritonContext>  _TRITON;
        osg::observer_ptr<const osgEarth::ImageLayer> _maskLayer;
        osg::ref_ptr<osg::TextureCubeMap> _cubeMap;
        
        osg::ref_ptr<osg::Texture2D> _planarReflectionMap;
        osg::ref_ptr<osg::RefMatrix> _planarReflectionProjection;

        mutable osg::ref_ptr<TritonHeightMap> _heightMapGenerator;

        osg::ref_ptr<VerticalDatum> _verticalDatum;
        osg::ref_ptr<const SpatialReference> _wgs84, _ecef;

        mutable osg::buffered_object<osgEarth::NativeProgramAdapterCollection> _adapters;

        struct CameraLocal
        {
            ::Triton::Camera* _tritonCam = nullptr;
        };
        mutable PerObjectFastMap<const osg::Camera*, CameraLocal> _local;
    };

} } // namespace osgEarth::Triton

#endif // OSGEARTH_TRITON_DRAWABLE_H
