<commit_before>/* Joystick_Plugin - for licensing and copyright see license.txt */

#include "StdAfx.h"
#include "Nodes/G2FlowBaseNode.h"
//#include <IScriptSystem.h>
//#include <ScriptHelpers.h>
#include <CPluginJoystick.h>

namespace JoystickPlugin
{
    HRESULT PollJoystick( DIJOYSTATE2* js, LPDIRECTINPUTDEVICE8 joystick );

    class CFlowJoystickNode :
        public CFlowBaseNode<eNCT_Instanced>,
        public CScriptableBase
    {
        private:

            SActivationInfo m_actInfo;
            int* m_buttons;
            int m_xAxis;
            int m_yAxis;
            int m_zAxis;
            int m_xRotate;
            int m_yRotate;
            int m_zRotate;
            int m_slider;
            int m_POV;
            bool m_bEnabled;

            LPDIRECTINPUTDEVICE8 m_currentJoystick;
            DIDEVCAPS m_CurrentCapabilities;

        public:

            CFlowJoystickNode( SActivationInfo* pActInfo )
            {
#ifndef SDK_VERSION_343
                Init( gEnv->pSystem->GetIScriptSystem(), gEnv->pSystem );
#else
                Init( gEnv->pSystem->GetIScriptSystem() );
#endif
                SetGlobalName( "Joystick" );

#undef SCRIPT_REG_CLASSNAME
#define SCRIPT_REG_CLASSNAME &CFlowJoystickNode::

                SCRIPT_REG_TEMPLFUNC( GetXAxis, "" );
                SCRIPT_REG_TEMPLFUNC( GetYAxis, "" );
                SCRIPT_REG_TEMPLFUNC( GetZAxis, "" );
                SCRIPT_REG_TEMPLFUNC( GetButtonState, "button" );
                SCRIPT_REG_TEMPLFUNC( SetJoystick, "joystick" );
                SCRIPT_REG_TEMPLFUNC( GetNumButtons, "" );
                SCRIPT_REG_TEMPLFUNC( GetPOV, "" );
                SCRIPT_REG_TEMPLFUNC( GetSlider, "" );
                SCRIPT_REG_TEMPLFUNC( GetXRotate, "" );
                SCRIPT_REG_TEMPLFUNC( GetYRotate, "" );
                SCRIPT_REG_TEMPLFUNC( GetZRotate, "" );

#undef SCRIPT_REG_CLASSNAME

                m_xAxis = 0;
                m_yAxis = 0;
                m_zAxis = 0;
                m_xRotate = 0;
                m_yRotate = 0;
                m_zRotate = 0;
                m_slider = 0;
                m_POV = 0;
                m_buttons = NULL;
                m_currentJoystick = NULL;
                m_bEnabled = true;
            }

            ~CFlowJoystickNode()
            {
                SAFE_DELETE( m_buttons );

                if ( m_currentJoystick )
                {
                    m_currentJoystick->Unacquire();
                }
            }

            int CFlowJoystickNode::GetButtonState( IFunctionHandler* pH, int button )
            {
                if ( !m_buttons || button > m_CurrentCapabilities.dwButtons || button < 1 )
                {
                    return pH->EndFunction();
                }

                return pH->EndFunction( m_buttons[button - 1] );
            }

            int CFlowJoystickNode::GetNumButtons( IFunctionHandler* pH )
            {
                return pH->EndFunction( ( int )m_CurrentCapabilities.dwButtons );
            }

            int CFlowJoystickNode::SetJoystick( IFunctionHandler* pH, int joystick )
            {
                if ( joystick > g_joysticks.size() || joystick < 1 )
                {
                    SetNewJoystick( 1 );
                    return pH->EndFunction();
                }

                SetNewJoystick( joystick );

                return pH->EndFunction();
            }

            int CFlowJoystickNode::GetXAxis( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_xAxis );
            }

            int CFlowJoystickNode::GetYAxis( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_yAxis );
            }

            int CFlowJoystickNode::GetZAxis( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_zAxis );
            }

            int CFlowJoystickNode::GetXRotate( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_xRotate );
            }

            int CFlowJoystickNode::GetYRotate( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_yRotate );
            }

            int CFlowJoystickNode::GetZRotate( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_zRotate );
            }

            int CFlowJoystickNode::GetPOV( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_POV );
            }

            int CFlowJoystickNode::GetSlider( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_slider );
            }

            IFlowNodePtr Clone( SActivationInfo* pActInfo )
            {
                return new CFlowJoystickNode( pActInfo );
            }

            virtual void GetMemoryUsage( ICrySizer* s ) const
            {
                s->Add( *this );
            }

            void Serialize( SActivationInfo* pActInfo, TSerialize ser )
            {
                if ( ser.IsReading() )
                {
                    m_actInfo = *pActInfo;
                }
            }

            enum EInputPorts
            {
                EIP_Enabled = 0,
                EIP_JoystickSelection
            };

            enum EOutputPorts
            {
                EOP_JoystickX = 0,
                EOP_JoystickY,
                EOP_JoystickZ,
                EOP_JoystickRotateX,
                EOP_JoystickRotateY,
                EOP_JoystickRotateZ,
                EOP_Slider,
                EOP_POV,
                EOP_ButtonPressed,
                EOP_ButtonReleased
            };

            virtual void GetConfiguration( SFlowNodeConfig& config )
            {
                string joysticks = "enum_string:";
                int i = 1;

                for ( TJoysticks::const_iterator sit = g_joysticks.begin(); sit != g_joysticks.end(); ++sit )
                {
                    char buffer[32];
                    itoa( i, buffer, 10 );

                    joysticks.append( "Joystick" );
                    joysticks.append( buffer );
                    joysticks.append( "=" );
                    joysticks.append( buffer );
                    joysticks.append( "," );
                    i++;
                }

                static const SInputPortConfig inputs[] =
                {
                    InputPortConfig<bool>( "Enabled", true, _HELP( "Enables/Disables the joystick" ) ),
                    InputPortConfig<string>( "Joystick", "1", _HELP( "Select a joystick" ), "Joystick", _UICONFIG( joysticks ) ),
                    {0}
                };

                static const SOutputPortConfig outputs[] =
                {
                    OutputPortConfig<int>( "X", _HELP( "X-axis, usually the left-right movement of a stick." ) ),
                    OutputPortConfig<int>( "Y", _HELP( "Y-axis, usually the forward-backward movement of a stick." ) ),
                    OutputPortConfig<int>( "Z", _HELP( "Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0." ) ),
                    OutputPortConfig<int>( "X-Rotate", _HELP( "X-axis rotation. If the joystick does not have this axis, the value is 0." ) ),
                    OutputPortConfig<int>( "Y-Rotate", _HELP( "Y-axis rotation. If the joystick does not have this axis, the value is 0." ) ),
                    OutputPortConfig<int>( "Z-Rotate", _HELP( "Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0." ) ),
                    OutputPortConfig<int>( "Slider", _HELP( "Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick." ) ),
                    OutputPortConfig<int>( "POV", _HELP( "Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as - 1. For indicators that have only five positions, the value for a controller is - 1, 0, 9,000, 18,000, or 27,000." ) ),
                    OutputPortConfig<int>( "ButtonPressed", _HELP( "Joystick button pressed" ) ),
                    OutputPortConfig<int>( "ButtonReleased", _HELP( "Joystick button released" ) ),
                    {0}
                };

                config.pInputPorts = inputs;
                config.pOutputPorts = outputs;
                config.sDescription = _HELP( "Joystick infos" );
                config.SetCategory( EFLN_APPROVED );
            }

            void SetNewJoystick( int joystick )
            {
                if ( joystick == 0 )
                {
                    joystick = 1;
                }

                TJoysticks::iterator iter = g_joysticks.begin();

                if ( joystick == 1 && g_joysticks.size() == 1 )
                {
                    m_currentJoystick = iter->first;
                    m_CurrentCapabilities.dwSize = sizeof( DIDEVCAPS );
                    m_CurrentCapabilities = iter->second;

                    SAFE_DELETE( m_buttons );
                    m_buttons = new int[m_CurrentCapabilities.dwButtons];
                }

                else if ( g_joysticks.size() > 1 )
                {
                    TJoysticks::iterator end = g_joysticks.end();

                    int i = 2;
                    ++iter;

                    for ( ; iter != end; ++iter )
                    {
                        if ( i == joystick )
                        {
                            break;
                        }

                        i++;
                    }

                    m_currentJoystick = iter->first;
                    m_CurrentCapabilities.dwSize = sizeof( DIDEVCAPS );
                    m_CurrentCapabilities = iter->second;

                    SAFE_DELETE( m_buttons );
                    m_buttons = new int[m_CurrentCapabilities.dwButtons];
                }
            }

            virtual void ProcessEvent( EFlowEvent event, SActivationInfo* pActInfo )
            {
                switch ( event )
                {
                    case eFE_Initialize:
                        {
                            m_actInfo = *pActInfo;
                            m_bEnabled = true;
                            pActInfo->pGraph->SetRegularlyUpdated( pActInfo->myID, true );
                            SetNewJoystick( atoi( GetPortString( &m_actInfo, EIP_JoystickSelection ) ) );

                            break;
                        }

                    case eFE_Activate:
                        {
                            if ( IsPortActive( pActInfo, EIP_Enabled ) )
                            {
                                m_bEnabled = GetPortBool( pActInfo, EIP_Enabled );
                            }

                            else if ( IsPortActive( pActInfo, EIP_JoystickSelection ) )
                            {
                                SetNewJoystick( atoi( GetPortString( &m_actInfo, EIP_JoystickSelection ) ) );
                            }

                            break;
                        }

                    case eFE_Update:
                        {
                            if ( m_currentJoystick == NULL || m_buttons == NULL || !m_bEnabled )
                            {
                                return;
                            }

                            DIJOYSTATE2 js;

                            if ( PollJoystick( &js, m_currentJoystick ) == DI_OK )
                            {
                                m_xAxis = static_cast<int>( js.lX );
                                m_yAxis = static_cast<int>( js.lY );
                                m_zAxis = static_cast<int>( js.lZ );

                                m_xRotate = static_cast<int>( js.lRx );
                                m_yRotate = static_cast<int>( js.lRy );
                                m_zRotate = static_cast<int>( js.lRz );

                                m_slider = static_cast<int>( js.rglSlider[0] );
                                m_POV = static_cast<int>( js.rgdwPOV[0] );

                                ActivateOutput( pActInfo, EOP_JoystickX, m_xAxis );
                                ActivateOutput( pActInfo, EOP_JoystickY, m_yAxis );
                                ActivateOutput( pActInfo, EOP_JoystickZ, m_zAxis );

                                ActivateOutput( pActInfo, EOP_JoystickRotateX, m_xRotate );
                                ActivateOutput( pActInfo, EOP_JoystickRotateY, m_yRotate );
                                ActivateOutput( pActInfo, EOP_JoystickRotateZ, m_zRotate );

                                ActivateOutput( pActInfo, EOP_Slider, m_slider );
                                ActivateOutput( pActInfo, EOP_POV, m_POV );

                                for ( int i = 0; i < m_CurrentCapabilities.dwButtons; i++ )
                                {
                                    BYTE button = js.rgbButtons[i];

                                    if ( button & 0x80 )
                                    {
                                        if ( m_buttons[i] != 1 )
                                        {
                                            m_buttons[i] = 1;
                                        }

                                        ActivateOutput( pActInfo, EOP_ButtonPressed, i + 1 );
                                    }

                                    else
                                    {
                                        if ( m_buttons[i] == 1 )
                                        {
                                            m_buttons[i] = 0;
                                            ActivateOutput( pActInfo, EOP_ButtonReleased, i + 1 );
                                        }
                                    }
                                }
                            }

                            break;
                        }
                }
            }

            virtual void GetMemoryStatistics( ICrySizer* s )
            {
                s->Add( *this );
            }
    };
}

REGISTER_FLOW_NODE_EX( "Plugin_Joystick:Input", JoystickPlugin::CFlowJoystickNode, CFlowJoystickNode );<commit_msg>new 344 cdk version syntax<commit_after>/* Joystick_Plugin - for licensing and copyright see license.txt */

#include "StdAfx.h"
#include "Nodes/G2FlowBaseNode.h"
//#include <IScriptSystem.h>
//#include <ScriptHelpers.h>
#include <CPluginJoystick.h>

namespace JoystickPlugin
{
    HRESULT PollJoystick( DIJOYSTATE2* js, LPDIRECTINPUTDEVICE8 joystick );

    class CFlowJoystickNode :
        public CFlowBaseNode<eNCT_Instanced>,
        public CScriptableBase
    {
        private:

            SActivationInfo m_actInfo;
            int* m_buttons;
            int m_xAxis;
            int m_yAxis;
            int m_zAxis;
            int m_xRotate;
            int m_yRotate;
            int m_zRotate;
            int m_slider;
            int m_POV;
            bool m_bEnabled;

            LPDIRECTINPUTDEVICE8 m_currentJoystick;
            DIDEVCAPS m_CurrentCapabilities;

        public:

            CFlowJoystickNode( SActivationInfo* pActInfo )
            {
#if CDK_VERSION < 343
                Init( gEnv->pSystem->GetIScriptSystem(), gEnv->pSystem );
#else
                Init( gEnv->pSystem->GetIScriptSystem() );
#endif
                SetGlobalName( "Joystick" );

#undef SCRIPT_REG_CLASSNAME
#define SCRIPT_REG_CLASSNAME &CFlowJoystickNode::

                SCRIPT_REG_TEMPLFUNC( GetXAxis, "" );
                SCRIPT_REG_TEMPLFUNC( GetYAxis, "" );
                SCRIPT_REG_TEMPLFUNC( GetZAxis, "" );
                SCRIPT_REG_TEMPLFUNC( GetButtonState, "button" );
                SCRIPT_REG_TEMPLFUNC( SetJoystick, "joystick" );
                SCRIPT_REG_TEMPLFUNC( GetNumButtons, "" );
                SCRIPT_REG_TEMPLFUNC( GetPOV, "" );
                SCRIPT_REG_TEMPLFUNC( GetSlider, "" );
                SCRIPT_REG_TEMPLFUNC( GetXRotate, "" );
                SCRIPT_REG_TEMPLFUNC( GetYRotate, "" );
                SCRIPT_REG_TEMPLFUNC( GetZRotate, "" );

#undef SCRIPT_REG_CLASSNAME

                m_xAxis = 0;
                m_yAxis = 0;
                m_zAxis = 0;
                m_xRotate = 0;
                m_yRotate = 0;
                m_zRotate = 0;
                m_slider = 0;
                m_POV = 0;
                m_buttons = NULL;
                m_currentJoystick = NULL;
                m_bEnabled = true;
            }

            ~CFlowJoystickNode()
            {
                SAFE_DELETE( m_buttons );

                if ( m_currentJoystick )
                {
                    m_currentJoystick->Unacquire();
                }
            }

            int CFlowJoystickNode::GetButtonState( IFunctionHandler* pH, int button )
            {
                if ( !m_buttons || button > m_CurrentCapabilities.dwButtons || button < 1 )
                {
                    return pH->EndFunction();
                }

                return pH->EndFunction( m_buttons[button - 1] );
            }

            int CFlowJoystickNode::GetNumButtons( IFunctionHandler* pH )
            {
                return pH->EndFunction( ( int )m_CurrentCapabilities.dwButtons );
            }

            int CFlowJoystickNode::SetJoystick( IFunctionHandler* pH, int joystick )
            {
                if ( joystick > g_joysticks.size() || joystick < 1 )
                {
                    SetNewJoystick( 1 );
                    return pH->EndFunction();
                }

                SetNewJoystick( joystick );

                return pH->EndFunction();
            }

            int CFlowJoystickNode::GetXAxis( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_xAxis );
            }

            int CFlowJoystickNode::GetYAxis( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_yAxis );
            }

            int CFlowJoystickNode::GetZAxis( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_zAxis );
            }

            int CFlowJoystickNode::GetXRotate( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_xRotate );
            }

            int CFlowJoystickNode::GetYRotate( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_yRotate );
            }

            int CFlowJoystickNode::GetZRotate( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_zRotate );
            }

            int CFlowJoystickNode::GetPOV( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_POV );
            }

            int CFlowJoystickNode::GetSlider( IFunctionHandler* pH )
            {
                return pH->EndFunction( m_slider );
            }

            IFlowNodePtr Clone( SActivationInfo* pActInfo )
            {
                return new CFlowJoystickNode( pActInfo );
            }

            virtual void GetMemoryUsage( ICrySizer* s ) const
            {
                s->Add( *this );
            }

            void Serialize( SActivationInfo* pActInfo, TSerialize ser )
            {
                if ( ser.IsReading() )
                {
                    m_actInfo = *pActInfo;
                }
            }

            enum EInputPorts
            {
                EIP_Enabled = 0,
                EIP_JoystickSelection
            };

            enum EOutputPorts
            {
                EOP_JoystickX = 0,
                EOP_JoystickY,
                EOP_JoystickZ,
                EOP_JoystickRotateX,
                EOP_JoystickRotateY,
                EOP_JoystickRotateZ,
                EOP_Slider,
                EOP_POV,
                EOP_ButtonPressed,
                EOP_ButtonReleased
            };

            virtual void GetConfiguration( SFlowNodeConfig& config )
            {
                string joysticks = "enum_string:";
                int i = 1;

                for ( TJoysticks::const_iterator sit = g_joysticks.begin(); sit != g_joysticks.end(); ++sit )
                {
                    char buffer[32];
                    itoa( i, buffer, 10 );

                    joysticks.append( "Joystick" );
                    joysticks.append( buffer );
                    joysticks.append( "=" );
                    joysticks.append( buffer );
                    joysticks.append( "," );
                    i++;
                }

                static const SInputPortConfig inputs[] =
                {
                    InputPortConfig<bool>( "Enabled", true, _HELP( "Enables/Disables the joystick" ) ),
                    InputPortConfig<string>( "Joystick", "1", _HELP( "Select a joystick" ), "Joystick", _UICONFIG( joysticks ) ),
                    {0}
                };

                static const SOutputPortConfig outputs[] =
                {
                    OutputPortConfig<int>( "X", _HELP( "X-axis, usually the left-right movement of a stick." ) ),
                    OutputPortConfig<int>( "Y", _HELP( "Y-axis, usually the forward-backward movement of a stick." ) ),
                    OutputPortConfig<int>( "Z", _HELP( "Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0." ) ),
                    OutputPortConfig<int>( "X-Rotate", _HELP( "X-axis rotation. If the joystick does not have this axis, the value is 0." ) ),
                    OutputPortConfig<int>( "Y-Rotate", _HELP( "Y-axis rotation. If the joystick does not have this axis, the value is 0." ) ),
                    OutputPortConfig<int>( "Z-Rotate", _HELP( "Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0." ) ),
                    OutputPortConfig<int>( "Slider", _HELP( "Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick." ) ),
                    OutputPortConfig<int>( "POV", _HELP( "Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as - 1. For indicators that have only five positions, the value for a controller is - 1, 0, 9,000, 18,000, or 27,000." ) ),
                    OutputPortConfig<int>( "ButtonPressed", _HELP( "Joystick button pressed" ) ),
                    OutputPortConfig<int>( "ButtonReleased", _HELP( "Joystick button released" ) ),
                    {0}
                };

                config.pInputPorts = inputs;
                config.pOutputPorts = outputs;
                config.sDescription = _HELP( "Joystick infos" );
                config.SetCategory( EFLN_APPROVED );
            }

            void SetNewJoystick( int joystick )
            {
                if ( joystick == 0 )
                {
                    joystick = 1;
                }

                TJoysticks::iterator iter = g_joysticks.begin();

                if ( joystick == 1 && g_joysticks.size() == 1 )
                {
                    m_currentJoystick = iter->first;
                    m_CurrentCapabilities.dwSize = sizeof( DIDEVCAPS );
                    m_CurrentCapabilities = iter->second;

                    SAFE_DELETE( m_buttons );
                    m_buttons = new int[m_CurrentCapabilities.dwButtons];
                }

                else if ( g_joysticks.size() > 1 )
                {
                    TJoysticks::iterator end = g_joysticks.end();

                    int i = 2;
                    ++iter;

                    for ( ; iter != end; ++iter )
                    {
                        if ( i == joystick )
                        {
                            break;
                        }

                        i++;
                    }

                    m_currentJoystick = iter->first;
                    m_CurrentCapabilities.dwSize = sizeof( DIDEVCAPS );
                    m_CurrentCapabilities = iter->second;

                    SAFE_DELETE( m_buttons );
                    m_buttons = new int[m_CurrentCapabilities.dwButtons];
                }
            }

            virtual void ProcessEvent( EFlowEvent event, SActivationInfo* pActInfo )
            {
                switch ( event )
                {
                    case eFE_Initialize:
                        {
                            m_actInfo = *pActInfo;
                            m_bEnabled = true;
                            pActInfo->pGraph->SetRegularlyUpdated( pActInfo->myID, true );
                            SetNewJoystick( atoi( GetPortString( &m_actInfo, EIP_JoystickSelection ) ) );

                            break;
                        }

                    case eFE_Activate:
                        {
                            if ( IsPortActive( pActInfo, EIP_Enabled ) )
                            {
                                m_bEnabled = GetPortBool( pActInfo, EIP_Enabled );
                            }

                            else if ( IsPortActive( pActInfo, EIP_JoystickSelection ) )
                            {
                                SetNewJoystick( atoi( GetPortString( &m_actInfo, EIP_JoystickSelection ) ) );
                            }

                            break;
                        }

                    case eFE_Update:
                        {
                            if ( m_currentJoystick == NULL || m_buttons == NULL || !m_bEnabled )
                            {
                                return;
                            }

                            DIJOYSTATE2 js;

                            if ( PollJoystick( &js, m_currentJoystick ) == DI_OK )
                            {
                                m_xAxis = static_cast<int>( js.lX );
                                m_yAxis = static_cast<int>( js.lY );
                                m_zAxis = static_cast<int>( js.lZ );

                                m_xRotate = static_cast<int>( js.lRx );
                                m_yRotate = static_cast<int>( js.lRy );
                                m_zRotate = static_cast<int>( js.lRz );

                                m_slider = static_cast<int>( js.rglSlider[0] );
                                m_POV = static_cast<int>( js.rgdwPOV[0] );

                                ActivateOutput( pActInfo, EOP_JoystickX, m_xAxis );
                                ActivateOutput( pActInfo, EOP_JoystickY, m_yAxis );
                                ActivateOutput( pActInfo, EOP_JoystickZ, m_zAxis );

                                ActivateOutput( pActInfo, EOP_JoystickRotateX, m_xRotate );
                                ActivateOutput( pActInfo, EOP_JoystickRotateY, m_yRotate );
                                ActivateOutput( pActInfo, EOP_JoystickRotateZ, m_zRotate );

                                ActivateOutput( pActInfo, EOP_Slider, m_slider );
                                ActivateOutput( pActInfo, EOP_POV, m_POV );

                                for ( int i = 0; i < m_CurrentCapabilities.dwButtons; i++ )
                                {
                                    BYTE button = js.rgbButtons[i];

                                    if ( button & 0x80 )
                                    {
                                        if ( m_buttons[i] != 1 )
                                        {
                                            m_buttons[i] = 1;
                                        }

                                        ActivateOutput( pActInfo, EOP_ButtonPressed, i + 1 );
                                    }

                                    else
                                    {
                                        if ( m_buttons[i] == 1 )
                                        {
                                            m_buttons[i] = 0;
                                            ActivateOutput( pActInfo, EOP_ButtonReleased, i + 1 );
                                        }
                                    }
                                }
                            }

                            break;
                        }
                }
            }

            virtual void GetMemoryStatistics( ICrySizer* s )
            {
                s->Add( *this );
            }
    };
}

REGISTER_FLOW_NODE_EX( "Plugin_Joystick:Input", JoystickPlugin::CFlowJoystickNode, CFlowJoystickNode );<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
//   File: list.cpp
//
//   Class: list
//   Functions: main
//-----------------------------------------------------------------------------

#include "list.h"

using namespace std;

namespace NP_ADT
{
	//-------------------------------------------------------------------------
	// constructor
	//-------------------------------------------------------------------------
	template<class datatype>
	CDLL<datatype>::CDLL(size_t n_elements, datatype datum)
		:m_size(0), handle(nullptr)
	{
		if (n_elements <= 0)
			throw out_of_range("Empty list");
		for (size_t i = 0; i < n_elements; i++)
			push_front(datum);
	}

	//-------------------------------------------------------------------------
	// copy constructor
	//-------------------------------------------------------------------------
	template<typename datatype>
	NP_ADT::CDLL<datatype>::CDLL(const CDLL<datatype> & cdll)
		: m_size(0), handle(nullptr)
	{
		CDLL::iterator r_it = cdll.begin();
		while (r_it != nullptr)
			push_front(*r_it++);
	}

	//-------------------------------------------------------------------------
	// insert element at front of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	void CDLL<datatype>::push_front(datatype datum)
	{
		node * temp = new node(datum, nullptr, nullptr);
		if (m_size++ == 0)
		{
			temp->next = temp;
			temp->prev = temp;
		}
		else {
			node * before = handle->prev;
			temp->next = handle;
			handle->prev = temp;
			temp->prev = before;
			before->next = temp;
		}
		handle = temp;
	}

	//-------------------------------------------------------------------------
	// insert element at end of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	void CDLL<datatype>::push_back(datatype datum)
	{
		node * temp = new node(datum, nullptr, nullptr);
		if (m_size++ == 0)
		{
			temp->next = temp;
			temp->prev = temp;
			handle = temp;
		}
		else {
			node * before = handle->prev;
			temp->next = handle;
			handle->prev = temp;
			temp->prev = before;
			before->next = temp;
		}
	}

	//-------------------------------------------------------------------------
	// removes front element and returns the data from that element
	//-------------------------------------------------------------------------
	template<typename datatype>
	datatype NP_ADT::CDLL<datatype>::pop_front()
	{
		if (handle == nullptr)
			throw runtime_error("Empty list");

		datatype poppedData = head()->data;

		if (m_size-- == 1) {
			handle = nullptr;
		}
		else {
			node * newHead = head()->next;
			newHead->prev = head()->prev;
			head()->prev->next = newHead;
			handle = newHead;
		}

		return poppedData;
	}

	//-------------------------------------------------------------------------
	// removes back element and returns the data from that element
	//-------------------------------------------------------------------------
	template<typename datatype>
	datatype NP_ADT::CDLL<datatype>::pop_back()
	{
		if (handle == nullptr)
			throw runtime_error("Empty list");

		datatype poppedData = tail()->data;

		if (m_size-- == 1) {
			handle = nullptr;
		}
		else {
			node * newTail = tail()->prev;
			newTail->next = tail()->next;
			tail()->next->prev = newTail;
		}

		return poppedData;
	}

	template<class datatype>
	datatype & CDLL<datatype>::front() const
	{
		if (head() != nullptr)
			return head()->data;
		else
			throw runtime_error("Empty list");
	}

	template<class datatype>
	inline datatype & CDLL<datatype>::back() const
	{
		if (tail() != nullptr)
			return tail()->data;
		else
			throw runtime_error("Empty list");
	}

	//-------------------------------------------------------------------------
	// constructor using iterators, copies from begin to one before end
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	NP_ADT::CDLL<datatype>::CDLL(iterator begin, iterator end)
		:m_size(0), handle(nullptr)
	{
		while (begin != end)
			push_front(*begin++);
	}*/

	//-----------------------------------------------------------------------------
	// empties the list
	//-----------------------------------------------------------------------------
	/*template<typename datatype>
	inline void NP_ADT::CDLL<datatype>::release()
	{
		while (handle != nullptr)
			pop_front();
	}*/

	//-------------------------------------------------------------------------
	// prints out a list
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	const datatype & NP_ADT::CDLL<datatype>::operator[](int index) const
	{
		CDLL::iterator p = x.begin(); // gets x.h
		sout << "(";
		while (p != nullptr)
		{
			sout << *p;
			if (p != x.end())
				sout << ",";
			++p; // advances iterator using next
		}
		sout << ")\n";
		return sout;
	}*/

	//-------------------------------------------------------------------------
	// returns a copy of rlist
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	CDLL<datatype> NP_ADT::CDLL<datatype>::operator=(const CDLL & rlist)
	{
		if (&rlist != this)
		{
			CDLL<datatype>::iterator r_it = rlist.begin();
			release();
			while (r_it != 0)
				push_front(*r_it++);
		}
		return *this;
	}*/

	//-------------------------------------------------------------------------
	// pre-increment
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++()
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		ptr = ptr->next;
		return *this;
	}*/

	//-------------------------------------------------------------------------
	// post-increment
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++(int)
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		iterator temp = *this;
		ptr = ptr->next;
		return temp;
	}*/

	//-------------------------------------------------------------------------
	// pre-decrement
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--()
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		ptr = ptr->prev;
		return *this;
	}*/

	//-------------------------------------------------------------------------
	// post-decrement
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--(int)
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		iterator temp = *this;
		ptr = ptr->prev;
		return temp;
	}*/

	//-------------------------------------------------------------------------
	// [] operator -- l-value
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	datatype & NP_ADT::CDLL<datatype>::operator[](int index)
	{
		iterator it;
		if (index >= 0)
		{
			if (index >= static_cast<int>(getSize()))
				throw out_of_range("index out-of-range");
			it = begin();
			for (int i = 0; i < index; i++)
				it++;
		}
		else
		{
			if (index < -(static_cast<int>(getSize())))
				throw out_of_range("index out-of-range");
			it = end();
			for (int i = -1; i > index; i--)
				it--;
		}
		return *it;
	}*/

	//-------------------------------------------------------------------------
	// ostream << overload
	//-------------------------------------------------------------------------
	//template<typename datatype>

	/*template <typename datatype>
	ostream & operator << (ostream& sout, const CDLL<datatype> & cdll)
	{

		return sout;
	}*/

} // end namespace NP_ADT

<commit_msg>add comments<commit_after>//-----------------------------------------------------------------------------
//   File: list.cpp
//
//   Class: list
//   Functions: main
//-----------------------------------------------------------------------------

#include "list.h"

using namespace std;

namespace NP_ADT
{
	//-------------------------------------------------------------------------
	// constructor
	//-------------------------------------------------------------------------
	template<class datatype>
	CDLL<datatype>::CDLL(size_t n_elements, datatype datum)
		:m_size(0), handle(nullptr)
	{
		if (n_elements <= 0)
			throw out_of_range("Empty list");
		for (size_t i = 0; i < n_elements; i++)
			push_front(datum);
	}

	//-------------------------------------------------------------------------
	// copy constructor
	//-------------------------------------------------------------------------
	template<typename datatype>
	NP_ADT::CDLL<datatype>::CDLL(const CDLL<datatype> & cdll)
		: m_size(0), handle(nullptr)
	{
		CDLL::iterator r_it = cdll.begin();
		while (r_it != nullptr)
			push_front(*r_it++);
	}

	//-------------------------------------------------------------------------
	// insert element at front of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	void CDLL<datatype>::push_front(datatype datum)
	{
		node * temp = new node(datum, nullptr, nullptr);
		if (m_size++ == 0)
		{
			temp->next = temp;
			temp->prev = temp;
		}
		else {
			node * before = handle->prev;
			temp->next = handle;
			handle->prev = temp;
			temp->prev = before;
			before->next = temp;
		}
		handle = temp;
	}

	//-------------------------------------------------------------------------
	// insert element at end of list
	//-------------------------------------------------------------------------
	template<typename datatype>
	void CDLL<datatype>::push_back(datatype datum)
	{
		node * temp = new node(datum, nullptr, nullptr);
		if (m_size++ == 0)
		{
			temp->next = temp;
			temp->prev = temp;
			handle = temp;
		}
		else {
			node * before = handle->prev;
			temp->next = handle;
			handle->prev = temp;
			temp->prev = before;
			before->next = temp;
		}
	}

	//-------------------------------------------------------------------------
	// removes front element and returns the data from that element
	//-------------------------------------------------------------------------
	template<typename datatype>
	datatype NP_ADT::CDLL<datatype>::pop_front()
	{
		if (handle == nullptr)
			throw runtime_error("Empty list");

		datatype poppedData = head()->data;

		if (m_size-- == 1) {
			handle = nullptr;
		}
		else {
			node * newHead = head()->next;
			newHead->prev = head()->prev;
			head()->prev->next = newHead;
			handle = newHead;
		}

		return poppedData;
	}

	//-------------------------------------------------------------------------
	// removes back element and returns the data from that element
	//-------------------------------------------------------------------------
	template<typename datatype>
	datatype NP_ADT::CDLL<datatype>::pop_back()
	{
		if (handle == nullptr)
			throw runtime_error("Empty list");

		datatype poppedData = tail()->data;

		if (m_size-- == 1) {
			handle = nullptr;
		}
		else {
			node * newTail = tail()->prev;
			newTail->next = tail()->next;
			tail()->next->prev = newTail;
		}

		return poppedData;
	}

	//-------------------------------------------------------------------------
	// returns data of the first item
	//-------------------------------------------------------------------------
	template<class datatype>
	datatype & CDLL<datatype>::front() const
	{
		if (head() != nullptr)
			return head()->data;
		else
			throw runtime_error("Empty list");
	}

	//-------------------------------------------------------------------------
	// returns data of the last item
	//-------------------------------------------------------------------------
	template<class datatype>
	inline datatype & CDLL<datatype>::back() const
	{
		if (tail() != nullptr)
			return tail()->data;
		else
			throw runtime_error("Empty list");
	}

	//-------------------------------------------------------------------------
	// constructor using iterators, copies from begin to one before end
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	NP_ADT::CDLL<datatype>::CDLL(iterator begin, iterator end)
		:m_size(0), handle(nullptr)
	{
		while (begin != end)
			push_front(*begin++);
	}*/

	//-----------------------------------------------------------------------------
	// empties the list
	//-----------------------------------------------------------------------------
	/*template<typename datatype>
	inline void NP_ADT::CDLL<datatype>::release()
	{
		while (handle != nullptr)
			pop_front();
	}*/

	//-------------------------------------------------------------------------
	// prints out a list
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	const datatype & NP_ADT::CDLL<datatype>::operator[](int index) const
	{
		CDLL::iterator p = x.begin(); // gets x.h
		sout << "(";
		while (p != nullptr)
		{
			sout << *p;
			if (p != x.end())
				sout << ",";
			++p; // advances iterator using next
		}
		sout << ")\n";
		return sout;
	}*/

	//-------------------------------------------------------------------------
	// returns a copy of rlist
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	CDLL<datatype> NP_ADT::CDLL<datatype>::operator=(const CDLL & rlist)
	{
		if (&rlist != this)
		{
			CDLL<datatype>::iterator r_it = rlist.begin();
			release();
			while (r_it != 0)
				push_front(*r_it++);
		}
		return *this;
	}*/

	//-------------------------------------------------------------------------
	// pre-increment
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++()
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		ptr = ptr->next;
		return *this;
	}*/

	//-------------------------------------------------------------------------
	// post-increment
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++(int)
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		iterator temp = *this;
		ptr = ptr->next;
		return temp;
	}*/

	//-------------------------------------------------------------------------
	// pre-decrement
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--()
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		ptr = ptr->prev;
		return *this;
	}*/

	//-------------------------------------------------------------------------
	// post-decrement
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--(int)
	{
		if (ptr == nullptr)
			throw runtime_error("nullptr pointer");
		iterator temp = *this;
		ptr = ptr->prev;
		return temp;
	}*/

	//-------------------------------------------------------------------------
	// [] operator -- l-value
	//-------------------------------------------------------------------------
	/*template<typename datatype>
	datatype & NP_ADT::CDLL<datatype>::operator[](int index)
	{
		iterator it;
		if (index >= 0)
		{
			if (index >= static_cast<int>(getSize()))
				throw out_of_range("index out-of-range");
			it = begin();
			for (int i = 0; i < index; i++)
				it++;
		}
		else
		{
			if (index < -(static_cast<int>(getSize())))
				throw out_of_range("index out-of-range");
			it = end();
			for (int i = -1; i > index; i--)
				it--;
		}
		return *it;
	}*/

	//-------------------------------------------------------------------------
	// ostream << overload
	//-------------------------------------------------------------------------
	//template<typename datatype>

	/*template <typename datatype>
	ostream & operator << (ostream& sout, const CDLL<datatype> & cdll)
	{

		return sout;
	}*/

} // end namespace NP_ADT

<|endoftext|>


<commit_before><commit_msg>Remove temporary output files<commit_after><|endoftext|>


<commit_before><commit_msg>Changed the point off of the surface to be calculated to be further off because it ended up thinking it collided with itself.<commit_after><|endoftext|>


<commit_before>#include "Renderer.h"
#include <fstream>

Renderer::Renderer()
    : m_world(nullptr),m_pixels(std::vector<RGBColor>()) {

}

Renderer::Renderer(World* world, const uint16_t image_width, const uint16_t image_height)
  : m_world(world), m_image_width(image_width), m_image_height(image_height), m_pixels(std::vector<RGBColor>(image_width * image_height, RGBColor(BACKGROUND_COLOR))) {

}

Renderer::~Renderer(){
    m_world = nullptr;
    m_pixels.clear();
}

void Renderer::exportImage(const std::string export_path) const {
    const int image_size = m_image_height * m_image_width * 4;
    const int headers_size = 14 + 40;
    const int filesize = image_size + headers_size;
    const int pixelsPerMeter = 2835;

    unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0,0,0, 54,0,0,0};
    //size of the file in bytes
    bmpfileheader[ 2] = (unsigned char)(filesize);
    bmpfileheader[ 3] = (unsigned char)(filesize>>8);
    bmpfileheader[ 4] = (unsigned char)(filesize>>16);
    bmpfileheader[ 5] = (unsigned char)(filesize>>24);

    unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0,24,0};
    //width of the image in bytes
    bmpinfoheader[ 4] = (unsigned char)(m_image_width);
    bmpinfoheader[ 5] = (unsigned char)(m_image_width>>8);
    bmpinfoheader[ 6] = (unsigned char)(m_image_width>>16);
    bmpinfoheader[ 7] = (unsigned char)(m_image_width>>24);

    //height of the image in bytes
    bmpinfoheader[ 8] = (unsigned char)(m_image_height);
    bmpinfoheader[ 9] = (unsigned char)(m_image_height>>8);
    bmpinfoheader[10] = (unsigned char)(m_image_height>>16);
    bmpinfoheader[11] = (unsigned char)(m_image_height>>24);

    // Size image in bytes
    bmpinfoheader[21] = (unsigned char)(image_size);
    bmpinfoheader[22] = (unsigned char)(image_size>>8);
    bmpinfoheader[23] = (unsigned char)(image_size>>16);
    bmpinfoheader[24] = (unsigned char)(image_size>>24);

    bmpinfoheader[25] = (unsigned char)(pixelsPerMeter);
    bmpinfoheader[26] = (unsigned char)(pixelsPerMeter>>8);
    bmpinfoheader[27] = (unsigned char)(pixelsPerMeter>>16);
    bmpinfoheader[28] = (unsigned char)(pixelsPerMeter>>24);

    bmpinfoheader[29] = (unsigned char)(pixelsPerMeter);
    bmpinfoheader[30] = (unsigned char)(pixelsPerMeter>>8);
    bmpinfoheader[31] = (unsigned char)(pixelsPerMeter>>16);
    bmpinfoheader[32] = (unsigned char)(pixelsPerMeter>>24);

    FILE *file = fopen(export_path.c_str(), "wb");//write-binary

    fwrite(bmpfileheader,1,14, file);
    fwrite(bmpinfoheader,1,40, file);

    for (int i = 0; i < m_pixels.size(); ++i){
        const RGBColor pixel = m_pixels[i];
        unsigned char color[3] = {
            (int) (pixel.b * 255),
            (int) (pixel.g * 255),
            (int) (pixel.r * 255)
        };
        fwrite(color, 1, 3, file);
    }
    fclose(file);
}
<commit_msg>Removed unnecessary copy constructor call<commit_after>#include "Renderer.h"
#include <fstream>

Renderer::Renderer()
    : m_world(nullptr),m_pixels(std::vector<RGBColor>()) {

}

Renderer::Renderer(World* world, const uint16_t image_width, const uint16_t image_height)
  : m_world(world), m_image_width(image_width), m_image_height(image_height), m_pixels(std::vector<RGBColor>(image_width * image_height, BACKGROUND_COLOR)) {

}

Renderer::~Renderer(){
    m_world = nullptr;
    m_pixels.clear();
}

void Renderer::exportImage(const std::string export_path) const {
    const int image_size = m_image_height * m_image_width * 4;
    const int headers_size = 14 + 40;
    const int filesize = image_size + headers_size;
    const int pixelsPerMeter = 2835;

    unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0,0,0, 54,0,0,0};
    //size of the file in bytes
    bmpfileheader[ 2] = (unsigned char)(filesize);
    bmpfileheader[ 3] = (unsigned char)(filesize>>8);
    bmpfileheader[ 4] = (unsigned char)(filesize>>16);
    bmpfileheader[ 5] = (unsigned char)(filesize>>24);

    unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0,24,0};
    //width of the image in bytes
    bmpinfoheader[ 4] = (unsigned char)(m_image_width);
    bmpinfoheader[ 5] = (unsigned char)(m_image_width>>8);
    bmpinfoheader[ 6] = (unsigned char)(m_image_width>>16);
    bmpinfoheader[ 7] = (unsigned char)(m_image_width>>24);

    //height of the image in bytes
    bmpinfoheader[ 8] = (unsigned char)(m_image_height);
    bmpinfoheader[ 9] = (unsigned char)(m_image_height>>8);
    bmpinfoheader[10] = (unsigned char)(m_image_height>>16);
    bmpinfoheader[11] = (unsigned char)(m_image_height>>24);

    // Size image in bytes
    bmpinfoheader[21] = (unsigned char)(image_size);
    bmpinfoheader[22] = (unsigned char)(image_size>>8);
    bmpinfoheader[23] = (unsigned char)(image_size>>16);
    bmpinfoheader[24] = (unsigned char)(image_size>>24);

    bmpinfoheader[25] = (unsigned char)(pixelsPerMeter);
    bmpinfoheader[26] = (unsigned char)(pixelsPerMeter>>8);
    bmpinfoheader[27] = (unsigned char)(pixelsPerMeter>>16);
    bmpinfoheader[28] = (unsigned char)(pixelsPerMeter>>24);

    bmpinfoheader[29] = (unsigned char)(pixelsPerMeter);
    bmpinfoheader[30] = (unsigned char)(pixelsPerMeter>>8);
    bmpinfoheader[31] = (unsigned char)(pixelsPerMeter>>16);
    bmpinfoheader[32] = (unsigned char)(pixelsPerMeter>>24);

    FILE *file = fopen(export_path.c_str(), "wb");//write-binary

    fwrite(bmpfileheader,1,14, file);
    fwrite(bmpinfoheader,1,40, file);

    for (int i = 0; i < m_pixels.size(); ++i){
        const RGBColor pixel = m_pixels[i];
        unsigned char color[3] = {
            (int) (pixel.b * 255),
            (int) (pixel.g * 255),
            (int) (pixel.r * 255)
        };
        fwrite(color, 1, 3, file);
    }
    fclose(file);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Aggregate
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "pch.h"
#include "handlers.h"
#include "crypt.hpp"

#if DEBUG_CGI

#ifdef _WIN32
#define SEP ';'
#else
#define SEP ':'
extern char ** environ;
#endif

namespace app
{
	class DebugPageHandler: public PageHandler
	{
		std::string m_service_url;
	public:
		struct DebugRequestState: FastCGI::RequestState
		{
			long long m_contentSize;
			char* m_buffer;
			DebugRequestState()
			: m_contentSize(0)
			, m_buffer(nullptr)
			{}
			~DebugRequestState()
			{
				free(m_buffer);
			}
			bool alloc(long long size)
			{
				free(m_buffer);
				m_buffer = (char*)malloc((size_t)size);
				m_contentSize = m_buffer ? size : 0;
				return m_buffer != nullptr;
			}
		};

		std::string name() const
		{
			return "DEBUG_CGI";
		}

		static void penv(FastCGI::Request& request, const char * const * envp)
		{
			request << "
\n";
			request << "

Name	Value

\n";
			size_t counter = 0;
			for ( ; *envp; ++envp)
			{
				const char* eq = strchr(*envp, '=');
				request << "<tr";
				if (counter++ % 2)
					request << " class='even'";
				request << ">";
				if (eq == *envp) request << " ";
				else if (eq == NULL) request << *envp;
				else request << std::string(*envp, eq);
				request << "	";
				if (eq == NULL) request << " ";
				else if (strncmp("PATH=", *envp, 5))
					request << eq + 1;
				else
				{
					const char* prev = eq + 1;
					const char* c = eq + 1;
					while (*c != 0)
					{
						while (*c != 0 && *c != SEP) ++c;
						request << std::string(prev, c);
						if (*c != 0) request << "
\n";
						if (*c != 0) ++c;
						prev = c;
					}
				}
				request << "
\n";
			}
			request << "
\n";
		}

		static void handlers(FastCGI::Request& request,
			HandlerMap::const_iterator begin,
			HandlerMap::const_iterator end)
		{
			request << "
\n";
			request << "

URL	Action	File

\n";
			size_t counter = 0;
			for ( ; begin != end; ++begin)
			{
				request << "<tr";
				if (counter++ % 2)
					request << " class='even'";
				request
					<< "><nobr><a href='" << begin->first << "'>" << begin->first << "</nobr>	"
					<< "<nobr>" << begin->second.ptr->name() << "</nobr>	" << begin->second.file << ":"
					<< begin->second.line << "
\n";
			}
			request << "

\n";
		}

		static void requests(FastCGI::Request& request, const FastCGI::Application::ReqList& list)
		{
			request << "
\n";
			request << "

URL	Remote Addr	Time (GMT)

\n";

			auto _cur = list.begin(), _end = list.end();
			size_t counter = 0;
			for ( ; _cur != _end; ++_cur)
			{
				if (_cur->resource == "/debug/?all")
					continue;

				tyme::tm_t gmt = tyme::gmtime(_cur->now);
				char timebuf[100];
				tyme::strftime(timebuf, "%a, %d-%b-%Y %H:%M:%S GMT", gmt );

				request << "<tr";
				if (counter++ % 2)
					request << " class='even'";
				request
					<< "><nobr><a href='http://" << _cur->server << _cur->resource << "'>" << _cur->resource << "</nobr>	"
					<< "<nobr>" << _cur->remote_addr << ":" << _cur->remote_port << "</nobr>	" << timebuf << "
\n";
			}
			request << "

\n";
		}

		static void cookies(FastCGI::Request& request, const std::map<std::string, std::string>& list)
		{
			request << "
\n";
			request << "

Name	Value

\n";

			auto _cur = list.begin(), _end = list.end();
			size_t counter = 0;
			for ( ; _cur != _end; ++_cur)
			{
				request << "<tr";
				if (counter++ % 2)
					request << " class='even'";
				request
					<< "><nobr>" << _cur->first << "</nobr>	"
					<< "" << _cur->second << "
\n";
			}
			request << "

\n";
		}

		bool restrictedPage() { return false; }
		const char* getPageTitle(PageTranslation& tr) { return "Debug"; }
		void prerender(FastCGI::SessionPtr session, Request& request, PageTranslation& tr)
		{
			crypt::session_t hash;
			crypt::session("reader.login", hash);
			request.setCookie("cookie-test", hash, tyme::now() + 86400*60);

			long long content_size = request.calcStreamSize();
			if (content_size > -1)
			{
				DebugRequestState* state = new (std::nothrow) DebugRequestState();
				if (state)
				{
					if (state->alloc(content_size))
						request.read(state->m_buffer, state->m_contentSize);

					request.setRequestState(FastCGI::RequestStatePtr(state));
				}
			}
		}

		void render(FastCGI::SessionPtr session, Request& request, PageTranslation& tr)
		{
			const char* QUERY_STRING = request.getParam("QUERY_STRING");
			bool all = (QUERY_STRING != NULL) && (strncmp(QUERY_STRING, "all", 3) == 0);

			request << "\n"
				"<title>Debug page</title>\n
\n"
				"
Debug page
\n"
				"
Table of Contents
\n"
				"
\n";
			if (all) request <<
				"
Environment
\n"
				;
			request <<
				"
Page Handlers
\n"
				"
Requests
\n"
				"
Variables
\n"
				"
Cookies
\n"
				"
Session
\n"
				"
\n"
				"
PID: " << request.app().pid() << "
\n"
				"
Request Number: " << request.app().requs().size() << "
\n";
			FastCGI::RequestStatePtr statePtr = request.getRequestState();
			DebugRequestState* state = static_cast<DebugRequestState*>(statePtr.get());
			if (state && state->m_contentSize > 0)
			{
				request << "
Data: " << state->m_contentSize << "
\n
";
				for (long long i = 0; i < state->m_contentSize; i++)
					request << state->m_buffer[i];
				request << "
\n";
			}

			if (all) {
				request << "
Environment
\n";
				penv(request, request.envp());
			}

			request << "
Page Handlers
\n";
			handlers(request, app::Handlers::begin(), app::Handlers::end());

			request << "
Requests
\n";
			requests(request, request.app().requs());

			request << "
Variables
\n";
			cookies(request, request.varDebugData());

			request << "
Cookies
\n";
			cookies(request, request.cookieDebugData());

			request << "
Session
\n";

			if (session.get())
			{
				char time[100];
				tyme::strftime(time, "%a, %d-%b-%Y %H:%M:%S GMT", tyme::gmtime(session->getStartTime()));
				request
					<< "
Current user: <a href=\"" << session->getEmail() << "\">" << session->getName() << "
\n"
					<< "The session has started on " << time << ".
";
			}
			else
			{
				request << "
There is no session in progress currently.
\n";
			}
		}

	};
}
REGISTER_HANDLER("/debug/", app::DebugPageHandler);
REGISTER_REDIRECT("/debug", "/debug/");

#endif
<commit_msg>Cleanup of the debug page<commit_after>/*
 * Copyright (C) 2013 Aggregate
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "pch.h"
#include "handlers.h"
#include "crypt.hpp"

#if DEBUG_CGI

#ifdef _WIN32
#define SEP ';'
#else
#define SEP ':'
extern char ** environ;
#endif

namespace app
{
	class DebugPageHandler: public PageHandler
	{
		std::string m_service_url;
	public:
		struct DebugRequestState: FastCGI::RequestState
		{
			long long m_contentSize;
			long long m_read;
			char* m_buffer;
			DebugRequestState()
			: m_contentSize(0)
			, m_read(0)
			, m_buffer(nullptr)
			{}
			~DebugRequestState()
			{
				free(m_buffer);
			}
			bool alloc(long long size)
			{
				free(m_buffer);
				m_buffer = (char*)malloc((size_t)size);
				m_contentSize = m_buffer ? size : 0;
				m_read = 0;
				return m_buffer != nullptr;
			}
		};

		std::string name() const
		{
			return "DEBUG_CGI";
		}

		static void penv(FastCGI::Request& request, const char * const * envp)
		{
			request << "
\n";
			request << "

Name	Value

\n";
			size_t counter = 0;
			for ( ; *envp; ++envp)
			{
				const char* eq = strchr(*envp, '=');
				request << "<tr";
				if (counter++ % 2)
					request << " class='even'";
				request << ">";
				if (eq == *envp) request << " ";
				else if (eq == NULL) request << *envp;
				else request << std::string(*envp, eq);
				request << "	";
				if (eq == NULL) request << " ";
				else if (strncmp("PATH=", *envp, 5))
					request << eq + 1;
				else
				{
					const char* prev = eq + 1;
					const char* c = eq + 1;
					while (*c != 0)
					{
						while (*c != 0 && *c != SEP) ++c;
						request << std::string(prev, c);
						if (*c != 0) request << "
\n";
						if (*c != 0) ++c;
						prev = c;
					}
				}
				request << "
\n";
			}
			request << "
\n";
		}

		static void handlers(FastCGI::Request& request,
			HandlerMap::const_iterator begin,
			HandlerMap::const_iterator end)
		{
			request << "
\n";
			request << "

URL	Action	File

\n";
			size_t counter = 0;
			for ( ; begin != end; ++begin)
			{
				request << "<tr";
				if (counter++ % 2)
					request << " class='even'";
				request
					<< "><nobr><a href='" << begin->first << "'>" << begin->first << "</nobr>	"
					<< "<nobr>" << begin->second.ptr->name() << "</nobr>	" << begin->second.file << ":"
					<< begin->second.line << "
\n";
			}
			request << "

\n";
		}

		static void requests(FastCGI::Request& request, const FastCGI::Application::ReqList& list)
		{
			request << "
\n";
			request << "

URL	Remote Addr	Time (GMT)

\n";

			auto _cur = list.begin(), _end = list.end();
			size_t counter = 0;
			for ( ; _cur != _end; ++_cur)
			{
				if (_cur->resource == "/debug/?all")
					continue;

				tyme::tm_t gmt = tyme::gmtime(_cur->now);
				char timebuf[100];
				tyme::strftime(timebuf, "%a, %d-%b-%Y %H:%M:%S GMT", gmt );

				request << "<tr";
				if (counter++ % 2)
					request << " class='even'";
				request
					<< "><nobr><a href='http://" << _cur->server << _cur->resource << "'>" << _cur->resource << "</nobr>	"
					<< "<nobr>" << _cur->remote_addr << ":" << _cur->remote_port << "</nobr>	" << timebuf << "
\n";
			}
			request << "

\n";
		}

		static void cookies(FastCGI::Request& request, const std::map<std::string, std::string>& list)
		{
			request << "
\n";
			request << "

Name	Value

\n";

			auto _cur = list.begin(), _end = list.end();
			size_t counter = 0;
			for ( ; _cur != _end; ++_cur)
			{
				request << "<tr";
				if (counter++ % 2)
					request << " class='even'";
				request
					<< "><nobr>" << _cur->first << "</nobr>	"
					<< "" << _cur->second << "
\n";
			}
			request << "

\n";
		}

		bool restrictedPage() { return false; }
		const char* getPageTitle(PageTranslation& tr) { return "Debug"; }
		void prerender(FastCGI::SessionPtr session, Request& request, PageTranslation& tr)
		{
			crypt::session_t hash;
			crypt::session("reader.login", hash);
			request.setCookie("cookie-test", hash, tyme::now() + 86400*60);

			long long content_size = request.calcStreamSize();
			if (content_size > -1)
			{
				DebugRequestState* state = new (std::nothrow) DebugRequestState();
				if (state)
				{
					if (state->alloc(content_size))
						state->m_read = request.read(state->m_buffer, state->m_contentSize);

					request.setRequestState(FastCGI::RequestStatePtr(state));
				}
			}
		}

		void render(FastCGI::SessionPtr session, Request& request, PageTranslation& tr)
		{
			bool all = request.getVariable("all") != NULL;

			request << "\n"
				"<title>Debug page</title>\n
\n"
				"
Debug page
\n"
				"
Table of Contents
\n"
				"
\n";
			if (all) request <<
				"
Environment
\n"
				;
			request <<
				"
Page Handlers
\n"
				"
Requests
\n"
				"
Variables
\n"
				"
Cookies
\n"
				"
Session
\n"
				"
\n"
				"
PID: " << request.app().pid() << "
\n"
				"
Request Number: " << request.app().requs().size() << "
\n";
			FastCGI::RequestStatePtr statePtr = request.getRequestState();
			DebugRequestState* state = static_cast<DebugRequestState*>(statePtr.get());
			if (state && state->m_contentSize > 0)
			{
				request << "
Data: " << state->m_contentSize;
				if (state->m_contentSize != state->m_read)
					request << " (" << state->m_contentSize - state->m_read << " read)";
				request << "
\n
";
				for (long long i = 0; i < state->m_read; i++)
					request << state->m_buffer[i];
				request << "
\n";
			}

			if (all) {
				request << "
Environment
\n";
				penv(request, request.envp());
			}

			request << "
Page Handlers
\n";
			handlers(request, app::Handlers::begin(), app::Handlers::end());

			request << "
Requests
\n";
			requests(request, request.app().requs());

			request << "
Variables
\n";
			cookies(request, request.varDebugData());

			request << "
Cookies
\n";
			cookies(request, request.cookieDebugData());

			request << "
Session
\n";

			if (session.get())
			{
				char time[100];
				tyme::strftime(time, "%a, %d-%b-%Y %H:%M:%S GMT", tyme::gmtime(session->getStartTime()));
				request
					<< "
Current user: <a href=\"" << session->getEmail() << "\">" << session->getName() << "
\n"
					<< "The session has started on " << time << ".
";
			}
			else
			{
				request << "
There is no session in progress currently.
\n";
			}
		}

	};
}
REGISTER_HANDLER("/debug/", app::DebugPageHandler);
REGISTER_REDIRECT("/debug", "/debug/");

#endif
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library 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 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 GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "OGLProgram.h"

#include "../base/Logger.h"
#include "../base/Exception.h"

#include "boost/tuple/tuple.hpp"
#include "boost/tuple/tuple_comparison.hpp"

#include <map>
#include <iostream>

namespace avg {

using namespace std;
typedef boost::tuple<OGLShaderPtr, OGLShaderPtr> ShaderPair;
typedef map<ShaderPair, OGLProgramPtr> ProgramCacheType;
static ProgramCacheType ProgramCache;

void OGLProgram::flushCache()
{
    ProgramCache.clear();
}

OGLProgramPtr OGLProgram::buildProgram(OGLShaderPtr fragmentShader)
{
    return OGLProgram::buildProgram( fragmentShader, OGLShaderPtr());
}

OGLProgramPtr OGLProgram::buildProgram(OGLShaderPtr fragmentShader, OGLShaderPtr vertexShader)
{
    ProgramCacheType::iterator pos;
    OGLProgramPtr prog;
    pos = ProgramCache.find( ShaderPair(fragmentShader,vertexShader) );
    if (pos != ProgramCache.end()){
        //Found it!
        prog = pos->second;
    } else {
        prog = OGLProgramPtr(new OGLProgram(fragmentShader, vertexShader));
        ProgramCache[ShaderPair(fragmentShader, vertexShader)] = prog;
        //cerr<<"Build Shader Program: "<<fragmentShader<<", "<<vertexShader<<endl;
    }
    return prog;
}

void OGLProgram::attachAndLink()
{
    int count = 0;
    for(vector<OGLShaderPtr>::iterator it=m_vShaders.begin(); it!=m_vShaders.end(); ++it) {
        if (*it) {
            glproc::AttachObject(m_hProgram, (*it)->getGLHandle());
            ++count;
        }
    }
    if (count == 0) {
        //No Programs ...
        m_hProgram = 0;
        return;
    }
    glproc::LinkProgram(m_hProgram);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::OGLProgram: glLinkProgram()");

    GLint bLinked;
    glproc::GetObjectParameteriv(m_hProgram, GL_OBJECT_LINK_STATUS_ARB, &bLinked);
    dumpInfoLog(m_hProgram);
    if (!bLinked) {
        throw(Exception(AVG_ERR_VIDEO_GENERAL,"Linking shader programs failed. Aborting."));
    }
}
OGLProgram::OGLProgram(OGLShaderPtr pFragmentShader)
{
    m_hProgram = glproc::CreateProgramObject();
    m_vShaders.push_back(pFragmentShader);
    attachAndLink();
}

OGLProgram::OGLProgram(OGLShaderPtr pFragmentShader, OGLShaderPtr pVertexShader)
{
    m_hProgram = glproc::CreateProgramObject();
    m_vShaders.push_back(pFragmentShader);
    m_vShaders.push_back(pVertexShader);
    attachAndLink();
}

OGLProgram::OGLProgram(vector<OGLShaderPtr> &vShaders)
{
    m_hProgram = glproc::CreateProgramObject();
    for(vector<OGLShaderPtr>::iterator it=vShaders.begin(); it!=vShaders.end(); ++it) {
        m_vShaders.push_back(*it);
    }
    attachAndLink();
}

OGLProgram::~OGLProgram()
{
    glproc::DeleteProgram(m_hProgram);
    //FIXME Deleteing the GLProgram breaks SDLDisplayEngine::render somehow???
}

void OGLProgram::activate()
{
   glproc::UseProgramObject(m_hProgram);
   OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::activate: glUseProgramObject()");
}

void OGLProgram::deactivate()
{
   glproc::UseProgramObject(0);
   OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::deactivate: glUseProgramObject()");
}
GLhandleARB OGLProgram::getProgram()
{
    return m_hProgram;
}

void OGLProgram::setUniformIntParam(const std::string& sName, int val)
{
    int loc = safeGetUniformLoc(sName);
    glproc::Uniform1i(loc, val);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}

void OGLProgram::setUniformFloatParam(const std::string& sName, float val)
{
    int loc = safeGetUniformLoc(sName);
    glproc::Uniform1f(loc, val);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}

void OGLProgram::setUniformFloatArrayParam(const std::string& sName, int count, float* pVal)
{
    int loc = safeGetUniformLoc(sName);
    glproc::Uniform1fv(loc, count, pVal);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}

int OGLProgram::safeGetUniformLoc(const std::string& sName)
{
    int loc = glproc::GetUniformLocation(m_hProgram, sName.c_str());
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
            "OGLProgram::setUniformIntParam: GetUniformLocation()");
    return loc;
}

}
<commit_msg>Workaround for windows crash at program end.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library 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 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 GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "OGLProgram.h"

#include "../base/Logger.h"
#include "../base/Exception.h"

#include "boost/tuple/tuple.hpp"
#include "boost/tuple/tuple_comparison.hpp"

#include <map>
#include <iostream>

namespace avg {

using namespace std;
typedef boost::tuple<OGLShaderPtr, OGLShaderPtr> ShaderPair;
typedef map<ShaderPair, OGLProgramPtr> ProgramCacheType;
static ProgramCacheType ProgramCache;

void OGLProgram::flushCache()
{
    ProgramCache.clear();
}

OGLProgramPtr OGLProgram::buildProgram(OGLShaderPtr fragmentShader)
{
    return OGLProgram::buildProgram( fragmentShader, OGLShaderPtr());
}

OGLProgramPtr OGLProgram::buildProgram(OGLShaderPtr fragmentShader, OGLShaderPtr vertexShader)
{
    ProgramCacheType::iterator pos;
    OGLProgramPtr prog;
    pos = ProgramCache.find( ShaderPair(fragmentShader,vertexShader) );
    if (pos != ProgramCache.end()){
        //Found it!
        prog = pos->second;
    } else {
        prog = OGLProgramPtr(new OGLProgram(fragmentShader, vertexShader));
        ProgramCache[ShaderPair(fragmentShader, vertexShader)] = prog;
        //cerr<<"Build Shader Program: "<<fragmentShader<<", "<<vertexShader<<endl;
    }
    return prog;
}

void OGLProgram::attachAndLink()
{
    int count = 0;
    for(vector<OGLShaderPtr>::iterator it=m_vShaders.begin(); it!=m_vShaders.end(); ++it) {
        if (*it) {
            glproc::AttachObject(m_hProgram, (*it)->getGLHandle());
            ++count;
        }
    }
    if (count == 0) {
        //No Programs ...
        m_hProgram = 0;
        return;
    }
    glproc::LinkProgram(m_hProgram);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::OGLProgram: glLinkProgram()");

    GLint bLinked;
    glproc::GetObjectParameteriv(m_hProgram, GL_OBJECT_LINK_STATUS_ARB, &bLinked);
    dumpInfoLog(m_hProgram);
    if (!bLinked) {
        throw(Exception(AVG_ERR_VIDEO_GENERAL,"Linking shader programs failed. Aborting."));
    }
}
OGLProgram::OGLProgram(OGLShaderPtr pFragmentShader)
{
    m_hProgram = glproc::CreateProgramObject();
    m_vShaders.push_back(pFragmentShader);
    attachAndLink();
}

OGLProgram::OGLProgram(OGLShaderPtr pFragmentShader, OGLShaderPtr pVertexShader)
{
    m_hProgram = glproc::CreateProgramObject();
    m_vShaders.push_back(pFragmentShader);
    m_vShaders.push_back(pVertexShader);
    attachAndLink();
}

OGLProgram::OGLProgram(vector<OGLShaderPtr> &vShaders)
{
    m_hProgram = glproc::CreateProgramObject();
    for(vector<OGLShaderPtr>::iterator it=vShaders.begin(); it!=vShaders.end(); ++it) {
        m_vShaders.push_back(*it);
    }
    attachAndLink();
}

OGLProgram::~OGLProgram()
{
    //TODO: Fix shader lifetime in GPUXxxFilter.
    //glproc::DeleteProgram(m_hProgram);
    //FIXME Deleteing the GLProgram breaks SDLDisplayEngine::render somehow???
}

void OGLProgram::activate()
{
   glproc::UseProgramObject(m_hProgram);
   OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::activate: glUseProgramObject()");
}

void OGLProgram::deactivate()
{
   glproc::UseProgramObject(0);
   OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::deactivate: glUseProgramObject()");
}
GLhandleARB OGLProgram::getProgram()
{
    return m_hProgram;
}

void OGLProgram::setUniformIntParam(const std::string& sName, int val)
{
    int loc = safeGetUniformLoc(sName);
    glproc::Uniform1i(loc, val);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}

void OGLProgram::setUniformFloatParam(const std::string& sName, float val)
{
    int loc = safeGetUniformLoc(sName);
    glproc::Uniform1f(loc, val);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}

void OGLProgram::setUniformFloatArrayParam(const std::string& sName, int count, float* pVal)
{
    int loc = safeGetUniformLoc(sName);
    glproc::Uniform1fv(loc, count, pVal);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}

int OGLProgram::safeGetUniformLoc(const std::string& sName)
{
    int loc = glproc::GetUniformLocation(m_hProgram, sName.c_str());
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
            "OGLProgram::setUniformIntParam: GetUniformLocation()");
    return loc;
}

}
<|endoftext|>


<commit_before>#include "gui/ng/spritewidget.hpp"

namespace namelessgui
{

RectangularWidget::RectangularWidget(std::string id)
	: Widget(id),
	  sf::RectangleShape(sf::Vector2f())
{
	setFillColor(sf::Color(255, 255, 0, 0));
	setSize({100, 100});
}

sf::Vector2f RectangularWidget::getSize() const
{
	return sf::RectangleShape::getSize();
}

void RectangularWidget::setScale(const sf::Vector2f& factors)
{
	sf::RectangleShape::setScale(factors);
}

void RectangularWidget::setScale(float scaleX, float scaleY)
{
	sf::RectangleShape::setScale(scaleX, scaleY);
}

sf::Vector2f RectangularWidget::getPosition() const
{
	return sf::RectangleShape::getPosition();
}

void RectangularWidget::setPosition(const sf::Vector2f& position)
{
	sf::RectangleShape::setPosition(position);
}

void RectangularWidget::render(sf::RenderTarget& target, sf::RenderStates states) const
{
	if(_visible)
		target.draw(static_cast<sf::RectangleShape>(*this), states);
	Widget::render(target, states);
}

void RectangularWidget::setSize(const sf::Vector2f& size)
{
	sf::RectangleShape::setSize(size);
}

sf::FloatRect RectangularWidget::getGlobalBounds()
{
	return sf::RectangleShape::getGlobalBounds();
}

void RectangularWidget::setTexture(const sf::Texture* texture, bool resetRect)
{
	sf::RectangleShape::setTexture(texture, resetRect);
}

} // namespace namelessgui
<commit_msg>Outline no longer accounts to widget area<commit_after>#include "gui/ng/spritewidget.hpp"

namespace namelessgui
{

RectangularWidget::RectangularWidget(std::string id)
	: Widget(id),
	  sf::RectangleShape(sf::Vector2f())
{
	setFillColor(sf::Color(255, 255, 0, 0));
	setSize({100, 100});
}

sf::Vector2f RectangularWidget::getSize() const
{
	return sf::RectangleShape::getSize();
}

void RectangularWidget::setScale(const sf::Vector2f& factors)
{
	sf::RectangleShape::setScale(factors);
}

void RectangularWidget::setScale(float scaleX, float scaleY)
{
	sf::RectangleShape::setScale(scaleX, scaleY);
}

sf::Vector2f RectangularWidget::getPosition() const
{
	return sf::RectangleShape::getPosition();
}

void RectangularWidget::setPosition(const sf::Vector2f& position)
{
	sf::RectangleShape::setPosition(position);
}

void RectangularWidget::render(sf::RenderTarget& target, sf::RenderStates states) const
{
	if(_visible)
		target.draw(static_cast<sf::RectangleShape>(*this), states);
	Widget::render(target, states);
}

void RectangularWidget::setSize(const sf::Vector2f& size)
{
	sf::RectangleShape::setSize(size);
}

sf::FloatRect RectangularWidget::getGlobalBounds()
{
	float outlineThickness = getOutlineThickness();
	sf::FloatRect bounds = sf::RectangleShape::getGlobalBounds();
	bounds.top += outlineThickness;
	bounds.left += outlineThickness;
	bounds.height -= 2 * outlineThickness;
	bounds.width -= 2 * outlineThickness;
	return bounds;
}

void RectangularWidget::setTexture(const sf::Texture* texture, bool resetRect)
{
	sf::RectangleShape::setTexture(texture, resetRect);
}

} // namespace namelessgui
<|endoftext|>


<commit_before>class Solution {
public:
    struct Node;
    using NodePtr = shared_ptr<Node>;

    struct Node {
        int length;
        NodePtr parent;
        vector<NodePtr> children;

        Node(NodePtr p) : length(0), parent(p) {}
        Node(int len) : length(len), parent(nullptr) {}
        Node(int len, NodePtr p) : length(len), parent(p) {}
    };

    int lengthLongestPath(string input) {
        const char *pb = input.data(), *pe = pb, *end = pb + input.size();
        bool isFile = false;

        while (pe < end && *pe != '\n' ) {
            if (*pe == '.') isFile = true;
            ++pe;
        }

        if (isFile) return pe - pb;

        NodePtr root = make_shared<Node>(pe - pb);
        pb = pe + 1;

        vector<NodePtr> files;

        NodePtr parent = root;
        int level = 1, levelNew;
        while (pb < end) {
            while (pb < end && *pb == '\t') ++pb;
            levelNew = pb - pe - 1;
            while (level > levelNew) {
                parent = parent->parent;
                level -= 1;
            }

            // child
            NodePtr n = make_shared<Node>(parent);
            parent->children.push_back(n);

            isFile = false;
            pe = pb + 1;
            while (pe < end && *pe != '\n') {
                if (*pe == '.') isFile = true;
                ++pe;
            }

            if (isFile) files.push_back(n);
            n->length = pe - pb + 1;

            // check next level
            level += 1;
            parent = n;
            pb = pe + 1;
        }

        int len, maxLength = numeric_limits<int>::min();
        for (auto& p : files) {
            len = p->length;
            while (p->parent) {
                p = p->parent;
                len += p->length;
            }
            if (maxLength < len) maxLength = len;
        }

        return maxLength;
    }
};
<commit_msg>update solution<commit_after>class Solution {
public:
    int lengthLongestPath(string input) {
        vector<int> length(1, 0);
        bool isFile;
        int level, len, maxlen = 0;

        for (int i = 0, n = input.size(); i < n; ++i) {
            // check level
            level = 0;
            while (i < n && input[i] == '\t') {
                ++level;
                ++i;
            }

            // check file
            len = 0;
            isFile = false;
            while (i < n && input[i] != '\n') {
                if (input[i] == '.') isFile = true;
                ++len;
                ++i;
            }

            // isFile
            if (isFile) {
                maxlen = max(maxlen, length[level] + len);
            } else {
                if (level + 1 < length.size()) {
                    length[level + 1] = length[level] + len + 1;
                } else if (level + 1 == length.size()) {
                    length.push_back(length.back() + len + 1);
                } else {
                    cout << "input error" << endl;
                }
            }
        }

        return maxlen;
    }
};
<|endoftext|>


<commit_before><commit_msg>Localization: fix bug on lossless_map_creator tool (#9928)<commit_after><|endoftext|>