/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
 *
 * This library is open source and may be redistributed and/or modified under  
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 * 
 * This library 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 
 * OpenSceneGraph Public License for more details.
 *
 * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski
 * Thanks to to my company http://www.ai.com.pl for allowing me free this work.
*/

#ifndef OSGSHADOW_DEBUGSHADOWMAP
#define OSGSHADOW_DEBUGSHADOWMAP 1

#include <osgShadow/ViewDependentShadowTechnique>
#include <osgShadow/ConvexPolyhedron>
#include <osg/MatrixTransform>
#include <osg/Geode>
#include <osg/Geometry>
#include <string>
#include <map>

namespace osgShadow {

/**
Class used as a layer for debuging resources used by derived xxxShadowMap classes.
As designed by its base ViewDepndentShadowTechnique, DebugShadowMap serves mainly as container of 
DebugShadowMap::ViewData objects. Most of the debuging support work is done by these objects.
DebugShadowMap technique only initializes them in initViewDependentData method. 

Debuging outputs present:
    Shadow maps (pseudo colored to improve readability)
    Shadow and related volumes (represented as convex polyhedra)
*/

class OSGSHADOW_EXPORT DebugShadowMap : public ViewDependentShadowTechnique 
{
    public :

        /*
        All classes stemming from ViewDependentShadowTechnique follow the same pattern.

        They are always based on some underlying level base Technique and they always
        derive their ViewData from ViewData structure defined in underlying base Technique. 

        I use some typedefs to make these inheritance patterns easier to declare/define.
        */

        /** Convenient typedef used in definition of ViewData struct and methods */
        typedef DebugShadowMap               ThisClass;
        /** Convenient typedef used in definition of ViewData struct and methods */
        typedef ViewDependentShadowTechnique BaseClass;

        /** Classic OSG constructor */
        DebugShadowMap();

        /** Classic OSG cloning constructor */
        DebugShadowMap(const DebugShadowMap& dsm, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY);

        /** Declaration of standard OSG object methods */
        META_Object( ViewDependentShadow, DebugShadowMap );

        /** Turn on/off debuging hud & rendering of debug volumes in main view */
        void setDebugDraw( bool draw ) { _doDebugDraw = draw; }

        /** Tell if debuging hud & rendering of debug volumes is active */
        bool getDebugDraw( void )      { return _doDebugDraw; }

    protected:
        /** Classic protected OSG destructor */
        virtual ~DebugShadowMap();

        osg::Vec2s  _hudSize;
        osg::Vec2s  _hudOrigin;
        osg::Vec2s  _viewportSize;
        osg::Vec2s  _viewportOrigin;
        osg::Vec2s  _orthoSize;
        osg::Vec2s  _orthoOrigin;

        bool        _doDebugDraw;

        osg::ref_ptr< osg::Shader > _depthColorFragmentShader;

        struct ViewData: public BaseClass::ViewData
        {
            /** 
            Texture used as ShadowMap - initialized by derived classes. 
            But it has to be defined now since DebugShadowMap::ViewData methods use it 
            */
            osg::ref_ptr< osg::Texture2D > _texture;
            /** 
            Camera used to render ShadowMap - initialized by derived classes.
            But it has to be defined now since DebugShadowMap::ViewData methods use it 
            */
            osg::ref_ptr< osg::Camera >    _camera;

            osg::Matrix                    _viewProjection;
            osg::Camera *                  _viewCamera;

            // Debug hud variables

            /** Coloring Shader used to present shadow depth map contents */
            osg::ref_ptr< osg::Shader >    _depthColorFragmentShader;

            struct PolytopeGeometry {

                ConvexPolyhedron                 _polytope;
                osg::ref_ptr< osg::Geometry >    _geometry[2];
                osg::Vec4                        _colorOutline;
                osg::Vec4                        _colorInside;
            };

            typedef std::map< std::string, PolytopeGeometry > PolytopeGeometryMap;

            osg::Vec2s								  _hudSize;
            osg::Vec2s								  _hudOrigin;
            osg::Vec2s                                _viewportSize;
            osg::Vec2s                                _viewportOrigin;
            osg::Vec2s                                _orthoSize;
            osg::Vec2s                                _orthoOrigin;

            bool                                     *_doDebugDrawPtr;

            PolytopeGeometryMap					      _polytopeGeometryMap;
            osg::ref_ptr< osg::Geode >                _geode[2];
            osg::ref_ptr< osg::MatrixTransform >      _transform[2];

            std::map< std::string, osg::Matrix >      _matrixMap;
            std::map< std::string, osg::Polytope >    _polytopeMap;
            std::map< std::string, osg::BoundingBox > _boundingBoxMap;

            osg::ref_ptr<osg::Camera>                 _cameraDebugHUD;			

            bool getDebugDraw()	{ return *_doDebugDrawPtr; }

            virtual void init( ThisClass * st, osgUtil::CullVisitor * cv );

            virtual void cull( );

            virtual void createDebugHUD( void );

            virtual void cullDebugGeometry( );

            virtual void updateDebugGeometry( const osg::Camera * screenCam, 
                const osg::Camera * shadowCam );

            void setDebugPolytope( const char * name,
                const ConvexPolyhedron & polytope = *(ConvexPolyhedron*)( NULL ),
                osg::Vec4 colorOutline = osg::Vec4(0,0,0,0), 
                osg::Vec4 colorInside = osg::Vec4(0,0,0,0) );

            bool DebugBoundingBox( const osg::BoundingBox & bb, const char * name = "" );
            bool DebugPolytope( const osg::Polytope & p, const char * name = "" );
            bool DebugMatrix( const osg::Matrix & m, const char * name = "" );

            static osg::Vec3d computeShadowTexelToPixelError
                ( const osg::Matrix & mvpwView, 
                  const osg::Matrix & mvpwShadow,
                  const osg::Vec3d & vWorld, 
                  const osg::Vec3d & vDelta = osg::Vec3d( 0.01,0.01,0.01 ) );

            static void displayShadowTexelToPixelErrors
                ( const osg::Camera * viewCam,
                  const osg::Camera * shadowCam,
                  const ConvexPolyhedron * hull );
        };

        META_ViewDependentShadowTechniqueData( ThisClass, ViewData )
};

} // namespace osgShadow

#endif
