diff --git a/extern/jsoncpp/src/lib_json/json_writer.cpp b/extern/jsoncpp/src/lib_json/json_writer.cpp index cd1d5064a8..d3df7704f2 100644 --- a/extern/jsoncpp/src/lib_json/json_writer.cpp +++ b/extern/jsoncpp/src/lib_json/json_writer.cpp @@ -542,7 +542,7 @@ StyledWriter::normalizeEOL( const std::string &text ) // ////////////////////////////////////////////////////////////////// StyledStreamWriter::StyledStreamWriter( std::string indentation ) - : document_(NULL) + : document_(nullptr) , rightMargin_( 74 ) , indentation_( indentation ) { @@ -559,7 +559,7 @@ StyledStreamWriter::write( std::ostream &out, const Value &root ) writeValue( root ); writeCommentAfterValueOnSameLine( root ); *document_ << "\n"; - document_ = NULL; // Forget the stream, for safety. + document_ = nullptr; // Forget the stream, for safety. } diff --git a/src/Actor.cpp b/src/Actor.cpp index 7f50a4f6f6..305db74e6d 100644 --- a/src/Actor.cpp +++ b/src/Actor.cpp @@ -86,7 +86,7 @@ void Actor::InitState() { StopTweening(); - m_pTempState = NULL; + m_pTempState = nullptr; m_baseRotation = RageVector3( 0, 0, 0 ); m_baseScale = RageVector3( 1, 1, 1 ); @@ -161,7 +161,7 @@ Actor::Actor() m_size = RageVector2( 1, 1 ); InitState(); - m_pParent = NULL; + m_pParent = nullptr; m_bFirstUpdate = true; } @@ -176,7 +176,7 @@ Actor::Actor( const Actor &cpy ): { /* Don't copy an Actor in the middle of rendering. */ ASSERT( cpy.m_pTempState == nullptr ); - m_pTempState = NULL; + m_pTempState = nullptr; #define CPY(x) x = cpy.x CPY( m_sName ); @@ -569,7 +569,7 @@ void Actor::SetTextureRenderStates() void Actor::EndDraw() { DISPLAY->PopMatrix(); - m_pTempState = NULL; + m_pTempState = nullptr; } void Actor::UpdateTweening( float fDeltaTime ) @@ -1298,7 +1298,7 @@ void Actor::SetParent( Actor *pParent ) Actor::TweenInfo::TweenInfo() { - m_pTween = NULL; + m_pTween = nullptr; } Actor::TweenInfo::~TweenInfo() @@ -1308,7 +1308,7 @@ Actor::TweenInfo::~TweenInfo() Actor::TweenInfo::TweenInfo( const TweenInfo &cpy ) { - m_pTween = NULL; + m_pTween = nullptr; *this = cpy; } diff --git a/src/Actor.h b/src/Actor.h index ac30557190..76f28fc458 100644 --- a/src/Actor.h +++ b/src/Actor.h @@ -1,755 +1,755 @@ -#ifndef ACTOR_H -#define ACTOR_H - -#include "PlayerNumber.h" -#include "RageTypes.h" -#include "RageUtil_AutoPtr.h" -#include "LuaReference.h" -#include "EnumHelper.h" -#include -class XNode; -struct lua_State; -class LuaClass; -#include "MessageManager.h" -#include "Tween.h" - -typedef AutoPtrCopyOnWrite apActorCommands; - -/** @brief The background layer. */ -#define DRAW_ORDER_BEFORE_EVERYTHING -200 -/** @brief The underlay layer. */ -#define DRAW_ORDER_UNDERLAY -100 -/** @brief The decorations layer. */ -#define DRAW_ORDER_DECORATIONS 0 -/** @brief The overlay layer. - * - * Normal screen elements go here. */ -#define DRAW_ORDER_OVERLAY +100 -/** @brief The transitions layer. */ -#define DRAW_ORDER_TRANSITIONS +200 -/** @brief The over everything layer. */ -#define DRAW_ORDER_AFTER_EVERYTHING +300 - -/** @brief The different horizontal alignments. */ -enum HorizAlign -{ - HorizAlign_Left, /**< Align to the left. */ - HorizAlign_Center, /**< Align to the center. */ - HorizAlign_Right, /**< Align to the right. */ - NUM_HorizAlign, /**< The number of horizontal alignments. */ - HorizAlign_Invalid -}; -LuaDeclareType( HorizAlign ); - -/** @brief The different vertical alignments. */ -enum VertAlign -{ - VertAlign_Top, /**< Align to the top. */ - VertAlign_Middle, /**< Align to the middle. */ - VertAlign_Bottom, /**< Align to the bottom. */ - NUM_VertAlign, /**< The number of vertical alignments. */ - VertAlign_Invalid -}; -LuaDeclareType( VertAlign ); - -/** @brief The left horizontal alignment constant. */ -#define align_left 0.0f -/** @brief The center horizontal alignment constant. */ -#define align_center 0.5f -/** @brief The right horizontal alignment constant. */ -#define align_right 1.0f -/** @brief The top vertical alignment constant. */ -#define align_top 0.0f -/** @brief The middle vertical alignment constant. */ -#define align_middle 0.5f -/** @brief The bottom vertical alignment constant. */ -#define align_bottom 1.0f - -// ssc futures: -/* -enum EffectAction -{ - EffectAction_None, // no_effect - // [Diffuse] - EffectAction_DiffuseBlink, // diffuse_blink - EffectAction_DiffuseShift, // diffuse_shift - EffectAction_DiffuseRamp, // diffuse_ramp - EffectAction_Rainbow, // rainbow - // [Glow] - EffectAction_GlowBlink, // glow_blink - EffectAction_GlowShift, // glow_shift - EffectAction_GlowRamp, // glow_ramp - // [Translate] - EffectAction_Bob, - EffectAction_Bounce, - EffectAction_Vibrate, - // [Rotate] - EffectAction_Spin, - EffectAction_Wag, - // [Zoom] - EffectAction_Pulse, - NUM_EffectAction, - EffectAction_Invalid -}; -LuaDeclareType( EffectAction ); -*/ - -/** @brief Base class for all objects that appear on the screen. */ -class Actor : public MessageSubscriber -{ -public: - /** @brief Set up the Actor with its initial settings. */ - Actor(); - /** - * @brief Copy a new Actor to the old one. - * @param cpy the new Actor to use in place of this one. */ - Actor( const Actor &cpy ); - virtual ~Actor(); - virtual Actor *Copy() const; - virtual void InitState(); - virtual void LoadFromNode( const XNode* pNode ); - - static void SetBGMTime( float fTime, float fBeat, float fTimeNoOffset, float fBeatNoOffset ); - static void SetPlayerBGMBeat( PlayerNumber pn, float fBeat, float fBeatNoOffset ); - static void SetBGMLight( int iLightNumber, float fCabinetLights ); - - /** - * @brief The list of the different effects. - * - * todo: split out into diffuse effects and translation effects, or - * create an effect stack instead. -aj */ - enum Effect { no_effect, - diffuse_blink, diffuse_shift, diffuse_ramp, - glow_blink, glow_shift, glow_ramp, rainbow, - wag, bounce, bob, pulse, spin, vibrate - }; - - /** @brief Various values an Actor's effect can be tied to. */ - enum EffectClock - { - CLOCK_TIMER, - CLOCK_TIMER_GLOBAL, - CLOCK_BGM_TIME, - CLOCK_BGM_BEAT, - CLOCK_BGM_TIME_NO_OFFSET, - CLOCK_BGM_BEAT_NO_OFFSET, - CLOCK_BGM_BEAT_PLAYER1, - CLOCK_BGM_BEAT_PLAYER2, - CLOCK_LIGHT_1 = 1000, - CLOCK_LIGHT_LAST = 1100, - NUM_CLOCKS - }; - - /* - * @brief What type of Effect this is. - * - * This is an internal enum for checking if an effect can be run; - * You can't have more than one of most EffectTypes in the Effect list. (You - * might be able to have mutliple EffectType_Translates; not sure yet.) -aj */ - /* - enum EffectType { - EffectType_Diffuse, - EffectType_Glow, - EffectType_Translate, - EffectType_Rotate, - EffectType_Zoom, - NUM_EffectType, - EffectType_Invalid - }; - */ - - // todo: use this instead of the Effect enum -aj - /* - // This is similar to Attributes in BitmapText as far as implementation. - struct Effect - { - Effect() : m_Action(EffectAction_None), m_Type(EffectType_Invalid), m_fSecsIntoEffect(0), - m_fEffectDelta(0), m_fEffectRampUp(0.5f), m_fEffectHoldAtHalf(0), - m_fEffectRampDown(0.5f), m_fEffectHoldAtZero(0), m_fEffectOffset(0), - m_EffectClock(CLOCK_TIMER), m_vEffectMagnitude(RageVector3(0,0,10)), - m_effectColor1(RageColor(1,1,1,1)), m_effectColor2(RageColor(1,1,1,1)) - { } - - RString m_sName; // friendly name - EffectAction m_Action; // replaces the old Effect enum - EffectType m_Type; // determined by EffectAction - float m_fSecsIntoEffect; - float m_fEffectDelta; - RageColor m_EffectColor1; - RageColor m_EffectColor2; - RageVector3 m_vEffectMagnitude; - EffectClock m_EffectClock; - // units depend on m_EffectClock - float m_fEffectRampUp; - float m_fEffectHoldAtHalf; - float m_fEffectRampDown; - float m_fEffectHoldAtZero; - float m_fEffectOffset; - }; - */ - - /** - * @brief The present state for the Tween. - */ - struct TweenState - { - void Init(); - static void MakeWeightedAverage( TweenState& average_out, const TweenState& ts1, const TweenState& ts2, float fPercentBetween ); - bool operator==( const TweenState &other ) const; - bool operator!=( const TweenState &other ) const { return !operator==(other); } - - // start and end position for tweening - RageVector3 pos; - RageVector3 rotation; - RageVector4 quat; - RageVector3 scale; - float fSkewX, fSkewY; - /** - * @brief The amount of cropping involved. - * - * If 0, there is no cropping. If 1, it's fully cropped. */ - RectF crop; - /** - * @brief The amount of fading involved. - * - * If 0, there is no fade. If 1, it's fully faded. */ - RectF fade; - /** - * @brief Four values making up the diffuse in this TweenState. - * - * 0 = UpperLeft, 1 = UpperRight, 2 = LowerLeft, 3 = LowerRight */ - RageColor diffuse[4]; - /** @brief The glow color for this TweenState. */ - RageColor glow; - /** @brief A magical value that nobody really knows the use for. ;) */ - float aux; - }; - - /** - * @brief Calls multiple functions for drawing the Actors. - * - * It calls the following in order: - * -# EarlyAbortDraw - * -# BeginDraw - * -# DrawPrimitives - * -# EndDraw - */ - void Draw(); - /** - * @brief Allow the Actor to be aborted early. - * - * Subclasses may wish to overwrite this to allow for - * aborted actors. - * @return false, as by default Actors shouldn't be aborted on drawing. */ - virtual bool EarlyAbortDraw() const { return false; } - /** @brief Start the drawing and push the transform on the world matrix stack. */ - virtual void BeginDraw(); - /** - * @brief Set the global rendering states of this Actor. - * - * This should be called at the beginning of an Actor's DrawPrimitives() call. */ - virtual void SetGlobalRenderStates(); - /** - * @brief Set the texture rendering states of this Actor. - * - * This should be called after setting a texture for the Actor. */ - virtual void SetTextureRenderStates(); - /** - * @brief Draw the primitives of the Actor. - * - * Derivative classes should override this function. */ - virtual void DrawPrimitives() {}; - /** @brief Pop the transform from the world matrix stack. */ - virtual void EndDraw(); - - // TODO: make Update non virtual and change all classes to override UpdateInternal - // instead. - bool IsFirstUpdate() const; - virtual void Update( float fDeltaTime ); // this can short circuit UpdateInternal - virtual void UpdateInternal( float fDeltaTime ); // override this - void UpdateTweening( float fDeltaTime ); - - /** - * @brief Retrieve the Actor's name. - * @return the Actor's name. */ - const RString &GetName() const { return m_sName; } - /** - * @brief Set the Actor's name to a new one. - * @param sName the new name for the Actor. */ - virtual void SetName( const RString &sName ) { m_sName = sName; } - /** - * @brief Give this Actor a new parent. - * @param pParent the new parent Actor. */ - void SetParent( Actor *pParent ); - /** - * @brief Retrieve the Actor's parent. - * @return the Actor's parent. */ - Actor *GetParent() { return m_pParent; } - /** - * @brief Retrieve the Actor's lineage. - * @return the Actor's lineage. */ - RString GetLineage() const; - - /** - * @brief Retrieve the Actor's x position. - * @return the Actor's x position. */ - float GetX() const { return m_current.pos.x; }; - /** - * @brief Retrieve the Actor's y position. - * @return the Actor's y position. */ - float GetY() const { return m_current.pos.y; }; - /** - * @brief Retrieve the Actor's z position. - * @return the Actor's z position. */ - float GetZ() const { return m_current.pos.z; }; - float GetDestX() const { return DestTweenState().pos.x; }; - float GetDestY() const { return DestTweenState().pos.y; }; - float GetDestZ() const { return DestTweenState().pos.z; }; - void SetX( float x ) { DestTweenState().pos.x = x; }; - void SetY( float y ) { DestTweenState().pos.y = y; }; - void SetZ( float z ) { DestTweenState().pos.z = z; }; - void SetXY( float x, float y ) { DestTweenState().pos.x = x; DestTweenState().pos.y = y; }; - /** - * @brief Add to the x position of this Actor. - * @param x the amount to add to the Actor's x position. */ - void AddX( float x ) { SetX( GetDestX()+x ); } - /** - * @brief Add to the y position of this Actor. - * @param y the amount to add to the Actor's y position. */ - void AddY( float y ) { SetY( GetDestY()+y ); } - /** - * @brief Add to the z position of this Actor. - * @param z the amount to add to the Actor's z position. */ - void AddZ( float z ) { SetZ( GetDestZ()+z ); } - - // height and width vary depending on zoom - float GetUnzoomedWidth() const { return m_size.x; } - float GetUnzoomedHeight() const { return m_size.y; } - float GetZoomedWidth() const { return m_size.x * m_baseScale.x * DestTweenState().scale.x; } - float GetZoomedHeight() const { return m_size.y * m_baseScale.y * DestTweenState().scale.y; } - void SetWidth( float width ) { m_size.x = width; } - void SetHeight( float height ) { m_size.y = height; } - - // Base values - float GetBaseZoomX() const { return m_baseScale.x; } - void SetBaseZoomX( float zoom ) { m_baseScale.x = zoom; } - float GetBaseZoomY() const { return m_baseScale.y; } - void SetBaseZoomY( float zoom ) { m_baseScale.y = zoom; } - float GetBaseZoomZ() const { return m_baseScale.z; } - void SetBaseZoomZ( float zoom ) { m_baseScale.z = zoom; } - void SetBaseZoom( float zoom ) { m_baseScale = RageVector3(zoom,zoom,zoom); } - void SetBaseRotationX( float rot ) { m_baseRotation.x = rot; } - void SetBaseRotationY( float rot ) { m_baseRotation.y = rot; } - void SetBaseRotationZ( float rot ) { m_baseRotation.z = rot; } - void SetBaseRotation( const RageVector3 &rot ) { m_baseRotation = rot; } - virtual void SetBaseAlpha( float fAlpha ) { m_fBaseAlpha = fAlpha; } - - /** - * @brief Retrieve the general zoom factor, using the x coordinate of the Actor. - * - * Note that this is not accurate in some cases. - * @return the zoom factor for the x coordinate of the Actor. */ - float GetZoom() const { return DestTweenState().scale.x; } - /** - * @brief Retrieve the zoom factor for the x coordinate of the Actor. - * @return the zoom factor for the x coordinate of the Actor. */ - float GetZoomX() const { return DestTweenState().scale.x; } - /** - * @brief Retrieve the zoom factor for the y coordinate of the Actor. - * @return the zoom factor for the y coordinate of the Actor. */ - float GetZoomY() const { return DestTweenState().scale.y; } - /** - * @brief Retrieve the zoom factor for the z coordinate of the Actor. - * @return the zoom factor for the z coordinate of the Actor. */ - float GetZoomZ() const { return DestTweenState().scale.z; } - /** - * @brief Set the zoom factor for all dimensions of the Actor. - * @param zoom the zoom factor for all dimensions. */ - void SetZoom( float zoom ) - { - DestTweenState().scale.x = zoom; - DestTweenState().scale.y = zoom; - DestTweenState().scale.z = zoom; - } - /** - * @brief Set the zoom factor for the x dimension of the Actor. - * @param zoom the zoom factor for the x dimension. */ - void SetZoomX( float zoom ) { DestTweenState().scale.x = zoom; } - /** - * @brief Set the zoom factor for the y dimension of the Actor. - * @param zoom the zoom factor for the y dimension. */ - void SetZoomY( float zoom ) { DestTweenState().scale.y = zoom; } - /** - * @brief Set the zoom factor for the z dimension of the Actor. - * @param zoom the zoom factor for the z dimension. */ - void SetZoomZ( float zoom ) { DestTweenState().scale.z = zoom; } - void ZoomTo( float fX, float fY ) { ZoomToWidth(fX); ZoomToHeight(fY); } - void ZoomToWidth( float zoom ) { SetZoomX( zoom / GetUnzoomedWidth() ); } - void ZoomToHeight( float zoom ) { SetZoomY( zoom / GetUnzoomedHeight() ); } - - float GetRotationX() const { return DestTweenState().rotation.x; } - float GetRotationY() const { return DestTweenState().rotation.y; } - float GetRotationZ() const { return DestTweenState().rotation.z; } - void SetRotationX( float rot ) { DestTweenState().rotation.x = rot; } - void SetRotationY( float rot ) { DestTweenState().rotation.y = rot; } - void SetRotationZ( float rot ) { DestTweenState().rotation.z = rot; } - // added in StepNXA, now available in sm-ssc: - void AddRotationX( float rot ) { DestTweenState().rotation.x += rot; }; - void AddRotationY( float rot ) { DestTweenState().rotation.y += rot; }; - void AddRotationZ( float rot ) { DestTweenState().rotation.z += rot; }; - // and these were normally in SM: - void AddRotationH( float rot ); - void AddRotationP( float rot ); - void AddRotationR( float rot ); - - void SetSkewX( float fAmount ) { DestTweenState().fSkewX = fAmount; } - float GetSkewX( float /* fAmount */ ) const { return DestTweenState().fSkewX; } - void SetSkewY( float fAmount ) { DestTweenState().fSkewY = fAmount; } - float GetSkewY( float /* fAmount */ ) const { return DestTweenState().fSkewY; } - - float GetCropLeft() const { return DestTweenState().crop.left; } - float GetCropTop() const { return DestTweenState().crop.top; } - float GetCropRight() const { return DestTweenState().crop.right; } - float GetCropBottom() const { return DestTweenState().crop.bottom; } - void SetCropLeft( float percent ) { DestTweenState().crop.left = percent; } - void SetCropTop( float percent ) { DestTweenState().crop.top = percent; } - void SetCropRight( float percent ) { DestTweenState().crop.right = percent; } - void SetCropBottom( float percent ) { DestTweenState().crop.bottom = percent; } - - void SetFadeLeft( float percent ) { DestTweenState().fade.left = percent; } - void SetFadeTop( float percent ) { DestTweenState().fade.top = percent; } - void SetFadeRight( float percent ) { DestTweenState().fade.right = percent; } - void SetFadeBottom( float percent ) { DestTweenState().fade.bottom = percent; } - - void SetGlobalDiffuseColor( RageColor c ); - - virtual void SetDiffuse( RageColor c ) { for(int i=0; i<4; i++) DestTweenState().diffuse[i] = c; }; - virtual void SetDiffuseAlpha( float f ) { for(int i = 0; i < 4; ++i) { RageColor c = GetDiffuses( i ); c.a = f; SetDiffuses( i, c ); } } - float GetCurrentDiffuseAlpha() const { return m_current.diffuse[0].a; } - void SetDiffuseColor( RageColor c ); - void SetDiffuses( int i, RageColor c ) { DestTweenState().diffuse[i] = c; }; - void SetDiffuseUpperLeft( RageColor c ) { DestTweenState().diffuse[0] = c; }; - void SetDiffuseUpperRight( RageColor c ) { DestTweenState().diffuse[1] = c; }; - void SetDiffuseLowerLeft( RageColor c ) { DestTweenState().diffuse[2] = c; }; - void SetDiffuseLowerRight( RageColor c ) { DestTweenState().diffuse[3] = c; }; - void SetDiffuseTopEdge( RageColor c ) { DestTweenState().diffuse[0] = DestTweenState().diffuse[1] = c; }; - void SetDiffuseRightEdge( RageColor c ) { DestTweenState().diffuse[1] = DestTweenState().diffuse[3] = c; }; - void SetDiffuseBottomEdge( RageColor c ) { DestTweenState().diffuse[2] = DestTweenState().diffuse[3] = c; }; - void SetDiffuseLeftEdge( RageColor c ) { DestTweenState().diffuse[0] = DestTweenState().diffuse[2] = c; }; - RageColor GetDiffuse() const { return DestTweenState().diffuse[0]; }; - RageColor GetDiffuses( int i ) const { return DestTweenState().diffuse[i]; }; - float GetDiffuseAlpha() const { return DestTweenState().diffuse[0].a; }; - void SetGlow( RageColor c ) { DestTweenState().glow = c; }; - RageColor GetGlow() const { return DestTweenState().glow; }; - - void SetAux( float f ) { DestTweenState().aux = f; } - float GetAux() const { return m_current.aux; } - - void BeginTweening( float time, ITween *pInterp ); - void BeginTweening( float time, TweenType tt = TWEEN_LINEAR ); - void StopTweening(); - void Sleep( float time ); - void QueueCommand( const RString& sCommandName ); - void QueueMessage( const RString& sMessageName ); - virtual void FinishTweening(); - virtual void HurryTweening( float factor ); - // Let ActorFrame and BGAnimation override - virtual float GetTweenTimeLeft() const; // Amount of time until all tweens have stopped - TweenState& DestTweenState() // where Actor will end when its tween finish - { - if( m_Tweens.empty() ) // not tweening - return m_current; - else - return m_Tweens.back()->state; - } - const TweenState& DestTweenState() const { return const_cast(this)->DestTweenState(); } - - /** @brief How do we handle stretching the Actor? */ - enum StretchType - { - fit_inside, /**< Have the Actor fit inside its parent, using the smaller zoom. */ - cover /**< Have the Actor cover its parent, using the larger zoom. */ - }; - - void ScaleToCover( const RectF &rect ) { ScaleTo( rect, cover ); } - void ScaleToFitInside( const RectF &rect ) { ScaleTo( rect, fit_inside); }; - void ScaleTo( const RectF &rect, StretchType st ); - - void StretchTo( const RectF &rect ); - - // Alignment settings. These need to be virtual for BitmapText - virtual void SetHorizAlign( float f ) { m_fHorizAlign = f; } - virtual void SetVertAlign( float f ) { m_fVertAlign = f; } - void SetHorizAlign( HorizAlign ha ) { SetHorizAlign( (ha == HorizAlign_Left)? 0.0f: (ha == HorizAlign_Center)? 0.5f: +1.0f ); } - void SetVertAlign( VertAlign va ) { SetVertAlign( (va == VertAlign_Top)? 0.0f: (va == VertAlign_Middle)? 0.5f: +1.0f ); } - virtual float GetHorizAlign() { return m_fHorizAlign; } - virtual float GetVertAlign() { return m_fVertAlign; } - - // effects -#if defined(SSC_FUTURES) - void StopEffects(); - Effect GetEffect( int i ) const { return m_Effects[i]; } -#else - void StopEffect() { m_Effect = no_effect; } - Effect GetEffect() const { return m_Effect; } -#endif - float GetSecsIntoEffect() const { return m_fSecsIntoEffect; } - float GetEffectDelta() const { return m_fEffectDelta; } - - // todo: account for SSC_FUTURES by adding an effect as an arg to each one -aj - void SetEffectColor1( RageColor c ) { m_effectColor1 = c; } - void SetEffectColor2( RageColor c ) { m_effectColor2 = c; } - void SetEffectPeriod( float fTime ); - float GetEffectPeriod() const; - void SetEffectTiming( float fRampUp, float fAtHalf, float fRampDown, float fAtZero ); - void SetEffectOffset( float fTime ) { m_fEffectOffset = fTime; } - void SetEffectClock( EffectClock c ) { m_EffectClock = c; } - void SetEffectClockString( const RString &s ); // convenience - - void SetEffectMagnitude( RageVector3 vec ) { m_vEffectMagnitude = vec; } - RageVector3 GetEffectMagnitude() const { return m_vEffectMagnitude; } - - void SetEffectDiffuseBlink( - float fEffectPeriodSeconds = 1.0f, - RageColor c1 = RageColor(0.5f,0.5f,0.5f,1), - RageColor c2 = RageColor(1,1,1,1) ); - void SetEffectDiffuseShift( float fEffectPeriodSeconds = 1.f, - RageColor c1 = RageColor(0,0,0,1), - RageColor c2 = RageColor(1,1,1,1) ); - void SetEffectDiffuseRamp( float fEffectPeriodSeconds = 1.f, - RageColor c1 = RageColor(0,0,0,1), - RageColor c2 = RageColor(1,1,1,1) ); - void SetEffectGlowBlink( float fEffectPeriodSeconds = 1.f, - RageColor c1 = RageColor(1,1,1,0.2f), - RageColor c2 = RageColor(1,1,1,0.8f) ); - void SetEffectGlowShift( - float fEffectPeriodSeconds = 1.0f, - RageColor c1 = RageColor(1,1,1,0.2f), - RageColor c2 = RageColor(1,1,1,0.8f) ); - void SetEffectGlowRamp( - float fEffectPeriodSeconds = 1.0f, - RageColor c1 = RageColor(1,1,1,0.2f), - RageColor c2 = RageColor(1,1,1,0.8f) ); - void SetEffectRainbow( - float fEffectPeriodSeconds = 2.0f ); - void SetEffectWag( - float fPeriod = 2.f, - RageVector3 vect = RageVector3(0,0,20) ); - void SetEffectBounce( - float fPeriod = 2.f, - RageVector3 vect = RageVector3(0,20,0) ); - void SetEffectBob( - float fPeriod = 2.f, - RageVector3 vect = RageVector3(0,20,0) ); - void SetEffectPulse( - float fPeriod = 2.f, - float fMinZoom = 0.5f, - float fMaxZoom = 1.f ); - void SetEffectSpin( RageVector3 vect = RageVector3(0,0,180) ); - void SetEffectVibrate( RageVector3 vect = RageVector3(10,10,10) ); - - - // other properties - /** - * @brief Determine if the Actor is visible at this time. - * @return true if it's visible, false otherwise. */ - bool GetVisible() const { return m_bVisible; } - void SetVisible( bool b ) { m_bVisible = b; } - void SetShadowLength( float fLength ) { m_fShadowLengthX = fLength; m_fShadowLengthY = fLength; } - void SetShadowLengthX( float fLengthX ) { m_fShadowLengthX = fLengthX; } - void SetShadowLengthY( float fLengthY ) { m_fShadowLengthY = fLengthY; } - void SetShadowColor( RageColor c ) { m_ShadowColor = c; } - // TODO: Implement hibernate as a tween type? - void SetHibernate( float fSecs ) { m_fHibernateSecondsLeft = fSecs; } - void SetDrawOrder( int iOrder ) { m_iDrawOrder = iOrder; } - int GetDrawOrder() const { return m_iDrawOrder; } - - virtual void EnableAnimation( bool b ) { m_bIsAnimating = b; } // Sprite needs to overload this - void StartAnimating() { this->EnableAnimation(true); } - void StopAnimating() { this->EnableAnimation(false); } - - // render states - void SetBlendMode( BlendMode mode ) { m_BlendMode = mode; } - void SetTextureWrapping( bool b ) { m_bTextureWrapping = b; } - void SetTextureFiltering( bool b ) { m_bTextureFiltering = b; } - void SetClearZBuffer( bool b ) { m_bClearZBuffer = b; } - void SetUseZBuffer( bool b ) { SetZTestMode(b?ZTEST_WRITE_ON_PASS:ZTEST_OFF); SetZWrite(b); } - virtual void SetZTestMode( ZTestMode mode ) { m_ZTestMode = mode; } - virtual void SetZWrite( bool b ) { m_bZWrite = b; } - void SetZBias( float f ) { m_fZBias = f; } - virtual void SetCullMode( CullMode mode ) { m_CullMode = mode; } - - // Lua - virtual void PushSelf( lua_State *L ); - virtual void PushContext( lua_State *L ); - - // Named commands - void AddCommand( const RString &sCmdName, apActorCommands apac ); - bool HasCommand( const RString &sCmdName ) const; - const apActorCommands *GetCommand( const RString &sCommandName ) const; - void PlayCommand( const RString &sCommandName ) { HandleMessage( Message(sCommandName) ); } // convenience - void PlayCommandNoRecurse( const Message &msg ); - - // Commands by reference - virtual void RunCommands( const LuaReference& cmds, const LuaReference *pParamTable = NULL ); - void RunCommands( const apActorCommands& cmds, const LuaReference *pParamTable = NULL ) { this->RunCommands( *cmds, pParamTable ); } // convenience - virtual void RunCommandsRecursively( const LuaReference& cmds, const LuaReference *pParamTable = NULL ) { RunCommands(cmds, pParamTable); } - // If we're a leaf, then execute this command. - virtual void RunCommandsOnLeaves( const LuaReference& cmds, const LuaReference *pParamTable = NULL ) { RunCommands(cmds, pParamTable); } - - // Messages - virtual void HandleMessage( const Message &msg ); - - // Animation - virtual int GetNumStates() const { return 1; } - virtual void SetState( int /* iNewState */ ) {} - virtual float GetAnimationLengthSeconds() const { return 0; } - virtual void SetSecondsIntoAnimation( float ) {} - virtual void SetUpdateRate( float ) {} - - HiddenPtr m_pLuaInstance; - -protected: - /** @brief the name of the Actor. */ - RString m_sName; - /** @brief the current parent of this Actor if it exists. */ - Actor *m_pParent; - - /** @brief Some general information about the Tween. */ - struct TweenInfo - { - // counters for tweening - TweenInfo(); - ~TweenInfo(); - TweenInfo( const TweenInfo &cpy ); - TweenInfo &operator=( const TweenInfo &rhs ); - - ITween *m_pTween; - /** @brief How far into the tween are we? */ - float m_fTimeLeftInTween; - /** @brief The number of seconds between Start and End positions/zooms. */ - float m_fTweenTime; - /** @brief The command to execute when this TweenState goes into effect. */ - RString m_sCommandName; - }; - - RageVector3 m_baseRotation; - RageVector3 m_baseScale; - float m_fBaseAlpha; - - RageVector2 m_size; - TweenState m_current; - TweenState m_start; - struct TweenStateAndInfo - { - TweenState state; - TweenInfo info; - }; - vector m_Tweens; - - /** @brief Temporary variables that are filled just before drawing */ - TweenState *m_pTempState; - - bool m_bFirstUpdate; - - // Stuff for alignment - /** @brief The particular horizontal alignment. - * - * Use the defined constant values for best effect. */ - float m_fHorizAlign; - /** @brief The particular vertical alignment. - * - * Use the defined constant values for best effect. */ - float m_fVertAlign; - - // Stuff for effects -#if defined(SSC_FUTURES) // be able to stack effects - vector m_Effects; -#else // compatibility - Effect m_Effect; -#endif - float m_fSecsIntoEffect; - float m_fEffectDelta; - - // units depend on m_EffectClock - float m_fEffectRampUp; - float m_fEffectHoldAtHalf; - float m_fEffectRampDown; - float m_fEffectHoldAtZero; - float m_fEffectOffset; - EffectClock m_EffectClock; - - /* This can be used in lieu of the fDeltaTime parameter to Update() to - * follow the effect clock. Actor::Update must be called first. */ - float GetEffectDeltaTime() const { return m_fEffectDelta; } - - // todo: account for SSC_FUTURES by having these be vectors too -aj - RageColor m_effectColor1; - RageColor m_effectColor2; - RageVector3 m_vEffectMagnitude; - - // other properties - bool m_bVisible; - bool m_bIsAnimating; - float m_fHibernateSecondsLeft; - float m_fShadowLengthX; - float m_fShadowLengthY; - RageColor m_ShadowColor; - /** @brief The draw order priority. - * - * The lower this number is, the sooner it is drawn. */ - int m_iDrawOrder; - - // render states - BlendMode m_BlendMode; - ZTestMode m_ZTestMode; - CullMode m_CullMode; - bool m_bTextureWrapping; - bool m_bTextureFiltering; - bool m_bClearZBuffer; - bool m_bZWrite; - /** - * @brief The amount of bias. - * - * If 0, there is no bias. If 1, there is a full bias. */ - float m_fZBias; - - // global state - static float g_fCurrentBGMTime, g_fCurrentBGMBeat; - static float g_fCurrentBGMTimeNoOffset, g_fCurrentBGMBeatNoOffset; - static vector g_vfCurrentBGMBeatPlayer; - static vector g_vfCurrentBGMBeatPlayerNoOffset; - -private: - // commands - map m_mapNameToCommands; -}; - -#endif - -/** - * @file - * @author Chris Danford (c) 2001-2004 - * @section LICENSE - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef ACTOR_H +#define ACTOR_H + +#include "PlayerNumber.h" +#include "RageTypes.h" +#include "RageUtil_AutoPtr.h" +#include "LuaReference.h" +#include "EnumHelper.h" +#include +class XNode; +struct lua_State; +class LuaClass; +#include "MessageManager.h" +#include "Tween.h" + +typedef AutoPtrCopyOnWrite apActorCommands; + +/** @brief The background layer. */ +#define DRAW_ORDER_BEFORE_EVERYTHING -200 +/** @brief The underlay layer. */ +#define DRAW_ORDER_UNDERLAY -100 +/** @brief The decorations layer. */ +#define DRAW_ORDER_DECORATIONS 0 +/** @brief The overlay layer. + * + * Normal screen elements go here. */ +#define DRAW_ORDER_OVERLAY +100 +/** @brief The transitions layer. */ +#define DRAW_ORDER_TRANSITIONS +200 +/** @brief The over everything layer. */ +#define DRAW_ORDER_AFTER_EVERYTHING +300 + +/** @brief The different horizontal alignments. */ +enum HorizAlign +{ + HorizAlign_Left, /**< Align to the left. */ + HorizAlign_Center, /**< Align to the center. */ + HorizAlign_Right, /**< Align to the right. */ + NUM_HorizAlign, /**< The number of horizontal alignments. */ + HorizAlign_Invalid +}; +LuaDeclareType( HorizAlign ); + +/** @brief The different vertical alignments. */ +enum VertAlign +{ + VertAlign_Top, /**< Align to the top. */ + VertAlign_Middle, /**< Align to the middle. */ + VertAlign_Bottom, /**< Align to the bottom. */ + NUM_VertAlign, /**< The number of vertical alignments. */ + VertAlign_Invalid +}; +LuaDeclareType( VertAlign ); + +/** @brief The left horizontal alignment constant. */ +#define align_left 0.0f +/** @brief The center horizontal alignment constant. */ +#define align_center 0.5f +/** @brief The right horizontal alignment constant. */ +#define align_right 1.0f +/** @brief The top vertical alignment constant. */ +#define align_top 0.0f +/** @brief The middle vertical alignment constant. */ +#define align_middle 0.5f +/** @brief The bottom vertical alignment constant. */ +#define align_bottom 1.0f + +// ssc futures: +/* +enum EffectAction +{ + EffectAction_None, // no_effect + // [Diffuse] + EffectAction_DiffuseBlink, // diffuse_blink + EffectAction_DiffuseShift, // diffuse_shift + EffectAction_DiffuseRamp, // diffuse_ramp + EffectAction_Rainbow, // rainbow + // [Glow] + EffectAction_GlowBlink, // glow_blink + EffectAction_GlowShift, // glow_shift + EffectAction_GlowRamp, // glow_ramp + // [Translate] + EffectAction_Bob, + EffectAction_Bounce, + EffectAction_Vibrate, + // [Rotate] + EffectAction_Spin, + EffectAction_Wag, + // [Zoom] + EffectAction_Pulse, + NUM_EffectAction, + EffectAction_Invalid +}; +LuaDeclareType( EffectAction ); +*/ + +/** @brief Base class for all objects that appear on the screen. */ +class Actor : public MessageSubscriber +{ +public: + /** @brief Set up the Actor with its initial settings. */ + Actor(); + /** + * @brief Copy a new Actor to the old one. + * @param cpy the new Actor to use in place of this one. */ + Actor( const Actor &cpy ); + virtual ~Actor(); + virtual Actor *Copy() const; + virtual void InitState(); + virtual void LoadFromNode( const XNode* pNode ); + + static void SetBGMTime( float fTime, float fBeat, float fTimeNoOffset, float fBeatNoOffset ); + static void SetPlayerBGMBeat( PlayerNumber pn, float fBeat, float fBeatNoOffset ); + static void SetBGMLight( int iLightNumber, float fCabinetLights ); + + /** + * @brief The list of the different effects. + * + * todo: split out into diffuse effects and translation effects, or + * create an effect stack instead. -aj */ + enum Effect { no_effect, + diffuse_blink, diffuse_shift, diffuse_ramp, + glow_blink, glow_shift, glow_ramp, rainbow, + wag, bounce, bob, pulse, spin, vibrate + }; + + /** @brief Various values an Actor's effect can be tied to. */ + enum EffectClock + { + CLOCK_TIMER, + CLOCK_TIMER_GLOBAL, + CLOCK_BGM_TIME, + CLOCK_BGM_BEAT, + CLOCK_BGM_TIME_NO_OFFSET, + CLOCK_BGM_BEAT_NO_OFFSET, + CLOCK_BGM_BEAT_PLAYER1, + CLOCK_BGM_BEAT_PLAYER2, + CLOCK_LIGHT_1 = 1000, + CLOCK_LIGHT_LAST = 1100, + NUM_CLOCKS + }; + + /* + * @brief What type of Effect this is. + * + * This is an internal enum for checking if an effect can be run; + * You can't have more than one of most EffectTypes in the Effect list. (You + * might be able to have mutliple EffectType_Translates; not sure yet.) -aj */ + /* + enum EffectType { + EffectType_Diffuse, + EffectType_Glow, + EffectType_Translate, + EffectType_Rotate, + EffectType_Zoom, + NUM_EffectType, + EffectType_Invalid + }; + */ + + // todo: use this instead of the Effect enum -aj + /* + // This is similar to Attributes in BitmapText as far as implementation. + struct Effect + { + Effect() : m_Action(EffectAction_None), m_Type(EffectType_Invalid), m_fSecsIntoEffect(0), + m_fEffectDelta(0), m_fEffectRampUp(0.5f), m_fEffectHoldAtHalf(0), + m_fEffectRampDown(0.5f), m_fEffectHoldAtZero(0), m_fEffectOffset(0), + m_EffectClock(CLOCK_TIMER), m_vEffectMagnitude(RageVector3(0,0,10)), + m_effectColor1(RageColor(1,1,1,1)), m_effectColor2(RageColor(1,1,1,1)) + { } + + RString m_sName; // friendly name + EffectAction m_Action; // replaces the old Effect enum + EffectType m_Type; // determined by EffectAction + float m_fSecsIntoEffect; + float m_fEffectDelta; + RageColor m_EffectColor1; + RageColor m_EffectColor2; + RageVector3 m_vEffectMagnitude; + EffectClock m_EffectClock; + // units depend on m_EffectClock + float m_fEffectRampUp; + float m_fEffectHoldAtHalf; + float m_fEffectRampDown; + float m_fEffectHoldAtZero; + float m_fEffectOffset; + }; + */ + + /** + * @brief The present state for the Tween. + */ + struct TweenState + { + void Init(); + static void MakeWeightedAverage( TweenState& average_out, const TweenState& ts1, const TweenState& ts2, float fPercentBetween ); + bool operator==( const TweenState &other ) const; + bool operator!=( const TweenState &other ) const { return !operator==(other); } + + // start and end position for tweening + RageVector3 pos; + RageVector3 rotation; + RageVector4 quat; + RageVector3 scale; + float fSkewX, fSkewY; + /** + * @brief The amount of cropping involved. + * + * If 0, there is no cropping. If 1, it's fully cropped. */ + RectF crop; + /** + * @brief The amount of fading involved. + * + * If 0, there is no fade. If 1, it's fully faded. */ + RectF fade; + /** + * @brief Four values making up the diffuse in this TweenState. + * + * 0 = UpperLeft, 1 = UpperRight, 2 = LowerLeft, 3 = LowerRight */ + RageColor diffuse[4]; + /** @brief The glow color for this TweenState. */ + RageColor glow; + /** @brief A magical value that nobody really knows the use for. ;) */ + float aux; + }; + + /** + * @brief Calls multiple functions for drawing the Actors. + * + * It calls the following in order: + * -# EarlyAbortDraw + * -# BeginDraw + * -# DrawPrimitives + * -# EndDraw + */ + void Draw(); + /** + * @brief Allow the Actor to be aborted early. + * + * Subclasses may wish to overwrite this to allow for + * aborted actors. + * @return false, as by default Actors shouldn't be aborted on drawing. */ + virtual bool EarlyAbortDraw() const { return false; } + /** @brief Start the drawing and push the transform on the world matrix stack. */ + virtual void BeginDraw(); + /** + * @brief Set the global rendering states of this Actor. + * + * This should be called at the beginning of an Actor's DrawPrimitives() call. */ + virtual void SetGlobalRenderStates(); + /** + * @brief Set the texture rendering states of this Actor. + * + * This should be called after setting a texture for the Actor. */ + virtual void SetTextureRenderStates(); + /** + * @brief Draw the primitives of the Actor. + * + * Derivative classes should override this function. */ + virtual void DrawPrimitives() {}; + /** @brief Pop the transform from the world matrix stack. */ + virtual void EndDraw(); + + // TODO: make Update non virtual and change all classes to override UpdateInternal + // instead. + bool IsFirstUpdate() const; + virtual void Update( float fDeltaTime ); // this can short circuit UpdateInternal + virtual void UpdateInternal( float fDeltaTime ); // override this + void UpdateTweening( float fDeltaTime ); + + /** + * @brief Retrieve the Actor's name. + * @return the Actor's name. */ + const RString &GetName() const { return m_sName; } + /** + * @brief Set the Actor's name to a new one. + * @param sName the new name for the Actor. */ + virtual void SetName( const RString &sName ) { m_sName = sName; } + /** + * @brief Give this Actor a new parent. + * @param pParent the new parent Actor. */ + void SetParent( Actor *pParent ); + /** + * @brief Retrieve the Actor's parent. + * @return the Actor's parent. */ + Actor *GetParent() { return m_pParent; } + /** + * @brief Retrieve the Actor's lineage. + * @return the Actor's lineage. */ + RString GetLineage() const; + + /** + * @brief Retrieve the Actor's x position. + * @return the Actor's x position. */ + float GetX() const { return m_current.pos.x; }; + /** + * @brief Retrieve the Actor's y position. + * @return the Actor's y position. */ + float GetY() const { return m_current.pos.y; }; + /** + * @brief Retrieve the Actor's z position. + * @return the Actor's z position. */ + float GetZ() const { return m_current.pos.z; }; + float GetDestX() const { return DestTweenState().pos.x; }; + float GetDestY() const { return DestTweenState().pos.y; }; + float GetDestZ() const { return DestTweenState().pos.z; }; + void SetX( float x ) { DestTweenState().pos.x = x; }; + void SetY( float y ) { DestTweenState().pos.y = y; }; + void SetZ( float z ) { DestTweenState().pos.z = z; }; + void SetXY( float x, float y ) { DestTweenState().pos.x = x; DestTweenState().pos.y = y; }; + /** + * @brief Add to the x position of this Actor. + * @param x the amount to add to the Actor's x position. */ + void AddX( float x ) { SetX( GetDestX()+x ); } + /** + * @brief Add to the y position of this Actor. + * @param y the amount to add to the Actor's y position. */ + void AddY( float y ) { SetY( GetDestY()+y ); } + /** + * @brief Add to the z position of this Actor. + * @param z the amount to add to the Actor's z position. */ + void AddZ( float z ) { SetZ( GetDestZ()+z ); } + + // height and width vary depending on zoom + float GetUnzoomedWidth() const { return m_size.x; } + float GetUnzoomedHeight() const { return m_size.y; } + float GetZoomedWidth() const { return m_size.x * m_baseScale.x * DestTweenState().scale.x; } + float GetZoomedHeight() const { return m_size.y * m_baseScale.y * DestTweenState().scale.y; } + void SetWidth( float width ) { m_size.x = width; } + void SetHeight( float height ) { m_size.y = height; } + + // Base values + float GetBaseZoomX() const { return m_baseScale.x; } + void SetBaseZoomX( float zoom ) { m_baseScale.x = zoom; } + float GetBaseZoomY() const { return m_baseScale.y; } + void SetBaseZoomY( float zoom ) { m_baseScale.y = zoom; } + float GetBaseZoomZ() const { return m_baseScale.z; } + void SetBaseZoomZ( float zoom ) { m_baseScale.z = zoom; } + void SetBaseZoom( float zoom ) { m_baseScale = RageVector3(zoom,zoom,zoom); } + void SetBaseRotationX( float rot ) { m_baseRotation.x = rot; } + void SetBaseRotationY( float rot ) { m_baseRotation.y = rot; } + void SetBaseRotationZ( float rot ) { m_baseRotation.z = rot; } + void SetBaseRotation( const RageVector3 &rot ) { m_baseRotation = rot; } + virtual void SetBaseAlpha( float fAlpha ) { m_fBaseAlpha = fAlpha; } + + /** + * @brief Retrieve the general zoom factor, using the x coordinate of the Actor. + * + * Note that this is not accurate in some cases. + * @return the zoom factor for the x coordinate of the Actor. */ + float GetZoom() const { return DestTweenState().scale.x; } + /** + * @brief Retrieve the zoom factor for the x coordinate of the Actor. + * @return the zoom factor for the x coordinate of the Actor. */ + float GetZoomX() const { return DestTweenState().scale.x; } + /** + * @brief Retrieve the zoom factor for the y coordinate of the Actor. + * @return the zoom factor for the y coordinate of the Actor. */ + float GetZoomY() const { return DestTweenState().scale.y; } + /** + * @brief Retrieve the zoom factor for the z coordinate of the Actor. + * @return the zoom factor for the z coordinate of the Actor. */ + float GetZoomZ() const { return DestTweenState().scale.z; } + /** + * @brief Set the zoom factor for all dimensions of the Actor. + * @param zoom the zoom factor for all dimensions. */ + void SetZoom( float zoom ) + { + DestTweenState().scale.x = zoom; + DestTweenState().scale.y = zoom; + DestTweenState().scale.z = zoom; + } + /** + * @brief Set the zoom factor for the x dimension of the Actor. + * @param zoom the zoom factor for the x dimension. */ + void SetZoomX( float zoom ) { DestTweenState().scale.x = zoom; } + /** + * @brief Set the zoom factor for the y dimension of the Actor. + * @param zoom the zoom factor for the y dimension. */ + void SetZoomY( float zoom ) { DestTweenState().scale.y = zoom; } + /** + * @brief Set the zoom factor for the z dimension of the Actor. + * @param zoom the zoom factor for the z dimension. */ + void SetZoomZ( float zoom ) { DestTweenState().scale.z = zoom; } + void ZoomTo( float fX, float fY ) { ZoomToWidth(fX); ZoomToHeight(fY); } + void ZoomToWidth( float zoom ) { SetZoomX( zoom / GetUnzoomedWidth() ); } + void ZoomToHeight( float zoom ) { SetZoomY( zoom / GetUnzoomedHeight() ); } + + float GetRotationX() const { return DestTweenState().rotation.x; } + float GetRotationY() const { return DestTweenState().rotation.y; } + float GetRotationZ() const { return DestTweenState().rotation.z; } + void SetRotationX( float rot ) { DestTweenState().rotation.x = rot; } + void SetRotationY( float rot ) { DestTweenState().rotation.y = rot; } + void SetRotationZ( float rot ) { DestTweenState().rotation.z = rot; } + // added in StepNXA, now available in sm-ssc: + void AddRotationX( float rot ) { DestTweenState().rotation.x += rot; }; + void AddRotationY( float rot ) { DestTweenState().rotation.y += rot; }; + void AddRotationZ( float rot ) { DestTweenState().rotation.z += rot; }; + // and these were normally in SM: + void AddRotationH( float rot ); + void AddRotationP( float rot ); + void AddRotationR( float rot ); + + void SetSkewX( float fAmount ) { DestTweenState().fSkewX = fAmount; } + float GetSkewX( float /* fAmount */ ) const { return DestTweenState().fSkewX; } + void SetSkewY( float fAmount ) { DestTweenState().fSkewY = fAmount; } + float GetSkewY( float /* fAmount */ ) const { return DestTweenState().fSkewY; } + + float GetCropLeft() const { return DestTweenState().crop.left; } + float GetCropTop() const { return DestTweenState().crop.top; } + float GetCropRight() const { return DestTweenState().crop.right; } + float GetCropBottom() const { return DestTweenState().crop.bottom; } + void SetCropLeft( float percent ) { DestTweenState().crop.left = percent; } + void SetCropTop( float percent ) { DestTweenState().crop.top = percent; } + void SetCropRight( float percent ) { DestTweenState().crop.right = percent; } + void SetCropBottom( float percent ) { DestTweenState().crop.bottom = percent; } + + void SetFadeLeft( float percent ) { DestTweenState().fade.left = percent; } + void SetFadeTop( float percent ) { DestTweenState().fade.top = percent; } + void SetFadeRight( float percent ) { DestTweenState().fade.right = percent; } + void SetFadeBottom( float percent ) { DestTweenState().fade.bottom = percent; } + + void SetGlobalDiffuseColor( RageColor c ); + + virtual void SetDiffuse( RageColor c ) { for(int i=0; i<4; i++) DestTweenState().diffuse[i] = c; }; + virtual void SetDiffuseAlpha( float f ) { for(int i = 0; i < 4; ++i) { RageColor c = GetDiffuses( i ); c.a = f; SetDiffuses( i, c ); } } + float GetCurrentDiffuseAlpha() const { return m_current.diffuse[0].a; } + void SetDiffuseColor( RageColor c ); + void SetDiffuses( int i, RageColor c ) { DestTweenState().diffuse[i] = c; }; + void SetDiffuseUpperLeft( RageColor c ) { DestTweenState().diffuse[0] = c; }; + void SetDiffuseUpperRight( RageColor c ) { DestTweenState().diffuse[1] = c; }; + void SetDiffuseLowerLeft( RageColor c ) { DestTweenState().diffuse[2] = c; }; + void SetDiffuseLowerRight( RageColor c ) { DestTweenState().diffuse[3] = c; }; + void SetDiffuseTopEdge( RageColor c ) { DestTweenState().diffuse[0] = DestTweenState().diffuse[1] = c; }; + void SetDiffuseRightEdge( RageColor c ) { DestTweenState().diffuse[1] = DestTweenState().diffuse[3] = c; }; + void SetDiffuseBottomEdge( RageColor c ) { DestTweenState().diffuse[2] = DestTweenState().diffuse[3] = c; }; + void SetDiffuseLeftEdge( RageColor c ) { DestTweenState().diffuse[0] = DestTweenState().diffuse[2] = c; }; + RageColor GetDiffuse() const { return DestTweenState().diffuse[0]; }; + RageColor GetDiffuses( int i ) const { return DestTweenState().diffuse[i]; }; + float GetDiffuseAlpha() const { return DestTweenState().diffuse[0].a; }; + void SetGlow( RageColor c ) { DestTweenState().glow = c; }; + RageColor GetGlow() const { return DestTweenState().glow; }; + + void SetAux( float f ) { DestTweenState().aux = f; } + float GetAux() const { return m_current.aux; } + + void BeginTweening( float time, ITween *pInterp ); + void BeginTweening( float time, TweenType tt = TWEEN_LINEAR ); + void StopTweening(); + void Sleep( float time ); + void QueueCommand( const RString& sCommandName ); + void QueueMessage( const RString& sMessageName ); + virtual void FinishTweening(); + virtual void HurryTweening( float factor ); + // Let ActorFrame and BGAnimation override + virtual float GetTweenTimeLeft() const; // Amount of time until all tweens have stopped + TweenState& DestTweenState() // where Actor will end when its tween finish + { + if( m_Tweens.empty() ) // not tweening + return m_current; + else + return m_Tweens.back()->state; + } + const TweenState& DestTweenState() const { return const_cast(this)->DestTweenState(); } + + /** @brief How do we handle stretching the Actor? */ + enum StretchType + { + fit_inside, /**< Have the Actor fit inside its parent, using the smaller zoom. */ + cover /**< Have the Actor cover its parent, using the larger zoom. */ + }; + + void ScaleToCover( const RectF &rect ) { ScaleTo( rect, cover ); } + void ScaleToFitInside( const RectF &rect ) { ScaleTo( rect, fit_inside); }; + void ScaleTo( const RectF &rect, StretchType st ); + + void StretchTo( const RectF &rect ); + + // Alignment settings. These need to be virtual for BitmapText + virtual void SetHorizAlign( float f ) { m_fHorizAlign = f; } + virtual void SetVertAlign( float f ) { m_fVertAlign = f; } + void SetHorizAlign( HorizAlign ha ) { SetHorizAlign( (ha == HorizAlign_Left)? 0.0f: (ha == HorizAlign_Center)? 0.5f: +1.0f ); } + void SetVertAlign( VertAlign va ) { SetVertAlign( (va == VertAlign_Top)? 0.0f: (va == VertAlign_Middle)? 0.5f: +1.0f ); } + virtual float GetHorizAlign() { return m_fHorizAlign; } + virtual float GetVertAlign() { return m_fVertAlign; } + + // effects +#if defined(SSC_FUTURES) + void StopEffects(); + Effect GetEffect( int i ) const { return m_Effects[i]; } +#else + void StopEffect() { m_Effect = no_effect; } + Effect GetEffect() const { return m_Effect; } +#endif + float GetSecsIntoEffect() const { return m_fSecsIntoEffect; } + float GetEffectDelta() const { return m_fEffectDelta; } + + // todo: account for SSC_FUTURES by adding an effect as an arg to each one -aj + void SetEffectColor1( RageColor c ) { m_effectColor1 = c; } + void SetEffectColor2( RageColor c ) { m_effectColor2 = c; } + void SetEffectPeriod( float fTime ); + float GetEffectPeriod() const; + void SetEffectTiming( float fRampUp, float fAtHalf, float fRampDown, float fAtZero ); + void SetEffectOffset( float fTime ) { m_fEffectOffset = fTime; } + void SetEffectClock( EffectClock c ) { m_EffectClock = c; } + void SetEffectClockString( const RString &s ); // convenience + + void SetEffectMagnitude( RageVector3 vec ) { m_vEffectMagnitude = vec; } + RageVector3 GetEffectMagnitude() const { return m_vEffectMagnitude; } + + void SetEffectDiffuseBlink( + float fEffectPeriodSeconds = 1.0f, + RageColor c1 = RageColor(0.5f,0.5f,0.5f,1), + RageColor c2 = RageColor(1,1,1,1) ); + void SetEffectDiffuseShift( float fEffectPeriodSeconds = 1.f, + RageColor c1 = RageColor(0,0,0,1), + RageColor c2 = RageColor(1,1,1,1) ); + void SetEffectDiffuseRamp( float fEffectPeriodSeconds = 1.f, + RageColor c1 = RageColor(0,0,0,1), + RageColor c2 = RageColor(1,1,1,1) ); + void SetEffectGlowBlink( float fEffectPeriodSeconds = 1.f, + RageColor c1 = RageColor(1,1,1,0.2f), + RageColor c2 = RageColor(1,1,1,0.8f) ); + void SetEffectGlowShift( + float fEffectPeriodSeconds = 1.0f, + RageColor c1 = RageColor(1,1,1,0.2f), + RageColor c2 = RageColor(1,1,1,0.8f) ); + void SetEffectGlowRamp( + float fEffectPeriodSeconds = 1.0f, + RageColor c1 = RageColor(1,1,1,0.2f), + RageColor c2 = RageColor(1,1,1,0.8f) ); + void SetEffectRainbow( + float fEffectPeriodSeconds = 2.0f ); + void SetEffectWag( + float fPeriod = 2.f, + RageVector3 vect = RageVector3(0,0,20) ); + void SetEffectBounce( + float fPeriod = 2.f, + RageVector3 vect = RageVector3(0,20,0) ); + void SetEffectBob( + float fPeriod = 2.f, + RageVector3 vect = RageVector3(0,20,0) ); + void SetEffectPulse( + float fPeriod = 2.f, + float fMinZoom = 0.5f, + float fMaxZoom = 1.f ); + void SetEffectSpin( RageVector3 vect = RageVector3(0,0,180) ); + void SetEffectVibrate( RageVector3 vect = RageVector3(10,10,10) ); + + + // other properties + /** + * @brief Determine if the Actor is visible at this time. + * @return true if it's visible, false otherwise. */ + bool GetVisible() const { return m_bVisible; } + void SetVisible( bool b ) { m_bVisible = b; } + void SetShadowLength( float fLength ) { m_fShadowLengthX = fLength; m_fShadowLengthY = fLength; } + void SetShadowLengthX( float fLengthX ) { m_fShadowLengthX = fLengthX; } + void SetShadowLengthY( float fLengthY ) { m_fShadowLengthY = fLengthY; } + void SetShadowColor( RageColor c ) { m_ShadowColor = c; } + // TODO: Implement hibernate as a tween type? + void SetHibernate( float fSecs ) { m_fHibernateSecondsLeft = fSecs; } + void SetDrawOrder( int iOrder ) { m_iDrawOrder = iOrder; } + int GetDrawOrder() const { return m_iDrawOrder; } + + virtual void EnableAnimation( bool b ) { m_bIsAnimating = b; } // Sprite needs to overload this + void StartAnimating() { this->EnableAnimation(true); } + void StopAnimating() { this->EnableAnimation(false); } + + // render states + void SetBlendMode( BlendMode mode ) { m_BlendMode = mode; } + void SetTextureWrapping( bool b ) { m_bTextureWrapping = b; } + void SetTextureFiltering( bool b ) { m_bTextureFiltering = b; } + void SetClearZBuffer( bool b ) { m_bClearZBuffer = b; } + void SetUseZBuffer( bool b ) { SetZTestMode(b?ZTEST_WRITE_ON_PASS:ZTEST_OFF); SetZWrite(b); } + virtual void SetZTestMode( ZTestMode mode ) { m_ZTestMode = mode; } + virtual void SetZWrite( bool b ) { m_bZWrite = b; } + void SetZBias( float f ) { m_fZBias = f; } + virtual void SetCullMode( CullMode mode ) { m_CullMode = mode; } + + // Lua + virtual void PushSelf( lua_State *L ); + virtual void PushContext( lua_State *L ); + + // Named commands + void AddCommand( const RString &sCmdName, apActorCommands apac ); + bool HasCommand( const RString &sCmdName ) const; + const apActorCommands *GetCommand( const RString &sCommandName ) const; + void PlayCommand( const RString &sCommandName ) { HandleMessage( Message(sCommandName) ); } // convenience + void PlayCommandNoRecurse( const Message &msg ); + + // Commands by reference + virtual void RunCommands( const LuaReference& cmds, const LuaReference *pParamTable = nullptr ); + void RunCommands( const apActorCommands& cmds, const LuaReference *pParamTable = nullptr ) { this->RunCommands( *cmds, pParamTable ); } // convenience + virtual void RunCommandsRecursively( const LuaReference& cmds, const LuaReference *pParamTable = nullptr ) { RunCommands(cmds, pParamTable); } + // If we're a leaf, then execute this command. + virtual void RunCommandsOnLeaves( const LuaReference& cmds, const LuaReference *pParamTable = nullptr ) { RunCommands(cmds, pParamTable); } + + // Messages + virtual void HandleMessage( const Message &msg ); + + // Animation + virtual int GetNumStates() const { return 1; } + virtual void SetState( int /* iNewState */ ) {} + virtual float GetAnimationLengthSeconds() const { return 0; } + virtual void SetSecondsIntoAnimation( float ) {} + virtual void SetUpdateRate( float ) {} + + HiddenPtr m_pLuaInstance; + +protected: + /** @brief the name of the Actor. */ + RString m_sName; + /** @brief the current parent of this Actor if it exists. */ + Actor *m_pParent; + + /** @brief Some general information about the Tween. */ + struct TweenInfo + { + // counters for tweening + TweenInfo(); + ~TweenInfo(); + TweenInfo( const TweenInfo &cpy ); + TweenInfo &operator=( const TweenInfo &rhs ); + + ITween *m_pTween; + /** @brief How far into the tween are we? */ + float m_fTimeLeftInTween; + /** @brief The number of seconds between Start and End positions/zooms. */ + float m_fTweenTime; + /** @brief The command to execute when this TweenState goes into effect. */ + RString m_sCommandName; + }; + + RageVector3 m_baseRotation; + RageVector3 m_baseScale; + float m_fBaseAlpha; + + RageVector2 m_size; + TweenState m_current; + TweenState m_start; + struct TweenStateAndInfo + { + TweenState state; + TweenInfo info; + }; + vector m_Tweens; + + /** @brief Temporary variables that are filled just before drawing */ + TweenState *m_pTempState; + + bool m_bFirstUpdate; + + // Stuff for alignment + /** @brief The particular horizontal alignment. + * + * Use the defined constant values for best effect. */ + float m_fHorizAlign; + /** @brief The particular vertical alignment. + * + * Use the defined constant values for best effect. */ + float m_fVertAlign; + + // Stuff for effects +#if defined(SSC_FUTURES) // be able to stack effects + vector m_Effects; +#else // compatibility + Effect m_Effect; +#endif + float m_fSecsIntoEffect; + float m_fEffectDelta; + + // units depend on m_EffectClock + float m_fEffectRampUp; + float m_fEffectHoldAtHalf; + float m_fEffectRampDown; + float m_fEffectHoldAtZero; + float m_fEffectOffset; + EffectClock m_EffectClock; + + /* This can be used in lieu of the fDeltaTime parameter to Update() to + * follow the effect clock. Actor::Update must be called first. */ + float GetEffectDeltaTime() const { return m_fEffectDelta; } + + // todo: account for SSC_FUTURES by having these be vectors too -aj + RageColor m_effectColor1; + RageColor m_effectColor2; + RageVector3 m_vEffectMagnitude; + + // other properties + bool m_bVisible; + bool m_bIsAnimating; + float m_fHibernateSecondsLeft; + float m_fShadowLengthX; + float m_fShadowLengthY; + RageColor m_ShadowColor; + /** @brief The draw order priority. + * + * The lower this number is, the sooner it is drawn. */ + int m_iDrawOrder; + + // render states + BlendMode m_BlendMode; + ZTestMode m_ZTestMode; + CullMode m_CullMode; + bool m_bTextureWrapping; + bool m_bTextureFiltering; + bool m_bClearZBuffer; + bool m_bZWrite; + /** + * @brief The amount of bias. + * + * If 0, there is no bias. If 1, there is a full bias. */ + float m_fZBias; + + // global state + static float g_fCurrentBGMTime, g_fCurrentBGMBeat; + static float g_fCurrentBGMTimeNoOffset, g_fCurrentBGMBeatNoOffset; + static vector g_vfCurrentBGMBeatPlayer; + static vector g_vfCurrentBGMBeatPlayerNoOffset; + +private: + // commands + map m_mapNameToCommands; +}; + +#endif + +/** + * @file + * @author Chris Danford (c) 2001-2004 + * @section LICENSE + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/ActorFrame.h b/src/ActorFrame.h index ba377ffcfb..5835f86029 100644 --- a/src/ActorFrame.h +++ b/src/ActorFrame.h @@ -1,164 +1,164 @@ -#ifndef ACTORFRAME_H -#define ACTORFRAME_H - -#include "Actor.h" - -/** @brief A container for other Actors. */ -class ActorFrame : public Actor -{ -public: - ActorFrame(); - ActorFrame( const ActorFrame &cpy ); - virtual ~ActorFrame(); - - /** @brief Set up the initial state. */ - virtual void InitState(); - void LoadFromNode( const XNode* pNode ); - virtual ActorFrame *Copy() const; - - /** - * @brief Add a new child to the ActorFrame. - * @param pActor the new Actor to add. */ - virtual void AddChild( Actor *pActor ); - /** - * @brief Remove the specified child from the ActorFrame. - * @param pActor the Actor to remove. */ - virtual void RemoveChild( Actor *pActor ); - void TransferChildren( ActorFrame *pTo ); - Actor* GetChild( const RString &sName ); - vector GetChildren() { return m_SubActors; } - int GetNumChildren() const { return m_SubActors.size(); } - - /** @brief Remove all of the children from the frame. */ - void RemoveAllChildren(); - /** - * @brief Move a particular actor to the tail. - * @param pActor the actor to go to the tail. - */ - void MoveToTail( Actor* pActor ); - /** - * @brief Move a particular actor to the head. - * @param pActor the actor to go to the head. - */ - void MoveToHead( Actor* pActor ); - void SortByDrawOrder(); - void SetDrawByZPosition( bool b ); - - void SetDrawFunction( const LuaReference &DrawFunction ) { m_DrawFunction = DrawFunction; } - void SetUpdateFunction( const LuaReference &UpdateFunction ) { m_UpdateFunction = UpdateFunction; } - - LuaReference GetDrawFunction() const { return m_DrawFunction; } - virtual bool AutoLoadChildren() const { return false; } // derived classes override to automatically LoadChildrenFromNode - void DeleteChildrenWhenDone( bool bDelete=true ) { m_bDeleteChildren = bDelete; } - void DeleteAllChildren(); - - // Commands - virtual void PushSelf( lua_State *L ); - void PushChildrenTable( lua_State *L ); - void PlayCommandOnChildren( const RString &sCommandName, const LuaReference *pParamTable = NULL ); - void PlayCommandOnLeaves( const RString &sCommandName, const LuaReference *pParamTable = NULL ); - - virtual void RunCommandsRecursively( const LuaReference& cmds, const LuaReference *pParamTable = NULL ); - virtual void RunCommandsOnChildren( const LuaReference& cmds, const LuaReference *pParamTable = NULL ); /* but not on self */ - void RunCommandsOnChildren( const apActorCommands& cmds, const LuaReference *pParamTable = NULL ) { this->RunCommandsOnChildren( *cmds, pParamTable ); } // convenience - virtual void RunCommandsOnLeaves( const LuaReference& cmds, const LuaReference *pParamTable = NULL ); /* but not on self */ - - virtual void UpdateInternal( float fDeltaTime ); - virtual void BeginDraw(); - virtual void DrawPrimitives(); - virtual void EndDraw(); - - // propagated commands - virtual void SetDiffuse( RageColor c ); - virtual void SetDiffuseAlpha( float f ); - virtual void SetBaseAlpha( float f ); - virtual void SetZTestMode( ZTestMode mode ); - virtual void SetZWrite( bool b ); - virtual void FinishTweening(); - virtual void HurryTweening( float factor ); - - void SetUpdateRate( float fUpdateRate ) { m_fUpdateRate = fUpdateRate; } - void SetFOV( float fFOV ) { m_fFOV = fFOV; } - void SetVanishPoint( float fX, float fY) { m_fVanishX = fX; m_fVanishY = fY; } - - void SetCustomLighting( bool bCustomLighting ) { m_bOverrideLighting = bCustomLighting; } - void SetAmbientLightColor( RageColor c ) { m_ambientColor = c; } - void SetDiffuseLightColor( RageColor c ) { m_diffuseColor = c; } - void SetSpecularLightColor( RageColor c ) { m_specularColor = c; } - void SetLightDirection( RageVector3 vec ) { m_lightDirection = vec; } - - virtual void SetPropagateCommands( bool b ); - - /** @brief Amount of time until all tweens (and all children's tweens) have stopped: */ - virtual float GetTweenTimeLeft() const; - - virtual void HandleMessage( const Message &msg ); - virtual void RunCommands( const LuaReference& cmds, const LuaReference *pParamTable = NULL ); - void RunCommands( const apActorCommands& cmds, const LuaReference *pParamTable = NULL ) { this->RunCommands( *cmds, pParamTable ); } // convenience - -protected: - void LoadChildrenFromNode( const XNode* pNode ); - - /** @brief The children Actors used by the ActorFrame. */ - vector m_SubActors; - bool m_bPropagateCommands; - bool m_bDeleteChildren; - bool m_bDrawByZPosition; - LuaReference m_UpdateFunction; - LuaReference m_DrawFunction; - - // state effects - float m_fUpdateRate; - float m_fFOV; // -1 = no change - float m_fVanishX; - float m_fVanishY; - /** - * @brief A flad to see if an override for the lighting is needed. - * - * If true, set lightning to m_bLightning. */ - bool m_bOverrideLighting; - bool m_bLighting; - - // lighting variables - RageColor m_ambientColor; - RageColor m_diffuseColor; - RageColor m_specularColor; - RageVector3 m_lightDirection; -}; -/** @brief an ActorFrame that handles deleting children Actors automatically. */ -class ActorFrameAutoDeleteChildren : public ActorFrame -{ -public: - ActorFrameAutoDeleteChildren() { DeleteChildrenWhenDone(true); } - virtual bool AutoLoadChildren() const { return true; } - virtual ActorFrameAutoDeleteChildren *Copy() const; -}; - -#endif - -/** - * @file - * @author Chris Danford (c) 2001-2004 - * @section LICENSE - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef ACTORFRAME_H +#define ACTORFRAME_H + +#include "Actor.h" + +/** @brief A container for other Actors. */ +class ActorFrame : public Actor +{ +public: + ActorFrame(); + ActorFrame( const ActorFrame &cpy ); + virtual ~ActorFrame(); + + /** @brief Set up the initial state. */ + virtual void InitState(); + void LoadFromNode( const XNode* pNode ); + virtual ActorFrame *Copy() const; + + /** + * @brief Add a new child to the ActorFrame. + * @param pActor the new Actor to add. */ + virtual void AddChild( Actor *pActor ); + /** + * @brief Remove the specified child from the ActorFrame. + * @param pActor the Actor to remove. */ + virtual void RemoveChild( Actor *pActor ); + void TransferChildren( ActorFrame *pTo ); + Actor* GetChild( const RString &sName ); + vector GetChildren() { return m_SubActors; } + int GetNumChildren() const { return m_SubActors.size(); } + + /** @brief Remove all of the children from the frame. */ + void RemoveAllChildren(); + /** + * @brief Move a particular actor to the tail. + * @param pActor the actor to go to the tail. + */ + void MoveToTail( Actor* pActor ); + /** + * @brief Move a particular actor to the head. + * @param pActor the actor to go to the head. + */ + void MoveToHead( Actor* pActor ); + void SortByDrawOrder(); + void SetDrawByZPosition( bool b ); + + void SetDrawFunction( const LuaReference &DrawFunction ) { m_DrawFunction = DrawFunction; } + void SetUpdateFunction( const LuaReference &UpdateFunction ) { m_UpdateFunction = UpdateFunction; } + + LuaReference GetDrawFunction() const { return m_DrawFunction; } + virtual bool AutoLoadChildren() const { return false; } // derived classes override to automatically LoadChildrenFromNode + void DeleteChildrenWhenDone( bool bDelete=true ) { m_bDeleteChildren = bDelete; } + void DeleteAllChildren(); + + // Commands + virtual void PushSelf( lua_State *L ); + void PushChildrenTable( lua_State *L ); + void PlayCommandOnChildren( const RString &sCommandName, const LuaReference *pParamTable = nullptr ); + void PlayCommandOnLeaves( const RString &sCommandName, const LuaReference *pParamTable = nullptr ); + + virtual void RunCommandsRecursively( const LuaReference& cmds, const LuaReference *pParamTable = nullptr ); + virtual void RunCommandsOnChildren( const LuaReference& cmds, const LuaReference *pParamTable = nullptr ); /* but not on self */ + void RunCommandsOnChildren( const apActorCommands& cmds, const LuaReference *pParamTable = nullptr ) { this->RunCommandsOnChildren( *cmds, pParamTable ); } // convenience + virtual void RunCommandsOnLeaves( const LuaReference& cmds, const LuaReference *pParamTable = nullptr ); /* but not on self */ + + virtual void UpdateInternal( float fDeltaTime ); + virtual void BeginDraw(); + virtual void DrawPrimitives(); + virtual void EndDraw(); + + // propagated commands + virtual void SetDiffuse( RageColor c ); + virtual void SetDiffuseAlpha( float f ); + virtual void SetBaseAlpha( float f ); + virtual void SetZTestMode( ZTestMode mode ); + virtual void SetZWrite( bool b ); + virtual void FinishTweening(); + virtual void HurryTweening( float factor ); + + void SetUpdateRate( float fUpdateRate ) { m_fUpdateRate = fUpdateRate; } + void SetFOV( float fFOV ) { m_fFOV = fFOV; } + void SetVanishPoint( float fX, float fY) { m_fVanishX = fX; m_fVanishY = fY; } + + void SetCustomLighting( bool bCustomLighting ) { m_bOverrideLighting = bCustomLighting; } + void SetAmbientLightColor( RageColor c ) { m_ambientColor = c; } + void SetDiffuseLightColor( RageColor c ) { m_diffuseColor = c; } + void SetSpecularLightColor( RageColor c ) { m_specularColor = c; } + void SetLightDirection( RageVector3 vec ) { m_lightDirection = vec; } + + virtual void SetPropagateCommands( bool b ); + + /** @brief Amount of time until all tweens (and all children's tweens) have stopped: */ + virtual float GetTweenTimeLeft() const; + + virtual void HandleMessage( const Message &msg ); + virtual void RunCommands( const LuaReference& cmds, const LuaReference *pParamTable = nullptr ); + void RunCommands( const apActorCommands& cmds, const LuaReference *pParamTable = nullptr ) { this->RunCommands( *cmds, pParamTable ); } // convenience + +protected: + void LoadChildrenFromNode( const XNode* pNode ); + + /** @brief The children Actors used by the ActorFrame. */ + vector m_SubActors; + bool m_bPropagateCommands; + bool m_bDeleteChildren; + bool m_bDrawByZPosition; + LuaReference m_UpdateFunction; + LuaReference m_DrawFunction; + + // state effects + float m_fUpdateRate; + float m_fFOV; // -1 = no change + float m_fVanishX; + float m_fVanishY; + /** + * @brief A flad to see if an override for the lighting is needed. + * + * If true, set lightning to m_bLightning. */ + bool m_bOverrideLighting; + bool m_bLighting; + + // lighting variables + RageColor m_ambientColor; + RageColor m_diffuseColor; + RageColor m_specularColor; + RageVector3 m_lightDirection; +}; +/** @brief an ActorFrame that handles deleting children Actors automatically. */ +class ActorFrameAutoDeleteChildren : public ActorFrame +{ +public: + ActorFrameAutoDeleteChildren() { DeleteChildrenWhenDone(true); } + virtual bool AutoLoadChildren() const { return true; } + virtual ActorFrameAutoDeleteChildren *Copy() const; +}; + +#endif + +/** + * @file + * @author Chris Danford (c) 2001-2004 + * @section LICENSE + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/ActorFrameTexture.cpp b/src/ActorFrameTexture.cpp index 555635df5b..f325e181a8 100644 --- a/src/ActorFrameTexture.cpp +++ b/src/ActorFrameTexture.cpp @@ -17,7 +17,7 @@ ActorFrameTexture::ActorFrameTexture() ++i; m_sTextureName = ssprintf( ConvertI64FormatString("ActorFrameTexture %lli"), i ); - m_pRenderTarget = NULL; + m_pRenderTarget = nullptr; } ActorFrameTexture::ActorFrameTexture( const ActorFrameTexture &cpy ): diff --git a/src/ActorMultiTexture.h b/src/ActorMultiTexture.h index 6f4d793361..5b3c34333e 100644 --- a/src/ActorMultiTexture.h +++ b/src/ActorMultiTexture.h @@ -1,73 +1,73 @@ -/** @brief ActorMultiTexture - A texture created from multiple textures. */ - -#ifndef ACTOR_MULTI_TEXTURE_H -#define ACTOR_MULTI_TEXTURE_H - -#include "Actor.h" -#include "RageDisplay.h" - -class RageTexture; - -class ActorMultiTexture: public Actor -{ -public: - ActorMultiTexture(); - ActorMultiTexture( const ActorMultiTexture &cpy ); - virtual ~ActorMultiTexture(); - - void LoadFromNode( const XNode* pNode ); - virtual ActorMultiTexture *Copy() const; - - virtual bool EarlyAbortDraw() const; - virtual void DrawPrimitives(); - - void ClearTextures(); - int AddTexture( RageTexture *pTexture ); - void SetTextureMode( int iIndex, TextureMode tm ); - - void SetSizeFromTexture( RageTexture *pTexture ); - void SetTextureCoords( const RectF &r ); - void SetEffectMode( EffectMode em ) { m_EffectMode = em; } - - virtual void PushSelf( lua_State *L ); - -private: - EffectMode m_EffectMode; - struct TextureUnitState - { - TextureUnitState(): m_pTexture(NULL), m_TextureMode(TextureMode_Modulate) {} - RageTexture *m_pTexture; - TextureMode m_TextureMode; - }; - vector m_aTextureUnits; - RectF m_Rect; -}; - -#endif - -/** - * @file - * @author Chris Danford (c) 2001-2004 - * @section LICENSE - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/** @brief ActorMultiTexture - A texture created from multiple textures. */ + +#ifndef ACTOR_MULTI_TEXTURE_H +#define ACTOR_MULTI_TEXTURE_H + +#include "Actor.h" +#include "RageDisplay.h" + +class RageTexture; + +class ActorMultiTexture: public Actor +{ +public: + ActorMultiTexture(); + ActorMultiTexture( const ActorMultiTexture &cpy ); + virtual ~ActorMultiTexture(); + + void LoadFromNode( const XNode* pNode ); + virtual ActorMultiTexture *Copy() const; + + virtual bool EarlyAbortDraw() const; + virtual void DrawPrimitives(); + + void ClearTextures(); + int AddTexture( RageTexture *pTexture ); + void SetTextureMode( int iIndex, TextureMode tm ); + + void SetSizeFromTexture( RageTexture *pTexture ); + void SetTextureCoords( const RectF &r ); + void SetEffectMode( EffectMode em ) { m_EffectMode = em; } + + virtual void PushSelf( lua_State *L ); + +private: + EffectMode m_EffectMode; + struct TextureUnitState + { + TextureUnitState(): m_pTexture(nullptr), m_TextureMode(TextureMode_Modulate) {} + RageTexture *m_pTexture; + TextureMode m_TextureMode; + }; + vector m_aTextureUnits; + RectF m_Rect; +}; + +#endif + +/** + * @file + * @author Chris Danford (c) 2001-2004 + * @section LICENSE + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/ActorProxy.cpp b/src/ActorProxy.cpp index 2284c86f95..31ecff50ac 100644 --- a/src/ActorProxy.cpp +++ b/src/ActorProxy.cpp @@ -6,7 +6,7 @@ REGISTER_ACTOR_CLASS( ActorProxy ); ActorProxy::ActorProxy() { - m_pActorTarget = NULL; + m_pActorTarget = nullptr; } bool ActorProxy::EarlyAbortDraw() const diff --git a/src/ActorUtil.cpp b/src/ActorUtil.cpp index 6d8630e716..403777e266 100644 --- a/src/ActorUtil.cpp +++ b/src/ActorUtil.cpp @@ -14,7 +14,7 @@ // Actor registration -static map *g_pmapRegistrees = NULL; +static map *g_pmapRegistrees = nullptr; static bool IsRegistered( const RString& sClassName ) { @@ -158,7 +158,7 @@ namespace return nullptr; } - XNode *pRet = NULL; + XNode *pRet = nullptr; if( ActorUtil::LoadTableFromStackShowErrors(L) ) pRet = XmlFileUtil::XNodeFromTable( L ); diff --git a/src/ActorUtil.h b/src/ActorUtil.h index 1be071be39..9634d0cd33 100644 --- a/src/ActorUtil.h +++ b/src/ActorUtil.h @@ -1,161 +1,161 @@ -#ifndef ActorUtil_H -#define ActorUtil_H - -#include "Actor.h" -#include "RageTexture.h" - -class XNode; - -typedef Actor* (*CreateActorFn)(); - -template -Actor *CreateActor() { return new T; } - -/** - * @brief Register the requested Actor with the specified external name. - * - * This should be called manually only if needed. */ -#define REGISTER_ACTOR_CLASS_WITH_NAME( className, externalClassName ) \ - struct Register##className { \ - Register##className() { ActorUtil::Register(#externalClassName, CreateActor); } \ - }; \ - className *className::Copy() const { return new className(*this); } \ - static Register##className register##className - -/** - * @brief Register the requested Actor so that it's more accessible. - * - * Each Actor class should have a REGISTER_ACTOR_CLASS in its CPP file. */ -#define REGISTER_ACTOR_CLASS( className ) REGISTER_ACTOR_CLASS_WITH_NAME( className, className ) - -enum FileType -{ - FT_Bitmap, - FT_Sound, - FT_Movie, - FT_Directory, - FT_Lua, - FT_Model, - NUM_FileType, - FileType_Invalid -}; -const RString& FileTypeToString( FileType ft ); - -/** @brief Utility functions for creating and manipulating Actors. */ -namespace ActorUtil -{ - // Every screen should register its class at program initialization. - void Register( const RString& sClassName, CreateActorFn pfn ); - - apActorCommands ParseActorCommands( const RString &sCommands, const RString &sName = "" ); - void SetXY( Actor& actor, const RString &sMetricsGroup ); - inline void PlayCommand( Actor& actor, const RString &sCommandName ) { actor.PlayCommand( sCommandName ); } - inline void OnCommand( Actor& actor ) - { - ASSERT_M( actor.HasCommand("On"), ssprintf("%s is missing an OnCommand.", actor.GetLineage().c_str()) ); - actor.PlayCommand("On"); - } - inline void OffCommand( Actor& actor ) - { - // HACK: It's very often that we command things to TweenOffScreen - // that we aren't drawing. We know that an Actor is not being - // used if its name is blank. So, do nothing on Actors with a blank name. - // (Do "playcommand" anyway; BGAs often have no name.) - if( actor.GetName().empty() ) - return; - ASSERT_M( actor.HasCommand("Off"), ssprintf("Actor %s is missing an OffCommand.", actor.GetLineage().c_str()) ); - actor.PlayCommand("Off"); - } - - void LoadCommand( Actor& actor, const RString &sMetricsGroup, const RString &sCommandName ); - void LoadCommandFromName( Actor& actor, const RString &sMetricsGroup, const RString &sCommandName, const RString &sName ); - void LoadAllCommands( Actor& actor, const RString &sMetricsGroup ); - void LoadAllCommandsFromName( Actor& actor, const RString &sMetricsGroup, const RString &sName ); - - inline void LoadAllCommandsAndSetXY( Actor& actor, const RString &sMetricsGroup ) - { - LoadAllCommands( actor, sMetricsGroup ); - SetXY( actor, sMetricsGroup ); - } - inline void LoadAllCommandsAndOnCommand( Actor& actor, const RString &sMetricsGroup ) - { - LoadAllCommands( actor, sMetricsGroup ); - OnCommand( actor ); - } - inline void SetXYAndOnCommand( Actor& actor, const RString &sMetricsGroup ) - { - SetXY( actor, sMetricsGroup ); - OnCommand( actor ); - } - inline void LoadAllCommandsAndSetXYAndOnCommand( Actor& actor, const RString &sMetricsGroup ) - { - LoadAllCommands( actor, sMetricsGroup ); - SetXY( actor, sMetricsGroup ); - OnCommand( actor ); - } - - /* convenience */ - inline void SetXY( Actor* pActor, const RString &sMetricsGroup ) { SetXY( *pActor, sMetricsGroup ); } - inline void PlayCommand( Actor* pActor, const RString &sCommandName ) { if(pActor) pActor->PlayCommand( sCommandName ); } - inline void OnCommand( Actor* pActor ) { if(pActor) ActorUtil::OnCommand( *pActor ); } - inline void OffCommand( Actor* pActor ) { if(pActor) ActorUtil::OffCommand( *pActor ); } - - inline void LoadAllCommands( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) LoadAllCommands( *pActor, sMetricsGroup ); } - - inline void LoadAllCommandsAndSetXY( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) LoadAllCommandsAndSetXY( *pActor, sMetricsGroup ); } - inline void LoadAllCommandsAndOnCommand( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) LoadAllCommandsAndOnCommand( *pActor, sMetricsGroup ); } - inline void SetXYAndOnCommand( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) SetXYAndOnCommand( *pActor, sMetricsGroup ); } - inline void LoadAllCommandsAndSetXYAndOnCommand( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) LoadAllCommandsAndSetXYAndOnCommand( *pActor, sMetricsGroup ); } - - // Return a Sprite, BitmapText, or Model depending on the file type - Actor* LoadFromNode( const XNode* pNode, Actor *pParentActor = NULL ); - Actor* MakeActor( const RString &sPath, Actor *pParentActor = NULL ); - RString GetSourcePath( const XNode *pNode ); - RString GetWhere( const XNode *pNode ); - bool GetAttrPath( const XNode *pNode, const RString &sName, RString &sOut ); - bool LoadTableFromStackShowErrors( Lua *L ); - - bool ResolvePath( RString &sPath, const RString &sName ); - - void SortByZPosition( vector &vActors ); - - FileType GetFileType( const RString &sPath ); -}; - -#define SET_XY( actor ) ActorUtil::SetXY( actor, m_sName ) -#define ON_COMMAND( actor ) ActorUtil::OnCommand( actor ) -#define OFF_COMMAND( actor ) ActorUtil::OffCommand( actor ) -#define SET_XY_AND_ON_COMMAND( actor ) ActorUtil::SetXYAndOnCommand( actor, m_sName ) -#define COMMAND( actor, command_name ) ActorUtil::PlayCommand( actor, command_name ) -#define LOAD_ALL_COMMANDS( actor ) ActorUtil::LoadAllCommands( actor, m_sName ) -#define LOAD_ALL_COMMANDS_AND_SET_XY( actor ) ActorUtil::LoadAllCommandsAndSetXY( actor, m_sName ) -#define LOAD_ALL_COMMANDS_AND_ON_COMMAND( actor ) ActorUtil::LoadAllCommandsAndOnCommand( actor, m_sName ) -#define LOAD_ALL_COMMANDS_AND_SET_XY_AND_ON_COMMAND( actor ) ActorUtil::LoadAllCommandsAndSetXYAndOnCommand( actor, m_sName ) - - -#endif - -/* - * (c) 2003-2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef ActorUtil_H +#define ActorUtil_H + +#include "Actor.h" +#include "RageTexture.h" + +class XNode; + +typedef Actor* (*CreateActorFn)(); + +template +Actor *CreateActor() { return new T; } + +/** + * @brief Register the requested Actor with the specified external name. + * + * This should be called manually only if needed. */ +#define REGISTER_ACTOR_CLASS_WITH_NAME( className, externalClassName ) \ + struct Register##className { \ + Register##className() { ActorUtil::Register(#externalClassName, CreateActor); } \ + }; \ + className *className::Copy() const { return new className(*this); } \ + static Register##className register##className + +/** + * @brief Register the requested Actor so that it's more accessible. + * + * Each Actor class should have a REGISTER_ACTOR_CLASS in its CPP file. */ +#define REGISTER_ACTOR_CLASS( className ) REGISTER_ACTOR_CLASS_WITH_NAME( className, className ) + +enum FileType +{ + FT_Bitmap, + FT_Sound, + FT_Movie, + FT_Directory, + FT_Lua, + FT_Model, + NUM_FileType, + FileType_Invalid +}; +const RString& FileTypeToString( FileType ft ); + +/** @brief Utility functions for creating and manipulating Actors. */ +namespace ActorUtil +{ + // Every screen should register its class at program initialization. + void Register( const RString& sClassName, CreateActorFn pfn ); + + apActorCommands ParseActorCommands( const RString &sCommands, const RString &sName = "" ); + void SetXY( Actor& actor, const RString &sMetricsGroup ); + inline void PlayCommand( Actor& actor, const RString &sCommandName ) { actor.PlayCommand( sCommandName ); } + inline void OnCommand( Actor& actor ) + { + ASSERT_M( actor.HasCommand("On"), ssprintf("%s is missing an OnCommand.", actor.GetLineage().c_str()) ); + actor.PlayCommand("On"); + } + inline void OffCommand( Actor& actor ) + { + // HACK: It's very often that we command things to TweenOffScreen + // that we aren't drawing. We know that an Actor is not being + // used if its name is blank. So, do nothing on Actors with a blank name. + // (Do "playcommand" anyway; BGAs often have no name.) + if( actor.GetName().empty() ) + return; + ASSERT_M( actor.HasCommand("Off"), ssprintf("Actor %s is missing an OffCommand.", actor.GetLineage().c_str()) ); + actor.PlayCommand("Off"); + } + + void LoadCommand( Actor& actor, const RString &sMetricsGroup, const RString &sCommandName ); + void LoadCommandFromName( Actor& actor, const RString &sMetricsGroup, const RString &sCommandName, const RString &sName ); + void LoadAllCommands( Actor& actor, const RString &sMetricsGroup ); + void LoadAllCommandsFromName( Actor& actor, const RString &sMetricsGroup, const RString &sName ); + + inline void LoadAllCommandsAndSetXY( Actor& actor, const RString &sMetricsGroup ) + { + LoadAllCommands( actor, sMetricsGroup ); + SetXY( actor, sMetricsGroup ); + } + inline void LoadAllCommandsAndOnCommand( Actor& actor, const RString &sMetricsGroup ) + { + LoadAllCommands( actor, sMetricsGroup ); + OnCommand( actor ); + } + inline void SetXYAndOnCommand( Actor& actor, const RString &sMetricsGroup ) + { + SetXY( actor, sMetricsGroup ); + OnCommand( actor ); + } + inline void LoadAllCommandsAndSetXYAndOnCommand( Actor& actor, const RString &sMetricsGroup ) + { + LoadAllCommands( actor, sMetricsGroup ); + SetXY( actor, sMetricsGroup ); + OnCommand( actor ); + } + + /* convenience */ + inline void SetXY( Actor* pActor, const RString &sMetricsGroup ) { SetXY( *pActor, sMetricsGroup ); } + inline void PlayCommand( Actor* pActor, const RString &sCommandName ) { if(pActor) pActor->PlayCommand( sCommandName ); } + inline void OnCommand( Actor* pActor ) { if(pActor) ActorUtil::OnCommand( *pActor ); } + inline void OffCommand( Actor* pActor ) { if(pActor) ActorUtil::OffCommand( *pActor ); } + + inline void LoadAllCommands( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) LoadAllCommands( *pActor, sMetricsGroup ); } + + inline void LoadAllCommandsAndSetXY( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) LoadAllCommandsAndSetXY( *pActor, sMetricsGroup ); } + inline void LoadAllCommandsAndOnCommand( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) LoadAllCommandsAndOnCommand( *pActor, sMetricsGroup ); } + inline void SetXYAndOnCommand( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) SetXYAndOnCommand( *pActor, sMetricsGroup ); } + inline void LoadAllCommandsAndSetXYAndOnCommand( Actor* pActor, const RString &sMetricsGroup ) { if(pActor) LoadAllCommandsAndSetXYAndOnCommand( *pActor, sMetricsGroup ); } + + // Return a Sprite, BitmapText, or Model depending on the file type + Actor* LoadFromNode( const XNode* pNode, Actor *pParentActor = nullptr ); + Actor* MakeActor( const RString &sPath, Actor *pParentActor = nullptr ); + RString GetSourcePath( const XNode *pNode ); + RString GetWhere( const XNode *pNode ); + bool GetAttrPath( const XNode *pNode, const RString &sName, RString &sOut ); + bool LoadTableFromStackShowErrors( Lua *L ); + + bool ResolvePath( RString &sPath, const RString &sName ); + + void SortByZPosition( vector &vActors ); + + FileType GetFileType( const RString &sPath ); +}; + +#define SET_XY( actor ) ActorUtil::SetXY( actor, m_sName ) +#define ON_COMMAND( actor ) ActorUtil::OnCommand( actor ) +#define OFF_COMMAND( actor ) ActorUtil::OffCommand( actor ) +#define SET_XY_AND_ON_COMMAND( actor ) ActorUtil::SetXYAndOnCommand( actor, m_sName ) +#define COMMAND( actor, command_name ) ActorUtil::PlayCommand( actor, command_name ) +#define LOAD_ALL_COMMANDS( actor ) ActorUtil::LoadAllCommands( actor, m_sName ) +#define LOAD_ALL_COMMANDS_AND_SET_XY( actor ) ActorUtil::LoadAllCommandsAndSetXY( actor, m_sName ) +#define LOAD_ALL_COMMANDS_AND_ON_COMMAND( actor ) ActorUtil::LoadAllCommandsAndOnCommand( actor, m_sName ) +#define LOAD_ALL_COMMANDS_AND_SET_XY_AND_ON_COMMAND( actor ) ActorUtil::LoadAllCommandsAndSetXYAndOnCommand( actor, m_sName ) + + +#endif + +/* + * (c) 2003-2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/AnnouncerManager.cpp b/src/AnnouncerManager.cpp index 748f1a8c96..f994733a5b 100644 --- a/src/AnnouncerManager.cpp +++ b/src/AnnouncerManager.cpp @@ -5,7 +5,7 @@ #include "RageFile.h" #include -AnnouncerManager* ANNOUNCER = NULL; // global object accessable from anywhere in the program +AnnouncerManager* ANNOUNCER = nullptr; // global object accessable from anywhere in the program const RString EMPTY_ANNOUNCER_NAME = "Empty"; diff --git a/src/AutoActor.cpp b/src/AutoActor.cpp index d004755df8..1ec49359f8 100644 --- a/src/AutoActor.cpp +++ b/src/AutoActor.cpp @@ -13,7 +13,7 @@ void AutoActor::Unload() AutoActor::AutoActor( const AutoActor &cpy ) { if( cpy.m_pActor == nullptr ) - m_pActor = NULL; + m_pActor = nullptr; else m_pActor = cpy.m_pActor->Copy(); } @@ -23,7 +23,7 @@ AutoActor &AutoActor::operator=( const AutoActor &cpy ) Unload(); if( cpy.m_pActor == nullptr ) - m_pActor = NULL; + m_pActor = nullptr; else m_pActor = cpy.m_pActor->Copy(); return *this; diff --git a/src/AutoActor.h b/src/AutoActor.h index d214ba9511..d9bc295c5c 100644 --- a/src/AutoActor.h +++ b/src/AutoActor.h @@ -12,7 +12,7 @@ class XNode; class AutoActor { public: - AutoActor(): m_pActor(NULL) {} + AutoActor(): m_pActor(nullptr) {} ~AutoActor() { Unload(); } AutoActor( const AutoActor &cpy ); AutoActor &operator =( const AutoActor &cpy ); diff --git a/src/AutoKeysounds.cpp b/src/AutoKeysounds.cpp index 98153a5743..a7f4e89737 100644 --- a/src/AutoKeysounds.cpp +++ b/src/AutoKeysounds.cpp @@ -122,9 +122,9 @@ void AutoKeysounds::LoadTracks( const Song *pSong, RageSoundReader *&pShared, Ra // two-track sound. //bool bTwoPlayers = GAMESTATE->GetNumPlayersEnabled() == 2; - pPlayer1 = NULL; - pPlayer2 = NULL; - pShared = NULL; + pPlayer1 = nullptr; + pPlayer2 = nullptr; + pShared = nullptr; vector vsMusicFile; const RString sMusicPath = pSong->GetMusicPath(); diff --git a/src/Background.cpp b/src/Background.cpp index 37c89b32bb..2f0215414f 100644 --- a/src/Background.cpp +++ b/src/Background.cpp @@ -147,15 +147,15 @@ static RageColor GetBrightnessColor( float fBrightnessPercent ) BackgroundImpl::BackgroundImpl() { m_bInitted = false; - m_pDancingCharacters = NULL; - m_pSong = NULL; + m_pDancingCharacters = nullptr; + m_pSong = nullptr; } BackgroundImpl::Layer::Layer() { m_iCurBGChangeIndex = -1; - m_pCurrentBGA = NULL; - m_pFadingBGA = NULL; + m_pCurrentBGA = nullptr; + m_pFadingBGA = nullptr; } void BackgroundImpl::Init() @@ -242,7 +242,7 @@ void BackgroundImpl::Unload() { FOREACH_BackgroundLayer( i ) m_Layer[i].Unload(); - m_pSong = NULL; + m_pSong = nullptr; m_fLastMusicSeconds = -9999; m_RandomBGAnimations.clear(); } @@ -254,8 +254,8 @@ void BackgroundImpl::Layer::Unload() m_BGAnimations.clear(); m_aBGChanges.clear(); - m_pCurrentBGA = NULL; - m_pFadingBGA = NULL; + m_pCurrentBGA = nullptr; + m_pFadingBGA = nullptr; m_iCurBGChangeIndex = -1; } @@ -743,7 +743,7 @@ void BackgroundImpl::Layer::UpdateCurBGChange( const Song *pSong, float fLastMus if( m_pFadingBGA == m_pCurrentBGA ) { - m_pFadingBGA = NULL; + m_pFadingBGA = nullptr; //LOG->Trace( "bg didn't actually change. Ignoring." ); } else @@ -779,7 +779,7 @@ void BackgroundImpl::Layer::UpdateCurBGChange( const Song *pSong, float fLastMus if( m_pFadingBGA ) { if( m_pFadingBGA->GetTweenTimeLeft() == 0 ) - m_pFadingBGA = NULL; + m_pFadingBGA = nullptr; } /* This is unaffected by the music rate. */ diff --git a/src/Banner.cpp b/src/Banner.cpp index 960034e8e6..52abc89141 100644 --- a/src/Banner.cpp +++ b/src/Banner.cpp @@ -248,13 +248,13 @@ public: static int ScaleToClipped( T* p, lua_State *L ) { p->ScaleToClipped(FArg(1),FArg(2)); return 0; } static int LoadFromSong( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadFromSong( NULL ); } + if( lua_isnil(L,1) ) { p->LoadFromSong(nullptr); } else { Song *pS = Luna::check(L,1); p->LoadFromSong( pS ); } return 0; } static int LoadFromCourse( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadFromCourse( NULL ); } + if( lua_isnil(L,1) ) { p->LoadFromCourse(nullptr); } else { Course *pC = Luna::check(L,1); p->LoadFromCourse( pC ); } return 0; } @@ -265,25 +265,25 @@ public: } static int LoadIconFromCharacter( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadIconFromCharacter( NULL ); } + if( lua_isnil(L,1) ) { p->LoadIconFromCharacter(nullptr); } else { Character *pC = Luna::check(L,1); p->LoadIconFromCharacter( pC ); } return 0; } static int LoadCardFromCharacter( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadIconFromCharacter( NULL ); } + if( lua_isnil(L,1) ) { p->LoadIconFromCharacter(nullptr); } else { Character *pC = Luna::check(L,1); p->LoadIconFromCharacter( pC ); } return 0; } static int LoadBannerFromUnlockEntry( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadBannerFromUnlockEntry( NULL ); } + if( lua_isnil(L,1) ) { p->LoadBannerFromUnlockEntry(nullptr); } else { UnlockEntry *pUE = Luna::check(L,1); p->LoadBannerFromUnlockEntry( pUE ); } return 0; } static int LoadBackgroundFromUnlockEntry( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadBackgroundFromUnlockEntry( NULL ); } + if( lua_isnil(L,1) ) { p->LoadBackgroundFromUnlockEntry(nullptr); } else { UnlockEntry *pUE = Luna::check(L,1); p->LoadBackgroundFromUnlockEntry( pUE ); } return 0; } diff --git a/src/BitmapText.cpp b/src/BitmapText.cpp index a257af2e85..18fde0ff64 100644 --- a/src/BitmapText.cpp +++ b/src/BitmapText.cpp @@ -42,7 +42,7 @@ BitmapText::BitmapText() } iReloadCounter++; - m_pFont = NULL; + m_pFont = nullptr; m_bUppercase = false; m_bRainbowScroll = false; @@ -98,7 +98,7 @@ BitmapText & BitmapText::operator=(const BitmapText &cpy) if( cpy.m_pFont != nullptr ) m_pFont = FONT->CopyFont( cpy.m_pFont ); else - m_pFont = NULL; + m_pFont = nullptr; return *this; } @@ -106,7 +106,7 @@ BitmapText & BitmapText::operator=(const BitmapText &cpy) BitmapText::BitmapText( const BitmapText &cpy ): Actor( cpy ) { - m_pFont = NULL; + m_pFont = nullptr; *this = cpy; } @@ -143,7 +143,7 @@ bool BitmapText::LoadFromFont( const RString& sFontFilePath ) if( m_pFont ) { FONT->UnloadFont( m_pFont ); - m_pFont = NULL; + m_pFont = nullptr; } m_pFont = FONT->LoadFont( sFontFilePath ); @@ -162,7 +162,7 @@ bool BitmapText::LoadFromTextureAndChars( const RString& sTexturePath, const RSt if( m_pFont ) { FONT->UnloadFont( m_pFont ); - m_pFont = NULL; + m_pFont = nullptr; } m_pFont = FONT->LoadFont( sTexturePath, sChars ); diff --git a/src/CharacterManager.cpp b/src/CharacterManager.cpp index 99d45c71c9..289864e4c4 100644 --- a/src/CharacterManager.cpp +++ b/src/CharacterManager.cpp @@ -7,7 +7,7 @@ #define CHARACTERS_DIR "/Characters/" -CharacterManager* CHARMAN = NULL; // global object accessable from anywhere in the program +CharacterManager* CHARMAN = nullptr; // global object accessable from anywhere in the program CharacterManager::CharacterManager() { diff --git a/src/ComboGraph.cpp b/src/ComboGraph.cpp index 6a6fe6b50b..0ec211e280 100644 --- a/src/ComboGraph.cpp +++ b/src/ComboGraph.cpp @@ -14,16 +14,16 @@ ComboGraph::ComboGraph() { DeleteChildrenWhenDone( true ); - m_pNormalCombo = NULL; - m_pMaxCombo = NULL; - m_pComboNumber = NULL; + m_pNormalCombo = nullptr; + m_pMaxCombo = nullptr; + m_pComboNumber = nullptr; } void ComboGraph::Load( RString sMetricsGroup ) { BODY_WIDTH.Load( sMetricsGroup, "BodyWidth" ); - Actor *pActor = NULL; + Actor *pActor = nullptr; m_pBacking = ActorUtil::MakeActor( THEME->GetPathG(sMetricsGroup,"Backing") ); m_pBacking->ZoomToWidth( BODY_WIDTH ); diff --git a/src/CourseLoaderCRS.cpp b/src/CourseLoaderCRS.cpp index 9c05c0ab68..a6b97fb4a4 100644 --- a/src/CourseLoaderCRS.cpp +++ b/src/CourseLoaderCRS.cpp @@ -250,7 +250,7 @@ bool CourseLoaderCRS::LoadFromMsd( const RString &sPath, const MsdFile &msd, Cou vector bits; split( sSong, "/", bits ); - Song *pSong = NULL; + Song *pSong = nullptr; if( bits.size() == 2 ) { new_entry.songCriteria.m_sGroupName = bits[0]; diff --git a/src/CourseUtil.cpp b/src/CourseUtil.cpp index a24fa4b574..38dd718218 100644 --- a/src/CourseUtil.cpp +++ b/src/CourseUtil.cpp @@ -450,7 +450,7 @@ void EditCourseUtil::UpdateAndSetTrail() { ASSERT( GAMESTATE->m_pCurStyle != nullptr ); StepsType st = GAMESTATE->m_pCurStyle->m_StepsType; - Trail *pTrail = NULL; + Trail *pTrail = nullptr; if( GAMESTATE->m_pCurCourse ) pTrail = GAMESTATE->m_pCurCourse->GetTrailForceRegenCache( st ); GAMESTATE->m_pCurTrail[PLAYER_1].Set( pTrail ); @@ -458,7 +458,7 @@ void EditCourseUtil::UpdateAndSetTrail() void EditCourseUtil::PrepareForPlay() { - GAMESTATE->m_pCurSong.Set( NULL ); // CurSong will be set if we back out. Set it back to NULL so that ScreenStage won't show the last song. + GAMESTATE->m_pCurSong.Set(nullptr); // CurSong will be set if we back out. Set it back to NULL so that ScreenStage won't show the last song. GAMESTATE->m_PlayMode.Set( PLAY_MODE_ENDLESS ); GAMESTATE->m_bSideIsJoined[0] = true; @@ -549,7 +549,7 @@ Course *CourseID::ToCourse() const if( sPath2.Left(1) != "/" ) sPath2 = "/" + sPath2; - Course *pCourse = NULL; + Course *pCourse = nullptr; if( m_Cache.Get(&pCourse) ) return pCourse; if( pCourse == nullptr && !sPath2.empty() ) diff --git a/src/CourseUtil.h b/src/CourseUtil.h index 6be86abe77..2afcd874ed 100644 --- a/src/CourseUtil.h +++ b/src/CourseUtil.h @@ -73,7 +73,7 @@ class CourseID { public: CourseID(): sPath(""), sFullTitle(""), m_Cache() { Unset(); } - void Unset() { FromCourse(NULL); } + void Unset() { FromCourse(nullptr); } void FromCourse( const Course *p ); Course *ToCourse() const; const RString &GetPath() const { return sPath; } diff --git a/src/CreateZip.cpp b/src/CreateZip.cpp index a9a8ca2adf..798db118c6 100644 --- a/src/CreateZip.cpp +++ b/src/CreateZip.cpp @@ -543,7 +543,7 @@ ulg crc32(ulg crc, const uch *buf, size_t len) class TZip { public: - TZip() : pfout(NULL),ooffset(0),oerr(false),writ(0),hasputcen(false),zfis(0),hfin(0) + TZip() : pfout(nullptr),ooffset(0),oerr(false),writ(0),hasputcen(false),zfis(0),hfin(0) { } ~TZip() @@ -717,7 +717,7 @@ ZRESULT TZip::set_times() unsigned short dosdate,dostime; filetime2dosdatetime(*ptm,&dosdate,&dostime); - times.atime = time(NULL); + times.atime = time(nullptr); times.mtime = times.atime; times.ctime = times.atime; timestamp = (unsigned short)dostime | (((unsigned long)dosdate)<<16); diff --git a/src/CryptManager.cpp b/src/CryptManager.cpp index 1c2427b7de..31bbe80605 100644 --- a/src/CryptManager.cpp +++ b/src/CryptManager.cpp @@ -1,527 +1,527 @@ -#include "global.h" -#include "CryptManager.h" -#include "RageUtil.h" -#include "RageLog.h" -#include "RageFile.h" -#include "RageFileManager.h" -#include "CryptHelpers.h" -#include "LuaBinding.h" -#include "LuaReference.h" -#include "LuaManager.h" - -#include "libtomcrypt/src/headers/tomcrypt.h" - -CryptManager* CRYPTMAN = NULL; // global and accessable from anywhere in our program - -static const RString PRIVATE_KEY_PATH = "Data/private.rsa"; -static const RString PUBLIC_KEY_PATH = "Data/public.rsa"; -static const RString ALTERNATE_PUBLIC_KEY_DIR = "Data/keys/"; - -static bool HashFile( RageFileBasic &f, unsigned char buf_hash[20], int iHash ) -{ - hash_state hash; - int iRet = hash_descriptor[iHash].init( &hash ); - ASSERT_M( iRet == CRYPT_OK, error_to_string(iRet) ); - - RString s; - while( !f.AtEOF() ) - { - s.erase(); - if( f.Read(s, 1024*4) == -1 ) - { - LOG->Warn( "Error reading %s: %s", f.GetDisplayPath().c_str(), f.GetError().c_str() ); - hash_descriptor[iHash].done( &hash, buf_hash ); - return false; - } - - iRet = hash_descriptor[iHash].process( &hash, (const unsigned char *) s.data(), s.size() ); - ASSERT_M( iRet == CRYPT_OK, error_to_string(iRet) ); - } - - iRet = hash_descriptor[iHash].done( &hash, buf_hash ); - ASSERT_M( iRet == CRYPT_OK, error_to_string(iRet) ); - - return true; -} - -#if defined(DISABLE_CRYPTO) -CryptManager::CryptManager() { } -CryptManager::~CryptManager() { } -void CryptManager::GenerateRSAKey( unsigned int keyLength, RString privFilename, RString pubFilename ) { } -void CryptManager::SignFileToFile( RString sPath, RString sSignatureFile ) { } -bool CryptManager::VerifyFileWithFile( RString sPath, RString sSignatureFile, RString sPublicKeyFile ) { return true; } -bool CryptManager::VerifyFileWithFile( RString sPath, RString sSignatureFile ) -{ - return true; -} - -void CryptManager::GetRandomBytes( void *pData, int iBytes ) -{ - uint8_t *pBuf = (uint8_t *) pData; - while( iBytes-- ) - *pBuf++ = (uint8_t) RandomInt( 256 ); -} - -#else - -static const int KEY_LENGTH = 1024; -#define MAX_SIGNATURE_SIZE_BYTES 1024 // 1 KB - - - - -/* - openssl genrsa -out testing -outform DER - openssl rsa -in testing -out testing2 -outform DER - openssl rsa -in testing -out testing2 -pubout -outform DER - - openssl pkcs8 -inform DER -outform DER -nocrypt -in private.rsa -out private.der - * - */ - -static PRNGWrapper *g_pPRNG = NULL; - - -CryptManager::CryptManager() -{ - // Register with Lua. - { - Lua *L = LUA->Get(); - lua_pushstring( L, "CRYPTMAN" ); - this->PushSelf( L ); - lua_settable( L, LUA_GLOBALSINDEX ); - LUA->Release( L ); - } - - ltc_mp = ltm_desc; - - g_pPRNG = new PRNGWrapper( &yarrow_desc ); -} - -void CryptManager::GenerateGlobalKeys() -{ - // - // generate keys if none are available - // - bool bGenerate = false; - RSAKeyWrapper key; - RString sKey; - RString sError; - if( !DoesFileExist(PRIVATE_KEY_PATH) || - !GetFileContents(PRIVATE_KEY_PATH, sKey) || - !key.Load(sKey, sError) ) - bGenerate = true; - if( !sError.empty() ) - LOG->Warn( "Error loading RSA key: %s", sError.c_str() ); - - sError.clear(); - if( !DoesFileExist(PUBLIC_KEY_PATH) || - !GetFileContents(PUBLIC_KEY_PATH, sKey) || - !key.Load(sKey, sError) ) - bGenerate = true; - if( !sError.empty() ) - LOG->Warn( "Error loading RSA key: %s", sError.c_str() ); - - if( bGenerate ) - { - LOG->Warn( "Keys missing or failed to load. Generating new keys" ); - GenerateRSAKeyToFile( KEY_LENGTH, PRIVATE_KEY_PATH, PUBLIC_KEY_PATH ); - } -} - -CryptManager::~CryptManager() -{ - SAFE_DELETE( g_pPRNG ); - // Unregister with Lua. - LUA->UnsetGlobal( "CRYPTMAN" ); -} - -static bool WriteFile( RString sFile, RString sBuf ) -{ - RageFile output; - if( !output.Open(sFile, RageFile::WRITE) ) - { - LOG->Warn( "WriteFile: opening %s failed: %s", sFile.c_str(), output.GetError().c_str() ); - return false; - } - - if( output.Write(sBuf) == -1 || output.Flush() == -1 ) - { - LOG->Warn( "WriteFile: writing %s failed: %s", sFile.c_str(), output.GetError().c_str() ); - output.Close(); - FILEMAN->Remove( sFile ); - return false; - } - - return true; -} - -void CryptManager::GenerateRSAKey( unsigned int keyLength, RString &sPrivKey, RString &sPubKey ) -{ - int iRet; - - rsa_key key; - iRet = rsa_make_key( &g_pPRNG->m_PRNG, g_pPRNG->m_iPRNG, keyLength / 8, 65537, &key ); - if( iRet != CRYPT_OK ) - { - LOG->Warn( "GenerateRSAKey(%i) error: %s", keyLength, error_to_string(iRet) ); - return; - } - - unsigned char buf[1024]; - unsigned long iSize = sizeof(buf); - iRet = rsa_export( buf, &iSize, PK_PUBLIC, &key ); - if( iRet != CRYPT_OK ) - { - LOG->Warn( "Export error: %s", error_to_string(iRet) ); - return; - } - - sPubKey = RString( (const char *) buf, iSize ); - - iSize = sizeof(buf); - iRet = rsa_export( buf, &iSize, PK_PRIVATE, &key ); - if( iRet != CRYPT_OK ) - { - LOG->Warn( "Export error: %s", error_to_string(iRet) ); - return; - } - - sPrivKey = RString( (const char *) buf, iSize ); -} - -void CryptManager::GenerateRSAKeyToFile( unsigned int keyLength, RString privFilename, RString pubFilename ) -{ - RString sPrivKey, sPubKey; - GenerateRSAKey( keyLength, sPrivKey, sPubKey ); - - if( !WriteFile(pubFilename, sPubKey) ) - return; - - if( !WriteFile(privFilename, sPrivKey) ) - { - FILEMAN->Remove( privFilename ); - return; - } -} - -void CryptManager::SignFileToFile( RString sPath, RString sSignatureFile ) -{ - RString sPrivFilename = PRIVATE_KEY_PATH; - if( sSignatureFile.empty() ) - sSignatureFile = sPath + SIGNATURE_APPEND; - - RString sPrivKey; - if( !GetFileContents(sPrivFilename, sPrivKey) ) - return; - - RString sSignature; - if( !Sign(sPath, sSignature, sPrivKey) ) - return; - - WriteFile( sSignatureFile, sSignature ); -} - -bool CryptManager::Sign( RString sPath, RString &sSignatureOut, RString sPrivKey ) -{ - if( !IsAFile(sPath) ) - { - LOG->Trace( "SignFileToFile: \"%s\" doesn't exist", sPath.c_str() ); - return false; - } - - RageFile file; - if( !file.Open(sPath) ) - { - LOG->Warn( "SignFileToFile: open(%s) failed: %s", sPath.c_str(), file.GetError().c_str() ); - return false; - } - - RSAKeyWrapper key; - RString sError; - if( !key.Load(sPrivKey, sError) ) - { - LOG->Warn( "Error loading RSA key: %s", sError.c_str() ); - return false; - } - - int iHash = register_hash( &sha1_desc ); - ASSERT( iHash >= 0 ); - - unsigned char buf_hash[20]; - if( !HashFile(file, buf_hash, iHash) ) - return false; - - unsigned char signature[256]; - unsigned long signature_len = sizeof(signature); - - int iRet = rsa_sign_hash_ex( - buf_hash, sizeof(buf_hash), - signature, &signature_len, - LTC_PKCS_1_V1_5, &g_pPRNG->m_PRNG, g_pPRNG->m_iPRNG, iHash, - 0, &key.m_Key); - if( iRet != CRYPT_OK ) - { - LOG->Warn( "SignFileToFile error: %s", error_to_string(iRet) ); - return false; - } - - sSignatureOut.assign( (const char *) signature, signature_len ); - return true; -} - -bool CryptManager::VerifyFileWithFile( RString sPath, RString sSignatureFile ) -{ - if( VerifyFileWithFile(sPath, sSignatureFile, PUBLIC_KEY_PATH) ) - return true; - - vector asKeys; - GetDirListing( ALTERNATE_PUBLIC_KEY_DIR, asKeys, false, true ); - for( unsigned i = 0; i < asKeys.size(); ++i ) - { - const RString &sKey = asKeys[i]; - LOG->Trace( "Trying alternate key \"%s\" ...", sKey.c_str() ); - - if( VerifyFileWithFile(sPath, sSignatureFile, sKey) ) - return true; - } - - return false; -} - -bool CryptManager::VerifyFileWithFile( RString sPath, RString sSignatureFile, RString sPublicKeyFile ) -{ - if( sSignatureFile.empty() ) - sSignatureFile = sPath + SIGNATURE_APPEND; - - RString sPublicKey; - if( !GetFileContents(sPublicKeyFile, sPublicKey) ) - return false; - - int iBytes = FILEMAN->GetFileSizeInBytes( sSignatureFile ); - if( iBytes > MAX_SIGNATURE_SIZE_BYTES ) - return false; - - RString sSignature; - if( !GetFileContents(sSignatureFile, sSignature) ) - return false; - - RageFile file; - if( !file.Open(sPath) ) - { - LOG->Warn( "Verify: open(%s) failed: %s", sPath.c_str(), file.GetError().c_str() ); - return false; - } - - return Verify( file, sSignature, sPublicKey ); -} - -bool CryptManager::Verify( RageFileBasic &file, RString sSignature, RString sPublicKey ) -{ - RSAKeyWrapper key; - RString sError; - if( !key.Load(sPublicKey, sError) ) - { - LOG->Warn( "Error loading RSA key: %s", sError.c_str() ); - return false; - } - - int iHash = register_hash( &sha1_desc ); - ASSERT( iHash >= 0 ); - - unsigned char buf_hash[20]; - HashFile( file, buf_hash, iHash ); - - int iMatch; - int iRet = rsa_verify_hash_ex( (const unsigned char *) sSignature.data(), sSignature.size(), - buf_hash, sizeof(buf_hash), - LTC_PKCS_1_EMSA, iHash, 0, &iMatch, &key.m_Key ); - - if( iRet != CRYPT_OK ) - { - LOG->Warn( "Verify(%s) failed: %s", file.GetDisplayPath().c_str(), error_to_string(iRet) ); - return false; - } - - if( !iMatch ) - { - LOG->Warn( "Verify(%s) failed: signature mismatch", file.GetDisplayPath().c_str() ); - return false; - } - - return true; -} - -void CryptManager::GetRandomBytes( void *pData, int iBytes ) -{ - int iRet = prng_descriptor[g_pPRNG->m_iPRNG].read( (unsigned char *) pData, iBytes, &g_pPRNG->m_PRNG ); - ASSERT( iRet == iBytes ); -} -#endif - -RString CryptManager::GetMD5ForFile( RString fn ) -{ - RageFile file; - if( !file.Open( fn, RageFile::READ ) ) - { - LOG->Warn( "GetMD5: Failed to open file '%s'", fn.c_str() ); - return RString(); - } - int iHash = register_hash( &md5_desc ); - ASSERT( iHash >= 0 ); - - unsigned char digest[16]; - HashFile( file, digest, iHash ); - - return RString( (const char *) digest, sizeof(digest) ); -} - -RString CryptManager::GetMD5ForString( RString sData ) -{ - unsigned char digest[16]; - - int iHash = register_hash( &md5_desc ); - - hash_state hash; - hash_descriptor[iHash].init( &hash ); - hash_descriptor[iHash].process( &hash, (const unsigned char *) sData.data(), sData.size() ); - hash_descriptor[iHash].done( &hash, digest ); - - return RString( (const char *) digest, sizeof(digest) ); -} - -RString CryptManager::GetSHA1ForString( RString sData ) -{ - unsigned char digest[20]; - - int iHash = register_hash( &sha1_desc ); - - hash_state hash; - hash_descriptor[iHash].init( &hash ); - hash_descriptor[iHash].process( &hash, (const unsigned char *) sData.data(), sData.size() ); - hash_descriptor[iHash].done( &hash, digest ); - - return RString( (const char *) digest, sizeof(digest) ); -} - -RString CryptManager::GetSHA1ForFile( RString fn ) -{ - RageFile file; - if( !file.Open( fn, RageFile::READ ) ) - { - LOG->Warn( "GetSHA1: Failed to open file '%s'", fn.c_str() ); - return RString(); - } - int iHash = register_hash( &sha1_desc ); - ASSERT( iHash >= 0 ); - - unsigned char digest[20]; - HashFile( file, digest, iHash ); - - return RString( (const char *) digest, sizeof(digest) ); -} - -RString CryptManager::GetPublicKeyFileName() -{ - return PUBLIC_KEY_PATH; -} - -/* Generate a version 4 random UUID. */ -RString CryptManager::GenerateRandomUUID() -{ - uint32_t buf[4]; - CryptManager::GetRandomBytes( buf, sizeof(buf) ); - - buf[1] &= 0xFFFF0FFF; - buf[1] |= 0x00004000; - buf[2] &= 0x0FFFFFFF; - buf[2] |= 0xA0000000; - - return ssprintf("%08x-%04x-%04x-%04x-%04x%08x", - buf[0], - buf[1] >> 16, buf[1] & 0xFFFF, - buf[2] >> 16, buf[2] & 0xFFFF, - buf[3]); -} - -// lua start -#include "LuaBinding.h" - -/** @brief Allow Lua to have access to the CryptManager. */ -class LunaCryptManager: public Luna -{ -public: - static int MD5String( T* p, lua_State *L ) - { - RString md5out; - md5out = p->GetMD5ForString(SArg(1)); - lua_pushstring( L, md5out ); - return 1; - } - static int MD5File( T* p, lua_State *L ) - { - RString md5fout; - md5fout = p->GetMD5ForFile(SArg(1)); - lua_pushstring( L, md5fout ); - return 1; - } - static int SHA1String( T* p, lua_State *L ) - { - RString sha1out; - sha1out = p->GetSHA1ForString(SArg(1)); - lua_pushstring( L, sha1out ); - return 1; - } - static int SHA1File( T* p, lua_State *L ) - { - RString sha1fout; - sha1fout = p->GetSHA1ForFile(SArg(1)); - lua_pushstring( L, sha1fout ); - return 1; - } - static int GenerateRandomUUID( T* p, lua_State *L ) - { - RString uuidOut; - uuidOut = p->GenerateRandomUUID(); - lua_pushstring( L, uuidOut ); - return 1; - } - - LunaCryptManager() - { - ADD_METHOD( MD5String ); - ADD_METHOD( MD5File ); - ADD_METHOD( SHA1String ); - ADD_METHOD( SHA1File ); - ADD_METHOD( GenerateRandomUUID ); - } -}; - -LUA_REGISTER_CLASS( CryptManager ) - -// lua end - -/* - * (c) 2004-2007 Chris Danford, Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "CryptManager.h" +#include "RageUtil.h" +#include "RageLog.h" +#include "RageFile.h" +#include "RageFileManager.h" +#include "CryptHelpers.h" +#include "LuaBinding.h" +#include "LuaReference.h" +#include "LuaManager.h" + +#include "libtomcrypt/src/headers/tomcrypt.h" + +CryptManager* CRYPTMAN = NULL; // global and accessable from anywhere in our program + +static const RString PRIVATE_KEY_PATH = "Data/private.rsa"; +static const RString PUBLIC_KEY_PATH = "Data/public.rsa"; +static const RString ALTERNATE_PUBLIC_KEY_DIR = "Data/keys/"; + +static bool HashFile( RageFileBasic &f, unsigned char buf_hash[20], int iHash ) +{ + hash_state hash; + int iRet = hash_descriptor[iHash].init( &hash ); + ASSERT_M( iRet == CRYPT_OK, error_to_string(iRet) ); + + RString s; + while( !f.AtEOF() ) + { + s.erase(); + if( f.Read(s, 1024*4) == -1 ) + { + LOG->Warn( "Error reading %s: %s", f.GetDisplayPath().c_str(), f.GetError().c_str() ); + hash_descriptor[iHash].done( &hash, buf_hash ); + return false; + } + + iRet = hash_descriptor[iHash].process( &hash, (const unsigned char *) s.data(), s.size() ); + ASSERT_M( iRet == CRYPT_OK, error_to_string(iRet) ); + } + + iRet = hash_descriptor[iHash].done( &hash, buf_hash ); + ASSERT_M( iRet == CRYPT_OK, error_to_string(iRet) ); + + return true; +} + +#if defined(DISABLE_CRYPTO) +CryptManager::CryptManager() { } +CryptManager::~CryptManager() { } +void CryptManager::GenerateRSAKey( unsigned int keyLength, RString privFilename, RString pubFilename ) { } +void CryptManager::SignFileToFile( RString sPath, RString sSignatureFile ) { } +bool CryptManager::VerifyFileWithFile( RString sPath, RString sSignatureFile, RString sPublicKeyFile ) { return true; } +bool CryptManager::VerifyFileWithFile( RString sPath, RString sSignatureFile ) +{ + return true; +} + +void CryptManager::GetRandomBytes( void *pData, int iBytes ) +{ + uint8_t *pBuf = (uint8_t *) pData; + while( iBytes-- ) + *pBuf++ = (uint8_t) RandomInt( 256 ); +} + +#else + +static const int KEY_LENGTH = 1024; +#define MAX_SIGNATURE_SIZE_BYTES 1024 // 1 KB + + + + +/* + openssl genrsa -out testing -outform DER + openssl rsa -in testing -out testing2 -outform DER + openssl rsa -in testing -out testing2 -pubout -outform DER + + openssl pkcs8 -inform DER -outform DER -nocrypt -in private.rsa -out private.der + * + */ + +static PRNGWrapper *g_pPRNG = nullptr; + + +CryptManager::CryptManager() +{ + // Register with Lua. + { + Lua *L = LUA->Get(); + lua_pushstring( L, "CRYPTMAN" ); + this->PushSelf( L ); + lua_settable( L, LUA_GLOBALSINDEX ); + LUA->Release( L ); + } + + ltc_mp = ltm_desc; + + g_pPRNG = new PRNGWrapper( &yarrow_desc ); +} + +void CryptManager::GenerateGlobalKeys() +{ + // + // generate keys if none are available + // + bool bGenerate = false; + RSAKeyWrapper key; + RString sKey; + RString sError; + if( !DoesFileExist(PRIVATE_KEY_PATH) || + !GetFileContents(PRIVATE_KEY_PATH, sKey) || + !key.Load(sKey, sError) ) + bGenerate = true; + if( !sError.empty() ) + LOG->Warn( "Error loading RSA key: %s", sError.c_str() ); + + sError.clear(); + if( !DoesFileExist(PUBLIC_KEY_PATH) || + !GetFileContents(PUBLIC_KEY_PATH, sKey) || + !key.Load(sKey, sError) ) + bGenerate = true; + if( !sError.empty() ) + LOG->Warn( "Error loading RSA key: %s", sError.c_str() ); + + if( bGenerate ) + { + LOG->Warn( "Keys missing or failed to load. Generating new keys" ); + GenerateRSAKeyToFile( KEY_LENGTH, PRIVATE_KEY_PATH, PUBLIC_KEY_PATH ); + } +} + +CryptManager::~CryptManager() +{ + SAFE_DELETE( g_pPRNG ); + // Unregister with Lua. + LUA->UnsetGlobal( "CRYPTMAN" ); +} + +static bool WriteFile( RString sFile, RString sBuf ) +{ + RageFile output; + if( !output.Open(sFile, RageFile::WRITE) ) + { + LOG->Warn( "WriteFile: opening %s failed: %s", sFile.c_str(), output.GetError().c_str() ); + return false; + } + + if( output.Write(sBuf) == -1 || output.Flush() == -1 ) + { + LOG->Warn( "WriteFile: writing %s failed: %s", sFile.c_str(), output.GetError().c_str() ); + output.Close(); + FILEMAN->Remove( sFile ); + return false; + } + + return true; +} + +void CryptManager::GenerateRSAKey( unsigned int keyLength, RString &sPrivKey, RString &sPubKey ) +{ + int iRet; + + rsa_key key; + iRet = rsa_make_key( &g_pPRNG->m_PRNG, g_pPRNG->m_iPRNG, keyLength / 8, 65537, &key ); + if( iRet != CRYPT_OK ) + { + LOG->Warn( "GenerateRSAKey(%i) error: %s", keyLength, error_to_string(iRet) ); + return; + } + + unsigned char buf[1024]; + unsigned long iSize = sizeof(buf); + iRet = rsa_export( buf, &iSize, PK_PUBLIC, &key ); + if( iRet != CRYPT_OK ) + { + LOG->Warn( "Export error: %s", error_to_string(iRet) ); + return; + } + + sPubKey = RString( (const char *) buf, iSize ); + + iSize = sizeof(buf); + iRet = rsa_export( buf, &iSize, PK_PRIVATE, &key ); + if( iRet != CRYPT_OK ) + { + LOG->Warn( "Export error: %s", error_to_string(iRet) ); + return; + } + + sPrivKey = RString( (const char *) buf, iSize ); +} + +void CryptManager::GenerateRSAKeyToFile( unsigned int keyLength, RString privFilename, RString pubFilename ) +{ + RString sPrivKey, sPubKey; + GenerateRSAKey( keyLength, sPrivKey, sPubKey ); + + if( !WriteFile(pubFilename, sPubKey) ) + return; + + if( !WriteFile(privFilename, sPrivKey) ) + { + FILEMAN->Remove( privFilename ); + return; + } +} + +void CryptManager::SignFileToFile( RString sPath, RString sSignatureFile ) +{ + RString sPrivFilename = PRIVATE_KEY_PATH; + if( sSignatureFile.empty() ) + sSignatureFile = sPath + SIGNATURE_APPEND; + + RString sPrivKey; + if( !GetFileContents(sPrivFilename, sPrivKey) ) + return; + + RString sSignature; + if( !Sign(sPath, sSignature, sPrivKey) ) + return; + + WriteFile( sSignatureFile, sSignature ); +} + +bool CryptManager::Sign( RString sPath, RString &sSignatureOut, RString sPrivKey ) +{ + if( !IsAFile(sPath) ) + { + LOG->Trace( "SignFileToFile: \"%s\" doesn't exist", sPath.c_str() ); + return false; + } + + RageFile file; + if( !file.Open(sPath) ) + { + LOG->Warn( "SignFileToFile: open(%s) failed: %s", sPath.c_str(), file.GetError().c_str() ); + return false; + } + + RSAKeyWrapper key; + RString sError; + if( !key.Load(sPrivKey, sError) ) + { + LOG->Warn( "Error loading RSA key: %s", sError.c_str() ); + return false; + } + + int iHash = register_hash( &sha1_desc ); + ASSERT( iHash >= 0 ); + + unsigned char buf_hash[20]; + if( !HashFile(file, buf_hash, iHash) ) + return false; + + unsigned char signature[256]; + unsigned long signature_len = sizeof(signature); + + int iRet = rsa_sign_hash_ex( + buf_hash, sizeof(buf_hash), + signature, &signature_len, + LTC_PKCS_1_V1_5, &g_pPRNG->m_PRNG, g_pPRNG->m_iPRNG, iHash, + 0, &key.m_Key); + if( iRet != CRYPT_OK ) + { + LOG->Warn( "SignFileToFile error: %s", error_to_string(iRet) ); + return false; + } + + sSignatureOut.assign( (const char *) signature, signature_len ); + return true; +} + +bool CryptManager::VerifyFileWithFile( RString sPath, RString sSignatureFile ) +{ + if( VerifyFileWithFile(sPath, sSignatureFile, PUBLIC_KEY_PATH) ) + return true; + + vector asKeys; + GetDirListing( ALTERNATE_PUBLIC_KEY_DIR, asKeys, false, true ); + for( unsigned i = 0; i < asKeys.size(); ++i ) + { + const RString &sKey = asKeys[i]; + LOG->Trace( "Trying alternate key \"%s\" ...", sKey.c_str() ); + + if( VerifyFileWithFile(sPath, sSignatureFile, sKey) ) + return true; + } + + return false; +} + +bool CryptManager::VerifyFileWithFile( RString sPath, RString sSignatureFile, RString sPublicKeyFile ) +{ + if( sSignatureFile.empty() ) + sSignatureFile = sPath + SIGNATURE_APPEND; + + RString sPublicKey; + if( !GetFileContents(sPublicKeyFile, sPublicKey) ) + return false; + + int iBytes = FILEMAN->GetFileSizeInBytes( sSignatureFile ); + if( iBytes > MAX_SIGNATURE_SIZE_BYTES ) + return false; + + RString sSignature; + if( !GetFileContents(sSignatureFile, sSignature) ) + return false; + + RageFile file; + if( !file.Open(sPath) ) + { + LOG->Warn( "Verify: open(%s) failed: %s", sPath.c_str(), file.GetError().c_str() ); + return false; + } + + return Verify( file, sSignature, sPublicKey ); +} + +bool CryptManager::Verify( RageFileBasic &file, RString sSignature, RString sPublicKey ) +{ + RSAKeyWrapper key; + RString sError; + if( !key.Load(sPublicKey, sError) ) + { + LOG->Warn( "Error loading RSA key: %s", sError.c_str() ); + return false; + } + + int iHash = register_hash( &sha1_desc ); + ASSERT( iHash >= 0 ); + + unsigned char buf_hash[20]; + HashFile( file, buf_hash, iHash ); + + int iMatch; + int iRet = rsa_verify_hash_ex( (const unsigned char *) sSignature.data(), sSignature.size(), + buf_hash, sizeof(buf_hash), + LTC_PKCS_1_EMSA, iHash, 0, &iMatch, &key.m_Key ); + + if( iRet != CRYPT_OK ) + { + LOG->Warn( "Verify(%s) failed: %s", file.GetDisplayPath().c_str(), error_to_string(iRet) ); + return false; + } + + if( !iMatch ) + { + LOG->Warn( "Verify(%s) failed: signature mismatch", file.GetDisplayPath().c_str() ); + return false; + } + + return true; +} + +void CryptManager::GetRandomBytes( void *pData, int iBytes ) +{ + int iRet = prng_descriptor[g_pPRNG->m_iPRNG].read( (unsigned char *) pData, iBytes, &g_pPRNG->m_PRNG ); + ASSERT( iRet == iBytes ); +} +#endif + +RString CryptManager::GetMD5ForFile( RString fn ) +{ + RageFile file; + if( !file.Open( fn, RageFile::READ ) ) + { + LOG->Warn( "GetMD5: Failed to open file '%s'", fn.c_str() ); + return RString(); + } + int iHash = register_hash( &md5_desc ); + ASSERT( iHash >= 0 ); + + unsigned char digest[16]; + HashFile( file, digest, iHash ); + + return RString( (const char *) digest, sizeof(digest) ); +} + +RString CryptManager::GetMD5ForString( RString sData ) +{ + unsigned char digest[16]; + + int iHash = register_hash( &md5_desc ); + + hash_state hash; + hash_descriptor[iHash].init( &hash ); + hash_descriptor[iHash].process( &hash, (const unsigned char *) sData.data(), sData.size() ); + hash_descriptor[iHash].done( &hash, digest ); + + return RString( (const char *) digest, sizeof(digest) ); +} + +RString CryptManager::GetSHA1ForString( RString sData ) +{ + unsigned char digest[20]; + + int iHash = register_hash( &sha1_desc ); + + hash_state hash; + hash_descriptor[iHash].init( &hash ); + hash_descriptor[iHash].process( &hash, (const unsigned char *) sData.data(), sData.size() ); + hash_descriptor[iHash].done( &hash, digest ); + + return RString( (const char *) digest, sizeof(digest) ); +} + +RString CryptManager::GetSHA1ForFile( RString fn ) +{ + RageFile file; + if( !file.Open( fn, RageFile::READ ) ) + { + LOG->Warn( "GetSHA1: Failed to open file '%s'", fn.c_str() ); + return RString(); + } + int iHash = register_hash( &sha1_desc ); + ASSERT( iHash >= 0 ); + + unsigned char digest[20]; + HashFile( file, digest, iHash ); + + return RString( (const char *) digest, sizeof(digest) ); +} + +RString CryptManager::GetPublicKeyFileName() +{ + return PUBLIC_KEY_PATH; +} + +/* Generate a version 4 random UUID. */ +RString CryptManager::GenerateRandomUUID() +{ + uint32_t buf[4]; + CryptManager::GetRandomBytes( buf, sizeof(buf) ); + + buf[1] &= 0xFFFF0FFF; + buf[1] |= 0x00004000; + buf[2] &= 0x0FFFFFFF; + buf[2] |= 0xA0000000; + + return ssprintf("%08x-%04x-%04x-%04x-%04x%08x", + buf[0], + buf[1] >> 16, buf[1] & 0xFFFF, + buf[2] >> 16, buf[2] & 0xFFFF, + buf[3]); +} + +// lua start +#include "LuaBinding.h" + +/** @brief Allow Lua to have access to the CryptManager. */ +class LunaCryptManager: public Luna +{ +public: + static int MD5String( T* p, lua_State *L ) + { + RString md5out; + md5out = p->GetMD5ForString(SArg(1)); + lua_pushstring( L, md5out ); + return 1; + } + static int MD5File( T* p, lua_State *L ) + { + RString md5fout; + md5fout = p->GetMD5ForFile(SArg(1)); + lua_pushstring( L, md5fout ); + return 1; + } + static int SHA1String( T* p, lua_State *L ) + { + RString sha1out; + sha1out = p->GetSHA1ForString(SArg(1)); + lua_pushstring( L, sha1out ); + return 1; + } + static int SHA1File( T* p, lua_State *L ) + { + RString sha1fout; + sha1fout = p->GetSHA1ForFile(SArg(1)); + lua_pushstring( L, sha1fout ); + return 1; + } + static int GenerateRandomUUID( T* p, lua_State *L ) + { + RString uuidOut; + uuidOut = p->GenerateRandomUUID(); + lua_pushstring( L, uuidOut ); + return 1; + } + + LunaCryptManager() + { + ADD_METHOD( MD5String ); + ADD_METHOD( MD5File ); + ADD_METHOD( SHA1String ); + ADD_METHOD( SHA1File ); + ADD_METHOD( GenerateRandomUUID ); + } +}; + +LUA_REGISTER_CLASS( CryptManager ) + +// lua end + +/* + * (c) 2004-2007 Chris Danford, Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/DateTime.cpp b/src/DateTime.cpp index a99230e0cc..722fc109be 100644 --- a/src/DateTime.cpp +++ b/src/DateTime.cpp @@ -1,352 +1,352 @@ -#include "global.h" -#include "DateTime.h" -#include "RageUtil.h" -#include "EnumHelper.h" -#include "LuaManager.h" -#include "LocalizedString.h" - -DateTime::DateTime() -{ - Init(); -} - -void DateTime::Init() -{ - ZERO( *this ); -} - -bool DateTime::operator<( const DateTime& other ) const -{ -#define COMPARE( v ) if(v!=other.v) return v( const DateTime& other ) const -{ -#define COMPARE( v ) if(v!=other.v) return v>other.v; - COMPARE( tm_year ); - COMPARE( tm_mon ); - COMPARE( tm_mday ); - COMPARE( tm_hour ); - COMPARE( tm_min ); - COMPARE( tm_sec ); -#undef COMPARE - // they're equal - return false; -} - -DateTime DateTime::GetNowDateTime() -{ - time_t now = time(NULL); - tm tNow; - localtime_r( &now, &tNow ); - DateTime dtNow; -#define COPY_M( v ) dtNow.v = tNow.v; - COPY_M( tm_year ); - COPY_M( tm_mon ); - COPY_M( tm_mday ); - COPY_M( tm_hour ); - COPY_M( tm_min ); - COPY_M( tm_sec ); -#undef COPY_M - return dtNow; -} - -DateTime DateTime::GetNowDate() -{ - DateTime tNow = GetNowDateTime(); - tNow.StripTime(); - return tNow; -} - -void DateTime::StripTime() -{ - tm_hour = 0; - tm_min = 0; - tm_sec = 0; -} - -// Common SQL/XML format: "YYYY-MM-DD HH:MM:SS" -RString DateTime::GetString() const -{ - RString s = ssprintf( "%d-%02d-%02d", - tm_year+1900, - tm_mon+1, - tm_mday ); - - if( tm_hour != 0 || - tm_min != 0 || - tm_sec != 0 ) - { - s += ssprintf( " %02d:%02d:%02d", - tm_hour, - tm_min, - tm_sec ); - } - - return s; -} - -bool DateTime::FromString( const RString sDateTime ) -{ - Init(); - - int ret; - - ret = sscanf( sDateTime, "%d-%d-%d %d:%d:%d", - &tm_year, - &tm_mon, - &tm_mday, - &tm_hour, - &tm_min, - &tm_sec ); - if( ret != 6 ) - { - ret = sscanf( sDateTime, "%d-%d-%d", - &tm_year, - &tm_mon, - &tm_mday ); - if( ret != 3 ) - { - return false; - } - } - - tm_year -= 1900; - tm_mon -= 1; - return true; -} - - - -RString DayInYearToString( int iDayInYear ) -{ - return ssprintf("DayInYear%03d",iDayInYear); -} - -int StringToDayInYear( RString sDayInYear ) -{ - int iDayInYear; - if( sscanf( sDayInYear, "DayInYear%d", &iDayInYear ) != 1 ) - return -1; - return iDayInYear; -} - -static const RString LAST_DAYS_NAME[NUM_LAST_DAYS] = -{ - "Today", - "Yesterday", - "Day2Ago", - "Day3Ago", - "Day4Ago", - "Day5Ago", - "Day6Ago", -}; - -RString LastDayToString( int iLastDayIndex ) -{ - return LAST_DAYS_NAME[iLastDayIndex]; -} - -static const char *DAY_OF_WEEK_TO_NAME[DAYS_IN_WEEK] = -{ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", -}; - -RString DayOfWeekToString( int iDayOfWeekIndex ) -{ - return DAY_OF_WEEK_TO_NAME[iDayOfWeekIndex]; -} - -RString HourInDayToString( int iHourInDayIndex ) -{ - return ssprintf("Hour%02d", iHourInDayIndex); -} - -static const char *MonthNames[] = -{ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", -}; -XToString( Month ); -XToLocalizedString( Month ); -LuaXType( Month ); - -RString LastWeekToString( int iLastWeekIndex ) -{ - switch( iLastWeekIndex ) - { - case 0: return "ThisWeek"; break; - case 1: return "LastWeek"; break; - default: return ssprintf("Week%02dAgo",iLastWeekIndex); break; - } -} - -RString LastDayToLocalizedString( int iLastDayIndex ) -{ - RString s = LastDayToString( iLastDayIndex ); - s.Replace( "Day", "" ); - s.Replace( "Ago", " Ago" ); - return s; -} - -RString LastWeekToLocalizedString( int iLastWeekIndex ) -{ - RString s = LastWeekToString( iLastWeekIndex ); - s.Replace( "Week", "" ); - s.Replace( "Ago", " Ago" ); - return s; -} - -RString HourInDayToLocalizedString( int iHourIndex ) -{ - int iBeginHour = iHourIndex; - iBeginHour--; - wrap( iBeginHour, 24 ); - iBeginHour++; - - return ssprintf("%02d:00+", iBeginHour ); -} - - -tm AddDays( tm start, int iDaysToMove ) -{ - /* - * This causes problems on OS X, which doesn't correctly handle range that are below - * their normal values (eg. mday = 0). According to the manpage, it should adjust them: - * - * "If structure members are outside their legal interval, they will be normalized (so - * that, e.g., 40 October is changed into 9 November)." - * - * Instead, it appears to simply fail. - * - * Refs: - * http://bugs.php.net/bug.php?id=10686 - * http://sourceforge.net/tracker/download.php?group_id=37892&atid=421366&file_id=79179&aid=91133 - * - * Note "Log starting 2004-03-07 03:50:42"; mday is 7, and PrintCaloriesBurned calls us - * with iDaysToMove = -7, resulting in an out-of-range value 0. This seems legal, but - * OS X chokes on it. - */ -/* start.tm_mday += iDaysToMove; - time_t seconds = mktime( &start ); - ASSERT( seconds != (time_t)-1 ); - */ - - /* This handles DST differently: it returns the time that was exactly n*60*60*24 seconds - * ago, where the above code always returns the same time of day. I prefer the above - * behavior, but I'm not sure that it mattersmatters. */ - time_t seconds = mktime( &start ); - seconds += iDaysToMove*60*60*24; - - tm time; - localtime_r( &seconds, &time ); - return time; -} - -tm GetYesterday( tm start ) -{ - return AddDays( start, -1 ); -} - -int GetDayOfWeek( tm time ) -{ - int iDayOfWeek = time.tm_wday; - ASSERT( iDayOfWeek < DAYS_IN_WEEK ); - return iDayOfWeek; -} - -tm GetNextSunday( tm start ) -{ - return AddDays( start, DAYS_IN_WEEK-GetDayOfWeek(start) ); -} - - -tm GetDayInYearAndYear( int iDayInYearIndex, int iYear ) -{ - /* If iDayInYearIndex is 200, set the date to Jan 200th, and let mktime - * round it. This shouldn't suffer from the OSX mktime() issue described - * above, since we're not giving it negative values. */ - tm when; - ZERO( when ); - when.tm_mon = 0; - when.tm_mday = iDayInYearIndex+1; - when.tm_year = iYear - 1900; - time_t then = mktime( &when ); - - localtime_r( &then, &when ); - return when; -} - -LuaFunction( MonthToString, MonthToString( Enum::Check(L, 1) ) ); -LuaFunction( MonthToLocalizedString, MonthToLocalizedString( Enum::Check(L, 1) ) ); -LuaFunction( MonthOfYear, GetLocalTime().tm_mon ); -LuaFunction( DayOfMonth, GetLocalTime().tm_mday ); -LuaFunction( Hour, GetLocalTime().tm_hour ); -LuaFunction( Minute, GetLocalTime().tm_min ); -LuaFunction( Second, GetLocalTime().tm_sec ); -LuaFunction( Year, GetLocalTime().tm_year+1900 ); -LuaFunction( Weekday, GetLocalTime().tm_wday ); -LuaFunction( DayOfYear, GetLocalTime().tm_yday ); - -/* - * (c) 2001-2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "DateTime.h" +#include "RageUtil.h" +#include "EnumHelper.h" +#include "LuaManager.h" +#include "LocalizedString.h" + +DateTime::DateTime() +{ + Init(); +} + +void DateTime::Init() +{ + ZERO( *this ); +} + +bool DateTime::operator<( const DateTime& other ) const +{ +#define COMPARE( v ) if(v!=other.v) return v( const DateTime& other ) const +{ +#define COMPARE( v ) if(v!=other.v) return v>other.v; + COMPARE( tm_year ); + COMPARE( tm_mon ); + COMPARE( tm_mday ); + COMPARE( tm_hour ); + COMPARE( tm_min ); + COMPARE( tm_sec ); +#undef COMPARE + // they're equal + return false; +} + +DateTime DateTime::GetNowDateTime() +{ + time_t now = time(nullptr); + tm tNow; + localtime_r( &now, &tNow ); + DateTime dtNow; +#define COPY_M( v ) dtNow.v = tNow.v; + COPY_M( tm_year ); + COPY_M( tm_mon ); + COPY_M( tm_mday ); + COPY_M( tm_hour ); + COPY_M( tm_min ); + COPY_M( tm_sec ); +#undef COPY_M + return dtNow; +} + +DateTime DateTime::GetNowDate() +{ + DateTime tNow = GetNowDateTime(); + tNow.StripTime(); + return tNow; +} + +void DateTime::StripTime() +{ + tm_hour = 0; + tm_min = 0; + tm_sec = 0; +} + +// Common SQL/XML format: "YYYY-MM-DD HH:MM:SS" +RString DateTime::GetString() const +{ + RString s = ssprintf( "%d-%02d-%02d", + tm_year+1900, + tm_mon+1, + tm_mday ); + + if( tm_hour != 0 || + tm_min != 0 || + tm_sec != 0 ) + { + s += ssprintf( " %02d:%02d:%02d", + tm_hour, + tm_min, + tm_sec ); + } + + return s; +} + +bool DateTime::FromString( const RString sDateTime ) +{ + Init(); + + int ret; + + ret = sscanf( sDateTime, "%d-%d-%d %d:%d:%d", + &tm_year, + &tm_mon, + &tm_mday, + &tm_hour, + &tm_min, + &tm_sec ); + if( ret != 6 ) + { + ret = sscanf( sDateTime, "%d-%d-%d", + &tm_year, + &tm_mon, + &tm_mday ); + if( ret != 3 ) + { + return false; + } + } + + tm_year -= 1900; + tm_mon -= 1; + return true; +} + + + +RString DayInYearToString( int iDayInYear ) +{ + return ssprintf("DayInYear%03d",iDayInYear); +} + +int StringToDayInYear( RString sDayInYear ) +{ + int iDayInYear; + if( sscanf( sDayInYear, "DayInYear%d", &iDayInYear ) != 1 ) + return -1; + return iDayInYear; +} + +static const RString LAST_DAYS_NAME[NUM_LAST_DAYS] = +{ + "Today", + "Yesterday", + "Day2Ago", + "Day3Ago", + "Day4Ago", + "Day5Ago", + "Day6Ago", +}; + +RString LastDayToString( int iLastDayIndex ) +{ + return LAST_DAYS_NAME[iLastDayIndex]; +} + +static const char *DAY_OF_WEEK_TO_NAME[DAYS_IN_WEEK] = +{ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", +}; + +RString DayOfWeekToString( int iDayOfWeekIndex ) +{ + return DAY_OF_WEEK_TO_NAME[iDayOfWeekIndex]; +} + +RString HourInDayToString( int iHourInDayIndex ) +{ + return ssprintf("Hour%02d", iHourInDayIndex); +} + +static const char *MonthNames[] = +{ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +}; +XToString( Month ); +XToLocalizedString( Month ); +LuaXType( Month ); + +RString LastWeekToString( int iLastWeekIndex ) +{ + switch( iLastWeekIndex ) + { + case 0: return "ThisWeek"; break; + case 1: return "LastWeek"; break; + default: return ssprintf("Week%02dAgo",iLastWeekIndex); break; + } +} + +RString LastDayToLocalizedString( int iLastDayIndex ) +{ + RString s = LastDayToString( iLastDayIndex ); + s.Replace( "Day", "" ); + s.Replace( "Ago", " Ago" ); + return s; +} + +RString LastWeekToLocalizedString( int iLastWeekIndex ) +{ + RString s = LastWeekToString( iLastWeekIndex ); + s.Replace( "Week", "" ); + s.Replace( "Ago", " Ago" ); + return s; +} + +RString HourInDayToLocalizedString( int iHourIndex ) +{ + int iBeginHour = iHourIndex; + iBeginHour--; + wrap( iBeginHour, 24 ); + iBeginHour++; + + return ssprintf("%02d:00+", iBeginHour ); +} + + +tm AddDays( tm start, int iDaysToMove ) +{ + /* + * This causes problems on OS X, which doesn't correctly handle range that are below + * their normal values (eg. mday = 0). According to the manpage, it should adjust them: + * + * "If structure members are outside their legal interval, they will be normalized (so + * that, e.g., 40 October is changed into 9 November)." + * + * Instead, it appears to simply fail. + * + * Refs: + * http://bugs.php.net/bug.php?id=10686 + * http://sourceforge.net/tracker/download.php?group_id=37892&atid=421366&file_id=79179&aid=91133 + * + * Note "Log starting 2004-03-07 03:50:42"; mday is 7, and PrintCaloriesBurned calls us + * with iDaysToMove = -7, resulting in an out-of-range value 0. This seems legal, but + * OS X chokes on it. + */ +/* start.tm_mday += iDaysToMove; + time_t seconds = mktime( &start ); + ASSERT( seconds != (time_t)-1 ); + */ + + /* This handles DST differently: it returns the time that was exactly n*60*60*24 seconds + * ago, where the above code always returns the same time of day. I prefer the above + * behavior, but I'm not sure that it mattersmatters. */ + time_t seconds = mktime( &start ); + seconds += iDaysToMove*60*60*24; + + tm time; + localtime_r( &seconds, &time ); + return time; +} + +tm GetYesterday( tm start ) +{ + return AddDays( start, -1 ); +} + +int GetDayOfWeek( tm time ) +{ + int iDayOfWeek = time.tm_wday; + ASSERT( iDayOfWeek < DAYS_IN_WEEK ); + return iDayOfWeek; +} + +tm GetNextSunday( tm start ) +{ + return AddDays( start, DAYS_IN_WEEK-GetDayOfWeek(start) ); +} + + +tm GetDayInYearAndYear( int iDayInYearIndex, int iYear ) +{ + /* If iDayInYearIndex is 200, set the date to Jan 200th, and let mktime + * round it. This shouldn't suffer from the OSX mktime() issue described + * above, since we're not giving it negative values. */ + tm when; + ZERO( when ); + when.tm_mon = 0; + when.tm_mday = iDayInYearIndex+1; + when.tm_year = iYear - 1900; + time_t then = mktime( &when ); + + localtime_r( &then, &when ); + return when; +} + +LuaFunction( MonthToString, MonthToString( Enum::Check(L, 1) ) ); +LuaFunction( MonthToLocalizedString, MonthToLocalizedString( Enum::Check(L, 1) ) ); +LuaFunction( MonthOfYear, GetLocalTime().tm_mon ); +LuaFunction( DayOfMonth, GetLocalTime().tm_mday ); +LuaFunction( Hour, GetLocalTime().tm_hour ); +LuaFunction( Minute, GetLocalTime().tm_min ); +LuaFunction( Second, GetLocalTime().tm_sec ); +LuaFunction( Year, GetLocalTime().tm_year+1900 ); +LuaFunction( Weekday, GetLocalTime().tm_wday ); +LuaFunction( DayOfYear, GetLocalTime().tm_yday ); + +/* + * (c) 2001-2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/DifficultyList.cpp b/src/DifficultyList.cpp index d9e4e7eddf..eb34782d07 100644 --- a/src/DifficultyList.cpp +++ b/src/DifficultyList.cpp @@ -45,7 +45,7 @@ void StepsDisplayList::LoadFromNode( const XNode* pNode ) MOVE_COMMAND.Load( m_sName, "MoveCommand" ); m_Lines.resize( MAX_METERS ); - m_CurSong = NULL; + m_CurSong = nullptr; FOREACH_ENUM( PlayerNumber, pn ) { diff --git a/src/DifficultyList.h b/src/DifficultyList.h index 0d0817fa91..a641db6ad9 100644 --- a/src/DifficultyList.h +++ b/src/DifficultyList.h @@ -1,100 +1,100 @@ -/* StepsDisplayList - Shows all available difficulties for a Song/Course. */ -#ifndef DIFFICULTY_LIST_H -#define DIFFICULTY_LIST_H - -#include "ActorFrame.h" -#include "PlayerNumber.h" -#include "StepsDisplay.h" -#include "ThemeMetric.h" - -class Song; -class Steps; - -class StepsDisplayList: public ActorFrame -{ -public: - StepsDisplayList(); - virtual ~StepsDisplayList(); - virtual StepsDisplayList *Copy() const; - virtual void LoadFromNode( const XNode* pNode ); - - void HandleMessage( const Message &msg ); - - void SetFromGameState(); - void TweenOnScreen(); - void TweenOffScreen(); - void Hide(); - void Show(); - - // Lua - void PushSelf( lua_State *L ); - -private: - void UpdatePositions(); - void PositionItems(); - int GetCurrentRowIndex( PlayerNumber pn ) const; - void HideRows(); - - ThemeMetric ITEMS_SPACING_Y; - ThemeMetric NUM_SHOWN_ITEMS; - ThemeMetric CAPITALIZE_DIFFICULTY_NAMES; - ThemeMetric MOVE_COMMAND; - - AutoActor m_Cursors[NUM_PLAYERS]; - ActorFrame m_CursorFrames[NUM_PLAYERS]; // contains Cursor so that color can fade independent of other tweens - - struct Line - { - StepsDisplay m_Meter; - }; - vector m_Lines; - - const Song *m_CurSong; - bool m_bShown; - - struct Row - { - Row() - { - m_Steps = NULL; - m_dc = Difficulty_Invalid; - m_fY = 0; - m_bHidden = false; - } - - const Steps *m_Steps; - Difficulty m_dc; - float m_fY; - bool m_bHidden; // currently off screen - }; - - vector m_Rows; - -}; - -#endif - -/* - * (c) 2003-2004 Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* StepsDisplayList - Shows all available difficulties for a Song/Course. */ +#ifndef DIFFICULTY_LIST_H +#define DIFFICULTY_LIST_H + +#include "ActorFrame.h" +#include "PlayerNumber.h" +#include "StepsDisplay.h" +#include "ThemeMetric.h" + +class Song; +class Steps; + +class StepsDisplayList: public ActorFrame +{ +public: + StepsDisplayList(); + virtual ~StepsDisplayList(); + virtual StepsDisplayList *Copy() const; + virtual void LoadFromNode( const XNode* pNode ); + + void HandleMessage( const Message &msg ); + + void SetFromGameState(); + void TweenOnScreen(); + void TweenOffScreen(); + void Hide(); + void Show(); + + // Lua + void PushSelf( lua_State *L ); + +private: + void UpdatePositions(); + void PositionItems(); + int GetCurrentRowIndex( PlayerNumber pn ) const; + void HideRows(); + + ThemeMetric ITEMS_SPACING_Y; + ThemeMetric NUM_SHOWN_ITEMS; + ThemeMetric CAPITALIZE_DIFFICULTY_NAMES; + ThemeMetric MOVE_COMMAND; + + AutoActor m_Cursors[NUM_PLAYERS]; + ActorFrame m_CursorFrames[NUM_PLAYERS]; // contains Cursor so that color can fade independent of other tweens + + struct Line + { + StepsDisplay m_Meter; + }; + vector m_Lines; + + const Song *m_CurSong; + bool m_bShown; + + struct Row + { + Row() + { + m_Steps = nullptr; + m_dc = Difficulty_Invalid; + m_fY = 0; + m_bHidden = false; + } + + const Steps *m_Steps; + Difficulty m_dc; + float m_fY; + bool m_bHidden; // currently off screen + }; + + vector m_Rows; + +}; + +#endif + +/* + * (c) 2003-2004 Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/EditMenu.cpp b/src/EditMenu.cpp index e94c8056a9..fd4062a6f3 100644 --- a/src/EditMenu.cpp +++ b/src/EditMenu.cpp @@ -429,7 +429,7 @@ void EditMenu::OnRowValueChanged( EditMenuRow row ) { Steps *pSteps = SongUtil::GetStepsByDifficulty( GetSelectedSong(), GetSelectedStepsType(), dc ); if( pSteps && UNLOCKMAN->StepsIsLocked( GetSelectedSong(), pSteps ) ) - pSteps = NULL; + pSteps = nullptr; EditMode mode = EDIT_MODE.GetValue(); switch( EDIT_MODE.GetValue() ) diff --git a/src/FadingBanner.cpp b/src/FadingBanner.cpp index b029dd4062..973b53e270 100644 --- a/src/FadingBanner.cpp +++ b/src/FadingBanner.cpp @@ -272,25 +272,25 @@ public: static int ScaleToClipped( T* p, lua_State *L ) { p->ScaleToClipped(FArg(1),FArg(2)); return 0; } static int LoadFromSong( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadFromSong( NULL ); } + if( lua_isnil(L,1) ) { p->LoadFromSong(nullptr); } else { Song *pS = Luna::check(L,1); p->LoadFromSong( pS ); } return 0; } static int LoadFromCourse( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadFromCourse( NULL ); } + if( lua_isnil(L,1) ) { p->LoadFromCourse(nullptr); } else { Course *pC = Luna::check(L,1); p->LoadFromCourse( pC ); } return 0; } static int LoadIconFromCharacter( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadIconFromCharacter( NULL ); } + if( lua_isnil(L,1) ) { p->LoadIconFromCharacter(nullptr); } else { Character *pC = Luna::check(L,1); p->LoadIconFromCharacter( pC ); } return 0; } static int LoadCardFromCharacter( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->LoadIconFromCharacter( NULL ); } + if( lua_isnil(L,1) ) { p->LoadIconFromCharacter(nullptr); } else { Character *pC = Luna::check(L,1); p->LoadIconFromCharacter( pC ); } return 0; } diff --git a/src/Font.cpp b/src/Font.cpp index 3418fd532e..7f2e7c97e7 100644 --- a/src/Font.cpp +++ b/src/Font.cpp @@ -190,12 +190,12 @@ FontPage::~FontPage() if( m_FontPageTextures.m_pTextureMain != nullptr ) { TEXTUREMAN->UnloadTexture( m_FontPageTextures.m_pTextureMain ); - m_FontPageTextures.m_pTextureMain = NULL; + m_FontPageTextures.m_pTextureMain = nullptr; } if( m_FontPageTextures.m_pTextureStroke != nullptr ) { TEXTUREMAN->UnloadTexture( m_FontPageTextures.m_pTextureStroke ); - m_FontPageTextures.m_pTextureStroke = NULL; + m_FontPageTextures.m_pTextureStroke = nullptr; } } @@ -221,7 +221,7 @@ int Font::GetLineHeightInSourcePixels( const wstring &szLine ) const } -Font::Font(): m_iRefCount(1), path(""), m_apPages(), m_pDefault(NULL), +Font::Font(): m_iRefCount(1), path(""), m_apPages(), m_pDefault(nullptr), m_iCharToGlyph(), m_bRightToLeft(false), // strokes aren't shown by default, hence the Color. m_DefaultStrokeColor(RageColor(0,0,0,0)), m_sChars("") {} @@ -238,7 +238,7 @@ void Font::Unload() m_apPages.clear(); m_iCharToGlyph.clear(); - m_pDefault = NULL; + m_pDefault = nullptr; /* Don't clear the refcount. We've unloaded, but that doesn't mean things * aren't still pointing to us. */ diff --git a/src/Font.h b/src/Font.h index d57a6b5eae..61d7d8bcf8 100644 --- a/src/Font.h +++ b/src/Font.h @@ -23,7 +23,7 @@ struct FontPageTextures RageTexture *m_pTextureStroke; /** @brief Set up the initial textures. */ - FontPageTextures(): m_pTextureMain(NULL), m_pTextureStroke(NULL) {} + FontPageTextures(): m_pTextureMain(nullptr), m_pTextureStroke(nullptr) {} }; /** @brief The components of a glyph (not technically a character). */ @@ -50,7 +50,7 @@ struct glyph RectF m_TexRect; /** @brief Set up the glyph with default values. */ - glyph() : m_pPage(NULL), m_FontPageTextures(), m_iHadvance(0), + glyph() : m_pPage(nullptr), m_FontPageTextures(), m_iHadvance(0), m_fWidth(0), m_fHeight(0), m_fHshift(0), m_TexRect() {} }; diff --git a/src/Foreground.cpp b/src/Foreground.cpp index a1f882cb87..13cde15e6f 100644 --- a/src/Foreground.cpp +++ b/src/Foreground.cpp @@ -20,7 +20,7 @@ void Foreground::Unload() m_BGAnimations.clear(); m_SubActors.clear(); m_fLastMusicSeconds = -9999; - m_pSong = NULL; + m_pSong = nullptr; } void Foreground::LoadFromSong( const Song *pSong ) diff --git a/src/GameCommand.cpp b/src/GameCommand.cpp index f352ca9a9a..90370e47b7 100644 --- a/src/GameCommand.cpp +++ b/src/GameCommand.cpp @@ -36,7 +36,7 @@ void GameCommand::Init() m_bInvalid = true; m_iIndex = -1; m_MultiPlayer = MultiPlayer_Invalid; - m_pStyle = NULL; + m_pStyle = nullptr; m_pm = PlayMode_Invalid; m_dc = Difficulty_Invalid; m_CourseDifficulty = Difficulty_Invalid; @@ -45,11 +45,11 @@ void GameCommand::Init() m_sAnnouncer = ""; m_sScreen = ""; m_LuaFunction.Unset(); - m_pSong = NULL; - m_pSteps = NULL; - m_pCourse = NULL; - m_pTrail = NULL; - m_pCharacter = NULL; + m_pSong = nullptr; + m_pSteps = nullptr; + m_pCourse = nullptr; + m_pTrail = nullptr; + m_pCharacter = nullptr; m_SortOrder = SortOrder_Invalid; m_sSoundPath = ""; m_vsScreensToPrepare.clear(); diff --git a/src/GameCommand.h b/src/GameCommand.h index f9d503227a..f903a3cbab 100644 --- a/src/GameCommand.h +++ b/src/GameCommand.h @@ -1,148 +1,148 @@ -/* GameCommand */ - -#ifndef GameCommand_H -#define GameCommand_H - -#include "GameConstantsAndTypes.h" -#include "PlayerNumber.h" -#include "Difficulty.h" -#include "LuaReference.h" -#include "Command.h" -#include - -class Song; -class Steps; -class Course; -class Trail; -class Character; -class Style; -class Game; -struct lua_State; - -class GameCommand -{ -public: - GameCommand(): m_Commands(), m_sName(""), m_sText(""), - m_bInvalid(true), m_sInvalidReason(""), - m_iIndex(-1), m_MultiPlayer(MultiPlayer_Invalid), - m_pStyle(NULL), m_pm(PlayMode_Invalid), - m_dc(Difficulty_Invalid), - m_CourseDifficulty(Difficulty_Invalid), - m_sAnnouncer(""), m_sPreferredModifiers(""), - m_sStageModifiers(""), m_sScreen(""), m_LuaFunction(), - m_pSong(NULL), m_pSteps(NULL), m_pCourse(NULL), - m_pTrail(NULL), m_pCharacter(NULL), m_SetEnv(), - m_sSongGroup(""), m_SortOrder(SortOrder_Invalid), - m_sSoundPath(""), m_vsScreensToPrepare(), m_iWeightPounds(-1), - m_iGoalCalories(-1), m_GoalType(GoalType_Invalid), - m_sProfileID(""), m_sUrl(""), m_bUrlExits(true), - m_bStopMusic(false), m_bApplyDefaultOptions(false), - m_bFadeMusic(false), m_fMusicFadeOutVolume(-1), - m_fMusicFadeOutSeconds(-1), m_bApplyCommitsScreens(true) - { - m_LuaFunction.Unset(); - } - void Init(); - - void Load( int iIndex, const Commands& cmds ); - void LoadOne( const Command& cmd ); - - void ApplyToAllPlayers() const; - void Apply( PlayerNumber pn ) const; -private: - void Apply( const vector &vpns ) const; - void ApplySelf( const vector &vpns ) const; -public: - - bool DescribesCurrentMode( PlayerNumber pn ) const; - bool DescribesCurrentModeForAllPlayers() const; - bool IsPlayable( RString *why = NULL ) const; - bool IsZero() const; - - /* If true, Apply() will apply m_sScreen. If false, it won't, and you need - * to do it yourself. */ - void ApplyCommitsScreens( bool bOn ) { m_bApplyCommitsScreens = bOn; } - - // Same as what was passed to Load. We need to keep the original commands - // so that we know the order of commands when it comes time to Apply. - Commands m_Commands; - - RString m_sName; // choice name - RString m_sText; // display text - bool m_bInvalid; - RString m_sInvalidReason; - int m_iIndex; - MultiPlayer m_MultiPlayer; - const Style* m_pStyle; - PlayMode m_pm; - Difficulty m_dc; - CourseDifficulty m_CourseDifficulty; - RString m_sAnnouncer; - RString m_sPreferredModifiers; - RString m_sStageModifiers; - RString m_sScreen; - LuaReference m_LuaFunction; - Song* m_pSong; - Steps* m_pSteps; - Course* m_pCourse; - Trail* m_pTrail; - Character* m_pCharacter; - std::map m_SetEnv; - RString m_sSongGroup; - SortOrder m_SortOrder; - RString m_sSoundPath; // "" for no sound - vector m_vsScreensToPrepare; - /** - * @brief What is the player's weight in pounds? - * - * If this value is -1, then no weight was specified. */ - int m_iWeightPounds; - int m_iGoalCalories; // -1 == none specified - GoalType m_GoalType; - RString m_sProfileID; - RString m_sUrl; - // sm-ssc adds: - bool m_bUrlExits; // for making stepmania not exit on url - - bool m_bStopMusic; - bool m_bApplyDefaultOptions; - // sm-ssc also adds: - bool m_bFadeMusic; - float m_fMusicFadeOutVolume; - // currently, GameSoundManager uses consts for fade out/in times, so this - // is kind of pointless, but I want to have it working eventually. -aj - float m_fMusicFadeOutSeconds; - - // Lua - void PushSelf( lua_State *L ); - -private: - bool m_bApplyCommitsScreens; -}; - -#endif - -/* - * (c) 2001-2004 Chris Danford, Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* GameCommand */ + +#ifndef GameCommand_H +#define GameCommand_H + +#include "GameConstantsAndTypes.h" +#include "PlayerNumber.h" +#include "Difficulty.h" +#include "LuaReference.h" +#include "Command.h" +#include + +class Song; +class Steps; +class Course; +class Trail; +class Character; +class Style; +class Game; +struct lua_State; + +class GameCommand +{ +public: + GameCommand(): m_Commands(), m_sName(""), m_sText(""), + m_bInvalid(true), m_sInvalidReason(""), + m_iIndex(-1), m_MultiPlayer(MultiPlayer_Invalid), + m_pStyle(nullptr), m_pm(PlayMode_Invalid), + m_dc(Difficulty_Invalid), + m_CourseDifficulty(Difficulty_Invalid), + m_sAnnouncer(""), m_sPreferredModifiers(""), + m_sStageModifiers(""), m_sScreen(""), m_LuaFunction(), + m_pSong(nullptr), m_pSteps(nullptr), m_pCourse(nullptr), + m_pTrail(nullptr), m_pCharacter(nullptr), m_SetEnv(), + m_sSongGroup(""), m_SortOrder(SortOrder_Invalid), + m_sSoundPath(""), m_vsScreensToPrepare(), m_iWeightPounds(-1), + m_iGoalCalories(-1), m_GoalType(GoalType_Invalid), + m_sProfileID(""), m_sUrl(""), m_bUrlExits(true), + m_bStopMusic(false), m_bApplyDefaultOptions(false), + m_bFadeMusic(false), m_fMusicFadeOutVolume(-1), + m_fMusicFadeOutSeconds(-1), m_bApplyCommitsScreens(true) + { + m_LuaFunction.Unset(); + } + void Init(); + + void Load( int iIndex, const Commands& cmds ); + void LoadOne( const Command& cmd ); + + void ApplyToAllPlayers() const; + void Apply( PlayerNumber pn ) const; +private: + void Apply( const vector &vpns ) const; + void ApplySelf( const vector &vpns ) const; +public: + + bool DescribesCurrentMode( PlayerNumber pn ) const; + bool DescribesCurrentModeForAllPlayers() const; + bool IsPlayable( RString *why = nullptr ) const; + bool IsZero() const; + + /* If true, Apply() will apply m_sScreen. If false, it won't, and you need + * to do it yourself. */ + void ApplyCommitsScreens( bool bOn ) { m_bApplyCommitsScreens = bOn; } + + // Same as what was passed to Load. We need to keep the original commands + // so that we know the order of commands when it comes time to Apply. + Commands m_Commands; + + RString m_sName; // choice name + RString m_sText; // display text + bool m_bInvalid; + RString m_sInvalidReason; + int m_iIndex; + MultiPlayer m_MultiPlayer; + const Style* m_pStyle; + PlayMode m_pm; + Difficulty m_dc; + CourseDifficulty m_CourseDifficulty; + RString m_sAnnouncer; + RString m_sPreferredModifiers; + RString m_sStageModifiers; + RString m_sScreen; + LuaReference m_LuaFunction; + Song* m_pSong; + Steps* m_pSteps; + Course* m_pCourse; + Trail* m_pTrail; + Character* m_pCharacter; + std::map m_SetEnv; + RString m_sSongGroup; + SortOrder m_SortOrder; + RString m_sSoundPath; // "" for no sound + vector m_vsScreensToPrepare; + /** + * @brief What is the player's weight in pounds? + * + * If this value is -1, then no weight was specified. */ + int m_iWeightPounds; + int m_iGoalCalories; // -1 == none specified + GoalType m_GoalType; + RString m_sProfileID; + RString m_sUrl; + // sm-ssc adds: + bool m_bUrlExits; // for making stepmania not exit on url + + bool m_bStopMusic; + bool m_bApplyDefaultOptions; + // sm-ssc also adds: + bool m_bFadeMusic; + float m_fMusicFadeOutVolume; + // currently, GameSoundManager uses consts for fade out/in times, so this + // is kind of pointless, but I want to have it working eventually. -aj + float m_fMusicFadeOutSeconds; + + // Lua + void PushSelf( lua_State *L ); + +private: + bool m_bApplyCommitsScreens; +}; + +#endif + +/* + * (c) 2001-2004 Chris Danford, Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/GameLoop.cpp b/src/GameLoop.cpp index ab42542437..7394552376 100644 --- a/src/GameLoop.cpp +++ b/src/GameLoop.cpp @@ -234,7 +234,7 @@ private: enum State { RENDERING_IDLE, RENDERING_START, RENDERING_ACTIVE, RENDERING_END }; State m_State; }; -static ConcurrentRenderer *g_pConcurrentRenderer = NULL; +static ConcurrentRenderer *g_pConcurrentRenderer = nullptr; ConcurrentRenderer::ConcurrentRenderer(): m_Event("ConcurrentRenderer") diff --git a/src/GameManager.cpp b/src/GameManager.cpp index 7cc24707bf..aa693fb087 100644 --- a/src/GameManager.cpp +++ b/src/GameManager.cpp @@ -12,7 +12,7 @@ #include "Style.h" -GameManager* GAMEMAN = NULL; // global and accessable from anywhere in our program +GameManager* GAMEMAN = nullptr; // global and accessable from anywhere in our program enum { @@ -3028,7 +3028,7 @@ void GameManager::GetEnabledGames( vector& aGamesOut ) const Game* GameManager::GetDefaultGame() { - const Game *pDefault = NULL; + const Game *pDefault = nullptr; if( pDefault == nullptr ) { for( size_t i=0; pDefault == nullptr && i < ARRAYLEN(g_Games); ++i ) diff --git a/src/GameSoundManager.cpp b/src/GameSoundManager.cpp index b327fee26a..237669c29a 100644 --- a/src/GameSoundManager.cpp +++ b/src/GameSoundManager.cpp @@ -18,7 +18,7 @@ #include "SongUtil.h" #include "LuaManager.h" -GameSoundManager *SOUND = NULL; +GameSoundManager *SOUND = nullptr; /* * When playing music, automatically search for an SM file for timing data. If one is diff --git a/src/GameSoundManager.h b/src/GameSoundManager.h index 1187924a37..13e9ce7731 100644 --- a/src/GameSoundManager.h +++ b/src/GameSoundManager.h @@ -21,7 +21,7 @@ public: { PlayMusicParams() { - pTiming = NULL; + pTiming = nullptr; bForceLoop = false; fStartSecond = 0; fLengthSeconds = -1; @@ -44,7 +44,7 @@ public: void PlayMusic( PlayMusicParams params, PlayMusicParams FallbackMusicParams = PlayMusicParams() ); void PlayMusic( RString sFile, - const TimingData *pTiming = NULL, + const TimingData *pTiming = nullptr, bool force_loop = false, float start_sec = 0, float length_sec = -1, diff --git a/src/GameState.cpp b/src/GameState.cpp index e19b2b230e..eee5d4df46 100644 --- a/src/GameState.cpp +++ b/src/GameState.cpp @@ -41,7 +41,7 @@ #include #include -GameState* GAMESTATE = NULL; // global and accessable from anywhere in our program +GameState* GAMESTATE = nullptr; // global and accessable from anywhere in our program #define NAME_BLACKLIST_FILE "/Data/NamesBlacklist.txt" @@ -75,7 +75,7 @@ struct GameStateImpl m_Subscriber.SubscribeToMessage( "RefreshCreditText" ); } }; -static GameStateImpl *g_pImpl = NULL; +static GameStateImpl *g_pImpl = nullptr; ThemeMetric ALLOW_LATE_JOIN("GameState","AllowLateJoin"); ThemeMetric USE_NAME_BLACKLIST("GameState","UseNameBlacklist"); @@ -106,7 +106,7 @@ static Preference g_Premium( "Premium", Premium_DoubleFor1Credit ); Preference GameState::m_bAutoJoin( "AutoJoin", false ); GameState::GameState() : - processedTiming( NULL ), + processedTiming(nullptr), m_pCurGame( Message_CurrentGameChanged ), m_pCurStyle( Message_CurrentStyleChanged ), m_PlayMode( Message_PlayModeChanged ), @@ -133,9 +133,9 @@ GameState::GameState() : { g_pImpl = new GameStateImpl; - SetCurrentStyle( NULL ); + SetCurrentStyle(nullptr); - m_pCurGame.Set( NULL ); + m_pCurGame.Set(nullptr); m_timeGameStarted.SetZero(); m_bDemonstrationOrJukebox = false; @@ -254,8 +254,8 @@ void GameState::ResetPlayer( PlayerNumber pn ) m_PreferredCourseDifficulty[pn].Set( Difficulty_Medium ); m_iPlayerStageTokens[pn] = 0; m_iAwardedExtraStages[pn] = 0; - m_pCurSteps[pn].Set( NULL ); - m_pCurTrail[pn].Set( NULL ); + m_pCurSteps[pn].Set(nullptr); + m_pCurTrail[pn].Set(nullptr); m_pPlayerState[pn]->Reset(); PROFILEMAN->UnloadProfile( pn ); ResetPlayerOptions(pn); @@ -278,7 +278,7 @@ void GameState::Reset() ASSERT( THEME != nullptr ); m_timeGameStarted.SetZero(); - SetCurrentStyle( NULL ); + SetCurrentStyle(nullptr); FOREACH_MultiPlayer( p ) m_MultiPlayerStatus[p] = MultiPlayerStatus_NotJoined; FOREACH_PlayerNumber( pn ) @@ -307,9 +307,9 @@ void GameState::Reset() m_iStageSeed = rand(); m_pCurSong.Set( GetDefaultSong() ); - m_pPreferredSong = NULL; - m_pCurCourse.Set( NULL ); - m_pPreferredCourse = NULL; + m_pPreferredSong = nullptr; + m_pCurCourse.Set(nullptr); + m_pPreferredCourse = nullptr; FOREACH_MultiPlayer( p ) m_pMultiPlayerState[p]->Reset(); @@ -343,7 +343,7 @@ void GameState::Reset() LIGHTSMAN->SetLightsMode( LIGHTSMODE_ATTRACT ); m_stEdit.Set( StepsType_Invalid ); - m_pEditSourceSteps.Set( NULL ); + m_pEditSourceSteps.Set(nullptr); m_stEditSource.Set( StepsType_Invalid ); m_iEditCourseEntryIndex.Set( -1 ); m_sEditLocalProfileID.Set( "" ); @@ -610,7 +610,7 @@ int GameState::GetNumStagesForCurrentSongAndStepsOrCourse() const int numSidesJoined = GetNumSidesJoined(); if( pStyle == nullptr ) { - const Steps *pSteps = NULL; + const Steps *pSteps = nullptr; if( this->GetMasterPlayerNumber() != PlayerNumber_Invalid ) pSteps = m_pCurSteps[this->GetMasterPlayerNumber()]; // Don't call GetFirstCompatibleStyle if numSidesJoined == 0. @@ -2169,7 +2169,7 @@ public: static int GetCurrentSong( T* p, lua_State *L ) { if(p->m_pCurSong) p->m_pCurSong->PushSelf(L); else lua_pushnil(L); return 1; } static int SetCurrentSong( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->m_pCurSong.Set( NULL ); } + if( lua_isnil(L,1) ) { p->m_pCurSong.Set(nullptr); } else { Song *pS = Luna::check( L, 1, true ); p->m_pCurSong.Set( pS ); } return 0; } @@ -2184,7 +2184,7 @@ public: static int SetCurrentSteps( T* p, lua_State *L ) { PlayerNumber pn = Enum::Check(L, 1); - if( lua_isnil(L,2) ) { p->m_pCurSteps[pn].Set( NULL ); } + if( lua_isnil(L,2) ) { p->m_pCurSteps[pn].Set(nullptr); } else { Steps *pS = Luna::check(L,2); p->m_pCurSteps[pn].Set( pS ); } ASSERT(p->m_pCurSteps[pn]->m_StepsType == p->m_pCurStyle->m_StepsType); @@ -2195,7 +2195,7 @@ public: static int GetCurrentCourse( T* p, lua_State *L ) { if(p->m_pCurCourse) p->m_pCurCourse->PushSelf(L); else lua_pushnil(L); return 1; } static int SetCurrentCourse( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->m_pCurCourse.Set( NULL ); } + if( lua_isnil(L,1) ) { p->m_pCurCourse.Set(nullptr); } else { Course *pC = Luna::check(L,1); p->m_pCurCourse.Set( pC ); } return 0; } @@ -2210,7 +2210,7 @@ public: static int SetCurrentTrail( T* p, lua_State *L ) { PlayerNumber pn = Enum::Check(L, 1); - if( lua_isnil(L,2) ) { p->m_pCurTrail[pn].Set( NULL ); } + if( lua_isnil(L,2) ) { p->m_pCurTrail[pn].Set(nullptr); } else { Trail *pS = Luna::check(L,2); p->m_pCurTrail[pn].Set( pS ); } MESSAGEMAN->Broadcast( (MessageID)(Message_CurrentTrailP1Changed+pn) ); return 0; @@ -2218,7 +2218,7 @@ public: static int GetPreferredSong( T* p, lua_State *L ) { if(p->m_pPreferredSong) p->m_pPreferredSong->PushSelf(L); else lua_pushnil(L); return 1; } static int SetPreferredSong( T* p, lua_State *L ) { - if( lua_isnil(L,1) ) { p->m_pPreferredSong = NULL; } + if( lua_isnil(L,1) ) { p->m_pPreferredSong = nullptr; } else { Song *pS = Luna::check(L,1); p->m_pPreferredSong = pS; } return 0; } diff --git a/src/GraphDisplay.cpp b/src/GraphDisplay.cpp index ec159e7551..2496ed5c32 100644 --- a/src/GraphDisplay.cpp +++ b/src/GraphDisplay.cpp @@ -126,7 +126,7 @@ public: ~GraphBody() { TEXTUREMAN->UnloadTexture( m_pTexture ); - m_pTexture = NULL; + m_pTexture = nullptr; } void DrawPrimitives() @@ -150,8 +150,8 @@ public: GraphDisplay::GraphDisplay() { - m_pGraphLine = NULL; - m_pGraphBody = NULL; + m_pGraphLine = nullptr; + m_pGraphBody = nullptr; } GraphDisplay::~GraphDisplay() diff --git a/src/InputFilter.cpp b/src/InputFilter.cpp index 5149ac3612..d28503ed47 100644 --- a/src/InputFilter.cpp +++ b/src/InputFilter.cpp @@ -82,7 +82,7 @@ namespace * this won't cause timing problems, because the event timestamp is preserved. */ static Preference g_fInputDebounceTime( "InputDebounceTime", 0 ); -InputFilter* INPUTFILTER = NULL; // global and accessable from anywhere in our program +InputFilter* INPUTFILTER = nullptr; // global and accessable from anywhere in our program static const float TIME_BEFORE_REPEATS = 0.375f; diff --git a/src/InputFilter.h b/src/InputFilter.h index a67d33a906..284dff94aa 100644 --- a/src/InputFilter.h +++ b/src/InputFilter.h @@ -61,9 +61,9 @@ public: void RepeatStopKey( const DeviceInput &di ); // If aButtonState is NULL, use the last reported state. - bool IsBeingPressed( const DeviceInput &di, const DeviceInputList *pButtonState = NULL ) const; - float GetSecsHeld( const DeviceInput &di, const DeviceInputList *pButtonState = NULL ) const; - float GetLevel( const DeviceInput &di, const DeviceInputList *pButtonState = NULL ) const; + bool IsBeingPressed( const DeviceInput &di, const DeviceInputList *pButtonState = nullptr ) const; + float GetSecsHeld( const DeviceInput &di, const DeviceInputList *pButtonState = nullptr ) const; + float GetLevel( const DeviceInput &di, const DeviceInputList *pButtonState = nullptr ) const; RString GetButtonComment( const DeviceInput &di ) const; void GetInputEvents( vector &aEventOut ); diff --git a/src/InputMapper.cpp b/src/InputMapper.cpp index 9e7f9c3059..8cc3fc9031 100644 --- a/src/InputMapper.cpp +++ b/src/InputMapper.cpp @@ -26,12 +26,12 @@ namespace PlayerNumber g_JoinControllers; }; -InputMapper* INPUTMAPPER = NULL; // global and accessable from anywhere in our program +InputMapper* INPUTMAPPER = nullptr; // global and accessable from anywhere in our program InputMapper::InputMapper() { g_JoinControllers = PLAYER_INVALID; - m_pInputScheme = NULL; + m_pInputScheme = nullptr; } InputMapper::~InputMapper() diff --git a/src/InputMapper.h b/src/InputMapper.h index d09f23c53e..dba2555427 100644 --- a/src/InputMapper.h +++ b/src/InputMapper.h @@ -173,7 +173,7 @@ public: float GetSecsHeld( const GameInput &GameI, MultiPlayer mp = MultiPlayer_Invalid ) const; float GetSecsHeld( GameButton MenuI, PlayerNumber pn ) const; - bool IsBeingPressed( const GameInput &GameI, MultiPlayer mp = MultiPlayer_Invalid, const DeviceInputList *pButtonState = NULL ) const; + bool IsBeingPressed( const GameInput &GameI, MultiPlayer mp = MultiPlayer_Invalid, const DeviceInputList *pButtonState = nullptr ) const; bool IsBeingPressed( GameButton MenuI, PlayerNumber pn ) const; void ResetKeyRepeat( const GameInput &GameI ); diff --git a/src/InputQueue.cpp b/src/InputQueue.cpp index fc9056b286..2f258ffd78 100644 --- a/src/InputQueue.cpp +++ b/src/InputQueue.cpp @@ -6,7 +6,7 @@ #include "InputMapper.h" -InputQueue* INPUTQUEUE = NULL; // global and accessable from anywhere in our program +InputQueue* INPUTQUEUE = nullptr; // global and accessable from anywhere in our program const unsigned MAX_INPUT_QUEUE_LENGTH = 32; @@ -95,7 +95,7 @@ bool InputQueueCode::EnteredCode( GameController controller ) const int iMinSearchIndexUsed = iQueueIndex; for( int b=0; b<(int) Press.m_aButtonsToPress.size(); ++b ) { - const InputEventPlus *pIEP = NULL; + const InputEventPlus *pIEP = nullptr; int iQueueSearchIndex = iQueueIndex; for( ; iQueueSearchIndex>=0; --iQueueSearchIndex ) // iterate newest to oldest { diff --git a/src/InputQueue.h b/src/InputQueue.h index cb7498470b..4412ba34c3 100644 --- a/src/InputQueue.h +++ b/src/InputQueue.h @@ -14,7 +14,7 @@ public: InputQueue(); void RememberInput( const InputEventPlus &gi ); - bool WasPressedRecently( GameController c, const GameButton button, const RageTimer &OldestTimeAllowed, InputEventPlus *pIEP = NULL ); + bool WasPressedRecently( GameController c, const GameButton button, const RageTimer &OldestTimeAllowed, InputEventPlus *pIEP = nullptr ); const vector &GetQueue( GameController c ) const { return m_aQueue[c]; } void ClearQueue( GameController c ); diff --git a/src/LifeMeterBar.cpp b/src/LifeMeterBar.cpp index b81f9efcd5..c3119efd01 100644 --- a/src/LifeMeterBar.cpp +++ b/src/LifeMeterBar.cpp @@ -1,421 +1,421 @@ -#include "global.h" -#include "LifeMeterBar.h" -#include "PrefsManager.h" -#include "RageLog.h" -#include "RageTimer.h" -#include "GameState.h" -#include "RageMath.h" -#include "ThemeManager.h" -#include "Song.h" -#include "StatsManager.h" -#include "ThemeMetric.h" -#include "PlayerState.h" -#include "Quad.h" -#include "ActorUtil.h" -#include "StreamDisplay.h" -#include "Steps.h" -#include "Course.h" - -static RString LIFE_PERCENT_CHANGE_NAME( size_t i ) { return "LifePercentChange" + ScoreEventToString( (ScoreEvent)i ); } - -LifeMeterBar::LifeMeterBar() -{ - DANGER_THRESHOLD.Load ("LifeMeterBar","DangerThreshold"); - INITIAL_VALUE.Load ("LifeMeterBar","InitialValue"); - HOT_VALUE.Load ("LifeMeterBar","HotValue"); - LIFE_MULTIPLIER.Load ( "LifeMeterBar","LifeMultiplier"); - MIN_STAY_ALIVE.Load ("LifeMeterBar","MinStayAlive"); - FORCE_LIFE_DIFFICULTY_ON_EXTRA_STAGE.Load ("LifeMeterBar","ForceLifeDifficultyOnExtraStage"); - EXTRA_STAGE_LIFE_DIFFICULTY.Load ("LifeMeterBar","ExtraStageLifeDifficulty"); - m_fLifePercentChange.Load( "LifeMeterBar", LIFE_PERCENT_CHANGE_NAME, NUM_ScoreEvent ); - - m_pPlayerState = NULL; - - SongOptions::DrainType dtype = GAMESTATE->m_SongOptions.GetStage().m_DrainType; - switch( dtype ) - { - case SongOptions::DRAIN_NORMAL: - m_fLifePercentage = INITIAL_VALUE; - break; - - /* These types only go down, so they always start at full. */ - case SongOptions::DRAIN_NO_RECOVER: - case SongOptions::DRAIN_SUDDEN_DEATH: - m_fLifePercentage = 1.0f; break; - default: - FAIL_M(ssprintf("Invalid DrainType: %i", dtype)); - } - - const RString sType = "LifeMeterBar"; - - m_fPassingAlpha = 0; - m_fHotAlpha = 0; - - m_fBaseLifeDifficulty = PREFSMAN->m_fLifeDifficultyScale; - m_fLifeDifficulty = m_fBaseLifeDifficulty; - - // set up progressive lifebar - m_iProgressiveLifebar = PREFSMAN->m_iProgressiveLifebar; - m_iMissCombo = 0; - - // set up combotoregainlife - m_iComboToRegainLife = 0; - - bool bExtra = GAMESTATE->IsAnExtraStage(); - RString sExtra = bExtra ? "extra " : ""; - - m_sprUnder.Load( THEME->GetPathG(sType,sExtra+"Under") ); - m_sprUnder->SetName( "Under" ); - ActorUtil::LoadAllCommandsAndSetXY( m_sprUnder, sType ); - this->AddChild( m_sprUnder ); - - m_sprDanger.Load( THEME->GetPathG(sType,sExtra+"Danger") ); - m_sprDanger->SetName( "Danger" ); - ActorUtil::LoadAllCommandsAndSetXY( m_sprDanger, sType ); - this->AddChild( m_sprDanger ); - - m_pStream = new StreamDisplay; - m_pStream->Load( bExtra ? "StreamDisplayExtra" : "StreamDisplay" ); - m_pStream->SetName( "Stream" ); - ActorUtil::LoadAllCommandsAndSetXY( m_pStream, sType ); - this->AddChild( m_pStream ); - - m_sprOver.Load( THEME->GetPathG(sType,sExtra+"Over") ); - m_sprOver->SetName( "Over" ); - ActorUtil::LoadAllCommandsAndSetXY( m_sprOver, sType ); - this->AddChild( m_sprOver ); -} - -LifeMeterBar::~LifeMeterBar() -{ - SAFE_DELETE( m_pStream ); -} - -void LifeMeterBar::Load( const PlayerState *pPlayerState, PlayerStageStats *pPlayerStageStats ) -{ - LifeMeter::Load( pPlayerState, pPlayerStageStats ); - - PlayerNumber pn = pPlayerState->m_PlayerNumber; - - // Change life difficulty to really easy if merciful beginner on - m_bMercifulBeginnerInEffect = - GAMESTATE->m_PlayMode == PLAY_MODE_REGULAR && - GAMESTATE->IsPlayerEnabled( pPlayerState ) && - GAMESTATE->m_pCurSteps[pn]->GetDifficulty() == Difficulty_Beginner && - PREFSMAN->m_bMercifulBeginner; - - AfterLifeChanged(); -} - -void LifeMeterBar::ChangeLife( TapNoteScore score ) -{ - float fDeltaLife=0.f; - switch( score ) - { - DEFAULT_FAIL( score ); - case TNS_W1: fDeltaLife = m_fLifePercentChange.GetValue(SE_W1); break; - case TNS_W2: fDeltaLife = m_fLifePercentChange.GetValue(SE_W2); break; - case TNS_W3: fDeltaLife = m_fLifePercentChange.GetValue(SE_W3); break; - case TNS_W4: fDeltaLife = m_fLifePercentChange.GetValue(SE_W4); break; - case TNS_W5: fDeltaLife = m_fLifePercentChange.GetValue(SE_W5); break; - case TNS_Miss: fDeltaLife = m_fLifePercentChange.GetValue(SE_Miss); break; - case TNS_HitMine: fDeltaLife = m_fLifePercentChange.GetValue(SE_HitMine); break; - case TNS_None: fDeltaLife = m_fLifePercentChange.GetValue(SE_Miss); break; - case TNS_CheckpointHit: fDeltaLife = m_fLifePercentChange.GetValue(SE_CheckpointHit); break; - case TNS_CheckpointMiss:fDeltaLife = m_fLifePercentChange.GetValue(SE_CheckpointMiss); break; - } - - // this was previously if( IsHot() && score < TNS_GOOD ) in 3.9... -freem - if( IsHot() && fDeltaLife < 0 ) - fDeltaLife = min( fDeltaLife, -0.10f ); // make it take a while to get back to "hot" - - switch( GAMESTATE->m_SongOptions.GetSong().m_DrainType ) - { - DEFAULT_FAIL( GAMESTATE->m_SongOptions.GetSong().m_DrainType ); - case SongOptions::DRAIN_NORMAL: - break; - case SongOptions::DRAIN_NO_RECOVER: - fDeltaLife = min( fDeltaLife, 0 ); - break; - case SongOptions::DRAIN_SUDDEN_DEATH: - if( score < MIN_STAY_ALIVE ) - fDeltaLife = -1.0f; - else - fDeltaLife = 0; - break; - } - - ChangeLife( fDeltaLife ); -} - -void LifeMeterBar::ChangeLife( HoldNoteScore score, TapNoteScore tscore ) -{ - float fDeltaLife=0.f; - SongOptions::DrainType dtype = GAMESTATE->m_SongOptions.GetSong().m_DrainType; - switch( dtype ) - { - case SongOptions::DRAIN_NORMAL: - switch( score ) - { - case HNS_Held: fDeltaLife = m_fLifePercentChange.GetValue(SE_Held); break; - case HNS_LetGo: fDeltaLife = m_fLifePercentChange.GetValue(SE_LetGo); break; - default: - FAIL_M(ssprintf("Invalid HoldNoteScore: %i", score)); - } - if( IsHot() && score == HNS_LetGo ) - fDeltaLife = -0.10f; // make it take a while to get back to "hot" - break; - case SongOptions::DRAIN_NO_RECOVER: - switch( score ) - { - case HNS_Held: fDeltaLife = +0.000f; break; - case HNS_LetGo: fDeltaLife = m_fLifePercentChange.GetValue(SE_LetGo); break; - default: - FAIL_M(ssprintf("Invalid HoldNoteScore: %i", score)); - } - break; - case SongOptions::DRAIN_SUDDEN_DEATH: - switch( score ) - { - case HNS_Held: fDeltaLife = +0; break; - case HNS_LetGo: fDeltaLife = -1.0f; break; - default: - FAIL_M(ssprintf("Invalid HoldNoteScore: %i", score)); - } - break; - default: - FAIL_M(ssprintf("Invalid DrainType: %i", dtype)); - } - - ChangeLife( fDeltaLife ); -} - -void LifeMeterBar::ChangeLife( float fDeltaLife ) -{ - bool bUseMercifulDrain = m_bMercifulBeginnerInEffect || PREFSMAN->m_bMercifulDrain; - if( bUseMercifulDrain && fDeltaLife < 0 ) - fDeltaLife *= SCALE( m_fLifePercentage, 0.f, 1.f, 0.5f, 1.f); - - // handle progressiveness and ComboToRegainLife here - if( fDeltaLife >= 0 ) - { - m_iMissCombo = 0; - m_iComboToRegainLife = max( m_iComboToRegainLife-1, 0 ); - if ( m_iComboToRegainLife > 0 ) - fDeltaLife = 0.0f; - } - else - { - fDeltaLife *= 1 + (float)m_iProgressiveLifebar/8 * m_iMissCombo; - // do this after; only successive W5/miss will increase the amount of life lost. - m_iMissCombo++; - m_iComboToRegainLife = PREFSMAN->m_iRegenComboAfterMiss; - } - - // If we've already failed, there's no point in letting them fill up the bar again. - if( m_pPlayerStageStats->m_bFailed ) - return; - - switch( GAMESTATE->m_SongOptions.GetSong().m_DrainType ) - { - case SongOptions::DRAIN_NORMAL: - case SongOptions::DRAIN_NO_RECOVER: - if( fDeltaLife > 0 ) - fDeltaLife *= m_fLifeDifficulty; - else - fDeltaLife /= m_fLifeDifficulty; - break; - case SongOptions::DRAIN_SUDDEN_DEATH: - // This should always -1.0f; - if( fDeltaLife < 0 ) - fDeltaLife = -1.0f; - else - fDeltaLife = 0; - break; - default: - break; - } - - m_fLifePercentage += fDeltaLife; - CLAMP( m_fLifePercentage, 0, LIFE_MULTIPLIER ); - AfterLifeChanged(); -} - -extern ThemeMetric PENALIZE_TAP_SCORE_NONE; -void LifeMeterBar::HandleTapScoreNone() -{ - if( PENALIZE_TAP_SCORE_NONE ) - ChangeLife( TNS_None ); -} - -void LifeMeterBar::AfterLifeChanged() -{ - m_pStream->SetPercent( m_fLifePercentage ); - - Message msg( "LifeChanged" ); - msg.SetParam( "Player", m_pPlayerState->m_PlayerNumber ); - msg.SetParam( "LifeMeter", LuaReference::CreateFromPush(*this) ); - MESSAGEMAN->Broadcast( msg ); -} - -bool LifeMeterBar::IsHot() const -{ - return m_fLifePercentage >= HOT_VALUE; -} - -bool LifeMeterBar::IsInDanger() const -{ - return m_fLifePercentage < DANGER_THRESHOLD; -} - -bool LifeMeterBar::IsFailing() const -{ - return m_fLifePercentage <= m_pPlayerState->m_PlayerOptions.GetCurrent().m_fPassmark; -} - - -void LifeMeterBar::Update( float fDeltaTime ) -{ - LifeMeter::Update( fDeltaTime ); - - m_fPassingAlpha += !IsFailing() ? +fDeltaTime*2 : -fDeltaTime*2; - CLAMP( m_fPassingAlpha, 0, 1 ); - - m_fHotAlpha += IsHot() ? + fDeltaTime*2 : -fDeltaTime*2; - CLAMP( m_fHotAlpha, 0, 1 ); - - m_pStream->SetPassingAlpha( m_fPassingAlpha ); - m_pStream->SetHotAlpha( m_fHotAlpha ); - - if( m_pPlayerState->m_HealthState == HealthState_Danger ) - m_sprDanger->SetVisible( true ); - else - m_sprDanger->SetVisible( false ); -} - - -void LifeMeterBar::UpdateNonstopLifebar() -{ - int iCleared, iTotal, iProgressiveLifebarDifficulty; - - switch( GAMESTATE->m_PlayMode ) - { - case PLAY_MODE_REGULAR: - if( GAMESTATE->IsEventMode() || GAMESTATE->m_bDemonstrationOrJukebox ) - return; - - iCleared = GAMESTATE->m_iCurrentStageIndex; - iTotal = PREFSMAN->m_iSongsPerPlay; - iProgressiveLifebarDifficulty = PREFSMAN->m_iProgressiveStageLifebar; - break; - case PLAY_MODE_NONSTOP: - iCleared = GAMESTATE->GetCourseSongIndex(); - iTotal = GAMESTATE->m_pCurCourse->GetEstimatedNumStages(); - iProgressiveLifebarDifficulty = PREFSMAN->m_iProgressiveNonstopLifebar; - break; - default: - return; - } - -// if (iCleared > iTotal) iCleared = iTotal; // clear/iTotal <= 1 -// if (iTotal == 0) iTotal = 1; // no division by 0 - - if( GAMESTATE->IsAnExtraStage() && FORCE_LIFE_DIFFICULTY_ON_EXTRA_STAGE ) - { - // extra stage is its own thing, should not be progressive - // and it should be as difficult as life 4 - // (e.g. it should not depend on life settings) - - m_iProgressiveLifebar = 0; - m_fLifeDifficulty = EXTRA_STAGE_LIFE_DIFFICULTY; - return; - } - - if( iTotal > 1 ) - m_fLifeDifficulty = m_fBaseLifeDifficulty - 0.2f * (int)(iProgressiveLifebarDifficulty * iCleared / (iTotal - 1)); - else - m_fLifeDifficulty = m_fBaseLifeDifficulty - 0.2f * iProgressiveLifebarDifficulty; - - if( m_fLifeDifficulty >= 0.4f ) - return; - - /* Approximate deductions for a miss - * Life 1 : 5 % - * Life 2 : 5.7 % - * Life 3 : 6.6 % - * Life 4 : 8 % - * Life 5 : 10 % - * Life 6 : 13.3 % - * Life 7 : 20 % - * Life 8 : 26.6 % - * Life 9 : 32 % - * Life 10: 40 % - * Life 11: 50 % - * Life 12: 57.1 % - * Life 13: 66.6 % - * Life 14: 80 % - * Life 15: 100 % - * Life 16+: 200 % - * - * Note there is 200%, because boos take off 1/2 as much as - * a miss, and a W5 would suck up half of your lifebar. - * - * Everything past 7 is intended mainly for nonstop mode. - */ - - // the lifebar is pretty harsh at 0.4 already (you lose - // about 20% of your lifebar); at 0.2 it would be 40%, which - // is too harsh at one difficulty level higher. Override. - int iLifeDifficulty = int( (1.8f - m_fLifeDifficulty)/0.2f ); - - // first eight values don't matter - float fDifficultyValues[16] = {0,0,0,0,0,0,0,0, - 0.3f, 0.25f, 0.2f, 0.16f, 0.14f, 0.12f, 0.10f, 0.08f}; - - if( iLifeDifficulty >= 16 ) - { - // judge 16 or higher - m_fLifeDifficulty = 0.04f; - return; - } - - m_fLifeDifficulty = fDifficultyValues[iLifeDifficulty]; - return; -} - -void LifeMeterBar::FillForHowToPlay( int NumW2s, int NumMisses ) -{ - m_iProgressiveLifebar = 0; // disable progressive lifebar - - float AmountForW2 = NumW2s * m_fLifeDifficulty * 0.008f; - float AmountForMiss = NumMisses / m_fLifeDifficulty * 0.08f; - - m_fLifePercentage = AmountForMiss - AmountForW2; - CLAMP( m_fLifePercentage, 0.0f, 1.0f ); - AfterLifeChanged(); -} - -/* - * (c) 2001-2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "LifeMeterBar.h" +#include "PrefsManager.h" +#include "RageLog.h" +#include "RageTimer.h" +#include "GameState.h" +#include "RageMath.h" +#include "ThemeManager.h" +#include "Song.h" +#include "StatsManager.h" +#include "ThemeMetric.h" +#include "PlayerState.h" +#include "Quad.h" +#include "ActorUtil.h" +#include "StreamDisplay.h" +#include "Steps.h" +#include "Course.h" + +static RString LIFE_PERCENT_CHANGE_NAME( size_t i ) { return "LifePercentChange" + ScoreEventToString( (ScoreEvent)i ); } + +LifeMeterBar::LifeMeterBar() +{ + DANGER_THRESHOLD.Load ("LifeMeterBar","DangerThreshold"); + INITIAL_VALUE.Load ("LifeMeterBar","InitialValue"); + HOT_VALUE.Load ("LifeMeterBar","HotValue"); + LIFE_MULTIPLIER.Load ( "LifeMeterBar","LifeMultiplier"); + MIN_STAY_ALIVE.Load ("LifeMeterBar","MinStayAlive"); + FORCE_LIFE_DIFFICULTY_ON_EXTRA_STAGE.Load ("LifeMeterBar","ForceLifeDifficultyOnExtraStage"); + EXTRA_STAGE_LIFE_DIFFICULTY.Load ("LifeMeterBar","ExtraStageLifeDifficulty"); + m_fLifePercentChange.Load( "LifeMeterBar", LIFE_PERCENT_CHANGE_NAME, NUM_ScoreEvent ); + + m_pPlayerState = nullptr; + + SongOptions::DrainType dtype = GAMESTATE->m_SongOptions.GetStage().m_DrainType; + switch( dtype ) + { + case SongOptions::DRAIN_NORMAL: + m_fLifePercentage = INITIAL_VALUE; + break; + + /* These types only go down, so they always start at full. */ + case SongOptions::DRAIN_NO_RECOVER: + case SongOptions::DRAIN_SUDDEN_DEATH: + m_fLifePercentage = 1.0f; break; + default: + FAIL_M(ssprintf("Invalid DrainType: %i", dtype)); + } + + const RString sType = "LifeMeterBar"; + + m_fPassingAlpha = 0; + m_fHotAlpha = 0; + + m_fBaseLifeDifficulty = PREFSMAN->m_fLifeDifficultyScale; + m_fLifeDifficulty = m_fBaseLifeDifficulty; + + // set up progressive lifebar + m_iProgressiveLifebar = PREFSMAN->m_iProgressiveLifebar; + m_iMissCombo = 0; + + // set up combotoregainlife + m_iComboToRegainLife = 0; + + bool bExtra = GAMESTATE->IsAnExtraStage(); + RString sExtra = bExtra ? "extra " : ""; + + m_sprUnder.Load( THEME->GetPathG(sType,sExtra+"Under") ); + m_sprUnder->SetName( "Under" ); + ActorUtil::LoadAllCommandsAndSetXY( m_sprUnder, sType ); + this->AddChild( m_sprUnder ); + + m_sprDanger.Load( THEME->GetPathG(sType,sExtra+"Danger") ); + m_sprDanger->SetName( "Danger" ); + ActorUtil::LoadAllCommandsAndSetXY( m_sprDanger, sType ); + this->AddChild( m_sprDanger ); + + m_pStream = new StreamDisplay; + m_pStream->Load( bExtra ? "StreamDisplayExtra" : "StreamDisplay" ); + m_pStream->SetName( "Stream" ); + ActorUtil::LoadAllCommandsAndSetXY( m_pStream, sType ); + this->AddChild( m_pStream ); + + m_sprOver.Load( THEME->GetPathG(sType,sExtra+"Over") ); + m_sprOver->SetName( "Over" ); + ActorUtil::LoadAllCommandsAndSetXY( m_sprOver, sType ); + this->AddChild( m_sprOver ); +} + +LifeMeterBar::~LifeMeterBar() +{ + SAFE_DELETE( m_pStream ); +} + +void LifeMeterBar::Load( const PlayerState *pPlayerState, PlayerStageStats *pPlayerStageStats ) +{ + LifeMeter::Load( pPlayerState, pPlayerStageStats ); + + PlayerNumber pn = pPlayerState->m_PlayerNumber; + + // Change life difficulty to really easy if merciful beginner on + m_bMercifulBeginnerInEffect = + GAMESTATE->m_PlayMode == PLAY_MODE_REGULAR && + GAMESTATE->IsPlayerEnabled( pPlayerState ) && + GAMESTATE->m_pCurSteps[pn]->GetDifficulty() == Difficulty_Beginner && + PREFSMAN->m_bMercifulBeginner; + + AfterLifeChanged(); +} + +void LifeMeterBar::ChangeLife( TapNoteScore score ) +{ + float fDeltaLife=0.f; + switch( score ) + { + DEFAULT_FAIL( score ); + case TNS_W1: fDeltaLife = m_fLifePercentChange.GetValue(SE_W1); break; + case TNS_W2: fDeltaLife = m_fLifePercentChange.GetValue(SE_W2); break; + case TNS_W3: fDeltaLife = m_fLifePercentChange.GetValue(SE_W3); break; + case TNS_W4: fDeltaLife = m_fLifePercentChange.GetValue(SE_W4); break; + case TNS_W5: fDeltaLife = m_fLifePercentChange.GetValue(SE_W5); break; + case TNS_Miss: fDeltaLife = m_fLifePercentChange.GetValue(SE_Miss); break; + case TNS_HitMine: fDeltaLife = m_fLifePercentChange.GetValue(SE_HitMine); break; + case TNS_None: fDeltaLife = m_fLifePercentChange.GetValue(SE_Miss); break; + case TNS_CheckpointHit: fDeltaLife = m_fLifePercentChange.GetValue(SE_CheckpointHit); break; + case TNS_CheckpointMiss:fDeltaLife = m_fLifePercentChange.GetValue(SE_CheckpointMiss); break; + } + + // this was previously if( IsHot() && score < TNS_GOOD ) in 3.9... -freem + if( IsHot() && fDeltaLife < 0 ) + fDeltaLife = min( fDeltaLife, -0.10f ); // make it take a while to get back to "hot" + + switch( GAMESTATE->m_SongOptions.GetSong().m_DrainType ) + { + DEFAULT_FAIL( GAMESTATE->m_SongOptions.GetSong().m_DrainType ); + case SongOptions::DRAIN_NORMAL: + break; + case SongOptions::DRAIN_NO_RECOVER: + fDeltaLife = min( fDeltaLife, 0 ); + break; + case SongOptions::DRAIN_SUDDEN_DEATH: + if( score < MIN_STAY_ALIVE ) + fDeltaLife = -1.0f; + else + fDeltaLife = 0; + break; + } + + ChangeLife( fDeltaLife ); +} + +void LifeMeterBar::ChangeLife( HoldNoteScore score, TapNoteScore tscore ) +{ + float fDeltaLife=0.f; + SongOptions::DrainType dtype = GAMESTATE->m_SongOptions.GetSong().m_DrainType; + switch( dtype ) + { + case SongOptions::DRAIN_NORMAL: + switch( score ) + { + case HNS_Held: fDeltaLife = m_fLifePercentChange.GetValue(SE_Held); break; + case HNS_LetGo: fDeltaLife = m_fLifePercentChange.GetValue(SE_LetGo); break; + default: + FAIL_M(ssprintf("Invalid HoldNoteScore: %i", score)); + } + if( IsHot() && score == HNS_LetGo ) + fDeltaLife = -0.10f; // make it take a while to get back to "hot" + break; + case SongOptions::DRAIN_NO_RECOVER: + switch( score ) + { + case HNS_Held: fDeltaLife = +0.000f; break; + case HNS_LetGo: fDeltaLife = m_fLifePercentChange.GetValue(SE_LetGo); break; + default: + FAIL_M(ssprintf("Invalid HoldNoteScore: %i", score)); + } + break; + case SongOptions::DRAIN_SUDDEN_DEATH: + switch( score ) + { + case HNS_Held: fDeltaLife = +0; break; + case HNS_LetGo: fDeltaLife = -1.0f; break; + default: + FAIL_M(ssprintf("Invalid HoldNoteScore: %i", score)); + } + break; + default: + FAIL_M(ssprintf("Invalid DrainType: %i", dtype)); + } + + ChangeLife( fDeltaLife ); +} + +void LifeMeterBar::ChangeLife( float fDeltaLife ) +{ + bool bUseMercifulDrain = m_bMercifulBeginnerInEffect || PREFSMAN->m_bMercifulDrain; + if( bUseMercifulDrain && fDeltaLife < 0 ) + fDeltaLife *= SCALE( m_fLifePercentage, 0.f, 1.f, 0.5f, 1.f); + + // handle progressiveness and ComboToRegainLife here + if( fDeltaLife >= 0 ) + { + m_iMissCombo = 0; + m_iComboToRegainLife = max( m_iComboToRegainLife-1, 0 ); + if ( m_iComboToRegainLife > 0 ) + fDeltaLife = 0.0f; + } + else + { + fDeltaLife *= 1 + (float)m_iProgressiveLifebar/8 * m_iMissCombo; + // do this after; only successive W5/miss will increase the amount of life lost. + m_iMissCombo++; + m_iComboToRegainLife = PREFSMAN->m_iRegenComboAfterMiss; + } + + // If we've already failed, there's no point in letting them fill up the bar again. + if( m_pPlayerStageStats->m_bFailed ) + return; + + switch( GAMESTATE->m_SongOptions.GetSong().m_DrainType ) + { + case SongOptions::DRAIN_NORMAL: + case SongOptions::DRAIN_NO_RECOVER: + if( fDeltaLife > 0 ) + fDeltaLife *= m_fLifeDifficulty; + else + fDeltaLife /= m_fLifeDifficulty; + break; + case SongOptions::DRAIN_SUDDEN_DEATH: + // This should always -1.0f; + if( fDeltaLife < 0 ) + fDeltaLife = -1.0f; + else + fDeltaLife = 0; + break; + default: + break; + } + + m_fLifePercentage += fDeltaLife; + CLAMP( m_fLifePercentage, 0, LIFE_MULTIPLIER ); + AfterLifeChanged(); +} + +extern ThemeMetric PENALIZE_TAP_SCORE_NONE; +void LifeMeterBar::HandleTapScoreNone() +{ + if( PENALIZE_TAP_SCORE_NONE ) + ChangeLife( TNS_None ); +} + +void LifeMeterBar::AfterLifeChanged() +{ + m_pStream->SetPercent( m_fLifePercentage ); + + Message msg( "LifeChanged" ); + msg.SetParam( "Player", m_pPlayerState->m_PlayerNumber ); + msg.SetParam( "LifeMeter", LuaReference::CreateFromPush(*this) ); + MESSAGEMAN->Broadcast( msg ); +} + +bool LifeMeterBar::IsHot() const +{ + return m_fLifePercentage >= HOT_VALUE; +} + +bool LifeMeterBar::IsInDanger() const +{ + return m_fLifePercentage < DANGER_THRESHOLD; +} + +bool LifeMeterBar::IsFailing() const +{ + return m_fLifePercentage <= m_pPlayerState->m_PlayerOptions.GetCurrent().m_fPassmark; +} + + +void LifeMeterBar::Update( float fDeltaTime ) +{ + LifeMeter::Update( fDeltaTime ); + + m_fPassingAlpha += !IsFailing() ? +fDeltaTime*2 : -fDeltaTime*2; + CLAMP( m_fPassingAlpha, 0, 1 ); + + m_fHotAlpha += IsHot() ? + fDeltaTime*2 : -fDeltaTime*2; + CLAMP( m_fHotAlpha, 0, 1 ); + + m_pStream->SetPassingAlpha( m_fPassingAlpha ); + m_pStream->SetHotAlpha( m_fHotAlpha ); + + if( m_pPlayerState->m_HealthState == HealthState_Danger ) + m_sprDanger->SetVisible( true ); + else + m_sprDanger->SetVisible( false ); +} + + +void LifeMeterBar::UpdateNonstopLifebar() +{ + int iCleared, iTotal, iProgressiveLifebarDifficulty; + + switch( GAMESTATE->m_PlayMode ) + { + case PLAY_MODE_REGULAR: + if( GAMESTATE->IsEventMode() || GAMESTATE->m_bDemonstrationOrJukebox ) + return; + + iCleared = GAMESTATE->m_iCurrentStageIndex; + iTotal = PREFSMAN->m_iSongsPerPlay; + iProgressiveLifebarDifficulty = PREFSMAN->m_iProgressiveStageLifebar; + break; + case PLAY_MODE_NONSTOP: + iCleared = GAMESTATE->GetCourseSongIndex(); + iTotal = GAMESTATE->m_pCurCourse->GetEstimatedNumStages(); + iProgressiveLifebarDifficulty = PREFSMAN->m_iProgressiveNonstopLifebar; + break; + default: + return; + } + +// if (iCleared > iTotal) iCleared = iTotal; // clear/iTotal <= 1 +// if (iTotal == 0) iTotal = 1; // no division by 0 + + if( GAMESTATE->IsAnExtraStage() && FORCE_LIFE_DIFFICULTY_ON_EXTRA_STAGE ) + { + // extra stage is its own thing, should not be progressive + // and it should be as difficult as life 4 + // (e.g. it should not depend on life settings) + + m_iProgressiveLifebar = 0; + m_fLifeDifficulty = EXTRA_STAGE_LIFE_DIFFICULTY; + return; + } + + if( iTotal > 1 ) + m_fLifeDifficulty = m_fBaseLifeDifficulty - 0.2f * (int)(iProgressiveLifebarDifficulty * iCleared / (iTotal - 1)); + else + m_fLifeDifficulty = m_fBaseLifeDifficulty - 0.2f * iProgressiveLifebarDifficulty; + + if( m_fLifeDifficulty >= 0.4f ) + return; + + /* Approximate deductions for a miss + * Life 1 : 5 % + * Life 2 : 5.7 % + * Life 3 : 6.6 % + * Life 4 : 8 % + * Life 5 : 10 % + * Life 6 : 13.3 % + * Life 7 : 20 % + * Life 8 : 26.6 % + * Life 9 : 32 % + * Life 10: 40 % + * Life 11: 50 % + * Life 12: 57.1 % + * Life 13: 66.6 % + * Life 14: 80 % + * Life 15: 100 % + * Life 16+: 200 % + * + * Note there is 200%, because boos take off 1/2 as much as + * a miss, and a W5 would suck up half of your lifebar. + * + * Everything past 7 is intended mainly for nonstop mode. + */ + + // the lifebar is pretty harsh at 0.4 already (you lose + // about 20% of your lifebar); at 0.2 it would be 40%, which + // is too harsh at one difficulty level higher. Override. + int iLifeDifficulty = int( (1.8f - m_fLifeDifficulty)/0.2f ); + + // first eight values don't matter + float fDifficultyValues[16] = {0,0,0,0,0,0,0,0, + 0.3f, 0.25f, 0.2f, 0.16f, 0.14f, 0.12f, 0.10f, 0.08f}; + + if( iLifeDifficulty >= 16 ) + { + // judge 16 or higher + m_fLifeDifficulty = 0.04f; + return; + } + + m_fLifeDifficulty = fDifficultyValues[iLifeDifficulty]; + return; +} + +void LifeMeterBar::FillForHowToPlay( int NumW2s, int NumMisses ) +{ + m_iProgressiveLifebar = 0; // disable progressive lifebar + + float AmountForW2 = NumW2s * m_fLifeDifficulty * 0.008f; + float AmountForMiss = NumMisses / m_fLifeDifficulty * 0.08f; + + m_fLifePercentage = AmountForMiss - AmountForW2; + CLAMP( m_fLifePercentage, 0.0f, 1.0f ); + AfterLifeChanged(); +} + +/* + * (c) 2001-2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/LifeMeterTime.cpp b/src/LifeMeterTime.cpp index 2d96eb4eb8..df550e3ee4 100644 --- a/src/LifeMeterTime.cpp +++ b/src/LifeMeterTime.cpp @@ -48,7 +48,7 @@ LifeMeterTime::LifeMeterTime() { m_fLifeTotalGainedSeconds = 0; m_fLifeTotalLostSeconds = 0; - m_pStream = NULL; + m_pStream = nullptr; } LifeMeterTime::~LifeMeterTime() diff --git a/src/LightsManager.cpp b/src/LightsManager.cpp index d1462e4171..678227d2f3 100644 --- a/src/LightsManager.cpp +++ b/src/LightsManager.cpp @@ -94,7 +94,7 @@ static void GetUsedGameInputs( vector &vGameInputsOut ) vGameInputsOut.push_back( input ); } -LightsManager* LIGHTSMAN = NULL; // global and accessable from anywhere in our program +LightsManager* LIGHTSMAN = nullptr; // global and accessable from anywhere in our program LightsManager::LightsManager() { diff --git a/src/LocalizedString.cpp b/src/LocalizedString.cpp index 8c73e52236..8a5ff7958e 100644 --- a/src/LocalizedString.cpp +++ b/src/LocalizedString.cpp @@ -39,7 +39,7 @@ LocalizedString::LocalizedString( const RString& sGroup, const RString& sName ) m_sGroup = sGroup; m_sName = sName; - m_pImpl = NULL; + m_pImpl = nullptr; CreateImpl(); } diff --git a/src/LuaManager.cpp b/src/LuaManager.cpp index 7bf631dab6..b3140ab5bd 100644 --- a/src/LuaManager.cpp +++ b/src/LuaManager.cpp @@ -16,7 +16,7 @@ #include #include -LuaManager *LUA = NULL; +LuaManager *LUA = nullptr; struct Impl { Impl(): g_pLock("Lua") {} @@ -25,7 +25,7 @@ struct Impl RageMutex g_pLock; }; -static Impl *pImpl = NULL; +static Impl *pImpl = nullptr; #if defined(_MSC_VER) /* "interaction between '_setjmp' and C++ object destruction is non-portable" @@ -226,7 +226,7 @@ static int LuaPanic( lua_State *L ) } // Actor registration -static vector *g_vRegisterActorTypes = NULL; +static vector *g_vRegisterActorTypes = nullptr; void LuaManager::Register( RegisterWithLuaFn pfn ) { @@ -315,7 +315,7 @@ void LuaManager::Release( Lua *&p ) if( bDoUnlock ) pImpl->g_pLock.Unlock(); - p = NULL; + p = nullptr; } /* diff --git a/src/MemoryCardManager.cpp b/src/MemoryCardManager.cpp index b5dd3314ef..220cdce787 100644 --- a/src/MemoryCardManager.cpp +++ b/src/MemoryCardManager.cpp @@ -13,7 +13,7 @@ #include "arch/MemoryCard/MemoryCardDriver_Null.h" #include "LuaManager.h" -MemoryCardManager* MEMCARDMAN = NULL; // global and accessable from anywhere in our program +MemoryCardManager* MEMCARDMAN = nullptr; // global and accessable from anywhere in our program static void MemoryCardOsMountPointInit( size_t /*PlayerNumber*/ i, RString &sNameOut, RString &defaultValueOut ) { @@ -253,7 +253,7 @@ bool ThreadedMemoryCardWorker::Unmount( const UsbStorageDevice *pDevice ) return true; } -static ThreadedMemoryCardWorker *g_pWorker = NULL; +static ThreadedMemoryCardWorker *g_pWorker = nullptr; MemoryCardManager::MemoryCardManager() { diff --git a/src/MenuTimer.cpp b/src/MenuTimer.cpp index 066b593e29..bf1261cfd1 100644 --- a/src/MenuTimer.cpp +++ b/src/MenuTimer.cpp @@ -19,7 +19,7 @@ MenuTimer::MenuTimer() m_fStallSecondsLeft = 0; m_bPaused = false; m_bSilent = false; - WARNING_COMMAND = NULL; + WARNING_COMMAND = nullptr; } MenuTimer::~MenuTimer() diff --git a/src/MessageManager.cpp b/src/MessageManager.cpp index 7de4eeb563..259ea526b1 100644 --- a/src/MessageManager.cpp +++ b/src/MessageManager.cpp @@ -9,7 +9,7 @@ #include #include -MessageManager* MESSAGEMAN = NULL; // global and accessable from anywhere in our program +MessageManager* MESSAGEMAN = nullptr; // global and accessable from anywhere in our program static const char *MessageIDNames[] = { diff --git a/src/MessageManager.h b/src/MessageManager.h index 6291aec29d..c8a7883f9e 100644 --- a/src/MessageManager.h +++ b/src/MessageManager.h @@ -1,297 +1,297 @@ -#ifndef MessageManager_H -#define MessageManager_H - -#include "LuaManager.h" -struct lua_State; -class LuaTable; -class LuaReference; - -/** @brief The various messages available to watch for. */ -enum MessageID -{ - Message_CurrentGameChanged, - Message_CurrentStyleChanged, - Message_PlayModeChanged, - Message_CurrentSongChanged, - Message_CurrentStepsP1Changed, - Message_CurrentStepsP2Changed, - Message_CurrentCourseChanged, - Message_CurrentTrailP1Changed, - Message_CurrentTrailP2Changed, - Message_GameplayLeadInChanged, - Message_EditStepsTypeChanged, - Message_EditCourseDifficultyChanged, - Message_EditSourceStepsChanged, - Message_EditSourceStepsTypeChanged, - Message_PreferredStepsTypeChanged, - Message_PreferredDifficultyP1Changed, - Message_PreferredDifficultyP2Changed, - Message_PreferredCourseDifficultyP1Changed, - Message_PreferredCourseDifficultyP2Changed, - Message_EditCourseEntryIndexChanged, - Message_EditLocalProfileIDChanged, - Message_GoalCompleteP1, - Message_GoalCompleteP2, - Message_NoteCrossed, - Message_NoteWillCrossIn400Ms, - Message_NoteWillCrossIn800Ms, - Message_NoteWillCrossIn1200Ms, - Message_CardRemovedP1, - Message_CardRemovedP2, - Message_BeatCrossed, - Message_MenuUpP1, - Message_MenuUpP2, - Message_MenuDownP1, - Message_MenuDownP2, - Message_MenuLeftP1, - Message_MenuLeftP2, - Message_MenuRightP1, - Message_MenuRightP2, - Message_MenuStartP1, - Message_MenuStartP2, - Message_MenuSelectionChanged, - Message_PlayerJoined, - Message_PlayerUnjoined, - Message_AutosyncChanged, - Message_PreferredSongGroupChanged, - Message_PreferredCourseGroupChanged, - Message_SortOrderChanged, - Message_LessonTry1, - Message_LessonTry2, - Message_LessonTry3, - Message_LessonCleared, - Message_LessonFailed, - Message_StorageDevicesChanged, - Message_AutoJoyMappingApplied, - Message_ScreenChanged, - Message_SongModified, - Message_ScoreMultiplierChangedP1, - Message_ScoreMultiplierChangedP2, - Message_StarPowerChangedP1, - Message_StarPowerChangedP2, - Message_CurrentComboChangedP1, - Message_CurrentComboChangedP2, - Message_StarMeterChangedP1, - Message_StarMeterChangedP2, - Message_LifeMeterChangedP1, - Message_LifeMeterChangedP2, - Message_UpdateScreenHeader, - Message_LeftClick, - Message_RightClick, - Message_MiddleClick, - Message_MouseWheelUp, - Message_MouseWheelDown, - NUM_MessageID, // leave this at the end - MessageID_Invalid -}; -const RString& MessageIDToString( MessageID m ); - -struct Message -{ - explicit Message( const RString &s ); - Message( const RString &s, const LuaReference ¶ms ); - ~Message(); - - void SetName( const RString &sName ) { m_sName = sName; } - RString GetName() const { return m_sName; } - - bool IsBroadcast() const { return m_bBroadcast; } - void SetBroadcast( bool b ) { m_bBroadcast = b; } - - void PushParamTable( lua_State *L ); - const LuaReference &GetParamTable() const; - void SetParamTable( const LuaReference ¶ms ); - - void GetParamFromStack( lua_State *L, const RString &sName ) const; - void SetParamFromStack( lua_State *L, const RString &sName ); - - template - bool GetParam( const RString &sName, T &val ) const - { - Lua *L = LUA->Get(); - GetParamFromStack( L, sName ); - bool bRet = LuaHelpers::Pop( L, val ); - LUA->Release( L ); - return bRet; - } - - template - void SetParam( const RString &sName, const T &val ) - { - Lua *L = LUA->Get(); - LuaHelpers::Push( L, val ); - SetParamFromStack( L, sName ); - LUA->Release( L ); - } - - bool operator==( const RString &s ) const { return m_sName == s; } - bool operator==( MessageID id ) const { return MessageIDToString(id) == m_sName; } - -private: - RString m_sName; - LuaTable *m_pParams; - bool m_bBroadcast; - - Message &operator=( const Message &rhs ); // don't use -/* Work around a gcc bug where HandleMessage( Message("Init") ) fails because the copy ctor is private. - * The copy ctor is not even used so I have no idea why it being private is an issue. Also, if the - * Message object were constructed implicitly (remove explicit above), it works: HandleMessage( "Init" ). - * Leaving this undefined but public changes a compile time error into a link time error. Hmm.*/ -public: - Message( const Message &rhs ); // don't use -}; - -class IMessageSubscriber -{ -public: - virtual ~IMessageSubscriber() { } - virtual void HandleMessage( const Message &msg ) = 0; - void ClearMessages( const RString sMessage = "" ); - -private: - friend class MessageManager; -}; - -class MessageSubscriber : public IMessageSubscriber -{ -public: - MessageSubscriber(): m_vsSubscribedTo() {} - MessageSubscriber( const MessageSubscriber &cpy ); - MessageSubscriber &operator=(const MessageSubscriber &cpy); - - // - // Messages - // - void SubscribeToMessage( MessageID message ); // will automatically unsubscribe - void SubscribeToMessage( const RString &sMessageName ); // will automatically unsubscribe - - void UnsubscribeAll(); - -private: - vector m_vsSubscribedTo; -}; - -/** @brief Deliver messages to any part of the program as needed. */ -class MessageManager -{ -public: - MessageManager(); - ~MessageManager(); - - void Subscribe( IMessageSubscriber* pSubscriber, const RString& sMessage ); - void Subscribe( IMessageSubscriber* pSubscriber, MessageID m ); - void Unsubscribe( IMessageSubscriber* pSubscriber, const RString& sMessage ); - void Unsubscribe( IMessageSubscriber* pSubscriber, MessageID m ); - void Broadcast( Message &msg ) const; - void Broadcast( const RString& sMessage ) const; - void Broadcast( MessageID m ) const; - bool IsSubscribedToMessage( IMessageSubscriber* pSubscriber, const RString &sMessage ) const; - inline bool IsSubscribedToMessage( IMessageSubscriber* pSubscriber, MessageID message ) const { return IsSubscribedToMessage( pSubscriber, MessageIDToString(message) ); } - - // Lua - void PushSelf( lua_State *L ); -}; - -extern MessageManager* MESSAGEMAN; // global and accessable from anywhere in our program - -template -class BroadcastOnChange -{ -private: - MessageID mSendWhenChanged; - T val; - -public: - explicit BroadcastOnChange( MessageID m ) { mSendWhenChanged = m; } - const T Get() const { return val; } - void Set( T t ) { val = t; MESSAGEMAN->Broadcast( MessageIDToString(mSendWhenChanged) ); } - operator T () const { return val; } - bool operator == ( const T &other ) const { return val == other; } - bool operator != ( const T &other ) const { return val != other; } -}; - -/** @brief Utilities for working with Lua. */ -namespace LuaHelpers -{ - template void Push( lua_State *L, const BroadcastOnChange &Object ) - { - LuaHelpers::Push( L, Object.Get() ); - } -} - -template -class BroadcastOnChange1D -{ -private: - typedef BroadcastOnChange MyType; - vector val; -public: - explicit BroadcastOnChange1D( MessageID m ) - { - for( unsigned i=0; i((MessageID)(m+i)) ); - } - const BroadcastOnChange& operator[]( unsigned i ) const { return val[i]; } - BroadcastOnChange& operator[]( unsigned i ) { return val[i]; } -}; - -template -class BroadcastOnChangePtr -{ -private: - MessageID mSendWhenChanged; - T *val; -public: - explicit BroadcastOnChangePtr( MessageID m ) { mSendWhenChanged = m; val = NULL; } - T* Get() const { return val; } - void Set( T* t ) { val = t; if(MESSAGEMAN) MESSAGEMAN->Broadcast( MessageIDToString(mSendWhenChanged) ); } - /* This is only intended to be used for setting temporary values; always - * restore the original value when finished, so listeners don't get confused - * due to missing a message. */ - void SetWithoutBroadcast( T* t ) { val = t; } - operator T* () const { return val; } - T* operator->() const { return val; } -}; - -template -class BroadcastOnChangePtr1D -{ -private: - typedef BroadcastOnChangePtr MyType; - vector val; -public: - explicit BroadcastOnChangePtr1D( MessageID m ) - { - for( unsigned i=0; i((MessageID)(m+i)) ); - } - const BroadcastOnChangePtr& operator[]( unsigned i ) const { return val[i]; } - BroadcastOnChangePtr& operator[]( unsigned i ) { return val[i]; } -}; - -#endif - -/* - * (c) 2003-2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef MessageManager_H +#define MessageManager_H + +#include "LuaManager.h" +struct lua_State; +class LuaTable; +class LuaReference; + +/** @brief The various messages available to watch for. */ +enum MessageID +{ + Message_CurrentGameChanged, + Message_CurrentStyleChanged, + Message_PlayModeChanged, + Message_CurrentSongChanged, + Message_CurrentStepsP1Changed, + Message_CurrentStepsP2Changed, + Message_CurrentCourseChanged, + Message_CurrentTrailP1Changed, + Message_CurrentTrailP2Changed, + Message_GameplayLeadInChanged, + Message_EditStepsTypeChanged, + Message_EditCourseDifficultyChanged, + Message_EditSourceStepsChanged, + Message_EditSourceStepsTypeChanged, + Message_PreferredStepsTypeChanged, + Message_PreferredDifficultyP1Changed, + Message_PreferredDifficultyP2Changed, + Message_PreferredCourseDifficultyP1Changed, + Message_PreferredCourseDifficultyP2Changed, + Message_EditCourseEntryIndexChanged, + Message_EditLocalProfileIDChanged, + Message_GoalCompleteP1, + Message_GoalCompleteP2, + Message_NoteCrossed, + Message_NoteWillCrossIn400Ms, + Message_NoteWillCrossIn800Ms, + Message_NoteWillCrossIn1200Ms, + Message_CardRemovedP1, + Message_CardRemovedP2, + Message_BeatCrossed, + Message_MenuUpP1, + Message_MenuUpP2, + Message_MenuDownP1, + Message_MenuDownP2, + Message_MenuLeftP1, + Message_MenuLeftP2, + Message_MenuRightP1, + Message_MenuRightP2, + Message_MenuStartP1, + Message_MenuStartP2, + Message_MenuSelectionChanged, + Message_PlayerJoined, + Message_PlayerUnjoined, + Message_AutosyncChanged, + Message_PreferredSongGroupChanged, + Message_PreferredCourseGroupChanged, + Message_SortOrderChanged, + Message_LessonTry1, + Message_LessonTry2, + Message_LessonTry3, + Message_LessonCleared, + Message_LessonFailed, + Message_StorageDevicesChanged, + Message_AutoJoyMappingApplied, + Message_ScreenChanged, + Message_SongModified, + Message_ScoreMultiplierChangedP1, + Message_ScoreMultiplierChangedP2, + Message_StarPowerChangedP1, + Message_StarPowerChangedP2, + Message_CurrentComboChangedP1, + Message_CurrentComboChangedP2, + Message_StarMeterChangedP1, + Message_StarMeterChangedP2, + Message_LifeMeterChangedP1, + Message_LifeMeterChangedP2, + Message_UpdateScreenHeader, + Message_LeftClick, + Message_RightClick, + Message_MiddleClick, + Message_MouseWheelUp, + Message_MouseWheelDown, + NUM_MessageID, // leave this at the end + MessageID_Invalid +}; +const RString& MessageIDToString( MessageID m ); + +struct Message +{ + explicit Message( const RString &s ); + Message( const RString &s, const LuaReference ¶ms ); + ~Message(); + + void SetName( const RString &sName ) { m_sName = sName; } + RString GetName() const { return m_sName; } + + bool IsBroadcast() const { return m_bBroadcast; } + void SetBroadcast( bool b ) { m_bBroadcast = b; } + + void PushParamTable( lua_State *L ); + const LuaReference &GetParamTable() const; + void SetParamTable( const LuaReference ¶ms ); + + void GetParamFromStack( lua_State *L, const RString &sName ) const; + void SetParamFromStack( lua_State *L, const RString &sName ); + + template + bool GetParam( const RString &sName, T &val ) const + { + Lua *L = LUA->Get(); + GetParamFromStack( L, sName ); + bool bRet = LuaHelpers::Pop( L, val ); + LUA->Release( L ); + return bRet; + } + + template + void SetParam( const RString &sName, const T &val ) + { + Lua *L = LUA->Get(); + LuaHelpers::Push( L, val ); + SetParamFromStack( L, sName ); + LUA->Release( L ); + } + + bool operator==( const RString &s ) const { return m_sName == s; } + bool operator==( MessageID id ) const { return MessageIDToString(id) == m_sName; } + +private: + RString m_sName; + LuaTable *m_pParams; + bool m_bBroadcast; + + Message &operator=( const Message &rhs ); // don't use +/* Work around a gcc bug where HandleMessage( Message("Init") ) fails because the copy ctor is private. + * The copy ctor is not even used so I have no idea why it being private is an issue. Also, if the + * Message object were constructed implicitly (remove explicit above), it works: HandleMessage( "Init" ). + * Leaving this undefined but public changes a compile time error into a link time error. Hmm.*/ +public: + Message( const Message &rhs ); // don't use +}; + +class IMessageSubscriber +{ +public: + virtual ~IMessageSubscriber() { } + virtual void HandleMessage( const Message &msg ) = 0; + void ClearMessages( const RString sMessage = "" ); + +private: + friend class MessageManager; +}; + +class MessageSubscriber : public IMessageSubscriber +{ +public: + MessageSubscriber(): m_vsSubscribedTo() {} + MessageSubscriber( const MessageSubscriber &cpy ); + MessageSubscriber &operator=(const MessageSubscriber &cpy); + + // + // Messages + // + void SubscribeToMessage( MessageID message ); // will automatically unsubscribe + void SubscribeToMessage( const RString &sMessageName ); // will automatically unsubscribe + + void UnsubscribeAll(); + +private: + vector m_vsSubscribedTo; +}; + +/** @brief Deliver messages to any part of the program as needed. */ +class MessageManager +{ +public: + MessageManager(); + ~MessageManager(); + + void Subscribe( IMessageSubscriber* pSubscriber, const RString& sMessage ); + void Subscribe( IMessageSubscriber* pSubscriber, MessageID m ); + void Unsubscribe( IMessageSubscriber* pSubscriber, const RString& sMessage ); + void Unsubscribe( IMessageSubscriber* pSubscriber, MessageID m ); + void Broadcast( Message &msg ) const; + void Broadcast( const RString& sMessage ) const; + void Broadcast( MessageID m ) const; + bool IsSubscribedToMessage( IMessageSubscriber* pSubscriber, const RString &sMessage ) const; + inline bool IsSubscribedToMessage( IMessageSubscriber* pSubscriber, MessageID message ) const { return IsSubscribedToMessage( pSubscriber, MessageIDToString(message) ); } + + // Lua + void PushSelf( lua_State *L ); +}; + +extern MessageManager* MESSAGEMAN; // global and accessable from anywhere in our program + +template +class BroadcastOnChange +{ +private: + MessageID mSendWhenChanged; + T val; + +public: + explicit BroadcastOnChange( MessageID m ) { mSendWhenChanged = m; } + const T Get() const { return val; } + void Set( T t ) { val = t; MESSAGEMAN->Broadcast( MessageIDToString(mSendWhenChanged) ); } + operator T () const { return val; } + bool operator == ( const T &other ) const { return val == other; } + bool operator != ( const T &other ) const { return val != other; } +}; + +/** @brief Utilities for working with Lua. */ +namespace LuaHelpers +{ + template void Push( lua_State *L, const BroadcastOnChange &Object ) + { + LuaHelpers::Push( L, Object.Get() ); + } +} + +template +class BroadcastOnChange1D +{ +private: + typedef BroadcastOnChange MyType; + vector val; +public: + explicit BroadcastOnChange1D( MessageID m ) + { + for( unsigned i=0; i((MessageID)(m+i)) ); + } + const BroadcastOnChange& operator[]( unsigned i ) const { return val[i]; } + BroadcastOnChange& operator[]( unsigned i ) { return val[i]; } +}; + +template +class BroadcastOnChangePtr +{ +private: + MessageID mSendWhenChanged; + T *val; +public: + explicit BroadcastOnChangePtr( MessageID m ) { mSendWhenChanged = m; val = nullptr; } + T* Get() const { return val; } + void Set( T* t ) { val = t; if(MESSAGEMAN) MESSAGEMAN->Broadcast( MessageIDToString(mSendWhenChanged) ); } + /* This is only intended to be used for setting temporary values; always + * restore the original value when finished, so listeners don't get confused + * due to missing a message. */ + void SetWithoutBroadcast( T* t ) { val = t; } + operator T* () const { return val; } + T* operator->() const { return val; } +}; + +template +class BroadcastOnChangePtr1D +{ +private: + typedef BroadcastOnChangePtr MyType; + vector val; +public: + explicit BroadcastOnChangePtr1D( MessageID m ) + { + for( unsigned i=0; i((MessageID)(m+i)) ); + } + const BroadcastOnChangePtr& operator[]( unsigned i ) const { return val[i]; } + BroadcastOnChangePtr& operator[]( unsigned i ) { return val[i]; } +}; + +#endif + +/* + * (c) 2003-2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/Model.cpp b/src/Model.cpp index 71d9af2e62..16032b8259 100644 --- a/src/Model.cpp +++ b/src/Model.cpp @@ -24,13 +24,13 @@ Model::Model() m_bTextureWrapping = true; SetUseZBuffer( true ); SetCullMode( CULL_BACK ); - m_pGeometry = NULL; - m_pCurAnimation = NULL; + m_pGeometry = nullptr; + m_pCurAnimation = nullptr; m_fDefaultAnimationRate = 1; m_fCurAnimationRate = 1; m_bLoop = true; m_bDrawCelShaded = false; - m_pTempGeometry = NULL; + m_pTempGeometry = nullptr; } Model::~Model() @@ -43,12 +43,12 @@ void Model::Clear() if( m_pGeometry ) { MODELMAN->UnloadModel( m_pGeometry ); - m_pGeometry = NULL; + m_pGeometry = nullptr; } m_vpBones.clear(); m_Materials.clear(); m_mapNameToAnimation.clear(); - m_pCurAnimation = NULL; + m_pCurAnimation = nullptr; if( m_pTempGeometry ) DISPLAY->DeleteCompiledGeometry( m_pTempGeometry ); @@ -607,7 +607,7 @@ void Model::SetBones( const msAnimation* pAnimation, float fFrame, vectorPositionKeys.size(); ++j ) { const msPositionKey *pPositionKey = &pBone->PositionKeys[j]; @@ -631,7 +631,7 @@ void Model::SetBones( const msAnimation* pAnimation, float fFrame, vectorPosition; // search for the adjacent rotation keys - const msRotationKey *pLastRotationKey = NULL, *pThisRotationKey = NULL; + const msRotationKey *pLastRotationKey = nullptr, *pThisRotationKey = nullptr; for( size_t j = 0; j < pBone->RotationKeys.size(); ++j ) { const msRotationKey *pRotationKey = &pBone->RotationKeys[j]; diff --git a/src/MusicWheel.cpp b/src/MusicWheel.cpp index b0c64bc0aa..c3d1d20592 100644 --- a/src/MusicWheel.cpp +++ b/src/MusicWheel.cpp @@ -187,7 +187,7 @@ void MusicWheel::BeginScreen() if( GAMESTATE->m_pCurSong != nullptr && GameState::GetNumStagesMultiplierForSong( GAMESTATE->m_pCurSong ) > GAMESTATE->GetSmallestNumStagesLeftForAnyHumanPlayer() ) { - GAMESTATE->m_pCurSong.Set( NULL ); + GAMESTATE->m_pCurSong.Set(nullptr); } /* Invalidate current Steps if it can't be played @@ -201,7 +201,7 @@ void MusicWheel::BeginScreen() SongUtil::GetPlayableSteps( GAMESTATE->m_pCurSong, vpPossibleSteps ); bool bStepsIsPossible = find( vpPossibleSteps.begin(), vpPossibleSteps.end(), GAMESTATE->m_pCurSteps[p] ) == vpPossibleSteps.end(); if( !bStepsIsPossible ) - GAMESTATE->m_pCurSteps[p].Set( NULL ); + GAMESTATE->m_pCurSteps[p].Set(nullptr); } } @@ -910,7 +910,7 @@ void MusicWheel::FilterWheelItemDatas(vector &aUnFilteredD const int iMaxStagesForSong = GAMESTATE->GetSmallestNumStagesLeftForAnyHumanPlayer(); - Song *pExtraStageSong = NULL; + Song *pExtraStageSong = nullptr; if( GAMESTATE->IsAnExtraStage() ) { Steps *pSteps; @@ -1342,7 +1342,7 @@ void MusicWheel::SetOpenSection( RString group ) if ( REMIND_WHEEL_POSITIONS && HIDE_INACTIVE_SECTIONS ) m_viWheelPositions.resize( SONGMAN->GetNumSongGroups() ); - const WheelItemBaseData *old = NULL; + const WheelItemBaseData *old = nullptr; if( !m_CurWheelItemData.empty() ) old = GetCurWheelItemData(m_iSelection); diff --git a/src/MusicWheelItem.cpp b/src/MusicWheelItem.cpp index 2b2e4e028a..e64d243e5a 100644 --- a/src/MusicWheelItem.cpp +++ b/src/MusicWheelItem.cpp @@ -75,7 +75,7 @@ MusicWheelItem::MusicWheelItem( RString sType ): FOREACH_ENUM( MusicWheelItemType, i ) { - m_pText[i] = NULL; + m_pText[i] = nullptr; // Don't init text for Type_Song. It uses a TextBanner. if( i == MusicWheelItemType_Song ) @@ -147,7 +147,7 @@ MusicWheelItem::MusicWheelItem( const MusicWheelItem &cpy ): { if( cpy.m_pText[i] == nullptr ) { - m_pText[i] = NULL; + m_pText[i] = nullptr; } else { @@ -345,7 +345,7 @@ void MusicWheelItem::RefreshGrades() Profile *pProfile = PROFILEMAN->GetProfile(ps); - HighScoreList *pHSL = NULL; + HighScoreList *pHSL = nullptr; if( PROFILEMAN->IsPersistentProfile(ps) && dc != Difficulty_Invalid ) { if( pWID->m_pSong ) diff --git a/src/MusicWheelItem.h b/src/MusicWheelItem.h index 6155e24d70..bfc94a3abf 100644 --- a/src/MusicWheelItem.h +++ b/src/MusicWheelItem.h @@ -1,110 +1,110 @@ -#ifndef MUSIC_WHEEL_ITEM_H -#define MUSIC_WHEEL_ITEM_H - -#include "ActorFrame.h" -#include "BitmapText.h" -#include "WheelNotifyIcon.h" -#include "TextBanner.h" -#include "GameConstantsAndTypes.h" -#include "GameCommand.h" -#include "WheelItemBase.h" -#include "AutoActor.h" -#include "ThemeMetric.h" - -class Course; -class Song; - -struct MusicWheelItemData; - -enum MusicWheelItemType -{ - MusicWheelItemType_Song, - MusicWheelItemType_SectionExpanded, - MusicWheelItemType_SectionCollapsed, - MusicWheelItemType_Roulette, - MusicWheelItemType_Course, - MusicWheelItemType_Sort, - MusicWheelItemType_Mode, - MusicWheelItemType_Random, - MusicWheelItemType_Portal, - MusicWheelItemType_Custom, - NUM_MusicWheelItemType, - MusicWheelItemType_Invalid, -}; -const RString& MusicWheelItemTypeToString( MusicWheelItemType i ); -/** @brief An item on the MusicWheel. */ -class MusicWheelItem : public WheelItemBase -{ -public: - MusicWheelItem(RString sType = "MusicWheelItem"); - MusicWheelItem( const MusicWheelItem &cpy ); - virtual ~MusicWheelItem(); - virtual MusicWheelItem *Copy() const { return new MusicWheelItem(*this); } - - virtual void LoadFromWheelItemData( const WheelItemBaseData* pWID, int iIndex, bool bHasFocus, int iDrawIndex ); - virtual void HandleMessage( const Message &msg ); - void RefreshGrades(); - -private: - ThemeMetric GRADES_SHOW_MACHINE; - - AutoActor m_sprColorPart[NUM_MusicWheelItemType]; - AutoActor m_sprNormalPart[NUM_MusicWheelItemType]; - AutoActor m_sprOverPart[NUM_MusicWheelItemType]; - - TextBanner m_TextBanner; // used by Type_Song instead of m_pText - BitmapText *m_pText[NUM_MusicWheelItemType]; - BitmapText *m_pTextSectionCount; - - WheelNotifyIcon m_WheelNotifyIcon; - AutoActor m_pGradeDisplay[NUM_PLAYERS]; -}; - -struct MusicWheelItemData : public WheelItemBaseData -{ - MusicWheelItemData() : m_pCourse(NULL), m_pSong(NULL), m_Flags(), - m_iSectionCount(0), m_sLabel(""), m_pAction() { } - MusicWheelItemData( WheelItemDataType type, Song* pSong, - RString sSectionName, Course* pCourse, - RageColor color, int iSectionCount ); - - Course* m_pCourse; - Song* m_pSong; - WheelNotifyIcon::Flags m_Flags; - - // for TYPE_SECTION - int m_iSectionCount; - - // for TYPE_SORT - RString m_sLabel; - HiddenPtr m_pAction; -}; - -#endif - -/** - * @file - * @author Chris Danford, Chris Gomez, Glenn Maynard (c) 2001-2004 - * @section LICENSE - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef MUSIC_WHEEL_ITEM_H +#define MUSIC_WHEEL_ITEM_H + +#include "ActorFrame.h" +#include "BitmapText.h" +#include "WheelNotifyIcon.h" +#include "TextBanner.h" +#include "GameConstantsAndTypes.h" +#include "GameCommand.h" +#include "WheelItemBase.h" +#include "AutoActor.h" +#include "ThemeMetric.h" + +class Course; +class Song; + +struct MusicWheelItemData; + +enum MusicWheelItemType +{ + MusicWheelItemType_Song, + MusicWheelItemType_SectionExpanded, + MusicWheelItemType_SectionCollapsed, + MusicWheelItemType_Roulette, + MusicWheelItemType_Course, + MusicWheelItemType_Sort, + MusicWheelItemType_Mode, + MusicWheelItemType_Random, + MusicWheelItemType_Portal, + MusicWheelItemType_Custom, + NUM_MusicWheelItemType, + MusicWheelItemType_Invalid, +}; +const RString& MusicWheelItemTypeToString( MusicWheelItemType i ); +/** @brief An item on the MusicWheel. */ +class MusicWheelItem : public WheelItemBase +{ +public: + MusicWheelItem(RString sType = "MusicWheelItem"); + MusicWheelItem( const MusicWheelItem &cpy ); + virtual ~MusicWheelItem(); + virtual MusicWheelItem *Copy() const { return new MusicWheelItem(*this); } + + virtual void LoadFromWheelItemData( const WheelItemBaseData* pWID, int iIndex, bool bHasFocus, int iDrawIndex ); + virtual void HandleMessage( const Message &msg ); + void RefreshGrades(); + +private: + ThemeMetric GRADES_SHOW_MACHINE; + + AutoActor m_sprColorPart[NUM_MusicWheelItemType]; + AutoActor m_sprNormalPart[NUM_MusicWheelItemType]; + AutoActor m_sprOverPart[NUM_MusicWheelItemType]; + + TextBanner m_TextBanner; // used by Type_Song instead of m_pText + BitmapText *m_pText[NUM_MusicWheelItemType]; + BitmapText *m_pTextSectionCount; + + WheelNotifyIcon m_WheelNotifyIcon; + AutoActor m_pGradeDisplay[NUM_PLAYERS]; +}; + +struct MusicWheelItemData : public WheelItemBaseData +{ + MusicWheelItemData() : m_pCourse(nullptr), m_pSong(nullptr), m_Flags(), + m_iSectionCount(0), m_sLabel(""), m_pAction() { } + MusicWheelItemData( WheelItemDataType type, Song* pSong, + RString sSectionName, Course* pCourse, + RageColor color, int iSectionCount ); + + Course* m_pCourse; + Song* m_pSong; + WheelNotifyIcon::Flags m_Flags; + + // for TYPE_SECTION + int m_iSectionCount; + + // for TYPE_SORT + RString m_sLabel; + HiddenPtr m_pAction; +}; + +#endif + +/** + * @file + * @author Chris Danford, Chris Gomez, Glenn Maynard (c) 2001-2004 + * @section LICENSE + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/NetworkSyncManager.cpp b/src/NetworkSyncManager.cpp index 6b9b133c2f..4014c14cd6 100644 --- a/src/NetworkSyncManager.cpp +++ b/src/NetworkSyncManager.cpp @@ -68,8 +68,8 @@ int NetworkSyncManager::GetSMOnlineSalt() static LocalizedString INITIALIZING_CLIENT_NETWORK ( "NetworkSyncManager", "Initializing Client Network..." ); NetworkSyncManager::NetworkSyncManager( LoadingWindow *ld ) { - LANserver = NULL; //So we know if it has been created yet - BroadcastReception = NULL; + LANserver = nullptr; //So we know if it has been created yet + BroadcastReception = nullptr; ld->SetText( INITIALIZING_CLIENT_NETWORK ); NetPlayerClient = new EzSockets; diff --git a/src/NetworkSyncManager.h b/src/NetworkSyncManager.h index 206ac3f408..8843be3954 100644 --- a/src/NetworkSyncManager.h +++ b/src/NetworkSyncManager.h @@ -1,241 +1,241 @@ -#ifndef NetworkSyncManager_H -#define NetworkSyncManager_H - -#include "PlayerNumber.h" -#include "Difficulty.h" -#include - -class LoadingWindow; - -const int NETPROTOCOLVERSION=3; -const int NETMAXBUFFERSIZE=1020; //1024 - 4 bytes for EzSockets -const int NETNUMTAPSCORES=8; - -// [SMLClientCommands name] -enum NSCommand -{ - NSCPing = 0, - NSCPingR, // 1 [SMLC_PingR] - NSCHello, // 2 [SMLC_Hello] - NSCGSR, // 3 [SMLC_GameStart] - NSCGON, // 4 [SMLC_GameOver] - NSCGSU, // 5 [SMLC_GameStatusUpdate] - NSCSU, // 6 [SMLC_StyleUpdate] - NSCCM, // 7 [SMLC_Chat] - NSCRSG, // 8 [SMLC_RequestStart] - NSCUUL, // 9 [SMLC_Reserved1] - NSCSMS, // 10 [SMLC_MusicSelect] - NSCUPOpts, // 11 [SMLC_PlayerOpts] - NSCSMOnline, // 12 [SMLC_SMO] - NSCFormatted, // 13 [SMLC_RESERVED1] - NSCAttack, // 14 [SMLC_RESERVED2] - NUM_NS_COMMANDS -}; - -enum SMOStepType -{ - SMOST_UNUSED = 0, - SMOST_HITMINE, - SMOST_AVOIDMINE, - SMOST_MISS, - SMOST_W5, - SMOST_W4, - SMOST_W3, - SMOST_W2, - SMOST_W1, - SMOST_LETGO, - SMOST_HELD - /* - ,SMOST_CHECKPOINTMISS, - SMOST_CHECKPOINTHIT - */ -}; - -const NSCommand NSServerOffset = (NSCommand)128; - -// TODO: Provide a Lua binding that gives access to this data. -aj -struct EndOfGame_PlayerData -{ - int name; - int score; - int grade; - Difficulty difficulty; - int tapScores[NETNUMTAPSCORES]; //This will be a const soon enough - RString playerOptions; -}; - -enum NSScoreBoardColumn -{ - NSSB_NAMES=0, - NSSB_COMBO, - NSSB_GRADE, - NUM_NSScoreBoardColumn, - NSScoreBoardColumn_Invalid -}; -/** @brief A special foreach loop going through each NSScoreBoardColumn. */ -#define FOREACH_NSScoreBoardColumn( sc ) FOREACH_ENUM( NSScoreBoardColumn, sc ) - -struct NetServerInfo -{ - RString Name; - RString Address; -}; - -class EzSockets; -class StepManiaLanServer; - -class PacketFunctions -{ -public: - unsigned char Data[NETMAXBUFFERSIZE]; //Data - int Position; //Other info (Used for following functions) - int size; //When sending these pacs, Position should - //be used; NOT size. - - //Commands used to operate on NetPackets - uint8_t Read1(); - uint16_t Read2(); - uint32_t Read4(); - RString ReadNT(); - - void Write1( uint8_t Data ); - void Write2( uint16_t Data ); - void Write4( uint32_t Data ); - void WriteNT( const RString& Data ); - - void ClearPacket(); -}; -/** @brief Uses ezsockets for primitive song syncing and score reporting. */ -class NetworkSyncManager -{ -public: - NetworkSyncManager( LoadingWindow *ld = NULL ); - ~NetworkSyncManager(); - - // If "useSMserver" then send score to server - void ReportScore( int playerID, int step, int score, int combo, float offset ); - void ReportSongOver(); - void ReportStyle(); // Report style, players, and names - void ReportNSSOnOff( int i ); // Report song selection screen on/off - void StartRequest( short position ); // Request a start; Block until granted. - RString GetServerName(); - - // SMOnline stuff - void SendSMOnline( ); - - bool Connect( const RString& addy, unsigned short port ); - - void PostStartUp( const RString& ServerIP ); - - void CloseConnection(); - - void DisplayStartupStatus(); // Notify user if connect attempt was successful or not. - - int m_playerLife[NUM_PLAYERS]; // Life (used for sending to server) - - void Update( float fDeltaTime ); - - bool useSMserver; - bool isSMOnline; - bool isSMOLoggedIn[NUM_PLAYERS]; - - vector m_PlayerStatus; - int m_ActivePlayers; - vector m_ActivePlayer; - vector m_PlayerNames; - - // Used for ScreenNetEvaluation - vector m_EvalPlayerData; - - // Used together: - bool ChangedScoreboard(int Column); // Returns true if scoreboard changed since function was last called. - RString m_Scoreboard[NUM_NSScoreBoardColumn]; - - // Used for chatting - void SendChat(const RString& message); - RString m_WaitingChat; - - // Used for options - void ReportPlayerOptions(); - - // Used for song checking/changing - RString m_sMainTitle; - RString m_sArtist; - RString m_sSubTitle; - int m_iSelectMode; - void SelectUserSong(); - - RString m_sChatText; - - PacketFunctions m_SMOnlinePacket; - - StepManiaLanServer *LANserver; - - int GetSMOnlineSalt(); - - RString MD5Hex( const RString &sInput ); - - void GetListOfLANServers( vector& AllServers ); - - // Aldo: Please move this method to a new class, I didn't want to create new files because I don't know how to properly update the files for each platform. - // I preferred to misplace code rather than cause unneeded headaches to non-windows users, although it would be nice to have in the wiki which files to - // update when adding new files. - static unsigned long GetCurrentSMBuild( LoadingWindow* ld ); -private: -#if !defined(WITHOUT_NETWORKING) - - void ProcessInput(); - SMOStepType TranslateStepType(int score); - void StartUp(); - - int m_playerID; // Currently unused, but need to stay - int m_step; - int m_score; - int m_combo; - - int m_startupStatus; // Used to see if attempt was successful or not. - int m_iSalt; - - bool m_scoreboardchange[NUM_NSScoreBoardColumn]; - - RString m_ServerName; - - EzSockets *NetPlayerClient; - EzSockets *BroadcastReception; - - vector m_vAllLANServers; - - int m_ServerVersion; // ServerVersion - - PacketFunctions m_packet; -#endif -}; - -extern NetworkSyncManager *NSMAN; - -#endif - -/* - * (c) 2003-2004 Charles Lohr, Joshua Allen - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef NetworkSyncManager_H +#define NetworkSyncManager_H + +#include "PlayerNumber.h" +#include "Difficulty.h" +#include + +class LoadingWindow; + +const int NETPROTOCOLVERSION=3; +const int NETMAXBUFFERSIZE=1020; //1024 - 4 bytes for EzSockets +const int NETNUMTAPSCORES=8; + +// [SMLClientCommands name] +enum NSCommand +{ + NSCPing = 0, + NSCPingR, // 1 [SMLC_PingR] + NSCHello, // 2 [SMLC_Hello] + NSCGSR, // 3 [SMLC_GameStart] + NSCGON, // 4 [SMLC_GameOver] + NSCGSU, // 5 [SMLC_GameStatusUpdate] + NSCSU, // 6 [SMLC_StyleUpdate] + NSCCM, // 7 [SMLC_Chat] + NSCRSG, // 8 [SMLC_RequestStart] + NSCUUL, // 9 [SMLC_Reserved1] + NSCSMS, // 10 [SMLC_MusicSelect] + NSCUPOpts, // 11 [SMLC_PlayerOpts] + NSCSMOnline, // 12 [SMLC_SMO] + NSCFormatted, // 13 [SMLC_RESERVED1] + NSCAttack, // 14 [SMLC_RESERVED2] + NUM_NS_COMMANDS +}; + +enum SMOStepType +{ + SMOST_UNUSED = 0, + SMOST_HITMINE, + SMOST_AVOIDMINE, + SMOST_MISS, + SMOST_W5, + SMOST_W4, + SMOST_W3, + SMOST_W2, + SMOST_W1, + SMOST_LETGO, + SMOST_HELD + /* + ,SMOST_CHECKPOINTMISS, + SMOST_CHECKPOINTHIT + */ +}; + +const NSCommand NSServerOffset = (NSCommand)128; + +// TODO: Provide a Lua binding that gives access to this data. -aj +struct EndOfGame_PlayerData +{ + int name; + int score; + int grade; + Difficulty difficulty; + int tapScores[NETNUMTAPSCORES]; //This will be a const soon enough + RString playerOptions; +}; + +enum NSScoreBoardColumn +{ + NSSB_NAMES=0, + NSSB_COMBO, + NSSB_GRADE, + NUM_NSScoreBoardColumn, + NSScoreBoardColumn_Invalid +}; +/** @brief A special foreach loop going through each NSScoreBoardColumn. */ +#define FOREACH_NSScoreBoardColumn( sc ) FOREACH_ENUM( NSScoreBoardColumn, sc ) + +struct NetServerInfo +{ + RString Name; + RString Address; +}; + +class EzSockets; +class StepManiaLanServer; + +class PacketFunctions +{ +public: + unsigned char Data[NETMAXBUFFERSIZE]; //Data + int Position; //Other info (Used for following functions) + int size; //When sending these pacs, Position should + //be used; NOT size. + + //Commands used to operate on NetPackets + uint8_t Read1(); + uint16_t Read2(); + uint32_t Read4(); + RString ReadNT(); + + void Write1( uint8_t Data ); + void Write2( uint16_t Data ); + void Write4( uint32_t Data ); + void WriteNT( const RString& Data ); + + void ClearPacket(); +}; +/** @brief Uses ezsockets for primitive song syncing and score reporting. */ +class NetworkSyncManager +{ +public: + NetworkSyncManager( LoadingWindow *ld = nullptr ); + ~NetworkSyncManager(); + + // If "useSMserver" then send score to server + void ReportScore( int playerID, int step, int score, int combo, float offset ); + void ReportSongOver(); + void ReportStyle(); // Report style, players, and names + void ReportNSSOnOff( int i ); // Report song selection screen on/off + void StartRequest( short position ); // Request a start; Block until granted. + RString GetServerName(); + + // SMOnline stuff + void SendSMOnline( ); + + bool Connect( const RString& addy, unsigned short port ); + + void PostStartUp( const RString& ServerIP ); + + void CloseConnection(); + + void DisplayStartupStatus(); // Notify user if connect attempt was successful or not. + + int m_playerLife[NUM_PLAYERS]; // Life (used for sending to server) + + void Update( float fDeltaTime ); + + bool useSMserver; + bool isSMOnline; + bool isSMOLoggedIn[NUM_PLAYERS]; + + vector m_PlayerStatus; + int m_ActivePlayers; + vector m_ActivePlayer; + vector m_PlayerNames; + + // Used for ScreenNetEvaluation + vector m_EvalPlayerData; + + // Used together: + bool ChangedScoreboard(int Column); // Returns true if scoreboard changed since function was last called. + RString m_Scoreboard[NUM_NSScoreBoardColumn]; + + // Used for chatting + void SendChat(const RString& message); + RString m_WaitingChat; + + // Used for options + void ReportPlayerOptions(); + + // Used for song checking/changing + RString m_sMainTitle; + RString m_sArtist; + RString m_sSubTitle; + int m_iSelectMode; + void SelectUserSong(); + + RString m_sChatText; + + PacketFunctions m_SMOnlinePacket; + + StepManiaLanServer *LANserver; + + int GetSMOnlineSalt(); + + RString MD5Hex( const RString &sInput ); + + void GetListOfLANServers( vector& AllServers ); + + // Aldo: Please move this method to a new class, I didn't want to create new files because I don't know how to properly update the files for each platform. + // I preferred to misplace code rather than cause unneeded headaches to non-windows users, although it would be nice to have in the wiki which files to + // update when adding new files. + static unsigned long GetCurrentSMBuild( LoadingWindow* ld ); +private: +#if !defined(WITHOUT_NETWORKING) + + void ProcessInput(); + SMOStepType TranslateStepType(int score); + void StartUp(); + + int m_playerID; // Currently unused, but need to stay + int m_step; + int m_score; + int m_combo; + + int m_startupStatus; // Used to see if attempt was successful or not. + int m_iSalt; + + bool m_scoreboardchange[NUM_NSScoreBoardColumn]; + + RString m_ServerName; + + EzSockets *NetPlayerClient; + EzSockets *BroadcastReception; + + vector m_vAllLANServers; + + int m_ServerVersion; // ServerVersion + + PacketFunctions m_packet; +#endif +}; + +extern NetworkSyncManager *NSMAN; + +#endif + +/* + * (c) 2003-2004 Charles Lohr, Joshua Allen + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/NoteData.h b/src/NoteData.h index 6a7b4bf1d0..19f4e1ab50 100644 --- a/src/NoteData.h +++ b/src/NoteData.h @@ -1,374 +1,374 @@ -#ifndef NOTE_DATA_H -#define NOTE_DATA_H - -#include "NoteTypes.h" -#include -#include -#include - -/** @brief Act on each non empty row in the specific track. */ -#define FOREACH_NONEMPTY_ROW_IN_TRACK( nd, track, row ) \ - for( int row = -1; (nd).GetNextTapNoteRowForTrack(track,row); ) -/** @brief Act on each non empty row in the specified track within the specified range. */ -#define FOREACH_NONEMPTY_ROW_IN_TRACK_RANGE( nd, track, row, start, last ) \ - for( int row = start-1; (nd).GetNextTapNoteRowForTrack(track,row) && row < (last); ) -/** @brief Act on each non empty row in the specified track within the specified range, - going in reverse order. */ -#define FOREACH_NONEMPTY_ROW_IN_TRACK_RANGE_REVERSE( nd, track, row, start, last ) \ - for( int row = last; (nd).GetPrevTapNoteRowForTrack(track,row) && row >= (start); ) -/** @brief Act on each non empty row for all of the tracks. */ -#define FOREACH_NONEMPTY_ROW_ALL_TRACKS( nd, row ) \ - for( int row = -1; (nd).GetNextTapNoteRowForAllTracks(row); ) -/** @brief Act on each non empty row for all of the tracks within the specified range. */ -#define FOREACH_NONEMPTY_ROW_ALL_TRACKS_RANGE( nd, row, start, last ) \ - for( int row = start-1; (nd).GetNextTapNoteRowForAllTracks(row) && row < (last); ) - -/** @brief Holds data about the notes that the player is supposed to hit. */ -class NoteData -{ -public: - typedef map TrackMap; - typedef map::iterator iterator; - typedef map::const_iterator const_iterator; - typedef map::reverse_iterator reverse_iterator; - typedef map::const_reverse_iterator const_reverse_iterator; - - NoteData(): m_TapNotes() {} - - iterator begin( int iTrack ) { return m_TapNotes[iTrack].begin(); } - const_iterator begin( int iTrack ) const { return m_TapNotes[iTrack].begin(); } - reverse_iterator rbegin( int iTrack ) { return m_TapNotes[iTrack].rbegin(); } - const_reverse_iterator rbegin( int iTrack ) const { return m_TapNotes[iTrack].rbegin(); } - iterator end( int iTrack ) { return m_TapNotes[iTrack].end(); } - const_iterator end( int iTrack ) const { return m_TapNotes[iTrack].end(); } - reverse_iterator rend( int iTrack ) { return m_TapNotes[iTrack].rend(); } - const_reverse_iterator rend( int iTrack ) const { return m_TapNotes[iTrack].rend(); } - iterator lower_bound( int iTrack, int iRow ) { return m_TapNotes[iTrack].lower_bound( iRow ); } - const_iterator lower_bound( int iTrack, int iRow ) const { return m_TapNotes[iTrack].lower_bound( iRow ); } - iterator upper_bound( int iTrack, int iRow ) { return m_TapNotes[iTrack].upper_bound( iRow ); } - const_iterator upper_bound( int iTrack, int iRow ) const { return m_TapNotes[iTrack].upper_bound( iRow ); } - void swap( NoteData &nd ) { m_TapNotes.swap( nd.m_TapNotes ); } - - - // This is ugly to make it templated but I don't want to have to write the same class twice. - template - class _all_tracks_iterator - { - ND *m_pNoteData; - vector m_vBeginIters; - - /* There isn't a "past the beginning" iterator so this is hard to make a true bidirectional iterator. - * Use the "past the end" iterator in place of the "past the beginning" iterator when in reverse. */ - vector m_vCurrentIters; - - vector m_vEndIters; - int m_iTrack; - bool m_bReverse; - - void Find( bool bReverse ); - public: - _all_tracks_iterator( ND &nd, int iStartRow, int iEndRow, bool bReverse, bool bInclusive ); - _all_tracks_iterator( const _all_tracks_iterator &other ); - _all_tracks_iterator &operator++(); // preincrement - _all_tracks_iterator operator++( int dummy ); // postincrement - //_all_tracks_iterator &operator--(); // predecrement - //_all_tracks_iterator operator--( int dummy ); // postdecrement - inline int Track() const { return m_iTrack; } - inline int Row() const { return m_vCurrentIters[m_iTrack]->first; } - inline bool IsAtEnd() const { return m_iTrack == -1; } - inline iter GetIter( int iTrack ) const { return m_vCurrentIters[iTrack]; } - inline TN &operator*() { DEBUG_ASSERT( !IsAtEnd() ); return m_vCurrentIters[m_iTrack]->second; } - inline TN *operator->() { DEBUG_ASSERT( !IsAtEnd() ); return &m_vCurrentIters[m_iTrack]->second; } - inline const TN &operator*() const { DEBUG_ASSERT( !IsAtEnd() ); return m_vCurrentIters[m_iTrack]->second; } - inline const TN *operator->() const { DEBUG_ASSERT( !IsAtEnd() ); return &m_vCurrentIters[m_iTrack]->second; } - }; - typedef _all_tracks_iterator all_tracks_iterator; - typedef _all_tracks_iterator all_tracks_const_iterator; - typedef all_tracks_iterator all_tracks_reverse_iterator; - typedef all_tracks_const_iterator all_tracks_const_reverse_iterator; -private: - // There's no point in inserting empty notes into the map. - // Any blank space in the map is defined to be empty. - vector m_TapNotes; - - /** - * @brief Determine whether this note is for Player 1 or Player 2. - * @param track the track/column the note is in. - * @param tn the note in question. Required for routine mode. - * @return true if it's for player 1, false for player 2. */ - bool IsPlayer1(const int track, const TapNote &tn) const; - - /** - * @brief Determine if the note in question should be counted as a tap. - * @param tn the note in question. - * @param row the row it lives in. - * @return true if it's a tap, false otherwise. */ - bool IsTap(const TapNote &tn, const int row) const; - - /** - * @brief Determine if the note in question should be counted as a mine. - * @param tn the note in question. - * @param row the row it lives in. - * @return true if it's a mine, false otherwise. */ - bool IsMine(const TapNote &tn, const int row) const; - - /** - * @brief Determine if the note in question should be counted as a lift. - * @param tn the note in question. - * @param row the row it lives in. - * @return true if it's a lift, false otherwise. */ - bool IsLift(const TapNote &tn, const int row) const; - - /** - * @brief Determine if the note in question should be counted as a fake. - * @param tn the note in question. - * @param row the row it lives in. - * @return true if it's a fake, false otherwise. */ - bool IsFake(const TapNote &tn, const int row) const; - - pair GetNumRowsWithSimultaneousTapsTwoPlayer(int minTaps = 2, - int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - -public: - void Init(); - - int GetNumTracks() const { return m_TapNotes.size(); } - void SetNumTracks( int iNewNumTracks ); - bool IsComposite() const; - bool operator==( const NoteData &nd ) const { return m_TapNotes == nd.m_TapNotes; } - bool operator!=( const NoteData &nd ) const { return m_TapNotes != nd.m_TapNotes; } - - /* Return the note at the given track and row. Row may be out of - * range; pretend the song goes on with TAP_EMPTYs indefinitely. */ - inline const TapNote &GetTapNote( unsigned track, int row ) const - { - const TrackMap &mapTrack = m_TapNotes[track]; - TrackMap::const_iterator iter = mapTrack.find( row ); - if( iter != mapTrack.end() ) - return iter->second; - else - return TAP_EMPTY; - } - - - inline iterator FindTapNote( unsigned iTrack, int iRow ) { return m_TapNotes[iTrack].find( iRow ); } - inline const_iterator FindTapNote( unsigned iTrack, int iRow ) const { return m_TapNotes[iTrack].find( iRow ); } - void RemoveTapNote( unsigned iTrack, iterator it ) { m_TapNotes[iTrack].erase( it ); } - - /** - * @brief Return an iterator range for [rowBegin,rowEnd). - * - * This can be used to efficiently iterate trackwise over a range of notes. - * It's like FOREACH_NONEMPTY_ROW_IN_TRACK_RANGE, except it only requires - * two map searches (iterating is constant time), but the iterators will - * become invalid if the notes they represent disappear, so you need to - * pay attention to how you modify the data. - * @param iTrack the column to use. - * @param iStartRow the starting point. - * @param iEndRow the ending point. - * @param begin the eventual beginning point of the range. - * @param end the eventual end point of the range. */ - void GetTapNoteRange(int iTrack, int iStartRow, int iEndRow, - TrackMap::const_iterator &begin, TrackMap::const_iterator &end ) const; - /** - * @brief Return a constant iterator range for [rowBegin,rowEnd). - * @param iTrack the column to use. - * @param iStartRow the starting point. - * @param iEndRow the ending point. - * @param begin the eventual beginning point of the range. - * @param end the eventual end point of the range. */ - void GetTapNoteRange( int iTrack, int iStartRow, int iEndRow, TrackMap::iterator &begin, TrackMap::iterator &end ); - all_tracks_iterator GetTapNoteRangeAllTracks( int iStartRow, int iEndRow, bool bInclusive = false ) - { - return all_tracks_iterator( *this, iStartRow, iEndRow, false, bInclusive ); - } - all_tracks_const_iterator GetTapNoteRangeAllTracks( int iStartRow, int iEndRow, bool bInclusive = false ) const - { - return all_tracks_const_iterator( *this, iStartRow, iEndRow, false, bInclusive ); - } - all_tracks_reverse_iterator GetTapNoteRangeAllTracksReverse( int iStartRow, int iEndRow, bool bInclusive = false ) - { - return all_tracks_iterator(*this, iStartRow, iEndRow, true, bInclusive ); - } - all_tracks_const_reverse_iterator GetTapNoteRangeAllTracksReverse( int iStartRow, int iEndRow, bool bInclusive = false ) const - { - return all_tracks_const_iterator(*this, iStartRow, iEndRow, true, bInclusive ); - } - - /* Return an iterator range include iStartRow to iEndRow. Extend the range to include - * hold notes overlapping the boundary. */ - void GetTapNoteRangeInclusive(int iTrack, int iStartRow, int iEndRow, - TrackMap::const_iterator &begin, TrackMap::const_iterator &end, bool bIncludeAdjacent=false ) const; - void GetTapNoteRangeInclusive(int iTrack, int iStartRow, int iEndRow, - TrackMap::iterator &begin, TrackMap::iterator &end, bool bIncludeAdjacent=false ); - - /* Return an iterator range include iStartRow to iEndRow. Shrink the range to exclude - * hold notes overlapping the boundary. */ - void GetTapNoteRangeExclusive(int iTrack, int iStartRow, int iEndRow, - TrackMap::const_iterator &begin, TrackMap::const_iterator &end ) const; - void GetTapNoteRangeExclusive(int iTrack, int iStartRow, int iEndRow, - TrackMap::iterator &begin, TrackMap::iterator &end ); - - - /* Returns the row of the first TapNote on the track that has a row greater than rowInOut. */ - bool GetNextTapNoteRowForTrack( int track, int &rowInOut ) const; - bool GetNextTapNoteRowForAllTracks( int &rowInOut ) const; - bool GetPrevTapNoteRowForTrack( int track, int &rowInOut ) const; - bool GetPrevTapNoteRowForAllTracks( int &rowInOut ) const; - - void MoveTapNoteTrack( int dest, int src ); - void SetTapNote( int track, int row, const TapNote& tn ); - /** - * @brief Add a hold note, merging other overlapping holds and destroying - * tap notes underneath. - * @param iTrack the column to work with. - * @param iStartRow the starting row. - * @param iEndRow the ending row. - * @param tn the tap note. */ - void AddHoldNote(int iTrack, - int iStartRow, - int iEndRow, - TapNote tn ); - - void ClearRangeForTrack( int rowBegin, int rowEnd, int iTrack ); - void ClearRange( int rowBegin, int rowEnd ); - void ClearAll(); - void CopyRange( const NoteData& from, int rowFromBegin, int rowFromEnd, int rowToBegin = 0 ); - void CopyAll( const NoteData& from ); - - bool IsRowEmpty( int row ) const; - bool IsRangeEmpty( int track, int rowBegin, int rowEnd ) const; - int GetNumTapNonEmptyTracks( int row ) const; - void GetTapNonEmptyTracks( int row, set& addTo ) const; - bool GetTapFirstNonEmptyTrack( int row, int &iNonEmptyTrackOut ) const; // return false if no non-empty tracks at row - bool GetTapFirstEmptyTrack( int row, int &iEmptyTrackOut ) const; // return false if no non-empty tracks at row - bool GetTapLastEmptyTrack( int row, int &iEmptyTrackOut ) const; // return false if no empty tracks at row - int GetNumTracksWithTap( int row ) const; - int GetNumTracksWithTapOrHoldHead( int row ) const; - int GetFirstTrackWithTap( int row ) const; - int GetFirstTrackWithTapOrHoldHead( int row ) const; - int GetLastTrackWithTapOrHoldHead( int row ) const; - - inline bool IsThereATapAtRow( int row ) const { return GetFirstTrackWithTap( row ) != -1; } - inline bool IsThereATapOrHoldHeadAtRow( int row ) const { return GetFirstTrackWithTapOrHoldHead( row ) != -1; } - void GetTracksHeldAtRow( int row, set& addTo ); - int GetNumTracksHeldAtRow( int row ); - - bool IsHoldNoteAtRow( int iTrack, int iRow, int *pHeadRow = NULL ) const; - bool IsHoldHeadOrBodyAtRow( int iTrack, int iRow, int *pHeadRow ) const; - - // statistics - bool IsEmpty() const; - bool IsTrackEmpty( int iTrack ) const { return m_TapNotes[iTrack].empty(); } - int GetFirstRow() const; // return the beat number of the first note - int GetLastRow() const; // return the beat number of the last note - float GetFirstBeat() const { return NoteRowToBeat( GetFirstRow() ); } - float GetLastBeat() const { return NoteRowToBeat( GetLastRow() ); } - int GetNumTapNotes( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - int GetNumTapNotesInRow( int iRow ) const; - int GetNumMines( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - int GetNumRowsWithTap( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - int GetNumRowsWithTapOrHoldHead( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - /* Optimization: for the default of start to end, use the second (faster). XXX: Second what? -- Steve */ - int GetNumHoldNotes( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - int GetNumRolls( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - - // Count rows that contain iMinTaps or more taps. - int GetNumRowsWithSimultaneousTaps( int iMinTaps, int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - int GetNumJumps( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const - { - return GetNumRowsWithSimultaneousTaps( 2, iStartIndex, iEndIndex ); - } - - - - // This row needs at least iMinSimultaneousPresses either tapped or held. - bool RowNeedsAtLeastSimultaneousPresses( int iMinSimultaneousPresses, int row ) const; - bool RowNeedsHands( int row ) const { return RowNeedsAtLeastSimultaneousPresses(3,row); } - - // Count rows that need iMinSimultaneousPresses either tapped or held. - int GetNumRowsWithSimultaneousPresses( int iMinSimultaneousPresses, int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - int GetNumHands( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const - { - return GetNumRowsWithSimultaneousPresses( 3, iStartIndex, iEndIndex ); - } - int GetNumQuads( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const - { - return GetNumRowsWithSimultaneousPresses( 4, iStartIndex, iEndIndex ); - } - - // and the other notetypes - int GetNumLifts( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - int GetNumFakes( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; - - // the couple/routine style variants of the above. - pair GetNumTapNotesTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - pair GetNumJumpsTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - pair GetNumHandsTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - pair GetNumQuadsTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - pair GetNumHoldNotesTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - pair GetNumMinesTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - pair GetNumRollsTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - pair GetNumLiftsTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - pair GetNumFakesTwoPlayer(int startRow = 0, - int endRow = MAX_NOTE_ROW) const; - - // Transformations - void LoadTransformed(const NoteData& original, - int iNewNumTracks, - const int iOriginalTrackToTakeFrom[] ); // -1 for iOriginalTracksToTakeFrom means no track - - // XML - XNode* CreateNode() const; - void LoadFromNode( const XNode* pNode ); -}; - -/** @brief Allow a quick way to swap notedata. */ -namespace std -{ - template<> inline void swap( NoteData &nd1, NoteData &nd2 ) { nd1.swap( nd2 ); } -} - -#endif - -/* - * (c) 2001-2004 Chris Danford, Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef NOTE_DATA_H +#define NOTE_DATA_H + +#include "NoteTypes.h" +#include +#include +#include + +/** @brief Act on each non empty row in the specific track. */ +#define FOREACH_NONEMPTY_ROW_IN_TRACK( nd, track, row ) \ + for( int row = -1; (nd).GetNextTapNoteRowForTrack(track,row); ) +/** @brief Act on each non empty row in the specified track within the specified range. */ +#define FOREACH_NONEMPTY_ROW_IN_TRACK_RANGE( nd, track, row, start, last ) \ + for( int row = start-1; (nd).GetNextTapNoteRowForTrack(track,row) && row < (last); ) +/** @brief Act on each non empty row in the specified track within the specified range, + going in reverse order. */ +#define FOREACH_NONEMPTY_ROW_IN_TRACK_RANGE_REVERSE( nd, track, row, start, last ) \ + for( int row = last; (nd).GetPrevTapNoteRowForTrack(track,row) && row >= (start); ) +/** @brief Act on each non empty row for all of the tracks. */ +#define FOREACH_NONEMPTY_ROW_ALL_TRACKS( nd, row ) \ + for( int row = -1; (nd).GetNextTapNoteRowForAllTracks(row); ) +/** @brief Act on each non empty row for all of the tracks within the specified range. */ +#define FOREACH_NONEMPTY_ROW_ALL_TRACKS_RANGE( nd, row, start, last ) \ + for( int row = start-1; (nd).GetNextTapNoteRowForAllTracks(row) && row < (last); ) + +/** @brief Holds data about the notes that the player is supposed to hit. */ +class NoteData +{ +public: + typedef map TrackMap; + typedef map::iterator iterator; + typedef map::const_iterator const_iterator; + typedef map::reverse_iterator reverse_iterator; + typedef map::const_reverse_iterator const_reverse_iterator; + + NoteData(): m_TapNotes() {} + + iterator begin( int iTrack ) { return m_TapNotes[iTrack].begin(); } + const_iterator begin( int iTrack ) const { return m_TapNotes[iTrack].begin(); } + reverse_iterator rbegin( int iTrack ) { return m_TapNotes[iTrack].rbegin(); } + const_reverse_iterator rbegin( int iTrack ) const { return m_TapNotes[iTrack].rbegin(); } + iterator end( int iTrack ) { return m_TapNotes[iTrack].end(); } + const_iterator end( int iTrack ) const { return m_TapNotes[iTrack].end(); } + reverse_iterator rend( int iTrack ) { return m_TapNotes[iTrack].rend(); } + const_reverse_iterator rend( int iTrack ) const { return m_TapNotes[iTrack].rend(); } + iterator lower_bound( int iTrack, int iRow ) { return m_TapNotes[iTrack].lower_bound( iRow ); } + const_iterator lower_bound( int iTrack, int iRow ) const { return m_TapNotes[iTrack].lower_bound( iRow ); } + iterator upper_bound( int iTrack, int iRow ) { return m_TapNotes[iTrack].upper_bound( iRow ); } + const_iterator upper_bound( int iTrack, int iRow ) const { return m_TapNotes[iTrack].upper_bound( iRow ); } + void swap( NoteData &nd ) { m_TapNotes.swap( nd.m_TapNotes ); } + + + // This is ugly to make it templated but I don't want to have to write the same class twice. + template + class _all_tracks_iterator + { + ND *m_pNoteData; + vector m_vBeginIters; + + /* There isn't a "past the beginning" iterator so this is hard to make a true bidirectional iterator. + * Use the "past the end" iterator in place of the "past the beginning" iterator when in reverse. */ + vector m_vCurrentIters; + + vector m_vEndIters; + int m_iTrack; + bool m_bReverse; + + void Find( bool bReverse ); + public: + _all_tracks_iterator( ND &nd, int iStartRow, int iEndRow, bool bReverse, bool bInclusive ); + _all_tracks_iterator( const _all_tracks_iterator &other ); + _all_tracks_iterator &operator++(); // preincrement + _all_tracks_iterator operator++( int dummy ); // postincrement + //_all_tracks_iterator &operator--(); // predecrement + //_all_tracks_iterator operator--( int dummy ); // postdecrement + inline int Track() const { return m_iTrack; } + inline int Row() const { return m_vCurrentIters[m_iTrack]->first; } + inline bool IsAtEnd() const { return m_iTrack == -1; } + inline iter GetIter( int iTrack ) const { return m_vCurrentIters[iTrack]; } + inline TN &operator*() { DEBUG_ASSERT( !IsAtEnd() ); return m_vCurrentIters[m_iTrack]->second; } + inline TN *operator->() { DEBUG_ASSERT( !IsAtEnd() ); return &m_vCurrentIters[m_iTrack]->second; } + inline const TN &operator*() const { DEBUG_ASSERT( !IsAtEnd() ); return m_vCurrentIters[m_iTrack]->second; } + inline const TN *operator->() const { DEBUG_ASSERT( !IsAtEnd() ); return &m_vCurrentIters[m_iTrack]->second; } + }; + typedef _all_tracks_iterator all_tracks_iterator; + typedef _all_tracks_iterator all_tracks_const_iterator; + typedef all_tracks_iterator all_tracks_reverse_iterator; + typedef all_tracks_const_iterator all_tracks_const_reverse_iterator; +private: + // There's no point in inserting empty notes into the map. + // Any blank space in the map is defined to be empty. + vector m_TapNotes; + + /** + * @brief Determine whether this note is for Player 1 or Player 2. + * @param track the track/column the note is in. + * @param tn the note in question. Required for routine mode. + * @return true if it's for player 1, false for player 2. */ + bool IsPlayer1(const int track, const TapNote &tn) const; + + /** + * @brief Determine if the note in question should be counted as a tap. + * @param tn the note in question. + * @param row the row it lives in. + * @return true if it's a tap, false otherwise. */ + bool IsTap(const TapNote &tn, const int row) const; + + /** + * @brief Determine if the note in question should be counted as a mine. + * @param tn the note in question. + * @param row the row it lives in. + * @return true if it's a mine, false otherwise. */ + bool IsMine(const TapNote &tn, const int row) const; + + /** + * @brief Determine if the note in question should be counted as a lift. + * @param tn the note in question. + * @param row the row it lives in. + * @return true if it's a lift, false otherwise. */ + bool IsLift(const TapNote &tn, const int row) const; + + /** + * @brief Determine if the note in question should be counted as a fake. + * @param tn the note in question. + * @param row the row it lives in. + * @return true if it's a fake, false otherwise. */ + bool IsFake(const TapNote &tn, const int row) const; + + pair GetNumRowsWithSimultaneousTapsTwoPlayer(int minTaps = 2, + int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + +public: + void Init(); + + int GetNumTracks() const { return m_TapNotes.size(); } + void SetNumTracks( int iNewNumTracks ); + bool IsComposite() const; + bool operator==( const NoteData &nd ) const { return m_TapNotes == nd.m_TapNotes; } + bool operator!=( const NoteData &nd ) const { return m_TapNotes != nd.m_TapNotes; } + + /* Return the note at the given track and row. Row may be out of + * range; pretend the song goes on with TAP_EMPTYs indefinitely. */ + inline const TapNote &GetTapNote( unsigned track, int row ) const + { + const TrackMap &mapTrack = m_TapNotes[track]; + TrackMap::const_iterator iter = mapTrack.find( row ); + if( iter != mapTrack.end() ) + return iter->second; + else + return TAP_EMPTY; + } + + + inline iterator FindTapNote( unsigned iTrack, int iRow ) { return m_TapNotes[iTrack].find( iRow ); } + inline const_iterator FindTapNote( unsigned iTrack, int iRow ) const { return m_TapNotes[iTrack].find( iRow ); } + void RemoveTapNote( unsigned iTrack, iterator it ) { m_TapNotes[iTrack].erase( it ); } + + /** + * @brief Return an iterator range for [rowBegin,rowEnd). + * + * This can be used to efficiently iterate trackwise over a range of notes. + * It's like FOREACH_NONEMPTY_ROW_IN_TRACK_RANGE, except it only requires + * two map searches (iterating is constant time), but the iterators will + * become invalid if the notes they represent disappear, so you need to + * pay attention to how you modify the data. + * @param iTrack the column to use. + * @param iStartRow the starting point. + * @param iEndRow the ending point. + * @param begin the eventual beginning point of the range. + * @param end the eventual end point of the range. */ + void GetTapNoteRange(int iTrack, int iStartRow, int iEndRow, + TrackMap::const_iterator &begin, TrackMap::const_iterator &end ) const; + /** + * @brief Return a constant iterator range for [rowBegin,rowEnd). + * @param iTrack the column to use. + * @param iStartRow the starting point. + * @param iEndRow the ending point. + * @param begin the eventual beginning point of the range. + * @param end the eventual end point of the range. */ + void GetTapNoteRange( int iTrack, int iStartRow, int iEndRow, TrackMap::iterator &begin, TrackMap::iterator &end ); + all_tracks_iterator GetTapNoteRangeAllTracks( int iStartRow, int iEndRow, bool bInclusive = false ) + { + return all_tracks_iterator( *this, iStartRow, iEndRow, false, bInclusive ); + } + all_tracks_const_iterator GetTapNoteRangeAllTracks( int iStartRow, int iEndRow, bool bInclusive = false ) const + { + return all_tracks_const_iterator( *this, iStartRow, iEndRow, false, bInclusive ); + } + all_tracks_reverse_iterator GetTapNoteRangeAllTracksReverse( int iStartRow, int iEndRow, bool bInclusive = false ) + { + return all_tracks_iterator(*this, iStartRow, iEndRow, true, bInclusive ); + } + all_tracks_const_reverse_iterator GetTapNoteRangeAllTracksReverse( int iStartRow, int iEndRow, bool bInclusive = false ) const + { + return all_tracks_const_iterator(*this, iStartRow, iEndRow, true, bInclusive ); + } + + /* Return an iterator range include iStartRow to iEndRow. Extend the range to include + * hold notes overlapping the boundary. */ + void GetTapNoteRangeInclusive(int iTrack, int iStartRow, int iEndRow, + TrackMap::const_iterator &begin, TrackMap::const_iterator &end, bool bIncludeAdjacent=false ) const; + void GetTapNoteRangeInclusive(int iTrack, int iStartRow, int iEndRow, + TrackMap::iterator &begin, TrackMap::iterator &end, bool bIncludeAdjacent=false ); + + /* Return an iterator range include iStartRow to iEndRow. Shrink the range to exclude + * hold notes overlapping the boundary. */ + void GetTapNoteRangeExclusive(int iTrack, int iStartRow, int iEndRow, + TrackMap::const_iterator &begin, TrackMap::const_iterator &end ) const; + void GetTapNoteRangeExclusive(int iTrack, int iStartRow, int iEndRow, + TrackMap::iterator &begin, TrackMap::iterator &end ); + + + /* Returns the row of the first TapNote on the track that has a row greater than rowInOut. */ + bool GetNextTapNoteRowForTrack( int track, int &rowInOut ) const; + bool GetNextTapNoteRowForAllTracks( int &rowInOut ) const; + bool GetPrevTapNoteRowForTrack( int track, int &rowInOut ) const; + bool GetPrevTapNoteRowForAllTracks( int &rowInOut ) const; + + void MoveTapNoteTrack( int dest, int src ); + void SetTapNote( int track, int row, const TapNote& tn ); + /** + * @brief Add a hold note, merging other overlapping holds and destroying + * tap notes underneath. + * @param iTrack the column to work with. + * @param iStartRow the starting row. + * @param iEndRow the ending row. + * @param tn the tap note. */ + void AddHoldNote(int iTrack, + int iStartRow, + int iEndRow, + TapNote tn ); + + void ClearRangeForTrack( int rowBegin, int rowEnd, int iTrack ); + void ClearRange( int rowBegin, int rowEnd ); + void ClearAll(); + void CopyRange( const NoteData& from, int rowFromBegin, int rowFromEnd, int rowToBegin = 0 ); + void CopyAll( const NoteData& from ); + + bool IsRowEmpty( int row ) const; + bool IsRangeEmpty( int track, int rowBegin, int rowEnd ) const; + int GetNumTapNonEmptyTracks( int row ) const; + void GetTapNonEmptyTracks( int row, set& addTo ) const; + bool GetTapFirstNonEmptyTrack( int row, int &iNonEmptyTrackOut ) const; // return false if no non-empty tracks at row + bool GetTapFirstEmptyTrack( int row, int &iEmptyTrackOut ) const; // return false if no non-empty tracks at row + bool GetTapLastEmptyTrack( int row, int &iEmptyTrackOut ) const; // return false if no empty tracks at row + int GetNumTracksWithTap( int row ) const; + int GetNumTracksWithTapOrHoldHead( int row ) const; + int GetFirstTrackWithTap( int row ) const; + int GetFirstTrackWithTapOrHoldHead( int row ) const; + int GetLastTrackWithTapOrHoldHead( int row ) const; + + inline bool IsThereATapAtRow( int row ) const { return GetFirstTrackWithTap( row ) != -1; } + inline bool IsThereATapOrHoldHeadAtRow( int row ) const { return GetFirstTrackWithTapOrHoldHead( row ) != -1; } + void GetTracksHeldAtRow( int row, set& addTo ); + int GetNumTracksHeldAtRow( int row ); + + bool IsHoldNoteAtRow( int iTrack, int iRow, int *pHeadRow = nullptr ) const; + bool IsHoldHeadOrBodyAtRow( int iTrack, int iRow, int *pHeadRow ) const; + + // statistics + bool IsEmpty() const; + bool IsTrackEmpty( int iTrack ) const { return m_TapNotes[iTrack].empty(); } + int GetFirstRow() const; // return the beat number of the first note + int GetLastRow() const; // return the beat number of the last note + float GetFirstBeat() const { return NoteRowToBeat( GetFirstRow() ); } + float GetLastBeat() const { return NoteRowToBeat( GetLastRow() ); } + int GetNumTapNotes( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + int GetNumTapNotesInRow( int iRow ) const; + int GetNumMines( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + int GetNumRowsWithTap( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + int GetNumRowsWithTapOrHoldHead( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + /* Optimization: for the default of start to end, use the second (faster). XXX: Second what? -- Steve */ + int GetNumHoldNotes( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + int GetNumRolls( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + + // Count rows that contain iMinTaps or more taps. + int GetNumRowsWithSimultaneousTaps( int iMinTaps, int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + int GetNumJumps( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const + { + return GetNumRowsWithSimultaneousTaps( 2, iStartIndex, iEndIndex ); + } + + + + // This row needs at least iMinSimultaneousPresses either tapped or held. + bool RowNeedsAtLeastSimultaneousPresses( int iMinSimultaneousPresses, int row ) const; + bool RowNeedsHands( int row ) const { return RowNeedsAtLeastSimultaneousPresses(3,row); } + + // Count rows that need iMinSimultaneousPresses either tapped or held. + int GetNumRowsWithSimultaneousPresses( int iMinSimultaneousPresses, int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + int GetNumHands( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const + { + return GetNumRowsWithSimultaneousPresses( 3, iStartIndex, iEndIndex ); + } + int GetNumQuads( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const + { + return GetNumRowsWithSimultaneousPresses( 4, iStartIndex, iEndIndex ); + } + + // and the other notetypes + int GetNumLifts( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + int GetNumFakes( int iStartIndex = 0, int iEndIndex = MAX_NOTE_ROW ) const; + + // the couple/routine style variants of the above. + pair GetNumTapNotesTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + pair GetNumJumpsTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + pair GetNumHandsTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + pair GetNumQuadsTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + pair GetNumHoldNotesTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + pair GetNumMinesTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + pair GetNumRollsTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + pair GetNumLiftsTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + pair GetNumFakesTwoPlayer(int startRow = 0, + int endRow = MAX_NOTE_ROW) const; + + // Transformations + void LoadTransformed(const NoteData& original, + int iNewNumTracks, + const int iOriginalTrackToTakeFrom[] ); // -1 for iOriginalTracksToTakeFrom means no track + + // XML + XNode* CreateNode() const; + void LoadFromNode( const XNode* pNode ); +}; + +/** @brief Allow a quick way to swap notedata. */ +namespace std +{ + template<> inline void swap( NoteData &nd1, NoteData &nd2 ) { nd1.swap( nd2 ); } +} + +#endif + +/* + * (c) 2001-2004 Chris Danford, Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/NoteDisplay.cpp b/src/NoteDisplay.cpp index eb9eb42d9b..33033781ed 100644 --- a/src/NoteDisplay.cpp +++ b/src/NoteDisplay.cpp @@ -119,7 +119,7 @@ struct NoteResource NoteResource( const NoteSkinAndPath &nsap ): m_nsap(nsap) { m_iRefCount = 0; - m_pActor = NULL; + m_pActor = nullptr; } ~NoteResource() @@ -173,7 +173,7 @@ static void DeleteNoteResource( NoteResource *pRes ) NoteColorActor::NoteColorActor() { - m_p = NULL; + m_p = nullptr; } NoteColorActor::~NoteColorActor() @@ -197,7 +197,7 @@ Actor *NoteColorActor::Get() NoteColorSprite::NoteColorSprite() { - m_p = NULL; + m_p = nullptr; } NoteColorSprite::~NoteColorSprite() @@ -750,7 +750,7 @@ void NoteDisplay::DrawTap(const TapNote& tn, int iCol, float fBeat, float fDrawDistanceBeforeTargetsPixels, float fFadeInPercentOfDrawFar) { - Actor* pActor = NULL; + Actor* pActor = nullptr; NotePart part = NotePart_Tap; /* if( tn.source == TapNote::addition ) diff --git a/src/NoteField.cpp b/src/NoteField.cpp index 4b026b8154..061852b475 100644 --- a/src/NoteField.cpp +++ b/src/NoteField.cpp @@ -38,8 +38,8 @@ static ThemeMetric1D ROUTINE_NOTESKIN( "NoteField", RoutineNoteSkinName NoteField::NoteField() { - m_pNoteData = NULL; - m_pCurDisplay = NULL; + m_pNoteData = nullptr; + m_pCurDisplay = nullptr; m_textMeasureNumber.LoadFromFont( THEME->GetPathF("NoteField","MeasureNumber") ); m_textMeasureNumber.SetZoom( 1.0f ); @@ -77,7 +77,7 @@ void NoteField::Unload() it != m_NoteDisplays.end(); ++it ) delete it->second; m_NoteDisplays.clear(); - m_pCurDisplay = NULL; + m_pCurDisplay = nullptr; memset( m_pDisplays, 0, sizeof(m_pDisplays) ); } diff --git a/src/NoteSkinManager.cpp b/src/NoteSkinManager.cpp index c1be0fc523..f4bc91e30d 100644 --- a/src/NoteSkinManager.cpp +++ b/src/NoteSkinManager.cpp @@ -18,7 +18,7 @@ #include "SpecialFiles.h" /** @brief Have the NoteSkinManager available throughout the program. */ -NoteSkinManager* NOTESKIN = NULL; +NoteSkinManager* NOTESKIN = nullptr; const RString GAME_COMMON_NOTESKIN_NAME = "common"; const RString GAME_BASE_NOTESKIN_NAME = "default"; @@ -47,7 +47,7 @@ namespace NoteSkinManager::NoteSkinManager() { - m_pCurGame = NULL; + m_pCurGame = nullptr; m_PlayerNumber = PlayerNumber_Invalid; m_GameController = GameController_Invalid; diff --git a/src/NoteSkinManager.h b/src/NoteSkinManager.h index 3917982fb7..95d89696aa 100644 --- a/src/NoteSkinManager.h +++ b/src/NoteSkinManager.h @@ -1,94 +1,95 @@ -#ifndef NOTE_SKIN_MANAGER_H -#define NOTE_SKIN_MANAGER_H - -#include "Actor.h" -#include "RageTypes.h" -#include "PlayerNumber.h" -#include "GameInput.h" -#include "IniFile.h" - -class Game; -struct NoteSkinData; - -/** @brief Loads note skins. */ -class NoteSkinManager -{ -public: - NoteSkinManager(); - ~NoteSkinManager(); - - void RefreshNoteSkinData( const Game* game ); - void GetNoteSkinNames( const Game* game, vector &AddTo ); - void GetNoteSkinNames( vector &AddTo ); // looks up current const Game* in GAMESTATE - bool DoesNoteSkinExist( const RString &sNoteSkin ); // looks up current const Game* in GAMESTATE - bool DoNoteSkinsExistForGame( const Game *pGame ); - - void SetCurrentNoteSkin( const RString &sNoteSkin ) { m_sCurrentNoteSkin = sNoteSkin; } - const RString &GetCurrentNoteSkin() { return m_sCurrentNoteSkin; } - void SetPlayerNumber( PlayerNumber pn ) { m_PlayerNumber = pn; } - void SetGameController( GameController gc ) { m_GameController = gc; } - RString GetPath( const RString &sButtonName, const RString &sElement ); - bool PushActorTemplate( Lua *L, const RString &sButton, const RString &sElement, bool bSpriteOnly ); - Actor *LoadActor( const RString &sButton, const RString &sElement, Actor *pParent = NULL, bool bSpriteOnly = false ); - - RString GetMetric( const RString &sButtonName, const RString &sValue ); - int GetMetricI( const RString &sButtonName, const RString &sValueName ); - float GetMetricF( const RString &sButtonName, const RString &sValueName ); - bool GetMetricB( const RString &sButtonName, const RString &sValueName ); - apActorCommands GetMetricA( const RString &sButtonName, const RString &sValueName ); - - // Lua - void PushSelf( lua_State *L ); - -protected: - RString GetPathFromDirAndFile( const RString &sDir, const RString &sFileName ); - void GetAllNoteSkinNamesForGame( const Game *pGame, vector &AddTo ); - - void LoadNoteSkinData( const RString &sNoteSkinName, NoteSkinData& data_out ); - void LoadNoteSkinDataRecursive( const RString &sNoteSkinName, NoteSkinData& data_out ); - RString m_sCurrentNoteSkin; - const Game* m_pCurGame; - - // xxx: is this the best way to implement this? -freem - PlayerNumber m_PlayerNumber; - GameController m_GameController; -}; - -extern NoteSkinManager* NOTESKIN; // global and accessable from anywhere in our program - -class LockNoteSkin -{ -public: - LockNoteSkin( const RString &sNoteSkin ) { ASSERT( NOTESKIN->GetCurrentNoteSkin().empty() ); NOTESKIN->SetCurrentNoteSkin( sNoteSkin ); } - ~LockNoteSkin() { NOTESKIN->SetCurrentNoteSkin( RString() ); } -}; - - -#endif - -/** - * @file - * @author Chris Danford (c) 2003-2004 - * @section LICENSE - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef NOTE_SKIN_MANAGER_H +#define NOTE_SKIN_MANAGER_H + +#include "Actor.h" +#include "RageTypes.h" +#include "PlayerNumber.h" +#include "GameInput.h" +#include "IniFile.h" + +class Game; +struct NoteSkinData; + +/** @brief Loads note skins. */ +class NoteSkinManager +{ +public: + NoteSkinManager(); + ~NoteSkinManager(); + + void RefreshNoteSkinData( const Game* game ); + void GetNoteSkinNames( const Game* game, vector &AddTo ); + void GetNoteSkinNames( vector &AddTo ); // looks up current const Game* in GAMESTATE + bool DoesNoteSkinExist( const RString &sNoteSkin ); // looks up current const Game* in GAMESTATE + bool DoNoteSkinsExistForGame( const Game *pGame ); + + void SetCurrentNoteSkin( const RString &sNoteSkin ) { m_sCurrentNoteSkin = sNoteSkin; } + const RString &GetCurrentNoteSkin() { return m_sCurrentNoteSkin; } + + void SetPlayerNumber( PlayerNumber pn ) { m_PlayerNumber = pn; } + void SetGameController( GameController gc ) { m_GameController = gc; } + RString GetPath( const RString &sButtonName, const RString &sElement ); + bool PushActorTemplate( Lua *L, const RString &sButton, const RString &sElement, bool bSpriteOnly ); + Actor *LoadActor( const RString &sButton, const RString &sElement, Actor *pParent = nullptr, bool bSpriteOnly = false ); + + RString GetMetric( const RString &sButtonName, const RString &sValue ); + int GetMetricI( const RString &sButtonName, const RString &sValueName ); + float GetMetricF( const RString &sButtonName, const RString &sValueName ); + bool GetMetricB( const RString &sButtonName, const RString &sValueName ); + apActorCommands GetMetricA( const RString &sButtonName, const RString &sValueName ); + + // Lua + void PushSelf( lua_State *L ); + +protected: + RString GetPathFromDirAndFile( const RString &sDir, const RString &sFileName ); + void GetAllNoteSkinNamesForGame( const Game *pGame, vector &AddTo ); + + void LoadNoteSkinData( const RString &sNoteSkinName, NoteSkinData& data_out ); + void LoadNoteSkinDataRecursive( const RString &sNoteSkinName, NoteSkinData& data_out ); + RString m_sCurrentNoteSkin; + const Game* m_pCurGame; + + // xxx: is this the best way to implement this? -freem + PlayerNumber m_PlayerNumber; + GameController m_GameController; +}; + +extern NoteSkinManager* NOTESKIN; // global and accessable from anywhere in our program + +class LockNoteSkin +{ +public: + LockNoteSkin( const RString &sNoteSkin ) { ASSERT( NOTESKIN->GetCurrentNoteSkin().empty() ); NOTESKIN->SetCurrentNoteSkin( sNoteSkin ); } + ~LockNoteSkin() { NOTESKIN->SetCurrentNoteSkin( RString() ); } +}; + + +#endif + +/** + * @file + * @author Chris Danford (c) 2003-2004 + * @section LICENSE + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/NotesLoaderSM.cpp b/src/NotesLoaderSM.cpp index 2aaaab7e0b..7b17df0490 100644 --- a/src/NotesLoaderSM.cpp +++ b/src/NotesLoaderSM.cpp @@ -969,7 +969,7 @@ bool SMLoader::LoadEditFromBuffer( const RString &sBuffer, const RString &sEditF bool SMLoader::LoadEditFromMsd( const MsdFile &msd, const RString &sEditFilePath, ProfileSlot slot, bool bAddStepsToSong ) { - Song* pSong = NULL; + Song* pSong = nullptr; for( unsigned i=0; iFinishTweening(); - m_Row[!m_iCurrentRow].SetFromHandler( NULL ); + m_Row[!m_iCurrentRow].SetFromHandler(nullptr); this->PlayCommand( "TweenOn" ); } diff --git a/src/PaneDisplay.cpp b/src/PaneDisplay.cpp index a628911afa..8fdee83275 100644 --- a/src/PaneDisplay.cpp +++ b/src/PaneDisplay.cpp @@ -179,7 +179,7 @@ void PaneDisplay::GetPaneTextAndLevel( PaneCategory c, RString & sTextOut, float { RadarValues rv; - HighScoreList *pHSL = NULL; + HighScoreList *pHSL = nullptr; ProfileSlot slot = ProfileSlot_Machine; switch( c ) { diff --git a/src/PercentageDisplay.cpp b/src/PercentageDisplay.cpp index 1e8591363b..955796ac79 100644 --- a/src/PercentageDisplay.cpp +++ b/src/PercentageDisplay.cpp @@ -16,8 +16,8 @@ REGISTER_ACTOR_CLASS( PercentageDisplay ); PercentageDisplay::PercentageDisplay() { - m_pPlayerState = NULL; - m_pPlayerStageStats = NULL; + m_pPlayerState = nullptr; + m_pPlayerStageStats = nullptr; m_Last = -1; m_LastMax = -1; diff --git a/src/Player.cpp b/src/Player.cpp index 001b4bc6d9..49efdb22f4 100644 --- a/src/Player.cpp +++ b/src/Player.cpp @@ -223,27 +223,27 @@ Player::Player( NoteData &nd, bool bVisibleParts ) : m_NoteData(nd) { m_bLoaded = false; - m_pPlayerState = NULL; - m_pPlayerStageStats = NULL; + m_pPlayerState = nullptr; + m_pPlayerStageStats = nullptr; m_fNoteFieldHeight = 0; - m_pLifeMeter = NULL; - m_pCombinedLifeMeter = NULL; - m_pScoreDisplay = NULL; - m_pSecondaryScoreDisplay = NULL; - m_pPrimaryScoreKeeper = NULL; - m_pSecondaryScoreKeeper = NULL; - m_pInventory = NULL; - m_pIterNeedsTapJudging = NULL; - m_pIterNeedsHoldJudging = NULL; - m_pIterUncrossedRows = NULL; - m_pIterUnjudgedRows = NULL; - m_pIterUnjudgedMineRows = NULL; + m_pLifeMeter = nullptr; + m_pCombinedLifeMeter = nullptr; + m_pScoreDisplay = nullptr; + m_pSecondaryScoreDisplay = nullptr; + m_pPrimaryScoreKeeper = nullptr; + m_pSecondaryScoreKeeper = nullptr; + m_pInventory = nullptr; + m_pIterNeedsTapJudging = nullptr; + m_pIterNeedsHoldJudging = nullptr; + m_pIterUncrossedRows = nullptr; + m_pIterUnjudgedRows = nullptr; + m_pIterUnjudgedMineRows = nullptr; m_bPaused = false; m_bDelay = false; - m_pAttackDisplay = NULL; + m_pAttackDisplay = nullptr; if( bVisibleParts ) { m_pAttackDisplay = new AttackDisplay; @@ -252,7 +252,7 @@ Player::Player( NoteData &nd, bool bVisibleParts ) : m_NoteData(nd) PlayerAI::InitFromDisk(); - m_pNoteField = NULL; + m_pNoteField = nullptr; if( bVisibleParts ) { m_pNoteField = new NoteField; @@ -504,14 +504,14 @@ void Player::Init( } else { - m_pActorWithComboPosition = NULL; - m_pActorWithJudgmentPosition = NULL; + m_pActorWithComboPosition = nullptr; + m_pActorWithJudgmentPosition = nullptr; } // Load HoldJudgments m_vpHoldJudgment.resize( GAMESTATE->GetCurrentStyle()->m_iColsPerPlayer ); for( int i = 0; i < GAMESTATE->GetCurrentStyle()->m_iColsPerPlayer; ++i ) - m_vpHoldJudgment[i] = NULL; + m_vpHoldJudgment[i] = nullptr; if( HasVisibleParts() ) { @@ -2209,7 +2209,7 @@ void Player::StepStrumHopo( int col, int row, const RageTimer &tm, bool bHeld, b const float fSecondsFromExact = fabsf( fNoteOffset ); TapNote tnDummy = TAP_ORIGINAL_TAP; - TapNote *pTN = NULL; + TapNote *pTN = nullptr; switch( pbt ) { DEFAULT_FAIL(pbt); diff --git a/src/Preference.h b/src/Preference.h index a1f7cc6186..91c6f69006 100644 --- a/src/Preference.h +++ b/src/Preference.h @@ -1,185 +1,185 @@ -/* Preference - Holds user-chosen preferences that are saved between sessions. */ - -#ifndef PREFERENCE_H -#define PREFERENCE_H - -#include "EnumHelper.h" -#include "LuaManager.h" -#include "RageUtil.h" -class XNode; - -struct lua_State; -class IPreference -{ -public: - IPreference( const RString& sName ); - virtual ~IPreference(); - void ReadFrom( const XNode* pNode, bool bIsStatic ); - void WriteTo( XNode* pNode ) const; - void ReadDefaultFrom( const XNode* pNode ); - - virtual void LoadDefault() = 0; - virtual void SetDefaultFromString( const RString &s ) = 0; - - virtual RString ToString() const = 0; - virtual void FromString( const RString &s ) = 0; - - virtual void SetFromStack( lua_State *L ); - virtual void PushValue( lua_State *L ) const; - - const RString &GetName() const { return m_sName; } - - static IPreference *GetPreferenceByName( const RString &sName ); - static void LoadAllDefaults(); - static void ReadAllPrefsFromNode( const XNode* pNode, bool bIsStatic ); - static void SavePrefsToNode( XNode* pNode ); - static void ReadAllDefaultsFromNode( const XNode* pNode ); - - RString GetName() { return m_sName; } - void SetStatic( bool b ) { m_bIsStatic = b; } -private: - RString m_sName; - bool m_bIsStatic; // loaded from Static.ini? If so, don't write to Preferences.ini -}; - -void BroadcastPreferenceChanged( const RString& sPreferenceName ); - -template -class Preference : public IPreference -{ -public: - Preference( const RString& sName, const T& defaultValue, void (pfnValidate)(T& val) = NULL ): - IPreference( sName ), - m_currentValue( defaultValue ), - m_defaultValue( defaultValue ), - m_pfnValidate( pfnValidate ) - { - LoadDefault(); - } - - RString ToString() const { return StringConversion::ToString( m_currentValue ); } - void FromString( const RString &s ) - { - if( !StringConversion::FromString(s, m_currentValue) ) - m_currentValue = m_defaultValue; - if( m_pfnValidate ) - m_pfnValidate( m_currentValue ); - } - void SetFromStack( lua_State *L ) - { - LuaHelpers::Pop( L, m_currentValue ); - if( m_pfnValidate ) - m_pfnValidate( m_currentValue ); - } - void PushValue( lua_State *L ) const - { - LuaHelpers::Push( L, m_currentValue ); - } - - void LoadDefault() - { - m_currentValue = m_defaultValue; - } - void SetDefaultFromString( const RString &s ) - { - T def = m_defaultValue; - if( !StringConversion::FromString(s, m_defaultValue) ) - m_defaultValue = def; - } - - const T &Get() const - { - return m_currentValue; - } - - const T &GetDefault() const - { - return m_defaultValue; - } - - operator const T () const - { - return Get(); - } - - void Set( const T& other ) - { - m_currentValue = other; - BroadcastPreferenceChanged( GetName() ); - } - - static Preference *GetPreferenceByName( const RString &sName ) - { - IPreference *pPreference = IPreference::GetPreferenceByName( sName ); - Preference *pRet = dynamic_cast *>(pPreference); - return pRet; - } - -private: - T m_currentValue; - T m_defaultValue; - void (*m_pfnValidate)(T& val); -}; - -/** @brief Utilities for working with Lua. */ -namespace LuaHelpers { template void Push( lua_State *L, const Preference &Object ) { LuaHelpers::Push( L, Object.Get() ); } } - -template -class Preference1D -{ -public: - typedef Preference PreferenceT; - vector m_v; - - Preference1D( void pfn(size_t i, RString &sNameOut, T &defaultValueOut ), size_t N ) - { - for( size_t i=0; i(sName, defaultValue) ); - } - } - - ~Preference1D() - { - for( size_t i=0; i& operator[]( size_t i ) const - { - return *m_v[i]; - } - Preference& operator[]( size_t i ) - { - return *m_v[i]; - } -}; - -#endif - -/* - * (c) 2001-2004 Chris Danford, Chris Gomez - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* Preference - Holds user-chosen preferences that are saved between sessions. */ + +#ifndef PREFERENCE_H +#define PREFERENCE_H + +#include "EnumHelper.h" +#include "LuaManager.h" +#include "RageUtil.h" +class XNode; + +struct lua_State; +class IPreference +{ +public: + IPreference( const RString& sName ); + virtual ~IPreference(); + void ReadFrom( const XNode* pNode, bool bIsStatic ); + void WriteTo( XNode* pNode ) const; + void ReadDefaultFrom( const XNode* pNode ); + + virtual void LoadDefault() = 0; + virtual void SetDefaultFromString( const RString &s ) = 0; + + virtual RString ToString() const = 0; + virtual void FromString( const RString &s ) = 0; + + virtual void SetFromStack( lua_State *L ); + virtual void PushValue( lua_State *L ) const; + + const RString &GetName() const { return m_sName; } + + static IPreference *GetPreferenceByName( const RString &sName ); + static void LoadAllDefaults(); + static void ReadAllPrefsFromNode( const XNode* pNode, bool bIsStatic ); + static void SavePrefsToNode( XNode* pNode ); + static void ReadAllDefaultsFromNode( const XNode* pNode ); + + RString GetName() { return m_sName; } + void SetStatic( bool b ) { m_bIsStatic = b; } +private: + RString m_sName; + bool m_bIsStatic; // loaded from Static.ini? If so, don't write to Preferences.ini +}; + +void BroadcastPreferenceChanged( const RString& sPreferenceName ); + +template +class Preference : public IPreference +{ +public: + Preference( const RString& sName, const T& defaultValue, void (pfnValidate)(T& val) = nullptr ): + IPreference( sName ), + m_currentValue( defaultValue ), + m_defaultValue( defaultValue ), + m_pfnValidate( pfnValidate ) + { + LoadDefault(); + } + + RString ToString() const { return StringConversion::ToString( m_currentValue ); } + void FromString( const RString &s ) + { + if( !StringConversion::FromString(s, m_currentValue) ) + m_currentValue = m_defaultValue; + if( m_pfnValidate ) + m_pfnValidate( m_currentValue ); + } + void SetFromStack( lua_State *L ) + { + LuaHelpers::Pop( L, m_currentValue ); + if( m_pfnValidate ) + m_pfnValidate( m_currentValue ); + } + void PushValue( lua_State *L ) const + { + LuaHelpers::Push( L, m_currentValue ); + } + + void LoadDefault() + { + m_currentValue = m_defaultValue; + } + void SetDefaultFromString( const RString &s ) + { + T def = m_defaultValue; + if( !StringConversion::FromString(s, m_defaultValue) ) + m_defaultValue = def; + } + + const T &Get() const + { + return m_currentValue; + } + + const T &GetDefault() const + { + return m_defaultValue; + } + + operator const T () const + { + return Get(); + } + + void Set( const T& other ) + { + m_currentValue = other; + BroadcastPreferenceChanged( GetName() ); + } + + static Preference *GetPreferenceByName( const RString &sName ) + { + IPreference *pPreference = IPreference::GetPreferenceByName( sName ); + Preference *pRet = dynamic_cast *>(pPreference); + return pRet; + } + +private: + T m_currentValue; + T m_defaultValue; + void (*m_pfnValidate)(T& val); +}; + +/** @brief Utilities for working with Lua. */ +namespace LuaHelpers { template void Push( lua_State *L, const Preference &Object ) { LuaHelpers::Push( L, Object.Get() ); } } + +template +class Preference1D +{ +public: + typedef Preference PreferenceT; + vector m_v; + + Preference1D( void pfn(size_t i, RString &sNameOut, T &defaultValueOut ), size_t N ) + { + for( size_t i=0; i(sName, defaultValue) ); + } + } + + ~Preference1D() + { + for( size_t i=0; i& operator[]( size_t i ) const + { + return *m_v[i]; + } + Preference& operator[]( size_t i ) + { + return *m_v[i]; + } +}; + +#endif + +/* + * (c) 2001-2004 Chris Danford, Chris Gomez + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/PrefsManager.cpp b/src/PrefsManager.cpp index 7348775935..77fb489fbe 100644 --- a/src/PrefsManager.cpp +++ b/src/PrefsManager.cpp @@ -16,7 +16,7 @@ //STATIC_INI_PATH = "Data/Static.ini"; // overlay on the 2 above, can't be overridden //TYPE_TXT_FILE = "Data/Type.txt"; -PrefsManager* PREFSMAN = NULL; // global and accessable from anywhere in our program +PrefsManager* PREFSMAN = nullptr; // global and accessable from anywhere in our program static const char *MusicWheelUsesSectionsNames[] = { "Never", diff --git a/src/ProfileManager.cpp b/src/ProfileManager.cpp index fa155cbad2..6d8ce6ddd5 100644 --- a/src/ProfileManager.cpp +++ b/src/ProfileManager.cpp @@ -25,7 +25,7 @@ #include "CharacterManager.h" -ProfileManager* PROFILEMAN = NULL; // global and accessable from anywhere in our program +ProfileManager* PROFILEMAN = nullptr; // global and accessable from anywhere in our program static void DefaultLocalProfileIDInit( size_t /*PlayerNumber*/ i, RString &sNameOut, RString &defaultValueOut ) { diff --git a/src/RageDisplay_D3D.cpp b/src/RageDisplay_D3D.cpp index 25fd9c410f..7f0bac4cd2 100644 --- a/src/RageDisplay_D3D.cpp +++ b/src/RageDisplay_D3D.cpp @@ -36,9 +36,9 @@ RString GetErrorString( HRESULT hr ) } // Globals -HMODULE g_D3D9_Module = NULL; -LPDIRECT3D9 g_pd3d = NULL; -LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; +HMODULE g_D3D9_Module = nullptr; +LPDIRECT3D9 g_pd3d = nullptr; +LPDIRECT3DDEVICE9 g_pd3dDevice = nullptr; D3DCAPS9 g_DeviceCaps; D3DDISPLAYMODE g_DesktopMode; D3DPRESENT_PARAMETERS g_d3dpp; @@ -252,13 +252,13 @@ RageDisplay_D3D::~RageDisplay_D3D() if( g_pd3dDevice ) { g_pd3dDevice->Release(); - g_pd3dDevice = NULL; + g_pd3dDevice = nullptr; } if( g_pd3d ) { g_pd3d->Release(); - g_pd3d = NULL; + g_pd3d = nullptr; } /* Even after we call Release(), D3D may still affect our window. It seems @@ -267,7 +267,7 @@ RageDisplay_D3D::~RageDisplay_D3D() if( g_D3D9_Module ) { FreeLibrary( g_D3D9_Module ); - g_D3D9_Module = NULL; + g_D3D9_Module = nullptr; } } @@ -621,7 +621,7 @@ bool RageDisplay_D3D::SupportsThreadedRendering() RageSurface* RageDisplay_D3D::CreateScreenshot() { - RageSurface * result = NULL; + RageSurface * result = nullptr; // Get the back buffer. IDirect3DSurface9* pSurface; @@ -702,7 +702,7 @@ void RageDisplay_D3D::SendCurrentMatrices() g_pd3dDevice->SetTextureStageState( tu, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 ); // If no texture is set for this texture unit, don't bother setting it up. - IDirect3DBaseTexture9* pTexture = NULL; + IDirect3DBaseTexture9* pTexture = nullptr; g_pd3dDevice->GetTexture( tu, &pTexture ); if( pTexture == nullptr ) continue; diff --git a/src/RageDisplay_GLES2.cpp b/src/RageDisplay_GLES2.cpp index cd87c132dc..336719f544 100644 --- a/src/RageDisplay_GLES2.cpp +++ b/src/RageDisplay_GLES2.cpp @@ -220,7 +220,7 @@ RageDisplay_GLES2::RageDisplay_GLES2() FixLittleEndian(); // RageDisplay_GLES2_Helpers::Init(); - g_pWind = NULL; + g_pWind = nullptr; } RString diff --git a/src/RageDisplay_OGL.cpp b/src/RageDisplay_OGL.cpp index 5f11fe43c4..b9b063dc92 100644 --- a/src/RageDisplay_OGL.cpp +++ b/src/RageDisplay_OGL.cpp @@ -64,7 +64,7 @@ static const GLenum RageSpriteVertexFormat = GL_T2F_C4F_N3F_V3F; static GLhandleARB g_bTextureMatrixShader = 0; static map g_mapRenderTargets; -static RenderTarget *g_pCurrentRenderTarget = NULL; +static RenderTarget *g_pCurrentRenderTarget = nullptr; static LowLevelWindow *g_pWind; @@ -262,7 +262,7 @@ RageDisplay_Legacy::RageDisplay_Legacy() FixLittleEndian(); RageDisplay_Legacy_Helpers::Init(); - g_pWind = NULL; + g_pWind = nullptr; g_bTextureMatrixShader = 0; } @@ -650,8 +650,8 @@ static void CheckPalettedTextures() /* If 8-bit palettes don't work, disable them entirely--don't trust 4-bit * palettes if it can't even get 8-bit ones right. */ - glColorTableEXT = NULL; - glGetColorTableParameterivEXT = NULL; + glColorTableEXT = nullptr; + glGetColorTableParameterivEXT = nullptr; LOG->Info( "Paletted textures disabled: %s.", sError.c_str() ); } @@ -2252,7 +2252,7 @@ public: if (bChanged) DISPLAY->UpdateTexture( m_iTexHandle, pSurface, 0, 0, pSurface->w, pSurface->h ); - pSurface->pixels = NULL; + pSurface->pixels = nullptr; m_iTexHandle = 0; glBindBufferARB( GL_PIXEL_UNPACK_BUFFER_ARB, 0 ); @@ -2482,7 +2482,7 @@ void RageDisplay_Legacy::SetRenderTarget( unsigned iTexture, bool bPreserveTextu if (g_pCurrentRenderTarget) g_pCurrentRenderTarget->FinishRenderingTo(); - g_pCurrentRenderTarget = NULL; + g_pCurrentRenderTarget = nullptr; return; } diff --git a/src/RageException.cpp b/src/RageException.cpp index 25ef7f4cdb..ec4458f660 100644 --- a/src/RageException.cpp +++ b/src/RageException.cpp @@ -15,7 +15,7 @@ using CrashHandler::DebugBreak; #endif static uint64_t g_HandlerThreadID = RageThread::GetInvalidThreadID(); -static void (*g_CleanupHandler)( const RString &sError ) = NULL; +static void (*g_CleanupHandler)( const RString &sError ) = nullptr; void RageException::SetCleanupHandler( void (*pHandler)(const RString &sError) ) { g_HandlerThreadID = RageThread::GetCurrentThreadID(); diff --git a/src/RageFile.cpp b/src/RageFile.cpp index f72aef0da0..8927dfa21c 100644 --- a/src/RageFile.cpp +++ b/src/RageFile.cpp @@ -13,7 +13,7 @@ RageFile::RageFile() { - m_File = NULL; + m_File = nullptr; } RageFile::RageFile( const RageFile &cpy ): @@ -83,7 +83,7 @@ void RageFile::Close() delete m_File; if( m_Mode & WRITE ) FILEMAN->CacheFile( m_File, m_Path ); - m_File = NULL; + m_File = nullptr; } #define ASSERT_OPEN ASSERT_M( IsOpen(), ssprintf("\"%s\" is not open.", m_Path.c_str()) ); diff --git a/src/RageFileBasic.cpp b/src/RageFileBasic.cpp index df6cdb8488..63d6cdc928 100644 --- a/src/RageFileBasic.cpp +++ b/src/RageFileBasic.cpp @@ -7,8 +7,8 @@ REGISTER_CLASS_TRAITS( RageFileBasic, pCopy->Copy() ); RageFileObj::RageFileObj() { - m_pReadBuffer = NULL; - m_pWriteBuffer = NULL; + m_pReadBuffer = nullptr; + m_pWriteBuffer = nullptr; ResetReadBuf(); @@ -35,7 +35,7 @@ RageFileObj::RageFileObj( const RageFileObj &cpy ): } else { - m_pReadBuffer = NULL; + m_pReadBuffer = nullptr; } if( cpy.m_pWriteBuffer != nullptr ) @@ -45,7 +45,7 @@ RageFileObj::RageFileObj( const RageFileObj &cpy ): } else { - m_pWriteBuffer = NULL; + m_pWriteBuffer = nullptr; } m_iReadBufAvail = cpy.m_iReadBufAvail; diff --git a/src/RageFileDriver.cpp b/src/RageFileDriver.cpp index 7bdf64668d..7497181d66 100644 --- a/src/RageFileDriver.cpp +++ b/src/RageFileDriver.cpp @@ -68,7 +68,7 @@ void RageFileDriver::FlushDirCache( const RString &sPath ) } -const struct FileDriverEntry *g_pFileDriverList = NULL; +const struct FileDriverEntry *g_pFileDriverList = nullptr; FileDriverEntry::FileDriverEntry( const RString &sType ) { @@ -79,7 +79,7 @@ FileDriverEntry::FileDriverEntry( const RString &sType ) FileDriverEntry::~FileDriverEntry() { - g_pFileDriverList = NULL; /* invalidate */ + g_pFileDriverList = nullptr; /* invalidate */ } RageFileDriver *MakeFileDriver( const RString &sType, const RString &sRoot ) diff --git a/src/RageFileDriverMemory.h b/src/RageFileDriverMemory.h index f431650698..d3467f94fe 100644 --- a/src/RageFileDriverMemory.h +++ b/src/RageFileDriverMemory.h @@ -1,74 +1,74 @@ -/* RageFileDriverMemory: Simple memory-based "filesystem". */ - -#ifndef RAGE_FILE_DRIVER_MEMORY_H -#define RAGE_FILE_DRIVER_MEMORY_H - -#include "RageFileDriver.h" -#include "RageFileBasic.h" -#include "RageThreads.h" - -struct RageFileObjMemFile; -class RageFileObjMem: public RageFileObj -{ -public: - RageFileObjMem( RageFileObjMemFile *pFile = NULL ); - RageFileObjMem( const RageFileObjMem &cpy ); - ~RageFileObjMem(); - - int ReadInternal( void *buffer, size_t bytes ); - int WriteInternal( const void *buffer, size_t bytes ); - int SeekInternal( int offset ); - int GetFileSize() const; - RageFileObjMem *Copy() const; - - /* Retrieve the contents of this file. */ - const RString &GetString() const; - void PutString( const RString &sBuf ); - -private: - RageFileObjMemFile *m_pFile; - int m_iFilePos; -}; - -class RageFileDriverMem: public RageFileDriver -{ -public: - RageFileDriverMem(); - ~RageFileDriverMem(); - - RageFileBasic *Open( const RString &sPath, int mode, int &err ); - void FlushDirCache( const RString & /* sPath */ ) { } - - bool Remove( const RString &sPath ); - -private: - RageMutex m_Mutex; - vector m_Files; -}; - -#endif - -/* - * (c) 2004 Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* RageFileDriverMemory: Simple memory-based "filesystem". */ + +#ifndef RAGE_FILE_DRIVER_MEMORY_H +#define RAGE_FILE_DRIVER_MEMORY_H + +#include "RageFileDriver.h" +#include "RageFileBasic.h" +#include "RageThreads.h" + +struct RageFileObjMemFile; +class RageFileObjMem: public RageFileObj +{ +public: + RageFileObjMem( RageFileObjMemFile *pFile = nullptr ); + RageFileObjMem( const RageFileObjMem &cpy ); + ~RageFileObjMem(); + + int ReadInternal( void *buffer, size_t bytes ); + int WriteInternal( const void *buffer, size_t bytes ); + int SeekInternal( int offset ); + int GetFileSize() const; + RageFileObjMem *Copy() const; + + /* Retrieve the contents of this file. */ + const RString &GetString() const; + void PutString( const RString &sBuf ); + +private: + RageFileObjMemFile *m_pFile; + int m_iFilePos; +}; + +class RageFileDriverMem: public RageFileDriver +{ +public: + RageFileDriverMem(); + ~RageFileDriverMem(); + + RageFileBasic *Open( const RString &sPath, int mode, int &err ); + void FlushDirCache( const RString & /* sPath */ ) { } + + bool Remove( const RString &sPath ); + +private: + RageMutex m_Mutex; + vector m_Files; +}; + +#endif + +/* + * (c) 2004 Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RageFileDriverTimeout.cpp b/src/RageFileDriverTimeout.cpp index 22689e4a9a..c234441350 100644 --- a/src/RageFileDriverTimeout.cpp +++ b/src/RageFileDriverTimeout.cpp @@ -161,10 +161,10 @@ ThreadedFileWorker::ThreadedFileWorker( RString sPath ): if( m_pChildDriver == nullptr ) WARN( ssprintf("ThreadedFileWorker: Mountpoint \"%s\" not found", sPath.c_str()) ); - m_pResultFile = NULL; - m_pRequestFile = NULL; - m_pResultBuffer = NULL; - m_pRequestBuffer = NULL; + m_pResultFile = nullptr; + m_pRequestFile = nullptr; + m_pResultBuffer = nullptr; + m_pRequestBuffer = nullptr; g_apWorkersMutex.Lock(); g_apWorkers.push_back( this ); @@ -220,7 +220,7 @@ void ThreadedFileWorker::HandleRequest( int iRequest ) delete m_pRequestFile; /* Clear m_pRequestFile, so RequestTimedOut doesn't double-delete. */ - m_pRequestFile = NULL; + m_pRequestFile = nullptr; break; case REQ_GET_FILE_SIZE: @@ -321,7 +321,7 @@ RageFileBasic *ThreadedFileWorker::Open( const RString &sPath, int iMode, int &i iErr = m_iResultRequest; RageFileBasic *pRet = m_pResultFile; - m_pResultFile = NULL; + m_pResultFile = nullptr; return pRet; } @@ -340,7 +340,7 @@ void ThreadedFileWorker::Close( RageFileBasic *pFile ) m_pRequestFile = pFile; if( !DoRequest(REQ_CLOSE) ) return; - m_pRequestFile = NULL; + m_pRequestFile = nullptr; } else { @@ -359,7 +359,7 @@ int ThreadedFileWorker::GetFileSize( RageFileBasic *&pFile ) if( IsTimedOut() ) { this->Close( pFile ); - pFile = NULL; + pFile = nullptr; } if( pFile == nullptr ) @@ -370,11 +370,11 @@ int ThreadedFileWorker::GetFileSize( RageFileBasic *&pFile ) if( !DoRequest(REQ_GET_FILE_SIZE) ) { /* If we time out, we can no longer access pFile. */ - pFile = NULL; + pFile = nullptr; return -1; } - m_pRequestFile = NULL; + m_pRequestFile = nullptr; return m_iResultRequest; } @@ -387,7 +387,7 @@ int ThreadedFileWorker::GetFD( RageFileBasic *&pFile ) if( IsTimedOut() ) { this->Close( pFile ); - pFile = NULL; + pFile = nullptr; } if( pFile == nullptr ) @@ -398,11 +398,11 @@ int ThreadedFileWorker::GetFD( RageFileBasic *&pFile ) if( !DoRequest(REQ_GET_FD) ) { /* If we time out, we can no longer access pFile. */ - pFile = NULL; + pFile = nullptr; return -1; } - m_pRequestFile = NULL; + m_pRequestFile = nullptr; return m_iResultRequest; } @@ -415,7 +415,7 @@ int ThreadedFileWorker::Seek( RageFileBasic *&pFile, int iPos, RString &sError ) if( IsTimedOut() ) { this->Close( pFile ); - pFile = NULL; + pFile = nullptr; } if( pFile == nullptr ) @@ -431,13 +431,13 @@ int ThreadedFileWorker::Seek( RageFileBasic *&pFile, int iPos, RString &sError ) { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; - pFile = NULL; + pFile = nullptr; return -1; } if( m_iResultRequest == -1 ) sError = m_sResultError; - m_pRequestFile = NULL; + m_pRequestFile = nullptr; return m_iResultRequest; } @@ -450,7 +450,7 @@ int ThreadedFileWorker::Read( RageFileBasic *&pFile, void *pBuf, int iSize, RStr if( IsTimedOut() ) { this->Close( pFile ); - pFile = NULL; + pFile = nullptr; } if( pFile == nullptr ) @@ -467,7 +467,7 @@ int ThreadedFileWorker::Read( RageFileBasic *&pFile, void *pBuf, int iSize, RStr { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; - pFile = NULL; + pFile = nullptr; return -1; } @@ -477,9 +477,9 @@ int ThreadedFileWorker::Read( RageFileBasic *&pFile, void *pBuf, int iSize, RStr else memcpy( pBuf, m_pResultBuffer, iGot ); - m_pRequestFile = NULL; + m_pRequestFile = nullptr; delete [] m_pResultBuffer; - m_pResultBuffer = NULL; + m_pResultBuffer = nullptr; return iGot; } @@ -492,7 +492,7 @@ int ThreadedFileWorker::Write( RageFileBasic *&pFile, const void *pBuf, int iSiz if( IsTimedOut() ) { this->Close( pFile ); - pFile = NULL; + pFile = nullptr; } if( pFile == nullptr ) @@ -510,7 +510,7 @@ int ThreadedFileWorker::Write( RageFileBasic *&pFile, const void *pBuf, int iSiz { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; - pFile = NULL; + pFile = nullptr; return -1; } @@ -518,9 +518,9 @@ int ThreadedFileWorker::Write( RageFileBasic *&pFile, const void *pBuf, int iSiz if( m_iResultRequest == -1 ) sError = m_sResultError; - m_pRequestFile = NULL; + m_pRequestFile = nullptr; delete [] m_pRequestBuffer; - m_pRequestBuffer = NULL; + m_pRequestBuffer = nullptr; return iGot; } @@ -533,7 +533,7 @@ int ThreadedFileWorker::Flush( RageFileBasic *&pFile, RString &sError ) if( IsTimedOut() ) { this->Close( pFile ); - pFile = NULL; + pFile = nullptr; } if( pFile == nullptr ) @@ -548,14 +548,14 @@ int ThreadedFileWorker::Flush( RageFileBasic *&pFile, RString &sError ) { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; - pFile = NULL; + pFile = nullptr; return -1; } if( m_iResultRequest == -1 ) sError = m_sResultError; - m_pRequestFile = NULL; + m_pRequestFile = nullptr; return m_iResultRequest; } @@ -568,7 +568,7 @@ RageFileBasic *ThreadedFileWorker::Copy( RageFileBasic *&pFile, RString &sError if( IsTimedOut() ) { this->Close( pFile ); - pFile = NULL; + pFile = nullptr; } if( pFile == nullptr ) @@ -582,13 +582,13 @@ RageFileBasic *ThreadedFileWorker::Copy( RageFileBasic *&pFile, RString &sError { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; - pFile = NULL; + pFile = nullptr; return nullptr; } RageFileBasic *pRet = m_pResultFile; - m_pRequestFile = NULL; - m_pResultFile = NULL; + m_pRequestFile = nullptr; + m_pResultFile = nullptr; return pRet; } @@ -848,7 +848,7 @@ public: TimedFilenameDB() { ExpireSeconds = -1; - m_pWorker = NULL; + m_pWorker = nullptr; } void SetWorker( ThreadedFileWorker *pWorker ) diff --git a/src/RageFileDriverZip.cpp b/src/RageFileDriverZip.cpp index 46a4a79388..dbd1fe7dc5 100644 --- a/src/RageFileDriverZip.cpp +++ b/src/RageFileDriverZip.cpp @@ -24,7 +24,7 @@ RageFileDriverZip::RageFileDriverZip(): m_Mutex( "RageFileDriverZip" ) { m_bFileOwned = false; - m_pZip = NULL; + m_pZip = nullptr; } RageFileDriverZip::RageFileDriverZip( const RString &sPath ): @@ -32,7 +32,7 @@ RageFileDriverZip::RageFileDriverZip( const RString &sPath ): m_Mutex( "RageFileDriverZip" ) { m_bFileOwned = false; - m_pZip = NULL; + m_pZip = nullptr; Load( sPath ); } diff --git a/src/RageFileManager.cpp b/src/RageFileManager.cpp index 2a0a196811..7c72bf75b4 100644 --- a/src/RageFileManager.cpp +++ b/src/RageFileManager.cpp @@ -18,7 +18,7 @@ #include #endif -RageFileManager *FILEMAN = NULL; +RageFileManager *FILEMAN = nullptr; /* Lock this before touching any of these globals (except FILEMAN itself). */ static RageEvent *g_Mutex; @@ -38,7 +38,7 @@ struct LoadedDriver int m_iRefs; - LoadedDriver() { m_pDriver = NULL; m_iRefs = 0; } + LoadedDriver() { m_pDriver = nullptr; m_iRefs = 0; } RString GetPath( const RString &sPath ) const; }; @@ -73,7 +73,7 @@ RageFileDriver *RageFileManager::GetFileDriver( RString sMountpoint ) sMountpoint += '/'; g_Mutex->Lock(); - RageFileDriver *pRet = NULL; + RageFileDriver *pRet = nullptr; for( unsigned i = 0; i < g_pDrivers.size(); ++i ) { if( g_pDrivers[i]->m_sType == "mountpoints" ) @@ -170,7 +170,7 @@ public: FDB->AddFile( apDrivers[i]->m_sMountPoint, 0, 0 ); } }; -static RageFileDriverMountpoints *g_Mountpoints = NULL; +static RageFileDriverMountpoints *g_Mountpoints = nullptr; static RString GetDirOfExecutable( RString argv0 ) { @@ -311,10 +311,10 @@ RageFileManager::~RageFileManager() g_pDrivers.clear(); // delete g_Mountpoints; // g_Mountpoints was in g_pDrivers - g_Mountpoints = NULL; + g_Mountpoints = nullptr; delete g_Mutex; - g_Mutex = NULL; + g_Mutex = nullptr; } /* path must be normalized (FixSlashesInPlace, CollapsePath). */ diff --git a/src/RageInput.cpp b/src/RageInput.cpp index a59e451c72..8e605d252e 100644 --- a/src/RageInput.cpp +++ b/src/RageInput.cpp @@ -7,7 +7,7 @@ #include "LuaManager.h" #include "LocalizedString.h" -RageInput* INPUTMAN = NULL; // globally accessable input device +RageInput* INPUTMAN = nullptr; // globally accessable input device static Preference g_sInputDrivers( "InputDrivers", "" ); // "" == DEFAULT_INPUT_DRIVER_LIST diff --git a/src/RageSound.cpp b/src/RageSound.cpp index 88abc1bf46..09f59d5720 100644 --- a/src/RageSound.cpp +++ b/src/RageSound.cpp @@ -48,7 +48,7 @@ RageSoundLoadParams::RageSoundLoadParams(): m_bSupportRateChanging(false), m_bSupportPan(false) {} RageSound::RageSound(): - m_Mutex( "RageSound" ), m_pSource(NULL), + m_Mutex( "RageSound" ), m_pSource(nullptr), m_sFilePath(""), m_Param(), m_iStreamFrame(0), m_iStoppedSourceFrame(0), m_bPlaying(false), m_bDeleteWhenFinished(false), m_sError("") @@ -67,7 +67,7 @@ RageSound::RageSound( const RageSound &cpy ): { ASSERT(SOUNDMAN != nullptr); - m_pSource = NULL; + m_pSource = nullptr; *this = cpy; } @@ -90,7 +90,7 @@ RageSound &RageSound::operator=( const RageSound &cpy ) if( cpy.m_pSource ) m_pSource = cpy.m_pSource->Copy(); else - m_pSource = NULL; + m_pSource = nullptr; m_sFilePath = cpy.m_sFilePath; @@ -105,7 +105,7 @@ void RageSound::Unload() LockMut(m_Mutex); delete m_pSource; - m_pSource = NULL; + m_pSource = nullptr; m_sFilePath = ""; } @@ -364,7 +364,7 @@ void RageSound::SoundIsFinishedPlaying() return; /* Get our current hardware position. */ - int64_t iCurrentHardwareFrame = SOUNDMAN->GetPosition( NULL ); + int64_t iCurrentHardwareFrame = SOUNDMAN->GetPosition(nullptr); m_Mutex.Lock(); diff --git a/src/RageSound.h b/src/RageSound.h index ffde44a9a0..1a62939c59 100644 --- a/src/RageSound.h +++ b/src/RageSound.h @@ -98,7 +98,7 @@ public: * they can be ignored most of the time, so we continue to work if a file * is broken or missing. */ - bool Load( RString sFile, bool bPrecache, const RageSoundLoadParams *pParams = NULL ); + bool Load( RString sFile, bool bPrecache, const RageSoundLoadParams *pParams = nullptr ); /* Using this version means the "don't care" about caching. Currently, * this always will not cache the sound; this may become a preference. */ @@ -121,7 +121,7 @@ public: RString GetError() const { return m_sError; } void Play( const RageSoundParams *params=NULL ); - void PlayCopy( const RageSoundParams *pParams = NULL ) const; + void PlayCopy( const RageSoundParams *pParams = nullptr ) const; void Stop(); /* Cleanly pause or unpause the sound. If the sound wasn't already playing, @@ -173,7 +173,7 @@ private: RString m_sError; - int GetSourceFrameFromHardwareFrame( int64_t iHardwareFrame, bool *bApproximate = NULL ) const; + int GetSourceFrameFromHardwareFrame( int64_t iHardwareFrame, bool *bApproximate = nullptr ) const; bool SetPositionFrames( int frames = -1 ); RageSoundParams::StopMode_t GetStopMode() const; // resolves M_AUTO diff --git a/src/RageSoundManager.cpp b/src/RageSoundManager.cpp index 90c9872f91..19b4db4cd3 100644 --- a/src/RageSoundManager.cpp +++ b/src/RageSoundManager.cpp @@ -33,9 +33,9 @@ static RageMutex g_SoundManMutex("SoundMan"); static Preference g_sSoundDrivers( "SoundDrivers", "" ); // "" == DEFAULT_SOUND_DRIVER_LIST -RageSoundManager *SOUNDMAN = NULL; +RageSoundManager *SOUNDMAN = nullptr; -RageSoundManager::RageSoundManager(): m_pDriver(NULL), m_fMixVolume(1.0f), +RageSoundManager::RageSoundManager(): m_pDriver(nullptr), m_fMixVolume(1.0f), m_fVolumeOfNonCriticalSounds(1.0f) {} static LocalizedString COULDNT_FIND_SOUND_DRIVER( "RageSoundManager", "Couldn't find a sound driver that works" ); diff --git a/src/RageSoundMixBuffer.cpp b/src/RageSoundMixBuffer.cpp index dca8a4f1ca..6290e986d2 100644 --- a/src/RageSoundMixBuffer.cpp +++ b/src/RageSoundMixBuffer.cpp @@ -12,7 +12,7 @@ static bool g_bVector = Vector::CheckForVector(); RageSoundMixBuffer::RageSoundMixBuffer() { m_iBufSize = m_iBufUsed = 0; - m_pMixbuf = NULL; + m_pMixbuf = nullptr; m_iOffset = 0; } diff --git a/src/RageSoundReader.h b/src/RageSoundReader.h index f7f51f850a..baba9c33bd 100644 --- a/src/RageSoundReader.h +++ b/src/RageSoundReader.h @@ -40,7 +40,7 @@ public: virtual float GetStreamToSourceRatio() const = 0; virtual RString GetError() const = 0; - int RetriedRead( float *pBuffer, int iFrames, int *iSourceFrame = NULL, float *fRate = NULL ); + int RetriedRead( float *pBuffer, int iFrames, int *iSourceFrame = nullptr, float *fRate = nullptr ); }; #endif diff --git a/src/RageSoundReader_Chain.cpp b/src/RageSoundReader_Chain.cpp index eeba173da3..1d51c3ef0e 100644 --- a/src/RageSoundReader_Chain.cpp +++ b/src/RageSoundReader_Chain.cpp @@ -55,7 +55,7 @@ void RageSoundReader_Chain::AddSound( int iIndex, float fOffsetSecs, float fPan s.iIndex = iIndex; s.iOffsetMS = lrintf( fOffsetSecs * 1000 ); s.fPan = fPan; - s.pSound = NULL; + s.pSound = nullptr; m_aSounds.push_back( s ); } @@ -130,7 +130,7 @@ void RageSoundReader_Chain::Finish() LOG->Warn( "Discarded sound with %i channels, not %i", it->GetNumChannels(), m_iChannels ); delete it; - it = NULL; + it = nullptr; } } } @@ -240,7 +240,7 @@ void RageSoundReader_Chain::ReleaseSound( Sound *s ) RageSoundReader *&pSound = s->pSound; delete pSound; - pSound = NULL; + pSound = nullptr; m_apActiveSounds.erase( it ); } diff --git a/src/RageSoundReader_FileReader.cpp b/src/RageSoundReader_FileReader.cpp index caa333e0b1..590188915b 100644 --- a/src/RageSoundReader_FileReader.cpp +++ b/src/RageSoundReader_FileReader.cpp @@ -18,7 +18,7 @@ RageSoundReader_FileReader *RageSoundReader_FileReader::TryOpenFile( RageFileBasic *pFile, RString &error, RString format, bool &bKeepTrying ) { - RageSoundReader_FileReader *Sample = NULL; + RageSoundReader_FileReader *Sample = nullptr; #ifndef NO_WAV_SUPPORT if( !format.CompareNoCase("wav") ) @@ -38,7 +38,7 @@ RageSoundReader_FileReader *RageSoundReader_FileReader::TryOpenFile( RageFileBas return nullptr; OpenResult ret = Sample->Open( pFile ); - pFile = NULL; // Sample owns it now + pFile = nullptr; // Sample owns it now if( ret == OPEN_OK ) return Sample; diff --git a/src/RageSoundReader_FileReader.h b/src/RageSoundReader_FileReader.h index 7184939a33..b7cbafc665 100644 --- a/src/RageSoundReader_FileReader.h +++ b/src/RageSoundReader_FileReader.h @@ -34,7 +34,7 @@ public: /* Open a file. If pPrebuffer is non-NULL, and the file is sufficiently small, * the (possibly compressed) data will be loaded entirely into memory, and pPrebuffer * will be set to true. */ - static RageSoundReader_FileReader *OpenFile( RString filename, RString &error, bool *pPrebuffer = NULL ); + static RageSoundReader_FileReader *OpenFile( RString filename, RString &error, bool *pPrebuffer = nullptr ); protected: void SetError( RString sError ) const { m_sError = sError; } diff --git a/src/RageSoundReader_MP3.cpp b/src/RageSoundReader_MP3.cpp index e2761ac43f..5706c47b1f 100644 --- a/src/RageSoundReader_MP3.cpp +++ b/src/RageSoundReader_MP3.cpp @@ -754,7 +754,7 @@ bool RageSoundReader_MP3::MADLIB_rewind() * set it, then we'll be desynced by a frame after an accurate seek. */ // mad->header_bytes = 0; mad->first_frame = true; - mad->Stream.this_frame = NULL; + mad->Stream.this_frame = nullptr; return true; } diff --git a/src/RageSoundReader_Merge.cpp b/src/RageSoundReader_Merge.cpp index 776a23c5d6..50c8b9ef9f 100644 --- a/src/RageSoundReader_Merge.cpp +++ b/src/RageSoundReader_Merge.cpp @@ -99,7 +99,7 @@ void RageSoundReader_Merge::Finish( int iPreferredSampleRate ) LOG->Warn( "Discarded sound with %i channels, not %i", it->GetNumChannels(), m_iChannels ); delete it; - it = NULL; + it = nullptr; } else { diff --git a/src/RageSoundReader_PitchChange.cpp b/src/RageSoundReader_PitchChange.cpp index 9d54e0e214..11d77fc286 100644 --- a/src/RageSoundReader_PitchChange.cpp +++ b/src/RageSoundReader_PitchChange.cpp @@ -1,124 +1,124 @@ -/* - * Implements properties: - * "Speed" - cause the sound to play faster or slower - * "Pitch" - raise or lower the pitch of the sound - * - * Pitch changing is implemented by combining speed changing and rate changing - * (via resampling). The resampler needs to be changed later than the speed - * changer; this class just controls parameters on the other two real filters. - */ - -#include "global.h" -#include "RageSoundReader_PitchChange.h" -#include "RageSoundReader_SpeedChange.h" -#include "RageSoundReader_Resample_Good.h" -#include "RageLog.h" - -RageSoundReader_PitchChange::RageSoundReader_PitchChange( RageSoundReader *pSource ): - RageSoundReader_Filter( NULL ) -{ - m_pSpeedChange = new RageSoundReader_SpeedChange( pSource ); - m_pResample = new RageSoundReader_Resample_Good( m_pSpeedChange, m_pSpeedChange->GetSampleRate() ); - m_pSource = m_pResample; - m_fSpeedRatio = 1.0f; - m_fPitchRatio = 1.0f; - m_fLastSetSpeedRatio = m_fSpeedRatio; - m_fLastSetPitchRatio = m_fPitchRatio; -} - -RageSoundReader_PitchChange::RageSoundReader_PitchChange( const RageSoundReader_PitchChange &cpy ): - RageSoundReader_Filter( cpy ) -{ - /* The source tree has already been copied. Our source is m_pResample; its source - * is m_pSpeedChange (and its source is a copy of the pSource we were initialized - * with). */ - m_pResample = dynamic_cast( &*m_pSource ); - m_pSpeedChange = dynamic_cast( m_pResample->GetSource() ); - m_fSpeedRatio = cpy.m_fSpeedRatio; - m_fPitchRatio = cpy.m_fPitchRatio; - m_fLastSetSpeedRatio = cpy.m_fLastSetSpeedRatio; - m_fLastSetPitchRatio = cpy.m_fLastSetPitchRatio; -} - -int RageSoundReader_PitchChange::Read( float *pBuf, int iFrames ) -{ - /* m_pSpeedChange->NextReadWillStep is true if speed changes will be applied - * immediately on the next Read(). When this is true, apply the ratio to the - * resampler and the speed changer simultaneously, so they take effect as - * closely together as possible. */ - if( (m_fLastSetSpeedRatio != m_fSpeedRatio || m_fLastSetPitchRatio != m_fPitchRatio) && - m_pSpeedChange->NextReadWillStep() ) - { - float fRate = GetStreamToSourceRatio(); - - /* This is the simple way: */ - // m_pResample->SetRate( m_fPitchRatio ); - // m_pSpeedChange->SetSpeedRatio( m_fSpeedRatio / m_fPitchRatio ); - - /* However, the resampler has a limited granularity due to internal fixed- - * point math, and the actual ratio will be slightly different than what - * we tell it to use. The actual ratio used is fActualPitchRatio. */ - m_pResample->SetRate( m_fPitchRatio ); - float fActualPitchRatio = m_pResample->GetRate(); - float fRequestedSpeedRatio = m_fSpeedRatio / fActualPitchRatio; - m_pSpeedChange->SetSpeedRatio( fRequestedSpeedRatio ); - - m_fLastSetSpeedRatio = m_fSpeedRatio; - m_fLastSetPitchRatio = m_fPitchRatio; - - /* If we just applied a new speed and it caused the ratio to change, return - * no data, so the caller can see the new ratio. */ - if( fRate != GetStreamToSourceRatio() ) - return 0; - } - - return RageSoundReader_Filter::Read( pBuf, iFrames ); -} - -bool RageSoundReader_PitchChange::SetProperty( const RString &sProperty, float fValue ) -{ - if( sProperty == "Rate" ) - { - /* Don't propagate this. m_pResample will take it, but it's under - * our control. */ - return false; - } - if( sProperty == "Speed" ) - { - SetSpeedRatio( fValue ); - return true; - } - - if( sProperty == "Pitch" ) - { - SetPitchRatio( fValue ); - return true; - } - - return RageSoundReader_Filter::SetProperty( sProperty, fValue ); -} - -/* - * Copyright (c) 2006 Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* + * Implements properties: + * "Speed" - cause the sound to play faster or slower + * "Pitch" - raise or lower the pitch of the sound + * + * Pitch changing is implemented by combining speed changing and rate changing + * (via resampling). The resampler needs to be changed later than the speed + * changer; this class just controls parameters on the other two real filters. + */ + +#include "global.h" +#include "RageSoundReader_PitchChange.h" +#include "RageSoundReader_SpeedChange.h" +#include "RageSoundReader_Resample_Good.h" +#include "RageLog.h" + +RageSoundReader_PitchChange::RageSoundReader_PitchChange( RageSoundReader *pSource ): + RageSoundReader_Filter(nullptr) +{ + m_pSpeedChange = new RageSoundReader_SpeedChange( pSource ); + m_pResample = new RageSoundReader_Resample_Good( m_pSpeedChange, m_pSpeedChange->GetSampleRate() ); + m_pSource = m_pResample; + m_fSpeedRatio = 1.0f; + m_fPitchRatio = 1.0f; + m_fLastSetSpeedRatio = m_fSpeedRatio; + m_fLastSetPitchRatio = m_fPitchRatio; +} + +RageSoundReader_PitchChange::RageSoundReader_PitchChange( const RageSoundReader_PitchChange &cpy ): + RageSoundReader_Filter( cpy ) +{ + /* The source tree has already been copied. Our source is m_pResample; its source + * is m_pSpeedChange (and its source is a copy of the pSource we were initialized + * with). */ + m_pResample = dynamic_cast( &*m_pSource ); + m_pSpeedChange = dynamic_cast( m_pResample->GetSource() ); + m_fSpeedRatio = cpy.m_fSpeedRatio; + m_fPitchRatio = cpy.m_fPitchRatio; + m_fLastSetSpeedRatio = cpy.m_fLastSetSpeedRatio; + m_fLastSetPitchRatio = cpy.m_fLastSetPitchRatio; +} + +int RageSoundReader_PitchChange::Read( float *pBuf, int iFrames ) +{ + /* m_pSpeedChange->NextReadWillStep is true if speed changes will be applied + * immediately on the next Read(). When this is true, apply the ratio to the + * resampler and the speed changer simultaneously, so they take effect as + * closely together as possible. */ + if( (m_fLastSetSpeedRatio != m_fSpeedRatio || m_fLastSetPitchRatio != m_fPitchRatio) && + m_pSpeedChange->NextReadWillStep() ) + { + float fRate = GetStreamToSourceRatio(); + + /* This is the simple way: */ + // m_pResample->SetRate( m_fPitchRatio ); + // m_pSpeedChange->SetSpeedRatio( m_fSpeedRatio / m_fPitchRatio ); + + /* However, the resampler has a limited granularity due to internal fixed- + * point math, and the actual ratio will be slightly different than what + * we tell it to use. The actual ratio used is fActualPitchRatio. */ + m_pResample->SetRate( m_fPitchRatio ); + float fActualPitchRatio = m_pResample->GetRate(); + float fRequestedSpeedRatio = m_fSpeedRatio / fActualPitchRatio; + m_pSpeedChange->SetSpeedRatio( fRequestedSpeedRatio ); + + m_fLastSetSpeedRatio = m_fSpeedRatio; + m_fLastSetPitchRatio = m_fPitchRatio; + + /* If we just applied a new speed and it caused the ratio to change, return + * no data, so the caller can see the new ratio. */ + if( fRate != GetStreamToSourceRatio() ) + return 0; + } + + return RageSoundReader_Filter::Read( pBuf, iFrames ); +} + +bool RageSoundReader_PitchChange::SetProperty( const RString &sProperty, float fValue ) +{ + if( sProperty == "Rate" ) + { + /* Don't propagate this. m_pResample will take it, but it's under + * our control. */ + return false; + } + if( sProperty == "Speed" ) + { + SetSpeedRatio( fValue ); + return true; + } + + if( sProperty == "Pitch" ) + { + SetPitchRatio( fValue ); + return true; + } + + return RageSoundReader_Filter::SetProperty( sProperty, fValue ); +} + +/* + * Copyright (c) 2006 Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RageSoundReader_Resample_Good.cpp b/src/RageSoundReader_Resample_Good.cpp index 4b90c97058..9e3fa77b34 100644 --- a/src/RageSoundReader_Resample_Good.cpp +++ b/src/RageSoundReader_Resample_Good.cpp @@ -467,7 +467,7 @@ public: * when filtering. This will only cause the low-pass filter to be rounded; * the conversion ratio will always be exact. */ m_iUpFactor = iUpFactor; - m_pPolyphase = NULL; + m_pPolyphase = nullptr; int iFilterIncrement = max( (iMaxDownFactor - iMinDownFactor)/10, 1 ); for( int iDownFactor = iMinDownFactor; iDownFactor <= iMaxDownFactor; iDownFactor += iFilterIncrement ) diff --git a/src/RageSoundReader_ThreadedBuffer.cpp b/src/RageSoundReader_ThreadedBuffer.cpp index a8f464ce65..a178bdc9a2 100644 --- a/src/RageSoundReader_ThreadedBuffer.cpp +++ b/src/RageSoundReader_ThreadedBuffer.cpp @@ -52,7 +52,7 @@ RageSoundReader_ThreadedBuffer::RageSoundReader_ThreadedBuffer( RageSoundReader } RageSoundReader_ThreadedBuffer::RageSoundReader_ThreadedBuffer( const RageSoundReader_ThreadedBuffer &cpy ): - RageSoundReader_Filter( NULL ), // don't touch m_pSource before DisableBuffering + RageSoundReader_Filter(nullptr), // don't touch m_pSource before DisableBuffering m_Event( "ThreadedBuffer" ) { bool bWasEnabled = cpy.DisableBuffering(); diff --git a/src/RageSoundReader_Vorbisfile.cpp b/src/RageSoundReader_Vorbisfile.cpp index b410d3df49..adb959c39a 100644 --- a/src/RageSoundReader_Vorbisfile.cpp +++ b/src/RageSoundReader_Vorbisfile.cpp @@ -87,7 +87,7 @@ RageSoundReader_FileReader::OpenResult RageSoundReader_Vorbisfile::Open( RageFil { SetError( ov_ssprintf(ret, "ov_open failed") ); delete vf; - vf = NULL; + vf = nullptr; switch( ret ) { case OV_ENOTVORBIS: @@ -279,7 +279,7 @@ int RageSoundReader_Vorbisfile::GetNextSourceFrame() const RageSoundReader_Vorbisfile::RageSoundReader_Vorbisfile() { - vf = NULL; + vf = nullptr; } RageSoundReader_Vorbisfile::~RageSoundReader_Vorbisfile() diff --git a/src/RageSoundReader_WAV.cpp b/src/RageSoundReader_WAV.cpp index d8361d29a4..c3eb96f626 100644 --- a/src/RageSoundReader_WAV.cpp +++ b/src/RageSoundReader_WAV.cpp @@ -200,7 +200,7 @@ public: WavReaderADPCM( RageFileBasic &f, const RageSoundReader_WAV::WavData &data ): WavReader(f, data) { - m_pBuffer = NULL; + m_pBuffer = nullptr; } virtual ~WavReaderADPCM() @@ -605,7 +605,7 @@ int RageSoundReader_WAV::Read( float *pBuf, int iFrames ) RageSoundReader_WAV::RageSoundReader_WAV() { - m_pImpl = NULL; + m_pImpl = nullptr; } RageSoundReader_WAV::~RageSoundReader_WAV() diff --git a/src/RageSurface.cpp b/src/RageSurface.cpp index 4423c5acac..84f1e82ba9 100644 --- a/src/RageSurface.cpp +++ b/src/RageSurface.cpp @@ -43,7 +43,7 @@ RageSurfaceFormat::RageSurfaceFormat(): Rmask(Mask[0]), Gmask(Mask[1]), Bmask(Mask[2]), Amask(Mask[3]), Rshift(Shift[0]), Gshift(Shift[1]), Bshift(Shift[2]), Ashift(Shift[3]) { - palette = NULL; + palette = nullptr; } RageSurfaceFormat::RageSurfaceFormat( const RageSurfaceFormat &cpy ): @@ -121,7 +121,7 @@ bool RageSurfaceFormat::Equivalent( const RageSurfaceFormat &rhs ) const RageSurface::RageSurface() { format = &fmt; - pixels = NULL; + pixels = nullptr; pixels_owned = true; } @@ -140,7 +140,7 @@ RageSurface::RageSurface( const RageSurface &cpy ) memcpy( pixels, cpy.pixels, pitch*h ); } else - pixels = NULL; + pixels = nullptr; } RageSurface::~RageSurface() diff --git a/src/RageSurfaceUtils.cpp b/src/RageSurfaceUtils.cpp index 5296926205..f6756f32e9 100644 --- a/src/RageSurfaceUtils.cpp +++ b/src/RageSurfaceUtils.cpp @@ -151,7 +151,7 @@ bool RageSurfaceUtils::ConvertSurface( const RageSurface *src, RageSurface *&dst if( width == src->w && height == src->h && src->format->Equivalent( *dst->format ) ) { delete dst; - dst = NULL; + dst = nullptr; return false; } diff --git a/src/RageSurfaceUtils_Palettize.cpp b/src/RageSurfaceUtils_Palettize.cpp index 72eb1d150b..35ab1b1fc6 100644 --- a/src/RageSurfaceUtils_Palettize.cpp +++ b/src/RageSurfaceUtils_Palettize.cpp @@ -170,7 +170,7 @@ void RageSurfaceUtils::Palettize( RageSurface *&pImg, int iColors, bool bDither acolorhash_hash acht; bool fs_direction = 0; - pixerror_t *thiserr = NULL, *nexterr = NULL; + pixerror_t *thiserr = nullptr, *nexterr = nullptr; if( bDither ) { @@ -222,7 +222,7 @@ void RageSurfaceUtils::Palettize( RageSurface *&pImg, int iColors, bool bDither if( ind == -1 ) { // No; search acolormap for closest match. - static int square_table[512], *pSquareTable = NULL; + static int square_table[512], *pSquareTable = nullptr; if( pSquareTable == nullptr ) { pSquareTable = square_table+256; diff --git a/src/RageSurface_Load.cpp b/src/RageSurface_Load.cpp index 050f2a1c82..104a5f25e7 100644 --- a/src/RageSurface_Load.cpp +++ b/src/RageSurface_Load.cpp @@ -12,7 +12,7 @@ static RageSurface *TryOpenFile( RString sPath, bool bHeaderOnly, RString &error, RString format, bool &bKeepTrying ) { - RageSurface *ret = NULL; + RageSurface *ret = nullptr; RageSurfaceUtils::OpenResult result; if( !format.CompareNoCase("png") ) result = RageSurface_Load_PNG( sPath, ret, bHeaderOnly, error ); diff --git a/src/RageSurface_Load_BMP.cpp b/src/RageSurface_Load_BMP.cpp index 7534179470..53269d9cf6 100644 --- a/src/RageSurface_Load_BMP.cpp +++ b/src/RageSurface_Load_BMP.cpp @@ -34,7 +34,7 @@ static RageSurfaceUtils::OpenResult LoadBMP( RageFile &f, RageSurface *&img, RSt return RageSurfaceUtils::OPEN_UNKNOWN_FILE_FORMAT; } - img = NULL; + img = nullptr; read_u32_le( f, sError ); /* file size */ read_u32_le( f, sError ); /* unused */ @@ -198,13 +198,13 @@ RageSurfaceUtils::OpenResult RageSurface_Load_BMP( const RString &sPath, RageSur } RageSurfaceUtils::OpenResult ret; - img = NULL; + img = nullptr; ret = LoadBMP( f, img, error ); if( ret != RageSurfaceUtils::OPEN_OK && img != nullptr ) { delete img; - img = NULL; + img = nullptr; } return ret; diff --git a/src/RageSurface_Load_JPEG.cpp b/src/RageSurface_Load_JPEG.cpp index c7f9e4842f..fbe3ef1180 100644 --- a/src/RageSurface_Load_JPEG.cpp +++ b/src/RageSurface_Load_JPEG.cpp @@ -68,7 +68,7 @@ void RageFile_JPEG_init_source( j_decompress_ptr cinfo ) { RageFile_source_mgr *src = (RageFile_source_mgr *) cinfo->src; src->start_of_file = true; - src->pub.next_input_byte = NULL; + src->pub.next_input_byte = nullptr; src->pub.bytes_in_buffer = 0; } @@ -123,7 +123,7 @@ static RageSurface *RageSurface_Load_JPEG( RageFile *f, const char *fn, char err jerr.pub.error_exit = my_error_exit; jerr.pub.output_message = my_output_message; - RageSurface *volatile img = NULL; /* volatile to prevent possible problems with setjmp */ + RageSurface *volatile img = nullptr; /* volatile to prevent possible problems with setjmp */ if( setjmp(jerr.setjmp_buffer) ) { diff --git a/src/RageSurface_Load_PNG.cpp b/src/RageSurface_Load_PNG.cpp index 1bdc4195f2..7b1d99992f 100644 --- a/src/RageSurface_Load_PNG.cpp +++ b/src/RageSurface_Load_PNG.cpp @@ -85,7 +85,7 @@ static RageSurface *RageSurface_Load_PNG( RageFile *f, const char *fn, char erro return nullptr; } - RageSurface *volatile img = NULL; + RageSurface *volatile img = nullptr; CHECKPOINT; if( setjmp(png_jmpbuf(png) )) { @@ -175,7 +175,7 @@ static RageSurface *RageSurface_Load_PNG( RageFile *f, const char *fn, char erro int ret = png_get_PLTE( png, info_ptr, &palette, &num_palette ); ASSERT( ret == PNG_INFO_PLTE ); - png_byte *trans = NULL; + png_byte *trans = nullptr; int num_trans = 0; png_get_tRNS( png, info_ptr, &trans, &num_trans, NULL ); diff --git a/src/RageThreads.cpp b/src/RageThreads.cpp index 67007c5b6c..2eeda545a0 100644 --- a/src/RageThreads.cpp +++ b/src/RageThreads.cpp @@ -35,7 +35,7 @@ bool RageThread::s_bSystemSupportsTLS = false; bool RageThread::s_bIsShowingDialog = false; #define MAX_THREADS 128 -//static vector *g_MutexList = NULL; /* watch out for static initialization order problems */ +//static vector *g_MutexList = nullptr; /* watch out for static initialization order problems */ struct ThreadSlot { @@ -58,7 +58,7 @@ struct ThreadSlot char m_szFormattedBuf[1024]; ThreadCheckpoint() { Set( NULL, 0, NULL ); } - void Set( const char *szFile, int iLine, const char *szMessage = NULL ); + void Set( const char *szFile, int iLine, const char *szMessage = nullptr ); const char *GetFormattedCheckpoint(); }; ThreadCheckpoint m_Checkpoints[CHECKPOINT_COUNT]; @@ -66,12 +66,12 @@ struct ThreadSlot const char *GetFormattedCheckpoint( int lineno ); ThreadSlot(): m_bUsed(false), m_iID(GetInvalidThreadId()), - m_pImpl(NULL), m_iCurCheckpoint(0), m_iNumCheckpoints(0) {} + m_pImpl(nullptr), m_iCurCheckpoint(0), m_iNumCheckpoints(0) {} void Init() { m_iID = GetInvalidThreadId(); m_iCurCheckpoint = m_iNumCheckpoints = 0; - m_pImpl = NULL; + m_pImpl = nullptr; /* Reset used last; otherwise, a thread creation might pick up the slot. */ m_bUsed = false; @@ -132,7 +132,7 @@ const char *ThreadSlot::GetFormattedCheckpoint( int lineno ) } static ThreadSlot g_ThreadSlots[MAX_THREADS]; -struct ThreadSlot *g_pUnknownThreadSlot = NULL; +struct ThreadSlot *g_pUnknownThreadSlot = nullptr; /* Lock this mutex before using or modifying m_pImpl. Other values are just identifiers, * so possibly racing over them is harmless (simply using a stale thread ID, etc). */ @@ -207,11 +207,11 @@ static ThreadSlot *GetUnknownThreadSlot() return g_pUnknownThreadSlot; } -RageThread::RageThread(): m_pSlot(NULL), m_sName("unnamed") {} +RageThread::RageThread(): m_pSlot(nullptr), m_sName("unnamed") {} /* Copying a thread does not start the copy. */ RageThread::RageThread( const RageThread &cpy ): - m_pSlot(NULL), m_sName(cpy.m_sName) {} + m_pSlot(nullptr), m_sName(cpy.m_sName) {} RageThread::~RageThread() { @@ -275,7 +275,7 @@ RageThreadRegister::~RageThreadRegister() LockMut( GetThreadSlotsLock() ); m_pSlot->Release(); - m_pSlot = NULL; + m_pSlot = nullptr; } const char *RageThread::GetCurrentThreadName() @@ -317,7 +317,7 @@ int RageThread::Wait() LockMut( GetThreadSlotsLock() ); m_pSlot->Release(); - m_pSlot = NULL; + m_pSlot = nullptr; return ret; } @@ -521,7 +521,7 @@ void RageMutex::MarkLockedMutex() } /* XXX: How can g_FreeMutexIDs and g_MutexList be threadsafed? */ -static set *g_FreeMutexIDs = NULL; +static set *g_FreeMutexIDs = nullptr; #endif RageMutex::RageMutex( const RString &name ): @@ -571,7 +571,7 @@ RageMutex::~RageMutex() if( g_MutexList->empty() ) { delete g_MutexList; - g_MutexList = NULL; + g_MutexList = nullptr; } delete m_pMutex; @@ -705,7 +705,7 @@ bool RageEvent::Wait( RageTimer *pTimeout ) /* A zero RageTimer also means no timeout. */ if( pTimeout != nullptr && pTimeout->IsZero() ) - pTimeout = NULL; + pTimeout = nullptr; bool bRet = m_pEvent->Wait( pTimeout ); m_LockedBy = GetThisThreadId(); diff --git a/src/RageThreads.h b/src/RageThreads.h index 1f32779c0e..c6dafb9a3f 100644 --- a/src/RageThreads.h +++ b/src/RageThreads.h @@ -132,9 +132,9 @@ class LockMutex public: LockMutex(RageMutex &mut, const char *file, int line); - LockMutex(RageMutex &mut): mutex(mut), file(NULL), line(-1), locked_at(-1), locked(true) { mutex.Lock(); } + LockMutex(RageMutex &mut): mutex(mut), file(nullptr), line(-1), locked_at(-1), locked(true) { mutex.Lock(); } ~LockMutex(); - LockMutex(LockMutex &cpy): mutex(cpy.mutex), file(NULL), line(-1), locked_at(cpy.locked_at), locked(true) { mutex.Lock(); } + LockMutex(LockMutex &cpy): mutex(cpy.mutex), file(nullptr), line(-1), locked_at(cpy.locked_at), locked(true) { mutex.Lock(); } /** * @brief Unlock the mutex (before this would normally go out of scope). @@ -161,7 +161,7 @@ public: * If false is returned, the wait timed out (and the mutex is locked, as if the * event had been signalled). */ - bool Wait( RageTimer *pTimeout = NULL ); + bool Wait( RageTimer *pTimeout = nullptr ); void Signal(); void Broadcast(); bool WaitTimeoutSupported() const; diff --git a/src/RageUtil.cpp b/src/RageUtil.cpp index af287a284d..cb3fff0c36 100644 --- a/src/RageUtil.cpp +++ b/src/RageUtil.cpp @@ -31,7 +31,7 @@ MersenneTwister::MersenneTwister( int iSeed ) : m_iNext(0) void MersenneTwister::Reset( int iSeed ) { if( iSeed == 0 ) - iSeed = time(NULL); + iSeed = time(nullptr); m_Values[0] = iSeed; m_iNext = 0; @@ -370,7 +370,7 @@ RString FormatNumberAndSuffix( int i ) struct tm GetLocalTime() { - const time_t t = time(NULL); + const time_t t = time(nullptr); struct tm tm; localtime_r( &t, &tm ); return tm; @@ -390,7 +390,7 @@ RString vssprintf( const char *szFormat, va_list argList ) RString sStr; #if defined(WIN32) && !defined(__MINGW32__) - char *pBuf = NULL; + char *pBuf = nullptr; int iChars = 1; int iUsed = 0; int iTry = 0; @@ -971,7 +971,7 @@ void MakeValidFilename( RString &sName ) } int g_argc = 0; -char **g_argv = NULL; +char **g_argv = nullptr; void SetCommandlineArguments( int argc, char **argv ) { @@ -1369,16 +1369,16 @@ void Regex::Set( const RString &sStr ) void Regex::Release() { pcre_free( m_pReg ); - m_pReg = NULL; + m_pReg = nullptr; m_sPattern = RString(); } -Regex::Regex( const RString &sStr ): m_pReg(NULL), m_iBackrefs(0), m_sPattern(RString()) +Regex::Regex( const RString &sStr ): m_pReg(nullptr), m_iBackrefs(0), m_sPattern(RString()) { Set( sStr ); } -Regex::Regex( const Regex &rhs ): m_pReg(NULL), m_iBackrefs(0), m_sPattern(RString()) +Regex::Regex( const Regex &rhs ): m_pReg(nullptr), m_iBackrefs(0), m_sPattern(RString()) { Set( rhs.m_sPattern ); } diff --git a/src/RageUtil.h b/src/RageUtil.h index 366f3905e6..47bd2ab976 100644 --- a/src/RageUtil.h +++ b/src/RageUtil.h @@ -641,7 +641,7 @@ namespace StringConversion class RageFileBasic; bool FileCopy( const RString &sSrcFile, const RString &sDstFile ); -bool FileCopy( RageFileBasic &in, RageFileBasic &out, RString &sError, bool *bReadError = NULL ); +bool FileCopy( RageFileBasic &in, RageFileBasic &out, RString &sError, bool *bReadError = nullptr ); template void GetAsNotInBs( const vector &as, const vector &bs, vector &difference ) diff --git a/src/RageUtil_AutoPtr.h b/src/RageUtil_AutoPtr.h index 2f75ac0970..bae6abf939 100644 --- a/src/RageUtil_AutoPtr.h +++ b/src/RageUtil_AutoPtr.h @@ -27,7 +27,7 @@ class AutoPtrCopyOnWrite { public: /* This constructor only exists to make us work with STL containers. */ - inline AutoPtrCopyOnWrite(): m_pPtr(NULL), m_iRefCount(new int(1)) + inline AutoPtrCopyOnWrite(): m_pPtr(nullptr), m_iRefCount(new int(1)) { } @@ -127,9 +127,9 @@ public: T& operator*() { return *m_pPtr; } T* operator->() { return m_pPtr; } - explicit HiddenPtr( T *p = NULL ): m_pPtr(p) {} + explicit HiddenPtr( T *p = nullptr ): m_pPtr(p) {} - HiddenPtr( const HiddenPtr &cpy ): m_pPtr(NULL) + HiddenPtr( const HiddenPtr &cpy ): m_pPtr(nullptr) { if( cpy.m_pPtr != nullptr ) m_pPtr = HiddenPtrTraits::Copy( cpy.m_pPtr ); @@ -140,7 +140,7 @@ public: HiddenPtr( const HiddenPtr &cpy ) { if( cpy.m_pPtr == nullptr ) - m_pPtr = NULL; + m_pPtr = nullptr; else m_pPtr = HiddenPtrTraits::Copy( cpy.m_pPtr ); } diff --git a/src/RageUtil_CachedObject.cpp b/src/RageUtil_CachedObject.cpp index e67ae85cd1..bc2bbc6373 100644 --- a/src/RageUtil_CachedObject.cpp +++ b/src/RageUtil_CachedObject.cpp @@ -20,7 +20,7 @@ struct User Object *p; if( !cache.Get(&p) ) { - p = NULL; + p = nullptr; cache.Set(p); } return p; diff --git a/src/RageUtil_CachedObject.h b/src/RageUtil_CachedObject.h index 50271205ca..5b8f4008de 100644 --- a/src/RageUtil_CachedObject.h +++ b/src/RageUtil_CachedObject.h @@ -18,13 +18,13 @@ template class CachedObject { public: - CachedObject(): m_pObject(NULL) + CachedObject(): m_pObject(nullptr) { /* A new object is being constructed, so invalidate negative caching. */ ClearCacheNegative(); } - CachedObject( const CachedObject &cpy ): m_pObject(NULL) + CachedObject( const CachedObject &cpy ): m_pObject(nullptr) { ClearCacheNegative(); } @@ -43,7 +43,7 @@ public: CachedObjectHelpers::Lock(); for( typename set::iterator p = m_spObjectPointers.begin(); p != m_spObjectPointers.end(); ++p ) { - (*p)->m_pCache = NULL; + (*p)->m_pCache = nullptr; (*p)->m_bCacheIsSet = false; } CachedObjectHelpers::Unlock(); @@ -57,7 +57,7 @@ public: { if( (*p)->m_pCache == pObject ) { - (*p)->m_pCache = NULL; + (*p)->m_pCache = nullptr; (*p)->m_bCacheIsSet = false; } } @@ -109,7 +109,7 @@ class CachedObjectPointer public: typedef CachedObject Object; - CachedObjectPointer() : m_pCache(NULL), m_bCacheIsSet(false) + CachedObjectPointer() : m_pCache(nullptr), m_bCacheIsSet(false) { Object::Register( this ); } @@ -153,7 +153,7 @@ public: void Unset() { CachedObjectHelpers::Lock(); - m_pCache = NULL; + m_pCache = nullptr; m_bCacheIsSet = false; CachedObjectHelpers::Unlock(); } diff --git a/src/RageUtil_CircularBuffer.h b/src/RageUtil_CircularBuffer.h index 5f29305643..5f3713dba8 100644 --- a/src/RageUtil_CircularBuffer.h +++ b/src/RageUtil_CircularBuffer.h @@ -1,300 +1,300 @@ -/* CircBuf - A fast, thread-safe, lockless circular buffer. */ - -#ifndef RAGE_UTIL_CIRCULAR_BUFFER -#define RAGE_UTIL_CIRCULAR_BUFFER - -/* Lock-free circular buffer. This should be threadsafe if one thread is reading - * and another is writing. */ -template -class CircBuf -{ - T *buf; - /* read_pos is the position data is read from; write_pos is the position - * data is written to. If read_pos == write_pos, the buffer is empty. - * - * There will always be at least one position empty, as a completely full - * buffer (read_pos == write_pos) is indistinguishable from an empty buffer. - * - * Invariants: read_pos < size, write_pos < size. */ - unsigned size; - unsigned m_iBlockSize; - - /* These are volatile to prevent reads and writes to them from being optimized. */ - volatile unsigned read_pos, write_pos; - -public: - CircBuf() - { - buf = NULL; - clear(); - } - - ~CircBuf() - { - delete[] buf; - } - - void swap( CircBuf &rhs ) - { - std::swap( size, rhs.size ); - std::swap( m_iBlockSize, rhs.m_iBlockSize ); - std::swap( read_pos, rhs.read_pos ); - std::swap( write_pos, rhs.write_pos ); - std::swap( buf, rhs.buf ); - } - - CircBuf &operator=( const CircBuf &rhs ) - { - CircBuf c( rhs ); - this->swap( c ); - return *this; - } - - CircBuf( const CircBuf &cpy ) - { - size = cpy.size; - read_pos = cpy.read_pos; - write_pos = cpy.write_pos; - m_iBlockSize = cpy.m_iBlockSize; - if( size ) - { - buf = new T[size]; - memcpy( buf, cpy.buf, size*sizeof(T) ); - } - else - { - buf = NULL; - } - } - - /* Return the number of elements available to read. */ - unsigned num_readable() const - { - const int rpos = read_pos; - const int wpos = write_pos; - if( rpos < wpos ) - /* The buffer looks like "eeeeDDDDeeee" (e = empty, D = data). */ - return wpos - rpos; - else if( rpos > wpos ) - /* The buffer looks like "DDeeeeeeeeDD" (e = empty, D = data). */ - return size - (rpos - wpos); - else // if( rpos == wpos ) - /* The buffer looks like "eeeeeeeeeeee" (e = empty, D = data). */ - return 0; - } - - /* Return the number of writable elements. */ - unsigned num_writable() const - { - const int rpos = read_pos; - const int wpos = write_pos; - - int ret; - if( rpos < wpos ) - /* The buffer looks like "eeeeDDDDeeee" (e = empty, D = data). */ - ret = size - (wpos - rpos); - else if( rpos > wpos ) - /* The buffer looks like "DDeeeeeeeeDD" (e = empty, D = data). */ - ret = rpos - wpos; - else // if( rpos == wpos ) - /* The buffer looks like "eeeeeeeeeeee" (e = empty, D = data). */ - ret = size; - - /* Subtract the blocksize, to account for the element that we never fill - * while keeping the entries aligned to m_iBlockSize. */ - return ret - m_iBlockSize; - } - - unsigned capacity() const { return size; } - - void reserve( unsigned n, int iBlockSize = 1 ) - { - m_iBlockSize = iBlockSize; - - clear(); - delete[] buf; - buf = NULL; - - /* Reserve an extra byte. We'll never fill more than n bytes; the extra - * byte is to guarantee that read_pos != write_pos when the buffer is full, - * since that would be ambiguous with an empty buffer. */ - if( n != 0 ) - { - size = n+1; - size = ((size + iBlockSize - 1) / iBlockSize) * iBlockSize; // round up - - buf = new T[size]; - } - else - size = 0; - } - - void clear() - { - read_pos = write_pos = 0; - } - - /* Indicate that n elements have been written. */ - void advance_write_pointer( int n ) - { - write_pos = (write_pos + n) % size; - } - - /* Indicate that n elements have been read. */ - void advance_read_pointer( int n ) - { - read_pos = (read_pos + n) % size; - } - - void get_write_pointers( T *pPointers[2], unsigned pSizes[2] ) - { - const int rpos = read_pos; - const int wpos = write_pos; - - if( rpos <= wpos ) - { - /* The buffer looks like "eeeeDDDDeeee" or "eeeeeeeeeeee" (e = empty, D = data). */ - pPointers[0] = buf+wpos; - pPointers[1] = buf; - - pSizes[0] = size - wpos; - pSizes[1] = rpos; - } - else if( rpos > wpos ) - { - /* The buffer looks like "DDeeeeeeeeDD" (e = empty, D = data). */ - pPointers[0] = buf+wpos; - pPointers[1] = NULL; - - pSizes[0] = rpos - wpos; - pSizes[1] = 0; - } - - /* Subtract the blocksize, to account for the element that we never fill - * while keeping the entries aligned to m_iBlockSize. */ - if( pSizes[1] ) - pSizes[1] -= m_iBlockSize; - else - pSizes[0] -= m_iBlockSize; - } - - /* Like get_write_pointers, but only return the first range available. */ - T *get_write_pointer( unsigned *pSizes ) - { - T *pBothPointers[2]; - unsigned iBothSizes[2]; - get_write_pointers( pBothPointers, iBothSizes ); - *pSizes = iBothSizes[0]; - return pBothPointers[0]; - } - - void get_read_pointers( T *pPointers[2], unsigned pSizes[2] ) - { - const int rpos = read_pos; - const int wpos = write_pos; - - if( rpos < wpos ) - { - /* The buffer looks like "eeeeDDDDeeee" (e = empty, D = data). */ - pPointers[0] = buf+rpos; - pPointers[1] = NULL; - - pSizes[0] = wpos - rpos; - pSizes[1] = 0; - } - else if( rpos > wpos ) - { - /* The buffer looks like "DDeeeeeeeeDD" (e = empty, D = data). */ - pPointers[0] = buf+rpos; - pPointers[1] = buf; - - pSizes[0] = size - rpos; - pSizes[1] = wpos; - } - else - { - /* The buffer looks like "eeeeeeeeeeee" (e = empty, D = data). */ - pPointers[0] = NULL; - pPointers[1] = NULL; - - pSizes[0] = 0; - pSizes[1] = 0; - } - } - - /* Write buffer_size elements from buffer, and advance the write pointer. If - * the data will not fit entirely, the write pointer will be unchanged - * and false will be returned. */ - bool write( const T *buffer, unsigned buffer_size ) - { - T *p[2]; - unsigned sizes[2]; - get_write_pointers( p, sizes ); - - if( buffer_size > sizes[0] + sizes[1] ) - return false; - - const int from_first = min( buffer_size, sizes[0] ); - memcpy( p[0], buffer, from_first*sizeof(T) ); - if( buffer_size > sizes[0] ) - memcpy( p[1], buffer+from_first, max(buffer_size-sizes[0], 0u)*sizeof(T) ); - - advance_write_pointer( buffer_size ); - - return true; - } - - /* Read buffer_size elements from buffer, and advance the read pointer. If - * the buffer can not be filled completely, the read pointer will be unchanged - * and false will be returned. */ - bool read( T *buffer, unsigned buffer_size ) - { - T *p[2]; - unsigned sizes[2]; - get_read_pointers( p, sizes ); - - if( buffer_size > sizes[0] + sizes[1] ) - return false; - - const int from_first = min( buffer_size, sizes[0] ); - memcpy( buffer, p[0], from_first*sizeof(T) ); - if( buffer_size > sizes[0] ) - memcpy( buffer+from_first, p[1], max(buffer_size-sizes[0], 0u)*sizeof(T) ); - - /* Set the data that we just read to 0xFF. This way, if we're passing pointesr - * through, we can tell if we accidentally get a stale pointer. */ - memset( p[0], 0xFF, from_first*sizeof(T) ); - if( buffer_size > sizes[0] ) - memset( p[1], 0xFF, max(buffer_size-sizes[0], 0u)*sizeof(T) ); - - advance_read_pointer( buffer_size ); - return true; - } -}; - -#endif - -/* - * Copyright (c) 2004 Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* CircBuf - A fast, thread-safe, lockless circular buffer. */ + +#ifndef RAGE_UTIL_CIRCULAR_BUFFER +#define RAGE_UTIL_CIRCULAR_BUFFER + +/* Lock-free circular buffer. This should be threadsafe if one thread is reading + * and another is writing. */ +template +class CircBuf +{ + T *buf; + /* read_pos is the position data is read from; write_pos is the position + * data is written to. If read_pos == write_pos, the buffer is empty. + * + * There will always be at least one position empty, as a completely full + * buffer (read_pos == write_pos) is indistinguishable from an empty buffer. + * + * Invariants: read_pos < size, write_pos < size. */ + unsigned size; + unsigned m_iBlockSize; + + /* These are volatile to prevent reads and writes to them from being optimized. */ + volatile unsigned read_pos, write_pos; + +public: + CircBuf() + { + buf = nullptr; + clear(); + } + + ~CircBuf() + { + delete[] buf; + } + + void swap( CircBuf &rhs ) + { + std::swap( size, rhs.size ); + std::swap( m_iBlockSize, rhs.m_iBlockSize ); + std::swap( read_pos, rhs.read_pos ); + std::swap( write_pos, rhs.write_pos ); + std::swap( buf, rhs.buf ); + } + + CircBuf &operator=( const CircBuf &rhs ) + { + CircBuf c( rhs ); + this->swap( c ); + return *this; + } + + CircBuf( const CircBuf &cpy ) + { + size = cpy.size; + read_pos = cpy.read_pos; + write_pos = cpy.write_pos; + m_iBlockSize = cpy.m_iBlockSize; + if( size ) + { + buf = new T[size]; + memcpy( buf, cpy.buf, size*sizeof(T) ); + } + else + { + buf = nullptr; + } + } + + /* Return the number of elements available to read. */ + unsigned num_readable() const + { + const int rpos = read_pos; + const int wpos = write_pos; + if( rpos < wpos ) + /* The buffer looks like "eeeeDDDDeeee" (e = empty, D = data). */ + return wpos - rpos; + else if( rpos > wpos ) + /* The buffer looks like "DDeeeeeeeeDD" (e = empty, D = data). */ + return size - (rpos - wpos); + else // if( rpos == wpos ) + /* The buffer looks like "eeeeeeeeeeee" (e = empty, D = data). */ + return 0; + } + + /* Return the number of writable elements. */ + unsigned num_writable() const + { + const int rpos = read_pos; + const int wpos = write_pos; + + int ret; + if( rpos < wpos ) + /* The buffer looks like "eeeeDDDDeeee" (e = empty, D = data). */ + ret = size - (wpos - rpos); + else if( rpos > wpos ) + /* The buffer looks like "DDeeeeeeeeDD" (e = empty, D = data). */ + ret = rpos - wpos; + else // if( rpos == wpos ) + /* The buffer looks like "eeeeeeeeeeee" (e = empty, D = data). */ + ret = size; + + /* Subtract the blocksize, to account for the element that we never fill + * while keeping the entries aligned to m_iBlockSize. */ + return ret - m_iBlockSize; + } + + unsigned capacity() const { return size; } + + void reserve( unsigned n, int iBlockSize = 1 ) + { + m_iBlockSize = iBlockSize; + + clear(); + delete[] buf; + buf = nullptr; + + /* Reserve an extra byte. We'll never fill more than n bytes; the extra + * byte is to guarantee that read_pos != write_pos when the buffer is full, + * since that would be ambiguous with an empty buffer. */ + if( n != 0 ) + { + size = n+1; + size = ((size + iBlockSize - 1) / iBlockSize) * iBlockSize; // round up + + buf = new T[size]; + } + else + size = 0; + } + + void clear() + { + read_pos = write_pos = 0; + } + + /* Indicate that n elements have been written. */ + void advance_write_pointer( int n ) + { + write_pos = (write_pos + n) % size; + } + + /* Indicate that n elements have been read. */ + void advance_read_pointer( int n ) + { + read_pos = (read_pos + n) % size; + } + + void get_write_pointers( T *pPointers[2], unsigned pSizes[2] ) + { + const int rpos = read_pos; + const int wpos = write_pos; + + if( rpos <= wpos ) + { + /* The buffer looks like "eeeeDDDDeeee" or "eeeeeeeeeeee" (e = empty, D = data). */ + pPointers[0] = buf+wpos; + pPointers[1] = buf; + + pSizes[0] = size - wpos; + pSizes[1] = rpos; + } + else if( rpos > wpos ) + { + /* The buffer looks like "DDeeeeeeeeDD" (e = empty, D = data). */ + pPointers[0] = buf+wpos; + pPointers[1] = nullptr; + + pSizes[0] = rpos - wpos; + pSizes[1] = 0; + } + + /* Subtract the blocksize, to account for the element that we never fill + * while keeping the entries aligned to m_iBlockSize. */ + if( pSizes[1] ) + pSizes[1] -= m_iBlockSize; + else + pSizes[0] -= m_iBlockSize; + } + + /* Like get_write_pointers, but only return the first range available. */ + T *get_write_pointer( unsigned *pSizes ) + { + T *pBothPointers[2]; + unsigned iBothSizes[2]; + get_write_pointers( pBothPointers, iBothSizes ); + *pSizes = iBothSizes[0]; + return pBothPointers[0]; + } + + void get_read_pointers( T *pPointers[2], unsigned pSizes[2] ) + { + const int rpos = read_pos; + const int wpos = write_pos; + + if( rpos < wpos ) + { + /* The buffer looks like "eeeeDDDDeeee" (e = empty, D = data). */ + pPointers[0] = buf+rpos; + pPointers[1] = nullptr; + + pSizes[0] = wpos - rpos; + pSizes[1] = 0; + } + else if( rpos > wpos ) + { + /* The buffer looks like "DDeeeeeeeeDD" (e = empty, D = data). */ + pPointers[0] = buf+rpos; + pPointers[1] = buf; + + pSizes[0] = size - rpos; + pSizes[1] = wpos; + } + else + { + /* The buffer looks like "eeeeeeeeeeee" (e = empty, D = data). */ + pPointers[0] = nullptr; + pPointers[1] = nullptr; + + pSizes[0] = 0; + pSizes[1] = 0; + } + } + + /* Write buffer_size elements from buffer, and advance the write pointer. If + * the data will not fit entirely, the write pointer will be unchanged + * and false will be returned. */ + bool write( const T *buffer, unsigned buffer_size ) + { + T *p[2]; + unsigned sizes[2]; + get_write_pointers( p, sizes ); + + if( buffer_size > sizes[0] + sizes[1] ) + return false; + + const int from_first = min( buffer_size, sizes[0] ); + memcpy( p[0], buffer, from_first*sizeof(T) ); + if( buffer_size > sizes[0] ) + memcpy( p[1], buffer+from_first, max(buffer_size-sizes[0], 0u)*sizeof(T) ); + + advance_write_pointer( buffer_size ); + + return true; + } + + /* Read buffer_size elements from buffer, and advance the read pointer. If + * the buffer can not be filled completely, the read pointer will be unchanged + * and false will be returned. */ + bool read( T *buffer, unsigned buffer_size ) + { + T *p[2]; + unsigned sizes[2]; + get_read_pointers( p, sizes ); + + if( buffer_size > sizes[0] + sizes[1] ) + return false; + + const int from_first = min( buffer_size, sizes[0] ); + memcpy( buffer, p[0], from_first*sizeof(T) ); + if( buffer_size > sizes[0] ) + memcpy( buffer+from_first, p[1], max(buffer_size-sizes[0], 0u)*sizeof(T) ); + + /* Set the data that we just read to 0xFF. This way, if we're passing pointesr + * through, we can tell if we accidentally get a stale pointer. */ + memset( p[0], 0xFF, from_first*sizeof(T) ); + if( buffer_size > sizes[0] ) + memset( p[1], 0xFF, max(buffer_size-sizes[0], 0u)*sizeof(T) ); + + advance_read_pointer( buffer_size ); + return true; + } +}; + +#endif + +/* + * Copyright (c) 2004 Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RageUtil_FileDB.cpp b/src/RageUtil_FileDB.cpp index 709a110808..ac11a91a6a 100644 --- a/src/RageUtil_FileDB.cpp +++ b/src/RageUtil_FileDB.cpp @@ -172,7 +172,7 @@ bool FilenameDB::ResolvePath( RString &sPath ) /* Resolve each component. */ RString ret = ""; - const FileSet *fs = NULL; + const FileSet *fs = nullptr; static const RString slash("/"); for(;;) @@ -340,7 +340,7 @@ FileSet *FilenameDB::GetFileSet( const RString &sDir_, bool bCreate ) * to the newly-created directory. Find the pointer we need to set. Be careful of * order of operations, here: since we just unlocked, any this->dirs searches we did * previously are no longer valid. */ - FileSet **pParentDirp = NULL; + FileSet **pParentDirp = nullptr; if( sDir != "/" ) { RString sParent = Dirname( sDir ); @@ -449,7 +449,7 @@ void FilenameDB::DelFileSet( map::iterator dir ) { File &ff = (File &) *f; if( ff.dirp == fs ) - ff.dirp = NULL; + ff.dirp = nullptr; } } @@ -478,7 +478,7 @@ void FilenameDB::DelFile( const RString &sPath ) void FilenameDB::FlushDirCache( const RString & /* sDir */ ) { - FileSet *pFileSet = NULL; + FileSet *pFileSet = nullptr; m_Mutex.Lock(); for(;;) @@ -524,7 +524,7 @@ void FilenameDB::FlushDirCache( const RString & /* sDir */ ) FileSet *pParent = it->second; set::iterator fileit = pParent->files.find( File(Basename(sDir)) ); if( fileit != pParent->files.end() ) - fileit->dirp = NULL; + fileit->dirp = nullptr; } } } @@ -558,7 +558,7 @@ void *FilenameDB::GetFilePriv( const RString &path ) ASSERT( !m_Mutex.IsLockedByThisThread() ); const File *pFile = GetFile( path ); - void *pRet = NULL; + void *pRet = nullptr; if( pFile != nullptr ) pRet = pFile->priv; diff --git a/src/ReceptorArrowRow.cpp b/src/ReceptorArrowRow.cpp index 276c63eb90..f1f516fc4d 100644 --- a/src/ReceptorArrowRow.cpp +++ b/src/ReceptorArrowRow.cpp @@ -1,119 +1,119 @@ -#include "global.h" -#include "ReceptorArrowRow.h" -#include "RageUtil.h" -#include "GameConstantsAndTypes.h" -#include "ArrowEffects.h" -#include "GameState.h" -#include "PlayerState.h" -#include "Style.h" - -ReceptorArrowRow::ReceptorArrowRow() -{ - m_pPlayerState = NULL; - m_fYReverseOffsetPixels = 0; - m_fFadeToFailPercent = 0; -} - -void ReceptorArrowRow::Load( const PlayerState* pPlayerState, float fYReverseOffset ) -{ - m_pPlayerState = pPlayerState; - m_fYReverseOffsetPixels = fYReverseOffset; - - const Style* pStyle = GAMESTATE->GetCurrentStyle(); - - for( int c=0; cm_iColsPerPlayer; c++ ) - { - m_ReceptorArrow.push_back( new ReceptorArrow ); - m_ReceptorArrow[c]->SetName( "ReceptorArrow" ); - m_ReceptorArrow[c]->Load( m_pPlayerState, c ); - this->AddChild( m_ReceptorArrow[c] ); - } -} - -ReceptorArrowRow::~ReceptorArrowRow() -{ - for( unsigned i = 0; i < m_ReceptorArrow.size(); ++i ) - delete m_ReceptorArrow[i]; -} - -void ReceptorArrowRow::Update( float fDeltaTime ) -{ - ActorFrame::Update( fDeltaTime ); - ArrowEffects::Update(); - - for( unsigned c=0; cm_PlayerOptions.GetCurrent().m_fDark) * (1 - m_fFadeToFailPercent); - CLAMP( fBaseAlpha, 0.0f, 1.0f ); - m_ReceptorArrow[c]->SetBaseAlpha( fBaseAlpha ); - - // set arrow XYZ - float fX = ArrowEffects::GetXPos( m_pPlayerState, c, 0 ); - const float fY = ArrowEffects::GetYPos( m_pPlayerState, c, 0, m_fYReverseOffsetPixels ); - const float fZ = ArrowEffects::GetZPos( m_pPlayerState, c, 0 ); - m_ReceptorArrow[c]->SetX( fX ); - m_ReceptorArrow[c]->SetY( fY ); - m_ReceptorArrow[c]->SetZ( fZ ); - - const float fRotation = ArrowEffects::ReceptorGetRotationZ( m_pPlayerState ); - m_ReceptorArrow[c]->SetRotationZ( fRotation ); - - const float fZoom = ArrowEffects::GetZoom( m_pPlayerState ); - m_ReceptorArrow[c]->SetZoom( fZoom ); - } -} - -void ReceptorArrowRow::DrawPrimitives() -{ - const Style* pStyle = GAMESTATE->GetCurrentStyle(); - for( unsigned i=0; im_iColumnDrawOrder[i]; - m_ReceptorArrow[c]->Draw(); - } -} - -void ReceptorArrowRow::Step( int iCol, TapNoteScore score ) -{ - ASSERT( iCol >= 0 && iCol < (int) m_ReceptorArrow.size() ); - m_ReceptorArrow[iCol]->Step( score ); -} - -void ReceptorArrowRow::SetPressed( int iCol ) -{ - ASSERT( iCol >= 0 && iCol < (int) m_ReceptorArrow.size() ); - m_ReceptorArrow[iCol]->SetPressed(); -} - -void ReceptorArrowRow::SetNoteUpcoming( int iCol, bool b ) -{ - ASSERT( iCol >= 0 && iCol < (int) m_ReceptorArrow.size() ); - m_ReceptorArrow[iCol]->SetNoteUpcoming(b); -} - - -/* - * (c) 2001-2003 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "ReceptorArrowRow.h" +#include "RageUtil.h" +#include "GameConstantsAndTypes.h" +#include "ArrowEffects.h" +#include "GameState.h" +#include "PlayerState.h" +#include "Style.h" + +ReceptorArrowRow::ReceptorArrowRow() +{ + m_pPlayerState = nullptr; + m_fYReverseOffsetPixels = 0; + m_fFadeToFailPercent = 0; +} + +void ReceptorArrowRow::Load( const PlayerState* pPlayerState, float fYReverseOffset ) +{ + m_pPlayerState = pPlayerState; + m_fYReverseOffsetPixels = fYReverseOffset; + + const Style* pStyle = GAMESTATE->GetCurrentStyle(); + + for( int c=0; cm_iColsPerPlayer; c++ ) + { + m_ReceptorArrow.push_back( new ReceptorArrow ); + m_ReceptorArrow[c]->SetName( "ReceptorArrow" ); + m_ReceptorArrow[c]->Load( m_pPlayerState, c ); + this->AddChild( m_ReceptorArrow[c] ); + } +} + +ReceptorArrowRow::~ReceptorArrowRow() +{ + for( unsigned i = 0; i < m_ReceptorArrow.size(); ++i ) + delete m_ReceptorArrow[i]; +} + +void ReceptorArrowRow::Update( float fDeltaTime ) +{ + ActorFrame::Update( fDeltaTime ); + ArrowEffects::Update(); + + for( unsigned c=0; cm_PlayerOptions.GetCurrent().m_fDark) * (1 - m_fFadeToFailPercent); + CLAMP( fBaseAlpha, 0.0f, 1.0f ); + m_ReceptorArrow[c]->SetBaseAlpha( fBaseAlpha ); + + // set arrow XYZ + float fX = ArrowEffects::GetXPos( m_pPlayerState, c, 0 ); + const float fY = ArrowEffects::GetYPos( m_pPlayerState, c, 0, m_fYReverseOffsetPixels ); + const float fZ = ArrowEffects::GetZPos( m_pPlayerState, c, 0 ); + m_ReceptorArrow[c]->SetX( fX ); + m_ReceptorArrow[c]->SetY( fY ); + m_ReceptorArrow[c]->SetZ( fZ ); + + const float fRotation = ArrowEffects::ReceptorGetRotationZ( m_pPlayerState ); + m_ReceptorArrow[c]->SetRotationZ( fRotation ); + + const float fZoom = ArrowEffects::GetZoom( m_pPlayerState ); + m_ReceptorArrow[c]->SetZoom( fZoom ); + } +} + +void ReceptorArrowRow::DrawPrimitives() +{ + const Style* pStyle = GAMESTATE->GetCurrentStyle(); + for( unsigned i=0; im_iColumnDrawOrder[i]; + m_ReceptorArrow[c]->Draw(); + } +} + +void ReceptorArrowRow::Step( int iCol, TapNoteScore score ) +{ + ASSERT( iCol >= 0 && iCol < (int) m_ReceptorArrow.size() ); + m_ReceptorArrow[iCol]->Step( score ); +} + +void ReceptorArrowRow::SetPressed( int iCol ) +{ + ASSERT( iCol >= 0 && iCol < (int) m_ReceptorArrow.size() ); + m_ReceptorArrow[iCol]->SetPressed(); +} + +void ReceptorArrowRow::SetNoteUpcoming( int iCol, bool b ) +{ + ASSERT( iCol >= 0 && iCol < (int) m_ReceptorArrow.size() ); + m_ReceptorArrow[iCol]->SetNoteUpcoming(b); +} + + +/* + * (c) 2001-2003 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RoomWheel.cpp b/src/RoomWheel.cpp index d9e68a39a9..aedb272289 100644 --- a/src/RoomWheel.cpp +++ b/src/RoomWheel.cpp @@ -131,7 +131,7 @@ void RoomWheel::RemoveItem( int index ) // If this item's data happened to be last selected, make it NULL. if( m_LastSelection == *i ) - m_LastSelection = NULL; + m_LastSelection = nullptr; SAFE_DELETE( *i ); m_CurWheelItemData.erase( i ); @@ -155,7 +155,7 @@ bool RoomWheel::Select() if( m_iSelection == 0 ) { // Since this is not actually an option outside of this wheel, NULL is a good idea. - m_LastSelection = NULL; + m_LastSelection = nullptr; ScreenTextEntry::TextEntry( SM_BackFromRoomName, ENTER_ROOM_NAME, "", 255 ); } return false; diff --git a/src/ScoreKeeperNormal.cpp b/src/ScoreKeeperNormal.cpp index 37cbdf20a1..3c46e68406 100644 --- a/src/ScoreKeeperNormal.cpp +++ b/src/ScoreKeeperNormal.cpp @@ -136,7 +136,7 @@ void ScoreKeeperNormal::Load( NoteDataUtil::TransformNoteData( nd, m_pPlayerState->m_PlayerOptions.GetStage(), pSteps->m_StepsType ); RadarValues rvPost; NoteDataUtil::CalculateRadarValues( nd, pSong->m_fMusicLengthSeconds, rvPost ); - GAMESTATE->SetProcessedTimingData(NULL); + GAMESTATE->SetProcessedTimingData(nullptr); iTotalPossibleDancePoints += this->GetPossibleDancePoints( rvPre, rvPost ); iTotalPossibleGradePoints += this->GetPossibleGradePoints( rvPre, rvPost ); @@ -238,7 +238,7 @@ void ScoreKeeperNormal::OnNextSong( int iSongInCourseIndex, const Steps* pSteps, m_iTapNotesHit = 0; - GAMESTATE->SetProcessedTimingData(NULL); + GAMESTATE->SetProcessedTimingData(nullptr); } static int GetScore(int p, int Z, int S, int n) diff --git a/src/ScreenContinue.cpp b/src/ScreenContinue.cpp index 2b15fa0fe0..b04a039258 100644 --- a/src/ScreenContinue.cpp +++ b/src/ScreenContinue.cpp @@ -1,143 +1,143 @@ -#include "global.h" -#include "ScreenContinue.h" -#include "ScreenManager.h" -#include "ActorUtil.h" -#include "GameState.h" -#include "RageLog.h" -#include "InputEventPlus.h" -#include "MenuTimer.h" -#include "MemoryCardManager.h" - - -REGISTER_SCREEN_CLASS( ScreenContinue ); - -void ScreenContinue::Init() -{ - ScreenWithMenuElementsSimple::Init(); - - this->SubscribeToMessage( Message_PlayerJoined ); - - FORCE_TIMER_WAIT.Load( m_sName, "ForceTimerWait" ); -} - -void ScreenContinue::BeginScreen() -{ - GAMESTATE->SetCurrentStyle( NULL ); - - // Unjoin human players with 0 stages left and reset non-human players. - // We need to reset non-human players because data in non-human (CPU) - // players will be filled, and there may be stale pointers to things like - // edit Steps. - FOREACH_ENUM( PlayerNumber, p ) - { - if( GAMESTATE->IsHumanPlayer(p) ) - { - bool bPlayerDone = GAMESTATE->m_iPlayerStageTokens[p] <= 0; - if( bPlayerDone ) - { - GAMESTATE->UnjoinPlayer( p ); - MEMCARDMAN->UnlockCard( p ); - } - } - else - { - GAMESTATE->ResetPlayer( p ); - } - } - - ScreenWithMenuElementsSimple::BeginScreen(); -} - -bool ScreenContinue::Input( const InputEventPlus &input ) -{ - if( input.MenuI == GAME_BUTTON_START && input.type == IET_FIRST_PRESS && GAMESTATE->JoinInput(input.pn) ) - return true; // handled - - if( IsTransitioning() ) - return true; - - if( input.type == IET_FIRST_PRESS && GAMESTATE->IsHumanPlayer(input.pn) && FORCE_TIMER_WAIT ) - { - switch( input.MenuI ) - { - case GAME_BUTTON_START: - case GAME_BUTTON_UP: - case GAME_BUTTON_DOWN: - case GAME_BUTTON_LEFT: - case GAME_BUTTON_RIGHT: - { - float fSeconds = floorf(m_MenuTimer->GetSeconds()) - 0.0001f; - fSeconds = max( fSeconds, 0.0001f ); // don't set to 0 - m_MenuTimer->SetSeconds( fSeconds ); - Message msg("HurryTimer"); - msg.SetParam( "PlayerNumber", input.pn ); - this->HandleMessage( msg ); - return true; // handled - } - default: break; - } - } - - return ScreenWithMenuElementsSimple::Input( input ); -} - -void ScreenContinue::HandleScreenMessage( const ScreenMessage SM ) -{ - if( SM == SM_MenuTimer ) - { - if( !IsTransitioning() ) - StartTransitioningScreen( SM_GoToNextScreen ); - return; - } - - ScreenWithMenuElementsSimple::HandleScreenMessage( SM ); -} - -void ScreenContinue::HandleMessage( const Message &msg ) -{ - if( msg == Message_PlayerJoined ) - { - ResetTimer(); - - bool bAllPlayersAreEnabled = true; - FOREACH_ENUM( PlayerNumber, p ) - { - if( !GAMESTATE->IsPlayerEnabled(p) ) - bAllPlayersAreEnabled = false; - } - - if( bAllPlayersAreEnabled ) - { - m_MenuTimer->Stop(); - if( !IsTransitioning() ) - StartTransitioningScreen( SM_GoToNextScreen ); - } - } - - ScreenWithMenuElementsSimple::HandleMessage( msg ); -} - -/* - * (c) 2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "ScreenContinue.h" +#include "ScreenManager.h" +#include "ActorUtil.h" +#include "GameState.h" +#include "RageLog.h" +#include "InputEventPlus.h" +#include "MenuTimer.h" +#include "MemoryCardManager.h" + + +REGISTER_SCREEN_CLASS( ScreenContinue ); + +void ScreenContinue::Init() +{ + ScreenWithMenuElementsSimple::Init(); + + this->SubscribeToMessage( Message_PlayerJoined ); + + FORCE_TIMER_WAIT.Load( m_sName, "ForceTimerWait" ); +} + +void ScreenContinue::BeginScreen() +{ + GAMESTATE->SetCurrentStyle(nullptr); + + // Unjoin human players with 0 stages left and reset non-human players. + // We need to reset non-human players because data in non-human (CPU) + // players will be filled, and there may be stale pointers to things like + // edit Steps. + FOREACH_ENUM( PlayerNumber, p ) + { + if( GAMESTATE->IsHumanPlayer(p) ) + { + bool bPlayerDone = GAMESTATE->m_iPlayerStageTokens[p] <= 0; + if( bPlayerDone ) + { + GAMESTATE->UnjoinPlayer( p ); + MEMCARDMAN->UnlockCard( p ); + } + } + else + { + GAMESTATE->ResetPlayer( p ); + } + } + + ScreenWithMenuElementsSimple::BeginScreen(); +} + +bool ScreenContinue::Input( const InputEventPlus &input ) +{ + if( input.MenuI == GAME_BUTTON_START && input.type == IET_FIRST_PRESS && GAMESTATE->JoinInput(input.pn) ) + return true; // handled + + if( IsTransitioning() ) + return true; + + if( input.type == IET_FIRST_PRESS && GAMESTATE->IsHumanPlayer(input.pn) && FORCE_TIMER_WAIT ) + { + switch( input.MenuI ) + { + case GAME_BUTTON_START: + case GAME_BUTTON_UP: + case GAME_BUTTON_DOWN: + case GAME_BUTTON_LEFT: + case GAME_BUTTON_RIGHT: + { + float fSeconds = floorf(m_MenuTimer->GetSeconds()) - 0.0001f; + fSeconds = max( fSeconds, 0.0001f ); // don't set to 0 + m_MenuTimer->SetSeconds( fSeconds ); + Message msg("HurryTimer"); + msg.SetParam( "PlayerNumber", input.pn ); + this->HandleMessage( msg ); + return true; // handled + } + default: break; + } + } + + return ScreenWithMenuElementsSimple::Input( input ); +} + +void ScreenContinue::HandleScreenMessage( const ScreenMessage SM ) +{ + if( SM == SM_MenuTimer ) + { + if( !IsTransitioning() ) + StartTransitioningScreen( SM_GoToNextScreen ); + return; + } + + ScreenWithMenuElementsSimple::HandleScreenMessage( SM ); +} + +void ScreenContinue::HandleMessage( const Message &msg ) +{ + if( msg == Message_PlayerJoined ) + { + ResetTimer(); + + bool bAllPlayersAreEnabled = true; + FOREACH_ENUM( PlayerNumber, p ) + { + if( !GAMESTATE->IsPlayerEnabled(p) ) + bAllPlayersAreEnabled = false; + } + + if( bAllPlayersAreEnabled ) + { + m_MenuTimer->Stop(); + if( !IsTransitioning() ) + StartTransitioningScreen( SM_GoToNextScreen ); + } + } + + ScreenWithMenuElementsSimple::HandleMessage( msg ); +} + +/* + * (c) 2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/ScreenDebugOverlay.cpp b/src/ScreenDebugOverlay.cpp index 36ecea7c65..4d0ef3c2a4 100644 --- a/src/ScreenDebugOverlay.cpp +++ b/src/ScreenDebugOverlay.cpp @@ -52,7 +52,7 @@ static LocalizedString ON ( "ScreenDebugOverlay", "on" ); static LocalizedString OFF ( "ScreenDebugOverlay", "off" ); class IDebugLine; -static vector *g_pvpSubscribers = NULL; +static vector *g_pvpSubscribers = nullptr; class IDebugLine { public: diff --git a/src/ScreenEdit.cpp b/src/ScreenEdit.cpp index fd6e58c620..a38ba7ed81 100644 --- a/src/ScreenEdit.cpp +++ b/src/ScreenEdit.cpp @@ -1095,7 +1095,7 @@ REGISTER_SCREEN_CLASS( ScreenEdit ); void ScreenEdit::Init() { - m_pSoundMusic = NULL; + m_pSoundMusic = nullptr; GAMESTATE->m_bIsUsingStepTiming = false; GAMESTATE->m_bInStepEditor = true; @@ -1672,7 +1672,7 @@ void ScreenEdit::UpdateTextInfo() m_textInfo.SetText( sText ); - GAMESTATE->SetProcessedTimingData(NULL); + GAMESTATE->SetProcessedTimingData(nullptr); } void ScreenEdit::DrawPrimitives() @@ -3474,7 +3474,7 @@ void ScreenEdit::HandleScreenMessage( const ScreenMessage SM ) else if( SM == SM_BackFromCourseModeMenu ) { const int num = ScreenMiniMenu::s_viLastAnswers[0]; - GAMESTATE->m_pCurCourse.Set( NULL ); + GAMESTATE->m_pCurCourse.Set(nullptr); if( num != 0 ) { const RString name = g_CourseMode.rows[0].choices[num]; @@ -4019,9 +4019,9 @@ void ScreenEdit::HandleScreenMessage( const ScreenMessage SM ) { pSong->DeleteSteps( pSteps ); if( m_pSteps == pSteps ) - m_pSteps = NULL; + m_pSteps = nullptr; if( GAMESTATE->m_pCurSteps[PLAYER_1].Get() == pSteps ) - GAMESTATE->m_pCurSteps[PLAYER_1].Set( NULL ); + GAMESTATE->m_pCurSteps[PLAYER_1].Set(nullptr); } @@ -4554,7 +4554,7 @@ void ScreenEdit::HandleMainMenuChoice( MainMenuChoice c, const vector &iAns } break; }; - GAMESTATE->SetProcessedTimingData(NULL); + GAMESTATE->SetProcessedTimingData(nullptr); } void ScreenEdit::HandleAlterMenuChoice(AlterMenuChoice c, const vector &iAnswers, bool bAllowUndo) diff --git a/src/ScreenEditMenu.cpp b/src/ScreenEditMenu.cpp index 2b234f09f4..1502e0decb 100644 --- a/src/ScreenEditMenu.cpp +++ b/src/ScreenEditMenu.cpp @@ -32,7 +32,7 @@ REGISTER_SCREEN_CLASS( ScreenEditMenu ); void ScreenEditMenu::Init() { // HACK: Disable any style set by the editor. - GAMESTATE->m_pCurStyle.Set( NULL ); + GAMESTATE->m_pCurStyle.Set(nullptr); // Enable all players. FOREACH_PlayerNumber( pn ) @@ -152,7 +152,7 @@ static void SetCurrentStepsDescription( const RString &s ) static void DeleteCurrentSteps() { GAMESTATE->m_pCurSong->DeleteSteps( GAMESTATE->m_pCurSteps[0] ); - GAMESTATE->m_pCurSteps[0].Set( NULL ); + GAMESTATE->m_pCurSteps[0].Set(nullptr); } static LocalizedString MISSING_MUSIC_FILE ( "ScreenEditMenu", "This song is missing a music file and cannot be edited." ); @@ -184,7 +184,7 @@ bool ScreenEditMenu::MenuStart( const InputEventPlus & ) EditMenuAction action = m_Selector.GetSelectedAction(); GAMESTATE->m_pCurSong.Set( pSong ); - GAMESTATE->m_pCurCourse.Set( NULL ); + GAMESTATE->m_pCurCourse.Set(nullptr); GAMESTATE->SetCurrentStyle( GAMEMAN->GetEditorStyleForStepsType(st) ); GAMESTATE->m_pCurSteps[PLAYER_1].Set( pSteps ); @@ -283,7 +283,7 @@ bool ScreenEditMenu::MenuStart( const InputEventPlus & ) GAMESTATE->m_pCurSong.Set( pSong ); GAMESTATE->m_pCurSteps[PLAYER_1].Set( pSteps ); - GAMESTATE->m_pCurCourse.Set( NULL ); + GAMESTATE->m_pCurCourse.Set(nullptr); } break; default: diff --git a/src/ScreenGameplay.cpp b/src/ScreenGameplay.cpp index 1252b148cf..7117b85d43 100644 --- a/src/ScreenGameplay.cpp +++ b/src/ScreenGameplay.cpp @@ -100,13 +100,13 @@ PlayerInfo::PlayerInfo(): m_pn(PLAYER_INVALID), m_mp(MultiPlayer_Invalid), m_bIsDummy(false), m_iDummyIndex(0), m_iAddToDifficulty(0), m_bPlayerEnabled(false), m_PlayerStateDummy(), m_PlayerStageStatsDummy(), m_SoundEffectControl(), - m_vpStepsQueue(), m_asModifiersQueue(), m_pLifeMeter(NULL), - m_ptextCourseSongNumber(NULL), m_ptextStepsDescription(NULL), - m_pPrimaryScoreDisplay(NULL), m_pSecondaryScoreDisplay(NULL), - m_pPrimaryScoreKeeper(NULL), m_pSecondaryScoreKeeper(NULL), - m_ptextPlayerOptions(NULL), m_pActiveAttackList(NULL), - m_NoteData(), m_pPlayer(NULL), m_pInventory(NULL), - m_pStepsDisplay(NULL), m_sprOniGameOver() {} + m_vpStepsQueue(), m_asModifiersQueue(), m_pLifeMeter(nullptr), + m_ptextCourseSongNumber(nullptr), m_ptextStepsDescription(nullptr), + m_pPrimaryScoreDisplay(nullptr), m_pSecondaryScoreDisplay(nullptr), + m_pPrimaryScoreKeeper(nullptr), m_pSecondaryScoreKeeper(nullptr), + m_ptextPlayerOptions(nullptr), m_pActiveAttackList(nullptr), + m_NoteData(), m_pPlayer(nullptr), m_pInventory(nullptr), + m_pStepsDisplay(nullptr), m_sprOniGameOver() {} void PlayerInfo::Load( PlayerNumber pn, MultiPlayer mp, bool bShowNoteField, int iAddToDifficulty ) { @@ -115,9 +115,9 @@ void PlayerInfo::Load( PlayerNumber pn, MultiPlayer mp, bool bShowNoteField, int m_bPlayerEnabled = IsEnabled(); m_bIsDummy = false; m_iAddToDifficulty = iAddToDifficulty; - m_pLifeMeter = NULL; - m_ptextCourseSongNumber = NULL; - m_ptextStepsDescription = NULL; + m_pLifeMeter = nullptr; + m_ptextCourseSongNumber = nullptr; + m_ptextStepsDescription = nullptr; if( !IsMultiPlayer() ) { @@ -173,11 +173,11 @@ void PlayerInfo::Load( PlayerNumber pn, MultiPlayer mp, bool bShowNoteField, int break; } - m_ptextPlayerOptions = NULL; - m_pActiveAttackList = NULL; + m_ptextPlayerOptions = nullptr; + m_pActiveAttackList = nullptr; m_pPlayer = new Player( m_NoteData, bShowNoteField ); - m_pInventory = NULL; - m_pStepsDisplay = NULL; + m_pInventory = nullptr; + m_pStepsDisplay = nullptr; if( IsMultiPlayer() ) { @@ -321,8 +321,8 @@ GetNextVisiblePlayerInfo( vector::iterator iter, vector ScreenGameplay::ScreenGameplay() { - m_pSongBackground = NULL; - m_pSongForeground = NULL; + m_pSongBackground = nullptr; + m_pSongForeground = nullptr; } void ScreenGameplay::Init() @@ -376,10 +376,10 @@ void ScreenGameplay::Init() if( !GAMESTATE->m_bDemonstrationOrJukebox ) MEMCARDMAN->PauseMountingThread(); - m_pSoundMusic = NULL; + m_pSoundMusic = nullptr; m_bPaused = false; - m_pCombinedLifeMeter = NULL; + m_pCombinedLifeMeter = nullptr; if( GAMESTATE->m_pCurSong == nullptr && GAMESTATE->m_pCurCourse == nullptr ) return; // ScreenDemonstration will move us to the next screen. We just need to survive for one update without crashing. @@ -1748,7 +1748,7 @@ void ScreenGameplay::Update( float fDeltaTime ) // update 2d dancing characters FOREACH_EnabledPlayerNumberInfo( m_vPlayerInfo, pi ) { - DancingCharacters *pCharacter = NULL; + DancingCharacters *pCharacter = nullptr; if( m_pSongBackground ) pCharacter = m_pSongBackground->GetDancingCharacters(); if( pCharacter != nullptr ) @@ -2345,7 +2345,7 @@ void ScreenGameplay::SaveStats() pss.m_radarPossible += rv; NoteDataWithScoring::GetActualRadarValues( nd, pss, fMusicLen, rv ); pss.m_radarActual += rv; - GAMESTATE->SetProcessedTimingData(NULL); + GAMESTATE->SetProcessedTimingData(nullptr); } } @@ -2469,7 +2469,7 @@ void ScreenGameplay::HandleScreenMessage( const ScreenMessage SM ) else if( SM == SM_LeaveGameplay ) { // update dancing characters for win / lose - DancingCharacters *pDancers = NULL; + DancingCharacters *pDancers = nullptr; if( m_pSongBackground ) pDancers = m_pSongBackground->GetDancingCharacters(); if( pDancers ) diff --git a/src/ScreenGameplaySyncMachine.cpp b/src/ScreenGameplaySyncMachine.cpp index 75679087a4..6db347c0e7 100644 --- a/src/ScreenGameplaySyncMachine.cpp +++ b/src/ScreenGameplaySyncMachine.cpp @@ -1,153 +1,153 @@ -#include "global.h" -#include "ScreenGameplaySyncMachine.h" -#include "NotesLoaderSSC.h" -#include "NotesLoaderSM.h" -#include "GameState.h" -#include "GameManager.h" -#include "PrefsManager.h" -#include "GamePreferences.h" -#include "AdjustSync.h" -#include "ScreenDimensions.h" -#include "InputEventPlus.h" -#include "SongUtil.h" - -REGISTER_SCREEN_CLASS( ScreenGameplaySyncMachine ); - -void ScreenGameplaySyncMachine::Init() -{ - GAMESTATE->m_PlayMode.Set( PLAY_MODE_REGULAR ); - GAMESTATE->SetCurrentStyle( GAMEMAN->GetHowToPlayStyleForGame(GAMESTATE->m_pCurGame) ); - AdjustSync::ResetOriginalSyncData(); - - RString sFile = THEME->GetPathO("ScreenGameplaySyncMachine","music"); - // Allow themers to use either a .ssc or .sm file for this. -aj - SSCLoader loaderSSC; - SMLoader loaderSM; - if(sFile.Right(4) == ".ssc") - loaderSSC.LoadFromSimfile( sFile, m_Song ); - else - loaderSM.LoadFromSimfile( sFile, m_Song ); - - m_Song.SetSongDir( Dirname(sFile) ); - m_Song.TidyUpData(); - - GAMESTATE->m_pCurSong.Set( &m_Song ); - // Needs proper StepsType -freem - vector vpSteps; - SongUtil::GetPlayableSteps( &m_Song, vpSteps ); - ASSERT_M(vpSteps.size() > 0, "No playable steps for ScreenGameplaySyncMachine"); - Steps *pSteps = vpSteps[0]; - GAMESTATE->m_pCurSteps[GAMESTATE->GetFirstHumanPlayer()].Set( pSteps ); - - GamePreferences::m_AutoPlay.Set( PC_HUMAN ); - - ScreenGameplayNormal::Init(); - - SO_GROUP_ASSIGN( GAMESTATE->m_SongOptions, ModsLevel_Stage, m_AutosyncType, SongOptions::AUTOSYNC_MACHINE ); - - ClearMessageQueue(); // remove all of the messages set in ScreenGameplay that animate "ready", "here we go", etc. - - GAMESTATE->m_bGameplayLeadIn.Set( false ); - - m_DancingState = STATE_DANCING; - - m_textSyncInfo.SetName( "SyncInfo" ); - m_textSyncInfo.LoadFromFont( THEME->GetPathF(m_sName,"SyncInfo") ); - ActorUtil::LoadAllCommands( m_textSyncInfo, m_sName ); - this->AddChild( &m_textSyncInfo ); - - this->SubscribeToMessage( Message_AutosyncChanged ); - - RefreshText(); -} - -void ScreenGameplaySyncMachine::Update( float fDelta ) -{ - ScreenGameplayNormal::Update( fDelta ); - RefreshText(); -} - -bool ScreenGameplaySyncMachine::Input( const InputEventPlus &input ) -{ - // Hack to make this work from Player2's controls - InputEventPlus _input = input; - - if( _input.GameI.controller != GameController_Invalid ) - _input.GameI.controller = GameController_1; - if( _input.pn != PLAYER_INVALID ) - _input.pn = PLAYER_1; - - return ScreenGameplay::Input( _input ); -} - -void ScreenGameplaySyncMachine::HandleScreenMessage( const ScreenMessage SM ) -{ - if( SM == SM_NotesEnded ) - { - ResetAndRestartCurrentSong(); - return; // handled - } - - ScreenGameplayNormal::HandleScreenMessage( SM ); - - if( SM == SM_GoToPrevScreen || SM == SM_GoToNextScreen ) - { - GAMESTATE->m_PlayMode.Set( PlayMode_Invalid ); - GAMESTATE->SetCurrentStyle( NULL ); - GAMESTATE->m_pCurSong.Set( NULL ); - } -} - -void ScreenGameplaySyncMachine::ResetAndRestartCurrentSong() -{ - m_pSoundMusic->Stop(); - ReloadCurrentSong(); - StartPlayingSong( 4, 0 ); - - // reset autosync - AdjustSync::ResetAutosync(); -} - -static LocalizedString OLD_OFFSET ( "ScreenGameplaySyncMachine", "Old offset" ); -static LocalizedString NEW_OFFSET ( "ScreenGameplaySyncMachine", "New offset" ); -static LocalizedString COLLECTING_SAMPLE( "ScreenGameplaySyncMachine", "Collecting sample" ); -static LocalizedString STANDARD_DEVIATION( "ScreenGameplaySyncMachine", "Standard deviation" ); -void ScreenGameplaySyncMachine::RefreshText() -{ - float fNew = PREFSMAN->m_fGlobalOffsetSeconds; - float fOld = AdjustSync::s_fGlobalOffsetSecondsOriginal; - float fStdDev = AdjustSync::s_fStandardDeviation; - RString s; - s += OLD_OFFSET.GetValue() + ssprintf( ": %0.3f\n", fOld ); - s += NEW_OFFSET.GetValue() + ssprintf( ": %0.3f\n", fNew ); - s += STANDARD_DEVIATION.GetValue() + ssprintf( ": %0.3f\n", fStdDev ); - s += COLLECTING_SAMPLE.GetValue() + ssprintf( ": %d / %d", AdjustSync::s_iAutosyncOffsetSample+1, AdjustSync::OFFSET_SAMPLE_COUNT ); - - m_textSyncInfo.SetText( s ); -} - - -/* - * (c) 2001-2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "ScreenGameplaySyncMachine.h" +#include "NotesLoaderSSC.h" +#include "NotesLoaderSM.h" +#include "GameState.h" +#include "GameManager.h" +#include "PrefsManager.h" +#include "GamePreferences.h" +#include "AdjustSync.h" +#include "ScreenDimensions.h" +#include "InputEventPlus.h" +#include "SongUtil.h" + +REGISTER_SCREEN_CLASS( ScreenGameplaySyncMachine ); + +void ScreenGameplaySyncMachine::Init() +{ + GAMESTATE->m_PlayMode.Set( PLAY_MODE_REGULAR ); + GAMESTATE->SetCurrentStyle( GAMEMAN->GetHowToPlayStyleForGame(GAMESTATE->m_pCurGame) ); + AdjustSync::ResetOriginalSyncData(); + + RString sFile = THEME->GetPathO("ScreenGameplaySyncMachine","music"); + // Allow themers to use either a .ssc or .sm file for this. -aj + SSCLoader loaderSSC; + SMLoader loaderSM; + if(sFile.Right(4) == ".ssc") + loaderSSC.LoadFromSimfile( sFile, m_Song ); + else + loaderSM.LoadFromSimfile( sFile, m_Song ); + + m_Song.SetSongDir( Dirname(sFile) ); + m_Song.TidyUpData(); + + GAMESTATE->m_pCurSong.Set( &m_Song ); + // Needs proper StepsType -freem + vector vpSteps; + SongUtil::GetPlayableSteps( &m_Song, vpSteps ); + ASSERT_M(vpSteps.size() > 0, "No playable steps for ScreenGameplaySyncMachine"); + Steps *pSteps = vpSteps[0]; + GAMESTATE->m_pCurSteps[GAMESTATE->GetFirstHumanPlayer()].Set( pSteps ); + + GamePreferences::m_AutoPlay.Set( PC_HUMAN ); + + ScreenGameplayNormal::Init(); + + SO_GROUP_ASSIGN( GAMESTATE->m_SongOptions, ModsLevel_Stage, m_AutosyncType, SongOptions::AUTOSYNC_MACHINE ); + + ClearMessageQueue(); // remove all of the messages set in ScreenGameplay that animate "ready", "here we go", etc. + + GAMESTATE->m_bGameplayLeadIn.Set( false ); + + m_DancingState = STATE_DANCING; + + m_textSyncInfo.SetName( "SyncInfo" ); + m_textSyncInfo.LoadFromFont( THEME->GetPathF(m_sName,"SyncInfo") ); + ActorUtil::LoadAllCommands( m_textSyncInfo, m_sName ); + this->AddChild( &m_textSyncInfo ); + + this->SubscribeToMessage( Message_AutosyncChanged ); + + RefreshText(); +} + +void ScreenGameplaySyncMachine::Update( float fDelta ) +{ + ScreenGameplayNormal::Update( fDelta ); + RefreshText(); +} + +bool ScreenGameplaySyncMachine::Input( const InputEventPlus &input ) +{ + // Hack to make this work from Player2's controls + InputEventPlus _input = input; + + if( _input.GameI.controller != GameController_Invalid ) + _input.GameI.controller = GameController_1; + if( _input.pn != PLAYER_INVALID ) + _input.pn = PLAYER_1; + + return ScreenGameplay::Input( _input ); +} + +void ScreenGameplaySyncMachine::HandleScreenMessage( const ScreenMessage SM ) +{ + if( SM == SM_NotesEnded ) + { + ResetAndRestartCurrentSong(); + return; // handled + } + + ScreenGameplayNormal::HandleScreenMessage( SM ); + + if( SM == SM_GoToPrevScreen || SM == SM_GoToNextScreen ) + { + GAMESTATE->m_PlayMode.Set( PlayMode_Invalid ); + GAMESTATE->SetCurrentStyle(nullptr); + GAMESTATE->m_pCurSong.Set(nullptr); + } +} + +void ScreenGameplaySyncMachine::ResetAndRestartCurrentSong() +{ + m_pSoundMusic->Stop(); + ReloadCurrentSong(); + StartPlayingSong( 4, 0 ); + + // reset autosync + AdjustSync::ResetAutosync(); +} + +static LocalizedString OLD_OFFSET ( "ScreenGameplaySyncMachine", "Old offset" ); +static LocalizedString NEW_OFFSET ( "ScreenGameplaySyncMachine", "New offset" ); +static LocalizedString COLLECTING_SAMPLE( "ScreenGameplaySyncMachine", "Collecting sample" ); +static LocalizedString STANDARD_DEVIATION( "ScreenGameplaySyncMachine", "Standard deviation" ); +void ScreenGameplaySyncMachine::RefreshText() +{ + float fNew = PREFSMAN->m_fGlobalOffsetSeconds; + float fOld = AdjustSync::s_fGlobalOffsetSecondsOriginal; + float fStdDev = AdjustSync::s_fStandardDeviation; + RString s; + s += OLD_OFFSET.GetValue() + ssprintf( ": %0.3f\n", fOld ); + s += NEW_OFFSET.GetValue() + ssprintf( ": %0.3f\n", fNew ); + s += STANDARD_DEVIATION.GetValue() + ssprintf( ": %0.3f\n", fStdDev ); + s += COLLECTING_SAMPLE.GetValue() + ssprintf( ": %d / %d", AdjustSync::s_iAutosyncOffsetSample+1, AdjustSync::OFFSET_SAMPLE_COUNT ); + + m_textSyncInfo.SetText( s ); +} + + +/* + * (c) 2001-2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/ScreenHighScores.cpp b/src/ScreenHighScores.cpp index d6130a5a88..4474fb9b8f 100644 --- a/src/ScreenHighScores.cpp +++ b/src/ScreenHighScores.cpp @@ -138,7 +138,7 @@ void ScoreScroller::ConfigureActor( Actor *pActor, int iItem ) const Song* pSong = data.m_pSong; Steps *pSteps = SongUtil::GetStepsByDifficulty( pSong, st, dc, false ); if( pSteps && UNLOCKMAN->StepsIsLocked(pSong, pSteps) ) - pSteps = NULL; + pSteps = nullptr; LuaHelpers::Push( L, pSteps ); } else if( data.m_pCourse != nullptr ) diff --git a/src/ScreenHighScores.h b/src/ScreenHighScores.h index 15c27d0730..096f04c57c 100644 --- a/src/ScreenHighScores.h +++ b/src/ScreenHighScores.h @@ -1,103 +1,103 @@ -#ifndef ScreenHighScores_H -#define ScreenHighScores_H - -#include "ScreenAttract.h" -#include "Course.h" -#include "DynamicActorScroller.h" - -typedef pair DifficultyAndStepsType; - -enum HighScoresType -{ - HighScoresType_AllSteps, // Top 1 HighScore for N Steps in each Song - HighScoresType_NonstopCourses, // Top 1 HighScore for N Trails in each Course - HighScoresType_OniCourses, - HighScoresType_SurvivalCourses, - HighScoresType_AllCourses, - NUM_HighScoresType, - HighScoresType_Invalid -}; -LuaDeclareType( HighScoresType ); - - -class ScoreScroller: public DynamicActorScroller -{ -public: - ScoreScroller(); - void LoadSongs( int iNumRecentScores ); - void LoadCourses( CourseType ct, int iNumRecentScores ); - void Load( RString sClassName ); - void SetDisplay( const vector &DifficultiesToShow ); - bool Scroll( int iDir ); - void ScrollTop(); - -protected: - virtual void ConfigureActor( Actor *pActor, int iItem ); - vector m_DifficultiesToShow; - - struct ScoreRowItemData // for all_steps and all_courses - { - ScoreRowItemData() { m_pSong = NULL; m_pCourse = NULL; } - - Song *m_pSong; - Course *m_pCourse; - }; - vector m_vScoreRowItemData; - - ThemeMetric SCROLLER_ITEMS_TO_DRAW; - ThemeMetric SCROLLER_SECONDS_PER_ITEM; -}; - -class ScreenHighScores: public ScreenAttract -{ -public: - virtual void Init(); - virtual void BeginScreen(); - - void HandleScreenMessage( const ScreenMessage SM ); - virtual bool Input( const InputEventPlus &input ); - virtual bool MenuStart( const InputEventPlus &input ); - virtual bool MenuBack( const InputEventPlus &input ); - virtual bool MenuLeft( const InputEventPlus &input ) { DoScroll(-1); return true; } - virtual bool MenuRight( const InputEventPlus &input ) { DoScroll(+1); return true; } - virtual bool MenuUp( const InputEventPlus &input ) { DoScroll(-1); return true; } - virtual bool MenuDown( const InputEventPlus &input ) { DoScroll(+1); return true; } - -private: - void DoScroll( int iDir ); - - ThemeMetric MANUAL_SCROLLING; - ThemeMetric HIGH_SCORES_TYPE; - ThemeMetric NUM_COLUMNS; - ThemeMetric1D COLUMN_DIFFICULTY; - ThemeMetric1D COLUMN_STEPS_TYPE; - ThemeMetric MAX_ITEMS_TO_SHOW; - ScoreScroller m_Scroller; -}; - -#endif - -/* - * (c) 2001-2007 Chris Danford, Ben Nordstrom, Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef ScreenHighScores_H +#define ScreenHighScores_H + +#include "ScreenAttract.h" +#include "Course.h" +#include "DynamicActorScroller.h" + +typedef pair DifficultyAndStepsType; + +enum HighScoresType +{ + HighScoresType_AllSteps, // Top 1 HighScore for N Steps in each Song + HighScoresType_NonstopCourses, // Top 1 HighScore for N Trails in each Course + HighScoresType_OniCourses, + HighScoresType_SurvivalCourses, + HighScoresType_AllCourses, + NUM_HighScoresType, + HighScoresType_Invalid +}; +LuaDeclareType( HighScoresType ); + + +class ScoreScroller: public DynamicActorScroller +{ +public: + ScoreScroller(); + void LoadSongs( int iNumRecentScores ); + void LoadCourses( CourseType ct, int iNumRecentScores ); + void Load( RString sClassName ); + void SetDisplay( const vector &DifficultiesToShow ); + bool Scroll( int iDir ); + void ScrollTop(); + +protected: + virtual void ConfigureActor( Actor *pActor, int iItem ); + vector m_DifficultiesToShow; + + struct ScoreRowItemData // for all_steps and all_courses + { + ScoreRowItemData() { m_pSong = nullptr; m_pCourse = nullptr; } + + Song *m_pSong; + Course *m_pCourse; + }; + vector m_vScoreRowItemData; + + ThemeMetric SCROLLER_ITEMS_TO_DRAW; + ThemeMetric SCROLLER_SECONDS_PER_ITEM; +}; + +class ScreenHighScores: public ScreenAttract +{ +public: + virtual void Init(); + virtual void BeginScreen(); + + void HandleScreenMessage( const ScreenMessage SM ); + virtual bool Input( const InputEventPlus &input ); + virtual bool MenuStart( const InputEventPlus &input ); + virtual bool MenuBack( const InputEventPlus &input ); + virtual bool MenuLeft( const InputEventPlus &input ) { DoScroll(-1); return true; } + virtual bool MenuRight( const InputEventPlus &input ) { DoScroll(+1); return true; } + virtual bool MenuUp( const InputEventPlus &input ) { DoScroll(-1); return true; } + virtual bool MenuDown( const InputEventPlus &input ) { DoScroll(+1); return true; } + +private: + void DoScroll( int iDir ); + + ThemeMetric MANUAL_SCROLLING; + ThemeMetric HIGH_SCORES_TYPE; + ThemeMetric NUM_COLUMNS; + ThemeMetric1D COLUMN_DIFFICULTY; + ThemeMetric1D COLUMN_STEPS_TYPE; + ThemeMetric MAX_ITEMS_TO_SHOW; + ScoreScroller m_Scroller; +}; + +#endif + +/* + * (c) 2001-2007 Chris Danford, Ben Nordstrom, Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/ScreenHowToPlay.cpp b/src/ScreenHowToPlay.cpp index 37d61ea05b..cc655edaab 100644 --- a/src/ScreenHowToPlay.cpp +++ b/src/ScreenHowToPlay.cpp @@ -69,9 +69,9 @@ ScreenHowToPlay::ScreenHowToPlay() m_iNumW2s = NUM_W2S; // initialize these because they might not be used. - m_pLifeMeterBar = NULL; - m_pmCharacter = NULL; - m_pmDancePad = NULL; + m_pLifeMeterBar = nullptr; + m_pmCharacter = nullptr; + m_pmDancePad = nullptr; } void ScreenHowToPlay::Init() diff --git a/src/ScreenInstallOverlay.cpp b/src/ScreenInstallOverlay.cpp index 5a9a49d42b..4fa62ea9b0 100644 --- a/src/ScreenInstallOverlay.cpp +++ b/src/ScreenInstallOverlay.cpp @@ -366,7 +366,7 @@ void ScreenInstallOverlay::Update( float fDeltaTime ) if( !playAfterLaunchInfo.sSongDir.empty() ) { - Song* pSong = NULL; + Song* pSong = nullptr; GAMESTATE->Reset(); RString sInitialScreen; if( playAfterLaunchInfo.sSongDir.length() > 0 ) diff --git a/src/ScreenJukebox.cpp b/src/ScreenJukebox.cpp index 9c7bf2dbc5..5e29483554 100644 --- a/src/ScreenJukebox.cpp +++ b/src/ScreenJukebox.cpp @@ -166,7 +166,7 @@ void ScreenJukebox::SetSong() ScreenJukebox::ScreenJukebox() { m_bDemonstration = false; - m_pCourseEntry = NULL; + m_pCourseEntry = nullptr; } void ScreenJukebox::Init() diff --git a/src/ScreenManager.cpp b/src/ScreenManager.cpp index d41adfbba6..dd95ea3ff7 100644 --- a/src/ScreenManager.cpp +++ b/src/ScreenManager.cpp @@ -73,13 +73,13 @@ #include "ActorUtil.h" -ScreenManager* SCREENMAN = NULL; // global and accessable from anywhere in our program +ScreenManager* SCREENMAN = nullptr; // global and accessable from anywhere in our program static Preference g_bDelayedScreenLoad( "DelayedScreenLoad", false ); //static Preference g_bPruneFonts( "PruneFonts", true ); // Screen registration -static map *g_pmapRegistrees = NULL; +static map *g_pmapRegistrees = nullptr; /** @brief Utility functions for the ScreenManager. */ namespace ScreenManagerUtil @@ -97,7 +97,7 @@ namespace ScreenManagerUtil LoadedScreen() { - m_pScreen = NULL; + m_pScreen = nullptr; m_bDeleteWhenDone = true; m_SendOnPop = SM_None; } @@ -561,7 +561,7 @@ void ScreenManager::PrepareScreen( const RString &sScreenName ) if( !sNewBGA.empty() && sNewBGA != g_pSharedBGA->GetName() ) { - Actor *pNewBGA = NULL; + Actor *pNewBGA = nullptr; for (Actor *a : g_vPreparedBackgrounds) { if( a->GetName() == sNewBGA ) @@ -632,7 +632,7 @@ bool ScreenManager::ActivatePreparedScreenAndBackground( const RString &sScreenN RString sNewBGA = THEME->GetPathB(sScreenName,"background"); if( sNewBGA != g_pSharedBGA->GetName() ) { - Actor *pNewBGA = NULL; + Actor *pNewBGA = nullptr; if( sNewBGA.empty() ) { pNewBGA = new Actor; diff --git a/src/ScreenMiniMenu.cpp b/src/ScreenMiniMenu.cpp index bd93036e33..d7102786dc 100644 --- a/src/ScreenMiniMenu.cpp +++ b/src/ScreenMiniMenu.cpp @@ -27,7 +27,7 @@ void FinishedLoadingScreen() {} // Settings: namespace { - const MenuDef* g_pMenuDef = NULL; + const MenuDef* g_pMenuDef = nullptr; ScreenMessage g_SendOnOK; ScreenMessage g_SendOnCancel; }; @@ -64,7 +64,7 @@ void ScreenMiniMenu::BeginScreen() LoadMenu( g_pMenuDef ); m_SMSendOnOK = g_SendOnOK; m_SMSendOnCancel = g_SendOnCancel; - g_pMenuDef = NULL; + g_pMenuDef = nullptr; ScreenOptions::BeginScreen(); diff --git a/src/ScreenMiniMenu.h b/src/ScreenMiniMenu.h index dc7c4112ee..80aabc148a 100644 --- a/src/ScreenMiniMenu.h +++ b/src/ScreenMiniMenu.h @@ -53,7 +53,7 @@ struct MenuRowDef MenuRowDef(int r, RString n, bool e, EditMode s, bool bTT, bool bTI, int d, vector options): - iRowCode(r), sName(n), bEnabled(e), pfnEnabled(NULL), + iRowCode(r), sName(n), bEnabled(e), pfnEnabled(nullptr), emShowIn(s), iDefaultChoice(d), choices(), bThemeTitle(bTT), bThemeItems(bTI) { @@ -77,7 +77,7 @@ struct MenuRowDef const char *c20=NULL, const char *c21=NULL, const char *c22=NULL, const char *c23=NULL, const char *c24=NULL, const char *c25=NULL ): - iRowCode(r), sName(n), bEnabled(e), pfnEnabled(NULL), + iRowCode(r), sName(n), bEnabled(e), pfnEnabled(nullptr), emShowIn(s), iDefaultChoice(d), choices(), bThemeTitle(bTT), bThemeItems(bTI) { @@ -92,7 +92,7 @@ struct MenuRowDef MenuRowDef( int r, RString n, bool e, EditMode s, bool bTT, bool bTI, int d, int low, int high ): - iRowCode(r), sName(n), bEnabled(e), pfnEnabled(NULL), + iRowCode(r), sName(n), bEnabled(e), pfnEnabled(nullptr), emShowIn(s), iDefaultChoice(d), choices(), bThemeTitle(bTT), bThemeItems(bTI) { diff --git a/src/ScreenNetRoom.cpp b/src/ScreenNetRoom.cpp index b18b84ed31..f117b251c2 100644 --- a/src/ScreenNetRoom.cpp +++ b/src/ScreenNetRoom.cpp @@ -252,7 +252,7 @@ bool ScreenNetRoom::MenuRight( const InputEventPlus &input ) void ScreenNetRoom::UpdateRoomsList() { int difference = 0; - RoomWheelItemData* itemData = NULL; + RoomWheelItemData* itemData = nullptr; difference = m_RoomWheel.GetNumItems() - m_Rooms.size(); diff --git a/src/ScreenOptions.cpp b/src/ScreenOptions.cpp index 9443ebb419..57b5e95c10 100644 --- a/src/ScreenOptions.cpp +++ b/src/ScreenOptions.cpp @@ -589,7 +589,7 @@ void ScreenOptions::PositionRows( bool bTween ) int P2Choice = GAMESTATE->IsHumanPlayer(PLAYER_2)? m_iCurrentRow[PLAYER_2]: m_iCurrentRow[PLAYER_1]; vector Rows( m_pRows ); - OptionRow *pSeparateExitRow = NULL; + OptionRow *pSeparateExitRow = nullptr; if( (bool)SEPARATE_EXIT_ROW && !Rows.empty() && Rows.back()->GetRowType() == OptionRow::RowType_Exit ) { @@ -744,7 +744,7 @@ void ScreenOptions::AfterChangeValueOrRow( PlayerNumber pn ) } const RString text = GetExplanationText( iCurRow ); - BitmapText *pText = NULL; + BitmapText *pText = nullptr; switch( m_InputMode ) { case INPUTMODE_INDIVIDUAL: diff --git a/src/ScreenOptionsCourseOverview.cpp b/src/ScreenOptionsCourseOverview.cpp index eb44d84b31..c65fd59bc1 100644 --- a/src/ScreenOptionsCourseOverview.cpp +++ b/src/ScreenOptionsCourseOverview.cpp @@ -88,7 +88,7 @@ void ScreenOptionsCourseOverview::BeginScreen() ScreenOptions::BeginScreen(); // clear the current song in case it's set when we back out from gameplay - GAMESTATE->m_pCurSong.Set( NULL ); + GAMESTATE->m_pCurSong.Set(nullptr); } ScreenOptionsCourseOverview::~ScreenOptionsCourseOverview() @@ -115,7 +115,7 @@ void ScreenOptionsCourseOverview::HandleScreenMessage( const ScreenMessage SM ) if( SM == SM_GoToPrevScreen ) { // If we're pointing to an unsaved course, it will be inaccessible once we're back on ScreenOptionsManageCourses. - GAMESTATE->m_pCurCourse.Set( NULL ); + GAMESTATE->m_pCurCourse.Set(nullptr); } else if( SM == SM_GoToNextScreen ) { @@ -169,8 +169,8 @@ void ScreenOptionsCourseOverview::HandleScreenMessage( const ScreenMessage SM ) return; } - GAMESTATE->m_pCurCourse.Set( NULL ); - GAMESTATE->m_pCurTrail[PLAYER_1].Set( NULL ); + GAMESTATE->m_pCurCourse.Set(nullptr); + GAMESTATE->m_pCurTrail[PLAYER_1].Set(nullptr); /* Our course is gone, so back out. */ StartTransitioningScreen( SM_GoToPrevScreen ); diff --git a/src/ScreenOptionsEditCourse.cpp b/src/ScreenOptionsEditCourse.cpp index 5ae02f9232..dd3de0709a 100644 --- a/src/ScreenOptionsEditCourse.cpp +++ b/src/ScreenOptionsEditCourse.cpp @@ -56,7 +56,7 @@ public: else { m_Def.m_vsChoices.push_back( "n/a" ); - m_vpSteps.push_back( NULL ); + m_vpSteps.push_back(nullptr); m_Def.m_vEnabledForPlayers.clear(); } @@ -274,7 +274,7 @@ void ScreenOptionsEditCourse::ImportOptions( int iRow, const vectorm_pCurCourse->m_vEntries.size() ) pSong = GAMESTATE->m_pCurCourse->m_vEntries[iEntryIndex].songID.ToSong(); @@ -379,14 +379,14 @@ void ScreenOptionsEditCourse::SetCurrentSong() if( row.GetRowType() == OptionRow::RowType_Exit ) { - GAMESTATE->m_pCurSong.Set( NULL ); - GAMESTATE->m_pCurSteps[PLAYER_1].Set( NULL ); + GAMESTATE->m_pCurSong.Set(nullptr); + GAMESTATE->m_pCurSteps[PLAYER_1].Set(nullptr); } else { iRow = m_iCurrentRow[PLAYER_1]; int iEntryIndex = RowToEntryIndex( iRow ); - Song *pSong = NULL; + Song *pSong = nullptr; if( iEntryIndex != -1 ) { int iCurrentSongRow = EntryIndexAndRowTypeToRow(iEntryIndex,RowType_Song); @@ -418,7 +418,7 @@ void ScreenOptionsEditCourse::SetCurrentSteps() } else { - GAMESTATE->m_pCurSteps[PLAYER_1].Set( NULL ); + GAMESTATE->m_pCurSteps[PLAYER_1].Set(nullptr); } } diff --git a/src/ScreenOptionsManageEditSteps.cpp b/src/ScreenOptionsManageEditSteps.cpp index 2797c11084..1ba3230f7a 100644 --- a/src/ScreenOptionsManageEditSteps.cpp +++ b/src/ScreenOptionsManageEditSteps.cpp @@ -61,8 +61,8 @@ void ScreenOptionsManageEditSteps::BeginScreen() SONGMAN->FreeAllLoadedFromProfile( ProfileSlot_Machine ); SONGMAN->LoadStepEditsFromProfileDir( PROFILEMAN->GetProfileDir(ProfileSlot_Machine), ProfileSlot_Machine ); SONGMAN->LoadCourseEditsFromProfileDir( PROFILEMAN->GetProfileDir(ProfileSlot_Machine), ProfileSlot_Machine ); - GAMESTATE->m_pCurSong.Set( NULL ); - GAMESTATE->m_pCurSteps[PLAYER_1].Set( NULL ); + GAMESTATE->m_pCurSong.Set(nullptr); + GAMESTATE->m_pCurSteps[PLAYER_1].Set(nullptr); vector vHands; @@ -177,7 +177,7 @@ void ScreenOptionsManageEditSteps::HandleScreenMessage( const ScreenMessage SM ) Steps *pSteps = GetStepsWithFocus(); FILEMAN->Remove( pSteps->GetFilename() ); SONGMAN->DeleteSteps( pSteps ); - GAMESTATE->m_pCurSteps[PLAYER_1].Set( NULL ); + GAMESTATE->m_pCurSteps[PLAYER_1].Set(nullptr); SCREENMAN->SetNewScreen( this->m_sName ); // reload } } diff --git a/src/ScreenOptionsMasterPrefs.h b/src/ScreenOptionsMasterPrefs.h index a9758491e1..6755c0e049 100644 --- a/src/ScreenOptionsMasterPrefs.h +++ b/src/ScreenOptionsMasterPrefs.h @@ -43,7 +43,7 @@ struct ConfOption name = n; m_sPrefName = name; // copy from name (not n), to allow refcounting MoveData = m; - MakeOptionsListCB = NULL; + MakeOptionsListCB = nullptr; m_iEffects = 0; m_bAllowThemeItems = true; #define PUSH( c ) if(c) names.push_back(c); diff --git a/src/ScreenOptionsReviewWorkout.cpp b/src/ScreenOptionsReviewWorkout.cpp index d4e0431f52..81fe0b6847 100644 --- a/src/ScreenOptionsReviewWorkout.cpp +++ b/src/ScreenOptionsReviewWorkout.cpp @@ -66,7 +66,7 @@ void ScreenOptionsCourseOverview::BeginScreen() ScreenOptions::BeginScreen(); // clear the current song in case it's set when we back out from gameplay - GAMESTATE->m_pCurSong.Set( NULL ); + GAMESTATE->m_pCurSong.Set(nullptr); } ScreenOptionsCourseOverview::~ScreenOptionsCourseOverview() diff --git a/src/ScreenPrompt.h b/src/ScreenPrompt.h index 8d93cc6c84..4254354c6a 100644 --- a/src/ScreenPrompt.h +++ b/src/ScreenPrompt.h @@ -1,88 +1,88 @@ -/* ScreenPrompt - Displays a prompt on top of another screen. */ - -#ifndef SCREEN_PROMPT_H -#define SCREEN_PROMPT_H - -#include "ScreenWithMenuElements.h" -#include "BitmapText.h" -#include "RageSound.h" - -enum PromptType -{ - PROMPT_OK, - PROMPT_YES_NO, - PROMPT_YES_NO_CANCEL -}; - -enum PromptAnswer -{ - ANSWER_YES, - ANSWER_NO, - ANSWER_CANCEL, - NUM_PromptAnswer -}; - -class ScreenPrompt : public ScreenWithMenuElements -{ -public: - static void SetPromptSettings( const RString &sText, PromptType type = PROMPT_OK, PromptAnswer defaultAnswer = ANSWER_NO, void(*OnYes)(void*) = NULL, void(*OnNo)(void*) = NULL, void* pCallbackData = NULL ); - static void Prompt( ScreenMessage smSendOnPop, const RString &sText, PromptType type = PROMPT_OK, PromptAnswer defaultAnswer = ANSWER_NO, void(*OnYes)(void*) = NULL, void(*OnNo)(void*) = NULL, void* pCallbackData = NULL ); - - virtual void Init(); - virtual void BeginScreen(); - virtual bool Input( const InputEventPlus &input ); - - static PromptAnswer s_LastAnswer; - static bool s_bCancelledLast; - - // Lua - //virtual void PushSelf( lua_State *L ); - -protected: - bool CanGoLeft() { return m_Answer > 0; } - bool CanGoRight(); - void Change( int dir ); - bool MenuLeft( const InputEventPlus &input ); - bool MenuRight( const InputEventPlus &input ); - bool MenuBack( const InputEventPlus &input ); - bool MenuStart( const InputEventPlus &input ); - - virtual void End( bool bCancelled ); - void PositionCursor(); - - virtual void TweenOffScreen(); - - BitmapText m_textQuestion; - AutoActor m_sprCursor; - BitmapText m_textAnswer[NUM_PromptAnswer]; - PromptAnswer m_Answer; - - RageSound m_sndChange; -}; - -#endif - -/* - * (c) 2001-2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* ScreenPrompt - Displays a prompt on top of another screen. */ + +#ifndef SCREEN_PROMPT_H +#define SCREEN_PROMPT_H + +#include "ScreenWithMenuElements.h" +#include "BitmapText.h" +#include "RageSound.h" + +enum PromptType +{ + PROMPT_OK, + PROMPT_YES_NO, + PROMPT_YES_NO_CANCEL +}; + +enum PromptAnswer +{ + ANSWER_YES, + ANSWER_NO, + ANSWER_CANCEL, + NUM_PromptAnswer +}; + +class ScreenPrompt : public ScreenWithMenuElements +{ +public: + static void SetPromptSettings( const RString &sText, PromptType type = PROMPT_OK, PromptAnswer defaultAnswer = ANSWER_NO, void(*OnYes)(void*) = nullptr, void(*OnNo)(void*) = nullptr, void* pCallbackData = nullptr ); + static void Prompt( ScreenMessage smSendOnPop, const RString &sText, PromptType type = PROMPT_OK, PromptAnswer defaultAnswer = ANSWER_NO, void(*OnYes)(void*) = nullptr, void(*OnNo)(void*) = nullptr, void* pCallbackData = nullptr ); + + virtual void Init(); + virtual void BeginScreen(); + virtual bool Input( const InputEventPlus &input ); + + static PromptAnswer s_LastAnswer; + static bool s_bCancelledLast; + + // Lua + //virtual void PushSelf( lua_State *L ); + +protected: + bool CanGoLeft() { return m_Answer > 0; } + bool CanGoRight(); + void Change( int dir ); + bool MenuLeft( const InputEventPlus &input ); + bool MenuRight( const InputEventPlus &input ); + bool MenuBack( const InputEventPlus &input ); + bool MenuStart( const InputEventPlus &input ); + + virtual void End( bool bCancelled ); + void PositionCursor(); + + virtual void TweenOffScreen(); + + BitmapText m_textQuestion; + AutoActor m_sprCursor; + BitmapText m_textAnswer[NUM_PromptAnswer]; + PromptAnswer m_Answer; + + RageSound m_sndChange; +}; + +#endif + +/* + * (c) 2001-2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/ScreenRanking.h b/src/ScreenRanking.h index 628fc410af..85fab7fdf8 100644 --- a/src/ScreenRanking.h +++ b/src/ScreenRanking.h @@ -35,8 +35,8 @@ protected: { PageToShow() { - pCourse = NULL; - pTrail = NULL; + pCourse = nullptr; + pTrail = nullptr; } int colorIndex; diff --git a/src/ScreenSelectMusic.cpp b/src/ScreenSelectMusic.cpp index 65fff87ef3..d381750d6a 100644 --- a/src/ScreenSelectMusic.cpp +++ b/src/ScreenSelectMusic.cpp @@ -1050,9 +1050,9 @@ void ScreenSelectMusic::HandleMessage( const Message &msg ) // TODO: Invalidate the CurSteps only if they are no longer playable. // That way, after music change will clamp to the nearest in the StepsDisplayList. - GAMESTATE->m_pCurSteps[master_pn].SetWithoutBroadcast( NULL ); + GAMESTATE->m_pCurSteps[master_pn].SetWithoutBroadcast(nullptr); FOREACH_ENUM( PlayerNumber, p ) - GAMESTATE->m_pCurSteps[p].SetWithoutBroadcast( NULL ); + GAMESTATE->m_pCurSteps[p].SetWithoutBroadcast(nullptr); /* If a course is selected, it may no longer be playable. * Let MusicWheel know about the late join. */ @@ -1421,7 +1421,7 @@ bool ScreenSelectMusic::MenuStart( const InputEventPlus &input ) if( CommonMetrics::AUTO_SET_STYLE ) { // Now that Steps have been chosen, set a Style that can play them. - const Style *pStyle = NULL; + const Style *pStyle = nullptr; if( GAMESTATE->IsCourseMode() ) pStyle = GAMESTATE->m_pCurCourse->GetCourseStyle( GAMESTATE->m_pCurGame, GAMESTATE->GetNumSidesJoined() ); if( pStyle == nullptr ) @@ -1535,7 +1535,7 @@ void ScreenSelectMusic::AfterStepsOrTrailChange( const vector &vpn Steps* pSteps = m_vpSteps.empty()? NULL: m_vpSteps[m_iSelection[pn]]; GAMESTATE->m_pCurSteps[pn].Set( pSteps ); - GAMESTATE->m_pCurTrail[pn].Set( NULL ); + GAMESTATE->m_pCurTrail[pn].Set(nullptr); int iScore = 0; if( pSteps ) @@ -1553,7 +1553,7 @@ void ScreenSelectMusic::AfterStepsOrTrailChange( const vector &vpn Course* pCourse = GAMESTATE->m_pCurCourse; Trail* pTrail = m_vpTrails.empty()? NULL: m_vpTrails[m_iSelection[pn]]; - GAMESTATE->m_pCurSteps[pn].Set( NULL ); + GAMESTATE->m_pCurSteps[pn].Set(nullptr); GAMESTATE->m_pCurTrail[pn].Set( pTrail ); int iScore = 0; @@ -1681,7 +1681,7 @@ void ScreenSelectMusic::AfterMusicChange() { m_sSampleMusicToPlay = ""; } - m_pSampleMusicTimingData = NULL; + m_pSampleMusicTimingData = nullptr; g_sCDTitlePath = ""; g_sBannerPath = ""; g_bWantFallbackCdTitle = false; @@ -1825,7 +1825,7 @@ void ScreenSelectMusic::AfterMusicChange() case WheelItemDataType_Course: { const Course *lCourse = m_MusicWheel.GetSelectedCourse(); - const Style *pStyle = NULL; + const Style *pStyle = nullptr; if( CommonMetrics::AUTO_SET_STYLE ) pStyle = pCourse->GetCourseStyle( GAMESTATE->m_pCurGame, GAMESTATE->GetNumSidesJoined() ); if( pStyle == nullptr ) diff --git a/src/ScreenServiceAction.cpp b/src/ScreenServiceAction.cpp index eb55486b5b..512e6a73c2 100644 --- a/src/ScreenServiceAction.cpp +++ b/src/ScreenServiceAction.cpp @@ -388,7 +388,7 @@ void ScreenServiceAction::BeginScreen() vector vsResults; for (RString const &s : vsActions) { - RString (*pfn)() = NULL; + RString (*pfn)() = nullptr; if( s == "ClearMachineStats" ) pfn = ClearMachineStats; else if( s == "ClearMachineEdits" ) pfn = ClearMachineEdits; diff --git a/src/ScreenSetTime.cpp b/src/ScreenSetTime.cpp index 4062f07c6c..93aa39c177 100644 --- a/src/ScreenSetTime.cpp +++ b/src/ScreenSetTime.cpp @@ -1,264 +1,264 @@ -#include "global.h" -#include "ScreenSetTime.h" -#include "ScreenManager.h" -#include "RageLog.h" -#include "InputMapper.h" -#include "ThemeManager.h" -#include "DateTime.h" -#include "EnumHelper.h" -#include "arch/ArchHooks/ArchHooks.h" -#include "InputEventPlus.h" - -static const char *SetTimeSelectionNames[] = { - "Year", - "Month", - "Day", - "Hour", - "Minute", - "Second", -}; -XToString( SetTimeSelection ); -/** @brief A foreach iterator through the time selections. */ -#define FOREACH_SetTimeSelection( s ) FOREACH_ENUM( SetTimeSelection, s ) - -const float g_X[NUM_SetTimeSelection] = -{ - 320, 320, 320, 320, 320, 320 -}; - -const float g_Y[NUM_SetTimeSelection] = -{ - 140, 180, 220, 260, 300, 340 -}; - -static float GetTitleX( SetTimeSelection s ) { return g_X[s] - 80; } -static float GetTitleY( SetTimeSelection s ) { return g_Y[s]; } -static float GetValueX( SetTimeSelection s ) { return g_X[s] + 80; } -static float GetValueY( SetTimeSelection s ) { return g_Y[s]; } - -REGISTER_SCREEN_CLASS( ScreenSetTime ); - -void ScreenSetTime::Init() -{ - ScreenWithMenuElements::Init(); - - m_Selection = hour; - - FOREACH_SetTimeSelection( s ) - { - BitmapText &title = m_textTitle[s]; - BitmapText &value = m_textValue[s]; - - title.LoadFromFont( THEME->GetPathF("Common","title") ); - title.SetDiffuse( RageColor(1,1,1,1) ); - title.SetText( SetTimeSelectionToString(s) ); - title.SetXY( GetTitleX(s), GetTitleY(s) ); - this->AddChild( &title ); - - title.SetDiffuse( RageColor(1,1,1,0) ); - title.BeginTweening( 0.3f, TWEEN_LINEAR ); - title.SetDiffuse( RageColor(1,1,1,1) ); - - value.LoadFromFont( THEME->GetPathF("Common","normal") ); - value.SetDiffuse( RageColor(1,1,1,1) ); - value.SetXY( GetValueX(s), GetValueY(s) ); - this->AddChild( &value ); - - value.SetDiffuse( RageColor(1,1,1,0) ); - value.BeginTweening( 0.3f, TWEEN_LINEAR ); - value.SetDiffuse( RageColor(1,1,1,1) ); - } - - m_soundChangeSelection.Load( THEME->GetPathS("ScreenSetTime","ChangeSelection") ); - m_soundChangeValue.Load( THEME->GetPathS("ScreenSetTime","ChangeValue") ); - - m_TimeOffset = 0; - m_Selection = (SetTimeSelection)0; - ChangeSelection( 0 ); -} - -void ScreenSetTime::Update( float fDelta ) -{ - Screen::Update( fDelta ); - - time_t iNow = time(NULL); - iNow += m_TimeOffset; - - tm now; - localtime_r( &iNow, &now ); - - int iPrettyHour = now.tm_hour%12; - if( iPrettyHour == 0 ) - iPrettyHour = 12; - RString sPrettyHour = ssprintf( "%d %s", iPrettyHour, now.tm_hour>=12 ? "pm" : "am" ); - - m_textValue[hour] .SetText( sPrettyHour ); - m_textValue[minute] .SetText( ssprintf("%02d",now.tm_min) ); - m_textValue[second] .SetText( ssprintf("%02d",now.tm_sec) ); - m_textValue[year] .SetText( ssprintf("%02d",now.tm_year+1900) ); - m_textValue[month] .SetText( MonthToString((Month)now.tm_mon) ); - m_textValue[day] .SetText( ssprintf("%02d",now.tm_mday) ); -} - -bool ScreenSetTime::Input( const InputEventPlus &input ) -{ - if( input.type != IET_FIRST_PRESS && input.type != IET_REPEAT ) - return false; // ignore - - if( IsTransitioning() ) - return false; - - return Screen::Input( input ); // default handler -} - -void ScreenSetTime::ChangeValue( int iDirection ) -{ - time_t iNow = time(NULL); - time_t iAdjusted = iNow + m_TimeOffset; - - tm adjusted; - localtime_r( &iAdjusted, &adjusted ); - - //tm now = GetLocalTime(); - switch( m_Selection ) - { - case hour: adjusted.tm_hour += iDirection; break; - case minute: adjusted.tm_min += iDirection; break; - case second: adjusted.tm_sec += iDirection; break; - case year: adjusted.tm_year += iDirection; break; - case month: adjusted.tm_mon += iDirection; break; - case day: adjusted.tm_mday += iDirection; break; - default: - FAIL_M(ssprintf("Invalid SetTimeSelection: %i", m_Selection)); - } - - /* Normalize: */ - iAdjusted = mktime( &adjusted ); - - m_TimeOffset = iAdjusted - iNow; - - m_soundChangeValue.Play(); -} - -void ScreenSetTime::ChangeSelection( int iDirection ) -{ - // set new value of m_Selection - SetTimeSelection OldSelection = m_Selection; - enum_add( m_Selection, iDirection ); - - ENUM_CLAMP( m_Selection, SetTimeSelection(0), SetTimeSelection(NUM_SetTimeSelection-1) ); - if( iDirection != 0 && m_Selection == OldSelection ) - return; // can't move any more - - m_textValue[OldSelection].StopEffect(); - m_textValue[m_Selection].SetEffectDiffuseShift( 1.f, - RageColor(0.3f,0.3f,0.3f,1), - RageColor(1,1,1,1) ); - - if( iDirection != 0 ) - m_soundChangeSelection.Play(); -} - -bool ScreenSetTime::MenuUp( const InputEventPlus &input ) -{ - ChangeSelection( -1 ); - return true; -} - -bool ScreenSetTime::MenuDown( const InputEventPlus &input ) -{ - ChangeSelection( +1 ); - return true; -} - -bool ScreenSetTime::MenuLeft( const InputEventPlus &input ) -{ - ChangeValue( -1 ); - return true; -} - -bool ScreenSetTime::MenuRight( const InputEventPlus &input ) -{ - ChangeValue( +1 ); - return true; -} - -bool ScreenSetTime::MenuStart( const InputEventPlus &input ) -{ - bool bHoldingLeftAndRight = - INPUTMAPPER->IsBeingPressed( GAME_BUTTON_RIGHT, input.pn ) && - INPUTMAPPER->IsBeingPressed( GAME_BUTTON_LEFT, input.pn ); - - if( bHoldingLeftAndRight ) - ChangeSelection( -1 ); - else if( m_Selection == NUM_SetTimeSelection -1 ) // last row - { - /* Save the new time. */ - time_t iNow = time(NULL); - time_t iAdjusted = iNow + m_TimeOffset; - - tm adjusted; - localtime_r( &iAdjusted, &adjusted ); - - HOOKS->SetTime( adjusted ); - - /* We're going to draw a little more while we transition out. We've already - * set the new time; don't over-adjust visually. */ - m_TimeOffset = 0; - - FOREACH_SetTimeSelection( s ) - { - BitmapText &title = m_textTitle[s]; - title.BeginTweening( 0.3f, TWEEN_LINEAR ); - title.SetDiffuse( RageColor(1,1,1,0) ); - - BitmapText &value = m_textValue[s]; - value.BeginTweening( 0.3f, TWEEN_LINEAR ); - value.SetDiffuse( RageColor(1,1,1,0) ); - } - - SCREENMAN->PlayStartSound(); - StartTransitioningScreen( SM_GoToNextScreen ); - } - else - ChangeSelection( +1 ); - return true; -} - -bool ScreenSetTime::MenuSelect( const InputEventPlus &input ) -{ - ChangeSelection( -1 ); - return true; -} - -bool ScreenSetTime::MenuBack( const InputEventPlus &input ) -{ - StartTransitioningScreen( SM_GoToPrevScreen ); - return true; -} - -/* - * (c) 2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ - +#include "global.h" +#include "ScreenSetTime.h" +#include "ScreenManager.h" +#include "RageLog.h" +#include "InputMapper.h" +#include "ThemeManager.h" +#include "DateTime.h" +#include "EnumHelper.h" +#include "arch/ArchHooks/ArchHooks.h" +#include "InputEventPlus.h" + +static const char *SetTimeSelectionNames[] = { + "Year", + "Month", + "Day", + "Hour", + "Minute", + "Second", +}; +XToString( SetTimeSelection ); +/** @brief A foreach iterator through the time selections. */ +#define FOREACH_SetTimeSelection( s ) FOREACH_ENUM( SetTimeSelection, s ) + +const float g_X[NUM_SetTimeSelection] = +{ + 320, 320, 320, 320, 320, 320 +}; + +const float g_Y[NUM_SetTimeSelection] = +{ + 140, 180, 220, 260, 300, 340 +}; + +static float GetTitleX( SetTimeSelection s ) { return g_X[s] - 80; } +static float GetTitleY( SetTimeSelection s ) { return g_Y[s]; } +static float GetValueX( SetTimeSelection s ) { return g_X[s] + 80; } +static float GetValueY( SetTimeSelection s ) { return g_Y[s]; } + +REGISTER_SCREEN_CLASS( ScreenSetTime ); + +void ScreenSetTime::Init() +{ + ScreenWithMenuElements::Init(); + + m_Selection = hour; + + FOREACH_SetTimeSelection( s ) + { + BitmapText &title = m_textTitle[s]; + BitmapText &value = m_textValue[s]; + + title.LoadFromFont( THEME->GetPathF("Common","title") ); + title.SetDiffuse( RageColor(1,1,1,1) ); + title.SetText( SetTimeSelectionToString(s) ); + title.SetXY( GetTitleX(s), GetTitleY(s) ); + this->AddChild( &title ); + + title.SetDiffuse( RageColor(1,1,1,0) ); + title.BeginTweening( 0.3f, TWEEN_LINEAR ); + title.SetDiffuse( RageColor(1,1,1,1) ); + + value.LoadFromFont( THEME->GetPathF("Common","normal") ); + value.SetDiffuse( RageColor(1,1,1,1) ); + value.SetXY( GetValueX(s), GetValueY(s) ); + this->AddChild( &value ); + + value.SetDiffuse( RageColor(1,1,1,0) ); + value.BeginTweening( 0.3f, TWEEN_LINEAR ); + value.SetDiffuse( RageColor(1,1,1,1) ); + } + + m_soundChangeSelection.Load( THEME->GetPathS("ScreenSetTime","ChangeSelection") ); + m_soundChangeValue.Load( THEME->GetPathS("ScreenSetTime","ChangeValue") ); + + m_TimeOffset = 0; + m_Selection = (SetTimeSelection)0; + ChangeSelection( 0 ); +} + +void ScreenSetTime::Update( float fDelta ) +{ + Screen::Update( fDelta ); + + time_t iNow = time(nullptr); + iNow += m_TimeOffset; + + tm now; + localtime_r( &iNow, &now ); + + int iPrettyHour = now.tm_hour%12; + if( iPrettyHour == 0 ) + iPrettyHour = 12; + RString sPrettyHour = ssprintf( "%d %s", iPrettyHour, now.tm_hour>=12 ? "pm" : "am" ); + + m_textValue[hour] .SetText( sPrettyHour ); + m_textValue[minute] .SetText( ssprintf("%02d",now.tm_min) ); + m_textValue[second] .SetText( ssprintf("%02d",now.tm_sec) ); + m_textValue[year] .SetText( ssprintf("%02d",now.tm_year+1900) ); + m_textValue[month] .SetText( MonthToString((Month)now.tm_mon) ); + m_textValue[day] .SetText( ssprintf("%02d",now.tm_mday) ); +} + +bool ScreenSetTime::Input( const InputEventPlus &input ) +{ + if( input.type != IET_FIRST_PRESS && input.type != IET_REPEAT ) + return false; // ignore + + if( IsTransitioning() ) + return false; + + return Screen::Input( input ); // default handler +} + +void ScreenSetTime::ChangeValue( int iDirection ) +{ + time_t iNow = time(nullptr); + time_t iAdjusted = iNow + m_TimeOffset; + + tm adjusted; + localtime_r( &iAdjusted, &adjusted ); + + //tm now = GetLocalTime(); + switch( m_Selection ) + { + case hour: adjusted.tm_hour += iDirection; break; + case minute: adjusted.tm_min += iDirection; break; + case second: adjusted.tm_sec += iDirection; break; + case year: adjusted.tm_year += iDirection; break; + case month: adjusted.tm_mon += iDirection; break; + case day: adjusted.tm_mday += iDirection; break; + default: + FAIL_M(ssprintf("Invalid SetTimeSelection: %i", m_Selection)); + } + + /* Normalize: */ + iAdjusted = mktime( &adjusted ); + + m_TimeOffset = iAdjusted - iNow; + + m_soundChangeValue.Play(); +} + +void ScreenSetTime::ChangeSelection( int iDirection ) +{ + // set new value of m_Selection + SetTimeSelection OldSelection = m_Selection; + enum_add( m_Selection, iDirection ); + + ENUM_CLAMP( m_Selection, SetTimeSelection(0), SetTimeSelection(NUM_SetTimeSelection-1) ); + if( iDirection != 0 && m_Selection == OldSelection ) + return; // can't move any more + + m_textValue[OldSelection].StopEffect(); + m_textValue[m_Selection].SetEffectDiffuseShift( 1.f, + RageColor(0.3f,0.3f,0.3f,1), + RageColor(1,1,1,1) ); + + if( iDirection != 0 ) + m_soundChangeSelection.Play(); +} + +bool ScreenSetTime::MenuUp( const InputEventPlus &input ) +{ + ChangeSelection( -1 ); + return true; +} + +bool ScreenSetTime::MenuDown( const InputEventPlus &input ) +{ + ChangeSelection( +1 ); + return true; +} + +bool ScreenSetTime::MenuLeft( const InputEventPlus &input ) +{ + ChangeValue( -1 ); + return true; +} + +bool ScreenSetTime::MenuRight( const InputEventPlus &input ) +{ + ChangeValue( +1 ); + return true; +} + +bool ScreenSetTime::MenuStart( const InputEventPlus &input ) +{ + bool bHoldingLeftAndRight = + INPUTMAPPER->IsBeingPressed( GAME_BUTTON_RIGHT, input.pn ) && + INPUTMAPPER->IsBeingPressed( GAME_BUTTON_LEFT, input.pn ); + + if( bHoldingLeftAndRight ) + ChangeSelection( -1 ); + else if( m_Selection == NUM_SetTimeSelection -1 ) // last row + { + /* Save the new time. */ + time_t iNow = time(nullptr); + time_t iAdjusted = iNow + m_TimeOffset; + + tm adjusted; + localtime_r( &iAdjusted, &adjusted ); + + HOOKS->SetTime( adjusted ); + + /* We're going to draw a little more while we transition out. We've already + * set the new time; don't over-adjust visually. */ + m_TimeOffset = 0; + + FOREACH_SetTimeSelection( s ) + { + BitmapText &title = m_textTitle[s]; + title.BeginTweening( 0.3f, TWEEN_LINEAR ); + title.SetDiffuse( RageColor(1,1,1,0) ); + + BitmapText &value = m_textValue[s]; + value.BeginTweening( 0.3f, TWEEN_LINEAR ); + value.SetDiffuse( RageColor(1,1,1,0) ); + } + + SCREENMAN->PlayStartSound(); + StartTransitioningScreen( SM_GoToNextScreen ); + } + else + ChangeSelection( +1 ); + return true; +} + +bool ScreenSetTime::MenuSelect( const InputEventPlus &input ) +{ + ChangeSelection( -1 ); + return true; +} + +bool ScreenSetTime::MenuBack( const InputEventPlus &input ) +{ + StartTransitioningScreen( SM_GoToPrevScreen ); + return true; +} + +/* + * (c) 2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + diff --git a/src/ScreenTextEntry.h b/src/ScreenTextEntry.h index ee78688dff..d35253223f 100644 --- a/src/ScreenTextEntry.h +++ b/src/ScreenTextEntry.h @@ -1,200 +1,200 @@ -#ifndef SCREEN_TEXT_ENTRY_H -#define SCREEN_TEXT_ENTRY_H - -#include "ScreenWithMenuElements.h" -#include "BitmapText.h" -#include "RageSound.h" -#include "ThemeMetric.h" -#include "InputEventPlus.h" - -/** @brief The list of possible keyboard rows. */ -enum KeyboardRow -{ - R1, - R2, - R3, - R4, - R5, - R6, - R7, - KEYBOARD_ROW_SPECIAL, - NUM_KeyboardRow, - KeyboardRow_Invalid -}; -/** @brief A special foreach loop for the KeyboardRow enum. */ -#define FOREACH_KeyboardRow( i ) FOREACH_ENUM( KeyboardRow, i ) -/** @brief The maximum number of keys per row. */ -const int KEYS_PER_ROW = 13; -/** @brief The list of very special keys inside some rows. */ -enum KeyboardRowSpecialKey -{ - SPACEBAR=2, /**< The space bar key. */ - BACKSPACE=5, /**< The backspace key. */ - CANCEL=8, - DONE=11 -}; - -/** @brief Displays a text entry box over the top of another screen. */ -class ScreenTextEntry : public ScreenWithMenuElements -{ -public: - static void SetTextEntrySettings( - RString sQuestion, - RString sInitialAnswer, - int iMaxInputLength, - bool(*Validate)(const RString &sAnswer,RString &sErrorOut) = NULL, - void(*OnOK)(const RString &sAnswer) = NULL, - void(*OnCancel)() = NULL, - bool bPassword = false, - bool (*ValidateAppend)(const RString &sAnswerBeforeChar, RString &sAppend) = NULL, - RString (*FormatAnswerForDisplay)(const RString &sAnswer) = NULL - ); - static void TextEntry( - ScreenMessage smSendOnPop, - RString sQuestion, - RString sInitialAnswer, - int iMaxInputLength, - bool(*Validate)(const RString &sAnswer,RString &sErrorOut) = NULL, - void(*OnOK)(const RString &sAnswer) = NULL, - void(*OnCancel)() = NULL, - bool bPassword = false, - bool (*ValidateAppend)(const RString &sAnswerBeforeChar, RString &sAppend) = NULL, - RString (*FormatAnswerForDisplay)(const RString &sAnswer) = NULL - ); - static void Password( - ScreenMessage smSendOnPop, - const RString &sQuestion, - void(*OnOK)(const RString &sPassword) = NULL, - void(*OnCancel)() = NULL ) - { - TextEntry( smSendOnPop, sQuestion, "", 255, NULL, OnOK, OnCancel, true ); - } - - struct TextEntrySettings { - TextEntrySettings(): smSendOnPop(), sQuestion(""), - sInitialAnswer(""), iMaxInputLength(0), - bPassword(false), Validate(), OnOK(), OnCancel(), - ValidateAppend(), FormatAnswerForDisplay() { } - ScreenMessage smSendOnPop; - RString sQuestion; - RString sInitialAnswer; - int iMaxInputLength; - /** @brief Is there a password involved with this setting? - * - * This parameter doesn't have to be used. */ - bool bPassword; - LuaReference Validate; // (RString sAnswer, RString sErrorOut; optional) - LuaReference OnOK; // (RString sAnswer; optional) - LuaReference OnCancel; // (optional) - LuaReference ValidateAppend; // (RString sAnswerBeforeChar, RString sAppend; optional) - LuaReference FormatAnswerForDisplay; // (RString sAnswer; optional) - - // see BitmapText.cpp Attribute::FromStack() and - // OptionRowHandler.cpp LoadInternal() for ideas on how to implement the - // main part, and ImportOption() from OptionRowHandler.cpp for functions. - void FromStack( lua_State *L ); - }; - void LoadFromTextEntrySettings( const TextEntrySettings &settings ); - - static bool FloatValidate( const RString &sAnswer, RString &sErrorOut ); - - virtual void Init(); - virtual void BeginScreen(); - - virtual void Update( float fDelta ); - virtual bool Input( const InputEventPlus &input ); - - static RString s_sLastAnswer; - static bool s_bCancelledLast; - - // Lua - virtual void PushSelf( lua_State *L ); - -protected: - void TryAppendToAnswer( RString s ); - void BackspaceInAnswer(); - virtual void TextEnteredDirectly() { } - - virtual void End( bool bCancelled ); -private: - virtual bool MenuStart( const InputEventPlus &input ); - virtual bool MenuBack( const InputEventPlus &input ); - - void UpdateAnswerText(); - - wstring m_sAnswer; - bool m_bShowAnswerCaret; - // todo: allow Left/Right to change caret location -aj - //int m_iCaretLocation; - - BitmapText m_textQuestion; - BitmapText m_textAnswer; - - RageSound m_sndType; - RageSound m_sndBackspace; - - RageTimer m_timerToggleCursor; -}; - -/** @brief Displays a text entry box and keyboard over the top of another screen. */ -class ScreenTextEntryVisual: public ScreenTextEntry -{ -public: - ~ScreenTextEntryVisual(); - void Init(); - void BeginScreen(); - -protected: - void MoveX( int iDir ); - void MoveY( int iDir ); - void PositionCursor(); - - virtual void TextEnteredDirectly(); - - virtual bool MenuLeft( const InputEventPlus &input ); - virtual bool MenuRight( const InputEventPlus &input ); - virtual bool MenuUp( const InputEventPlus &input ); - virtual bool MenuDown( const InputEventPlus &input ); - - virtual bool MenuStart( const InputEventPlus &input ); - - int m_iFocusX; - KeyboardRow m_iFocusY; - - AutoActor m_sprCursor; - BitmapText *m_ptextKeys[NUM_KeyboardRow][KEYS_PER_ROW]; - - RageSound m_sndChange; - - ThemeMetric ROW_START_X; - ThemeMetric ROW_START_Y; - ThemeMetric ROW_END_X; - ThemeMetric ROW_END_Y; -}; - -#endif - -/* - * (c) 2001-2004 Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef SCREEN_TEXT_ENTRY_H +#define SCREEN_TEXT_ENTRY_H + +#include "ScreenWithMenuElements.h" +#include "BitmapText.h" +#include "RageSound.h" +#include "ThemeMetric.h" +#include "InputEventPlus.h" + +/** @brief The list of possible keyboard rows. */ +enum KeyboardRow +{ + R1, + R2, + R3, + R4, + R5, + R6, + R7, + KEYBOARD_ROW_SPECIAL, + NUM_KeyboardRow, + KeyboardRow_Invalid +}; +/** @brief A special foreach loop for the KeyboardRow enum. */ +#define FOREACH_KeyboardRow( i ) FOREACH_ENUM( KeyboardRow, i ) +/** @brief The maximum number of keys per row. */ +const int KEYS_PER_ROW = 13; +/** @brief The list of very special keys inside some rows. */ +enum KeyboardRowSpecialKey +{ + SPACEBAR=2, /**< The space bar key. */ + BACKSPACE=5, /**< The backspace key. */ + CANCEL=8, + DONE=11 +}; + +/** @brief Displays a text entry box over the top of another screen. */ +class ScreenTextEntry : public ScreenWithMenuElements +{ +public: + static void SetTextEntrySettings( + RString sQuestion, + RString sInitialAnswer, + int iMaxInputLength, + bool(*Validate)(const RString &sAnswer,RString &sErrorOut) = nullptr, + void(*OnOK)(const RString &sAnswer) = nullptr, + void(*OnCancel)() = nullptr, + bool bPassword = false, + bool (*ValidateAppend)(const RString &sAnswerBeforeChar, RString &sAppend) = nullptr, + RString (*FormatAnswerForDisplay)(const RString &sAnswer) = nullptr + ); + static void TextEntry( + ScreenMessage smSendOnPop, + RString sQuestion, + RString sInitialAnswer, + int iMaxInputLength, + bool(*Validate)(const RString &sAnswer,RString &sErrorOut) = nullptr, + void(*OnOK)(const RString &sAnswer) = nullptr, + void(*OnCancel)() = nullptr, + bool bPassword = false, + bool (*ValidateAppend)(const RString &sAnswerBeforeChar, RString &sAppend) = nullptr, + RString (*FormatAnswerForDisplay)(const RString &sAnswer) = nullptr + ); + static void Password( + ScreenMessage smSendOnPop, + const RString &sQuestion, + void(*OnOK)(const RString &sPassword) = nullptr, + void(*OnCancel)() = nullptr ) + { + TextEntry( smSendOnPop, sQuestion, "", 255, NULL, OnOK, OnCancel, true ); + } + + struct TextEntrySettings { + TextEntrySettings(): smSendOnPop(), sQuestion(""), + sInitialAnswer(""), iMaxInputLength(0), + bPassword(false), Validate(), OnOK(), OnCancel(), + ValidateAppend(), FormatAnswerForDisplay() { } + ScreenMessage smSendOnPop; + RString sQuestion; + RString sInitialAnswer; + int iMaxInputLength; + /** @brief Is there a password involved with this setting? + * + * This parameter doesn't have to be used. */ + bool bPassword; + LuaReference Validate; // (RString sAnswer, RString sErrorOut; optional) + LuaReference OnOK; // (RString sAnswer; optional) + LuaReference OnCancel; // (optional) + LuaReference ValidateAppend; // (RString sAnswerBeforeChar, RString sAppend; optional) + LuaReference FormatAnswerForDisplay; // (RString sAnswer; optional) + + // see BitmapText.cpp Attribute::FromStack() and + // OptionRowHandler.cpp LoadInternal() for ideas on how to implement the + // main part, and ImportOption() from OptionRowHandler.cpp for functions. + void FromStack( lua_State *L ); + }; + void LoadFromTextEntrySettings( const TextEntrySettings &settings ); + + static bool FloatValidate( const RString &sAnswer, RString &sErrorOut ); + + virtual void Init(); + virtual void BeginScreen(); + + virtual void Update( float fDelta ); + virtual bool Input( const InputEventPlus &input ); + + static RString s_sLastAnswer; + static bool s_bCancelledLast; + + // Lua + virtual void PushSelf( lua_State *L ); + +protected: + void TryAppendToAnswer( RString s ); + void BackspaceInAnswer(); + virtual void TextEnteredDirectly() { } + + virtual void End( bool bCancelled ); +private: + virtual bool MenuStart( const InputEventPlus &input ); + virtual bool MenuBack( const InputEventPlus &input ); + + void UpdateAnswerText(); + + wstring m_sAnswer; + bool m_bShowAnswerCaret; + // todo: allow Left/Right to change caret location -aj + //int m_iCaretLocation; + + BitmapText m_textQuestion; + BitmapText m_textAnswer; + + RageSound m_sndType; + RageSound m_sndBackspace; + + RageTimer m_timerToggleCursor; +}; + +/** @brief Displays a text entry box and keyboard over the top of another screen. */ +class ScreenTextEntryVisual: public ScreenTextEntry +{ +public: + ~ScreenTextEntryVisual(); + void Init(); + void BeginScreen(); + +protected: + void MoveX( int iDir ); + void MoveY( int iDir ); + void PositionCursor(); + + virtual void TextEnteredDirectly(); + + virtual bool MenuLeft( const InputEventPlus &input ); + virtual bool MenuRight( const InputEventPlus &input ); + virtual bool MenuUp( const InputEventPlus &input ); + virtual bool MenuDown( const InputEventPlus &input ); + + virtual bool MenuStart( const InputEventPlus &input ); + + int m_iFocusX; + KeyboardRow m_iFocusY; + + AutoActor m_sprCursor; + BitmapText *m_ptextKeys[NUM_KeyboardRow][KEYS_PER_ROW]; + + RageSound m_sndChange; + + ThemeMetric ROW_START_X; + ThemeMetric ROW_START_Y; + ThemeMetric ROW_END_X; + ThemeMetric ROW_END_Y; +}; + +#endif + +/* + * (c) 2001-2004 Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/ScreenWithMenuElements.cpp b/src/ScreenWithMenuElements.cpp index 386be3b1f8..66a754cd9f 100644 --- a/src/ScreenWithMenuElements.cpp +++ b/src/ScreenWithMenuElements.cpp @@ -21,10 +21,10 @@ REGISTER_SCREEN_CLASS( ScreenWithMenuElements ); ScreenWithMenuElements::ScreenWithMenuElements() { - m_MenuTimer = NULL; + m_MenuTimer = nullptr; FOREACH_PlayerNumber( p ) - m_MemoryCardDisplay[p] = NULL; - m_MenuTimer = NULL; + m_MemoryCardDisplay[p] = nullptr; + m_MenuTimer = nullptr; } void ScreenWithMenuElements::Init() diff --git a/src/Song.h b/src/Song.h index c4c164a8d6..a13a9f9438 100644 --- a/src/Song.h +++ b/src/Song.h @@ -417,7 +417,7 @@ public: void AddSteps( Steps* pSteps ); void DeleteSteps( const Steps* pSteps, bool bReAutoGen = true ); - void FreeAllLoadedFromProfile( ProfileSlot slot = ProfileSlot_Invalid, const set *setInUse = NULL ); + void FreeAllLoadedFromProfile( ProfileSlot slot = ProfileSlot_Invalid, const set *setInUse = nullptr ); bool WasLoadedFromProfile() const { return m_LoadedFromProfile != ProfileSlot_Invalid; } void GetStepsLoadedFromProfile( ProfileSlot slot, vector &vpStepsOut ) const; int GetNumStepsLoadedFromProfile( ProfileSlot slot ) const; diff --git a/src/SongManager.cpp b/src/SongManager.cpp index 6a76c022c7..2927cf033c 100644 --- a/src/SongManager.cpp +++ b/src/SongManager.cpp @@ -36,7 +36,7 @@ #include "UnlockManager.h" #include "SpecialFiles.h" -SongManager* SONGMAN = NULL; // global and accessable from anywhere in our program +SongManager* SONGMAN = nullptr; // global and accessable from anywhere in our program const RString ADDITIONAL_SONGS_DIR = "/AdditionalSongs/"; const RString ADDITIONAL_COURSES_DIR = "/AdditionalCourses/"; @@ -1191,10 +1191,10 @@ void SongManager::GetExtraStageInfo( bool bExtra2, const Style *sd, Song*& pSong return; // Choose a hard song for the extra stage - Song* pExtra1Song = NULL; // the absolute hardest Song and Steps. Use this for extra stage 1. - Steps* pExtra1Notes = NULL; - Song* pExtra2Song = NULL; // a medium-hard Song and Steps. Use this for extra stage 2. - Steps* pExtra2Notes = NULL; + Song* pExtra1Song = nullptr; // the absolute hardest Song and Steps. Use this for extra stage 1. + Steps* pExtra1Notes = nullptr; + Song* pExtra2Song = nullptr; // a medium-hard Song and Steps. Use this for extra stage 2. + Steps* pExtra2Notes = nullptr; const vector &apSongs = GetSongs( sGroup ); for( unsigned s=0; s::GetSong */ static int GetSongFromSteps( T* p, lua_State *L ) { - Song *pSong = NULL; - if( lua_isnil(L,1) ) { pSong = NULL; } + Song *pSong = nullptr; + if( lua_isnil(L,1) ) { pSong = nullptr; } else { Steps *pSteps = Luna::check(L,1); pSong = pSteps->m_pSong; } if(pSong) pSong->PushSelf(L); else lua_pushnil(L); diff --git a/src/SongUtil.cpp b/src/SongUtil.cpp index d50d316cb4..62b42476b6 100644 --- a/src/SongUtil.cpp +++ b/src/SongUtil.cpp @@ -225,7 +225,7 @@ Steps* SongUtil::GetClosestNotes( const Song *pSong, StepsType st, Difficulty dc ASSERT( dc != Difficulty_Invalid ); const vector& vpSteps = (st == StepsType_Invalid)? pSong->GetAllSteps() : pSong->GetStepsByStepsType(st); - Steps *pClosest = NULL; + Steps *pClosest = nullptr; int iClosestDistance = 999; for( unsigned i=0; i - -class Song; -class Steps; -class Profile; -class XNode; - -void AppendOctal( int n, int digits, RString &out ); - -/** @brief The criteria for dealing with songs. */ -class SongCriteria -{ -public: - /** - * @brief What group name are we searching for for Songs? - * - * If an empty string, don't bother using this for searching. */ - RString m_sGroupName; - bool m_bUseSongGenreAllowedList; - vector m_vsSongGenreAllowedList; - enum Selectable { Selectable_Yes, Selectable_No, Selectable_DontCare } m_Selectable; - bool m_bUseSongAllowedList; - vector m_vpSongAllowedList; - /** @brief How many songs does this take max? Don't use this if it's -1. */ - int m_iMaxStagesForSong; // don't filter if -1 - // float m_fMinBPM; // don't filter if -1 - // float m_fMaxBPM; // don't filter if -1 - /** @brief Is this song used for tutorial purposes? */ - enum Tutorial - { - Tutorial_Yes, /**< This song is used for tutorial purposes. */ - Tutorial_No, /**< This song is not used for tutorial purposes. */ - Tutorial_DontCare /**< This song can or cannot be used for tutorial purposes. */ - } m_Tutorial; - /** @brief Is this song used for locking/unlocking purposes? */ - enum Locked - { - Locked_Locked, /**< This song is a locked song. */ - Locked_Unlocked, /**< This song is an unlocked song. */ - Locked_DontCare /**< This song can or cannot be locked or unlocked. */ - } m_Locked; - - /** @brief Set up some initial song criteria. */ - SongCriteria(): m_sGroupName(""), m_bUseSongGenreAllowedList(false), - m_vsSongGenreAllowedList(), m_Selectable(Selectable_DontCare), - m_bUseSongAllowedList(false), m_vpSongAllowedList(), - m_iMaxStagesForSong(-1), m_Tutorial(Tutorial_DontCare), - m_Locked(Locked_DontCare) - { - // m_fMinBPM = -1; - // m_fMaxBPM = -1; - } - - /** - * @brief Determine if the song matches the current criteria. - * @param p the song to compare against the criteria. - * @return true of the song matches the criteria, false otherwise. - */ - bool Matches( const Song *p ) const; - /** - * @brief Determine if two sets of criteria are equivalent. - * @param other the other criteria. - * @return true if the two sets of criteria are equal, false otherwise. - */ - bool operator==( const SongCriteria &other ) const - { -/** @brief A quick way to match every part of the song criterium. */ -#define X(x) (x == other.x) - return - X(m_sGroupName) && - X(m_bUseSongGenreAllowedList) && - X(m_vsSongGenreAllowedList) && - X(m_Selectable) && - X(m_bUseSongAllowedList) && - X(m_vpSongAllowedList) && - X(m_iMaxStagesForSong) && - //X(m_fMinBPM) && - //X(m_fMaxBPM) && - X(m_Tutorial) && - X(m_Locked); -#undef X - } - /** - * @brief Determine if two sets of criteria are not equivalent. - * @param other the other criteria. - * @return true if the two sets of criteria are not equal, false otherwise. - */ - bool operator!=( const SongCriteria &other ) const { return !operator==( other ); } -}; - -/** @brief A set of song utilities to make working with songs easier. */ -namespace SongUtil -{ - void GetSteps( - const Song *pSong, - vector& arrayAddTo, - StepsType st = StepsType_Invalid, - Difficulty dc = Difficulty_Invalid, - int iMeterLow = -1, - int iMeterHigh = -1, - const RString &sDescription = "", - const RString &sCredit = "", - bool bIncludeAutoGen = true, - unsigned uHash = 0, - int iMaxToGet = -1 - ); - Steps* GetOneSteps( - const Song *pSong, - StepsType st = StepsType_Invalid, - Difficulty dc = Difficulty_Invalid, - int iMeterLow = -1, - int iMeterHigh = -1, - const RString &sDescription = "", - const RString &sCredit = "", - unsigned uHash = 0, - bool bIncludeAutoGen = true - ); - Steps* GetStepsByDifficulty( const Song *pSong, StepsType st, Difficulty dc, bool bIncludeAutoGen = true ); - Steps* GetStepsByMeter( const Song *pSong, StepsType st, int iMeterLow, int iMeterHigh ); - Steps* GetStepsByDescription( const Song *pSong, StepsType st, RString sDescription ); - Steps* GetStepsByCredit( const Song *pSong, StepsType st, RString sCredit ); - Steps* GetClosestNotes( const Song *pSong, StepsType st, Difficulty dc, bool bIgnoreLocked=false ); - - void AdjustDuplicateSteps( Song *pSong ); // part of TidyUpData - void DeleteDuplicateSteps( Song *pSong, vector &vSteps ); - - RString MakeSortString( RString s ); - void SortSongPointerArrayByTitle( vector &vpSongsInOut ); - void SortSongPointerArrayByBPM( vector &vpSongsInOut ); - void SortSongPointerArrayByGrades( vector &vpSongsInOut, bool bDescending ); - void SortSongPointerArrayByArtist( vector &vpSongsInOut ); - void SortSongPointerArrayByDisplayArtist( vector &vpSongsInOut ); - void SortSongPointerArrayByGenre( vector &vpSongsInOut ); - void SortSongPointerArrayByGroupAndTitle( vector &vpSongsInOut ); - void SortSongPointerArrayByNumPlays( vector &vpSongsInOut, ProfileSlot slot, bool bDescending ); - void SortSongPointerArrayByNumPlays( vector &vpSongsInOut, const Profile* pProfile, bool bDescending ); - void SortSongPointerArrayByStepsTypeAndMeter( vector &vpSongsInOut, StepsType st, Difficulty dc ); - RString GetSectionNameFromSongAndSort( const Song *pSong, SortOrder so ); - void SortSongPointerArrayBySectionName( vector &vpSongsInOut, SortOrder so ); - void SortByMostRecentlyPlayedForMachine( vector &vpSongsInOut ); - void SortSongPointerArrayByLength( vector &vpSongsInOut ); - - int CompareSongPointersByGroup(const Song *pSong1, const Song *pSong2); - - /** - * @brief Determine if the requested description for an edit is unique. - * @param pSong the song the edit is for. - * @param st the steps type for the edit. - * @param sPreferredDescription the requested description. - * @param pExclude the steps that want the description. - * @return true if it is unique, false otherwise. - */ - bool IsEditDescriptionUnique( const Song* pSong, StepsType st, const RString &sPreferredDescription, const Steps *pExclude ); - bool IsChartNameUnique( const Song* pSong, StepsType st, const RString &name, const Steps *pExclude ); - RString MakeUniqueEditDescription( const Song* pSong, StepsType st, const RString &sPreferredDescription ); - bool ValidateCurrentEditStepsDescription( const RString &sAnswer, RString &sErrorOut ); - bool ValidateCurrentStepsDescription( const RString &sAnswer, RString &sErrorOut ); - bool ValidateCurrentStepsCredit( const RString &sAnswer, RString &sErrorOut ); - bool ValidateCurrentStepsChartName(const RString &answer, RString &error); - - void GetAllSongGenres( vector &vsOut ); - /** - * @brief Filter the selection of songs to only match certain criteria. - * @param sc the intended song criteria. - * @param in the starting batch of songs. - * @param out the resulting batch. - * @param doCareAboutGame a flag to see if we should only get playable steps. */ - void FilterSongs( const SongCriteria &sc, const vector &in, vector &out, - bool doCareAboutGame = false ); - - void GetPlayableStepsTypes( const Song *pSong, set &vOut ); - void GetPlayableSteps( const Song *pSong, vector &vOut ); - bool IsStepsTypePlayable( Song *pSong, StepsType st ); - bool IsStepsPlayable( Song *pSong, Steps *pSteps ); - - /** - * @brief Determine if the song has any playable steps in the present game. - * @param s the current song. - * @return true if the song has playable steps, false otherwise. */ - bool IsSongPlayable( Song *s ); - - bool GetStepsTypeAndDifficultyFromSortOrder( SortOrder so, StepsType &st, Difficulty &dc ); -} - -class SongID -{ - RString sDir; - mutable CachedObjectPointer m_Cache; - -public: - /** - * @brief Set up the SongID with default values. - * - * This used to call Unset() to do the same thing. */ - SongID(): sDir(""), m_Cache() { m_Cache.Unset(); } - void Unset() { FromSong(NULL); } - void FromSong( const Song *p ); - Song *ToSong() const; - bool operator<( const SongID &other ) const - { - return sDir < other.sDir; - } - bool operator==( const SongID &other ) const - { - return sDir == other.sDir; - } - - XNode* CreateNode() const; - void LoadFromNode( const XNode* pNode ); - void FromString( RString _sDir ) { sDir = _sDir; } - RString ToString() const; - bool IsValid() const; -}; - - -#endif - -/** - * @file - * @author Chris Danford, Glenn Maynard (c) 2001-2004 - * @section LICENSE - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/** @brief SongUtil - Utility functions that deal with Song. */ + +#ifndef SONG_UTIL_H +#define SONG_UTIL_H + +#include "GameConstantsAndTypes.h" +#include "Difficulty.h" +#include "RageUtil_CachedObject.h" +#include + +class Song; +class Steps; +class Profile; +class XNode; + +void AppendOctal( int n, int digits, RString &out ); + +/** @brief The criteria for dealing with songs. */ +class SongCriteria +{ +public: + /** + * @brief What group name are we searching for for Songs? + * + * If an empty string, don't bother using this for searching. */ + RString m_sGroupName; + bool m_bUseSongGenreAllowedList; + vector m_vsSongGenreAllowedList; + enum Selectable { Selectable_Yes, Selectable_No, Selectable_DontCare } m_Selectable; + bool m_bUseSongAllowedList; + vector m_vpSongAllowedList; + /** @brief How many songs does this take max? Don't use this if it's -1. */ + int m_iMaxStagesForSong; // don't filter if -1 + // float m_fMinBPM; // don't filter if -1 + // float m_fMaxBPM; // don't filter if -1 + /** @brief Is this song used for tutorial purposes? */ + enum Tutorial + { + Tutorial_Yes, /**< This song is used for tutorial purposes. */ + Tutorial_No, /**< This song is not used for tutorial purposes. */ + Tutorial_DontCare /**< This song can or cannot be used for tutorial purposes. */ + } m_Tutorial; + /** @brief Is this song used for locking/unlocking purposes? */ + enum Locked + { + Locked_Locked, /**< This song is a locked song. */ + Locked_Unlocked, /**< This song is an unlocked song. */ + Locked_DontCare /**< This song can or cannot be locked or unlocked. */ + } m_Locked; + + /** @brief Set up some initial song criteria. */ + SongCriteria(): m_sGroupName(""), m_bUseSongGenreAllowedList(false), + m_vsSongGenreAllowedList(), m_Selectable(Selectable_DontCare), + m_bUseSongAllowedList(false), m_vpSongAllowedList(), + m_iMaxStagesForSong(-1), m_Tutorial(Tutorial_DontCare), + m_Locked(Locked_DontCare) + { + // m_fMinBPM = -1; + // m_fMaxBPM = -1; + } + + /** + * @brief Determine if the song matches the current criteria. + * @param p the song to compare against the criteria. + * @return true of the song matches the criteria, false otherwise. + */ + bool Matches( const Song *p ) const; + /** + * @brief Determine if two sets of criteria are equivalent. + * @param other the other criteria. + * @return true if the two sets of criteria are equal, false otherwise. + */ + bool operator==( const SongCriteria &other ) const + { +/** @brief A quick way to match every part of the song criterium. */ +#define X(x) (x == other.x) + return + X(m_sGroupName) && + X(m_bUseSongGenreAllowedList) && + X(m_vsSongGenreAllowedList) && + X(m_Selectable) && + X(m_bUseSongAllowedList) && + X(m_vpSongAllowedList) && + X(m_iMaxStagesForSong) && + //X(m_fMinBPM) && + //X(m_fMaxBPM) && + X(m_Tutorial) && + X(m_Locked); +#undef X + } + /** + * @brief Determine if two sets of criteria are not equivalent. + * @param other the other criteria. + * @return true if the two sets of criteria are not equal, false otherwise. + */ + bool operator!=( const SongCriteria &other ) const { return !operator==( other ); } +}; + +/** @brief A set of song utilities to make working with songs easier. */ +namespace SongUtil +{ + void GetSteps( + const Song *pSong, + vector& arrayAddTo, + StepsType st = StepsType_Invalid, + Difficulty dc = Difficulty_Invalid, + int iMeterLow = -1, + int iMeterHigh = -1, + const RString &sDescription = "", + const RString &sCredit = "", + bool bIncludeAutoGen = true, + unsigned uHash = 0, + int iMaxToGet = -1 + ); + Steps* GetOneSteps( + const Song *pSong, + StepsType st = StepsType_Invalid, + Difficulty dc = Difficulty_Invalid, + int iMeterLow = -1, + int iMeterHigh = -1, + const RString &sDescription = "", + const RString &sCredit = "", + unsigned uHash = 0, + bool bIncludeAutoGen = true + ); + Steps* GetStepsByDifficulty( const Song *pSong, StepsType st, Difficulty dc, bool bIncludeAutoGen = true ); + Steps* GetStepsByMeter( const Song *pSong, StepsType st, int iMeterLow, int iMeterHigh ); + Steps* GetStepsByDescription( const Song *pSong, StepsType st, RString sDescription ); + Steps* GetStepsByCredit( const Song *pSong, StepsType st, RString sCredit ); + Steps* GetClosestNotes( const Song *pSong, StepsType st, Difficulty dc, bool bIgnoreLocked=false ); + + void AdjustDuplicateSteps( Song *pSong ); // part of TidyUpData + void DeleteDuplicateSteps( Song *pSong, vector &vSteps ); + + RString MakeSortString( RString s ); + void SortSongPointerArrayByTitle( vector &vpSongsInOut ); + void SortSongPointerArrayByBPM( vector &vpSongsInOut ); + void SortSongPointerArrayByGrades( vector &vpSongsInOut, bool bDescending ); + void SortSongPointerArrayByArtist( vector &vpSongsInOut ); + void SortSongPointerArrayByDisplayArtist( vector &vpSongsInOut ); + void SortSongPointerArrayByGenre( vector &vpSongsInOut ); + void SortSongPointerArrayByGroupAndTitle( vector &vpSongsInOut ); + void SortSongPointerArrayByNumPlays( vector &vpSongsInOut, ProfileSlot slot, bool bDescending ); + void SortSongPointerArrayByNumPlays( vector &vpSongsInOut, const Profile* pProfile, bool bDescending ); + void SortSongPointerArrayByStepsTypeAndMeter( vector &vpSongsInOut, StepsType st, Difficulty dc ); + RString GetSectionNameFromSongAndSort( const Song *pSong, SortOrder so ); + void SortSongPointerArrayBySectionName( vector &vpSongsInOut, SortOrder so ); + void SortByMostRecentlyPlayedForMachine( vector &vpSongsInOut ); + void SortSongPointerArrayByLength( vector &vpSongsInOut ); + + int CompareSongPointersByGroup(const Song *pSong1, const Song *pSong2); + + /** + * @brief Determine if the requested description for an edit is unique. + * @param pSong the song the edit is for. + * @param st the steps type for the edit. + * @param sPreferredDescription the requested description. + * @param pExclude the steps that want the description. + * @return true if it is unique, false otherwise. + */ + bool IsEditDescriptionUnique( const Song* pSong, StepsType st, const RString &sPreferredDescription, const Steps *pExclude ); + bool IsChartNameUnique( const Song* pSong, StepsType st, const RString &name, const Steps *pExclude ); + RString MakeUniqueEditDescription( const Song* pSong, StepsType st, const RString &sPreferredDescription ); + bool ValidateCurrentEditStepsDescription( const RString &sAnswer, RString &sErrorOut ); + bool ValidateCurrentStepsDescription( const RString &sAnswer, RString &sErrorOut ); + bool ValidateCurrentStepsCredit( const RString &sAnswer, RString &sErrorOut ); + bool ValidateCurrentStepsChartName(const RString &answer, RString &error); + + void GetAllSongGenres( vector &vsOut ); + /** + * @brief Filter the selection of songs to only match certain criteria. + * @param sc the intended song criteria. + * @param in the starting batch of songs. + * @param out the resulting batch. + * @param doCareAboutGame a flag to see if we should only get playable steps. */ + void FilterSongs( const SongCriteria &sc, const vector &in, vector &out, + bool doCareAboutGame = false ); + + void GetPlayableStepsTypes( const Song *pSong, set &vOut ); + void GetPlayableSteps( const Song *pSong, vector &vOut ); + bool IsStepsTypePlayable( Song *pSong, StepsType st ); + bool IsStepsPlayable( Song *pSong, Steps *pSteps ); + + /** + * @brief Determine if the song has any playable steps in the present game. + * @param s the current song. + * @return true if the song has playable steps, false otherwise. */ + bool IsSongPlayable( Song *s ); + + bool GetStepsTypeAndDifficultyFromSortOrder( SortOrder so, StepsType &st, Difficulty &dc ); +} + +class SongID +{ + RString sDir; + mutable CachedObjectPointer m_Cache; + +public: + /** + * @brief Set up the SongID with default values. + * + * This used to call Unset() to do the same thing. */ + SongID(): sDir(""), m_Cache() { m_Cache.Unset(); } + void Unset() { FromSong(nullptr); } + void FromSong( const Song *p ); + Song *ToSong() const; + bool operator<( const SongID &other ) const + { + return sDir < other.sDir; + } + bool operator==( const SongID &other ) const + { + return sDir == other.sDir; + } + + XNode* CreateNode() const; + void LoadFromNode( const XNode* pNode ); + void FromString( RString _sDir ) { sDir = _sDir; } + RString ToString() const; + bool IsValid() const; +}; + + +#endif + +/** + * @file + * @author Chris Danford, Glenn Maynard (c) 2001-2004 + * @section LICENSE + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/SoundEffectControl.cpp b/src/SoundEffectControl.cpp index 2055e6bda1..7c0ee64518 100644 --- a/src/SoundEffectControl.cpp +++ b/src/SoundEffectControl.cpp @@ -12,8 +12,8 @@ SoundEffectControl::SoundEffectControl() m_bLocked = false; m_fSample = 0.0f; m_fLastLevel = 0.0f; - m_pPlayerState = NULL; - m_pNoteData = NULL; + m_pPlayerState = nullptr; + m_pNoteData = nullptr; } void SoundEffectControl::Load( const RString &sType, PlayerState *pPlayerState, const NoteData *pNoteData ) diff --git a/src/SoundEffectControl.h b/src/SoundEffectControl.h index 97ab713991..e299b6e024 100644 --- a/src/SoundEffectControl.h +++ b/src/SoundEffectControl.h @@ -14,7 +14,7 @@ public: void Load( const RString &sType, PlayerState *pPlayerState, const NoteData *pNoteData ); void SetSoundReader( RageSoundReader *pPlayer ); - void ReleaseSound() { SetSoundReader(NULL); } + void ReleaseSound() { SetSoundReader(nullptr); } void Update( float fDeltaTime ); diff --git a/src/Sprite.cpp b/src/Sprite.cpp index beab4388f5..b74df5a794 100644 --- a/src/Sprite.cpp +++ b/src/Sprite.cpp @@ -20,7 +20,7 @@ REGISTER_ACTOR_CLASS( Sprite ); Sprite::Sprite() { - m_pTexture = NULL; + m_pTexture = nullptr; m_iCurState = 0; m_fSecsIntoState = 0.0f; m_bUsingCustomTexCoords = false; @@ -60,7 +60,7 @@ Sprite::Sprite( const Sprite &cpy ): if( cpy.m_pTexture != nullptr ) m_pTexture = TEXTUREMAN->CopyTexture( cpy.m_pTexture ); else - m_pTexture = NULL; + m_pTexture = nullptr; } void Sprite::InitState() @@ -235,7 +235,7 @@ void Sprite::UnloadTexture() if( m_pTexture != nullptr ) // If there was a previous bitmap... { TEXTUREMAN->UnloadTexture( m_pTexture ); // Unload it. - m_pTexture = NULL; + m_pTexture = nullptr; /* Make sure we're reset to frame 0, so if we're reused, we aren't left * on a frame number that may be greater than the number of frames in @@ -301,7 +301,7 @@ void Sprite::LoadFromTexture( RageTextureID ID ) { // LOG->Trace( "Sprite::LoadFromTexture( %s )", ID.filename.c_str() ); - RageTexture *pTexture = NULL; + RageTexture *pTexture = nullptr; if( m_pTexture && m_pTexture->GetID() == ID ) pTexture = m_pTexture; else diff --git a/src/StageStats.cpp b/src/StageStats.cpp index c7f85794a3..1b52b3e892 100644 --- a/src/StageStats.cpp +++ b/src/StageStats.cpp @@ -20,7 +20,7 @@ StageStats::StageStats() m_playMode = PlayMode_Invalid; m_Stage = Stage_Invalid; m_iStageIndex = -1; - m_pStyle = NULL; + m_pStyle = nullptr; m_vpPlayedSongs.clear(); m_vpPossibleSongs.clear(); m_EarnedExtraStage = EarnedExtraStage_No; @@ -264,7 +264,7 @@ void StageStats::FinalizeScores( bool bSummary ) Profile* pProfile = PROFILEMAN->GetMachineProfile(); StepsType st = GAMESTATE->GetCurrentStyle()->m_StepsType; - const HighScoreList *pHSL = NULL; + const HighScoreList *pHSL = nullptr; if( bSummary ) { pHSL = &pProfile->GetCategoryHighScoreList( st, m_player[p].m_rc ); diff --git a/src/StatsManager.cpp b/src/StatsManager.cpp index 4d81758b47..81617ee7fd 100644 --- a/src/StatsManager.cpp +++ b/src/StatsManager.cpp @@ -14,7 +14,7 @@ #include "CryptManager.h" #include "XmlFileUtil.h" -StatsManager* STATSMAN = NULL; // global object accessable from anywhere in the program +StatsManager* STATSMAN = nullptr; // global object accessable from anywhere in the program void AddPlayerStatsToProfile( Profile *pProfile, const StageStats &ss, PlayerNumber pn ); XNode* MakeRecentScoreNode( const StageStats &ss, Trail *pTrail, const PlayerStageStats &pss, MultiPlayer mp ); @@ -165,7 +165,7 @@ void AddPlayerStatsToProfile( Profile *pProfile, const StageStats &ss, PlayerNum XNode* MakeRecentScoreNode( const StageStats &ss, Trail *pTrail, const PlayerStageStats &pss, MultiPlayer mp ) { - XNode* pNode = NULL; + XNode* pNode = nullptr; if( GAMESTATE->IsCourseMode() ) { pNode = new XNode( "HighScoreForACourseAndTrail" ); @@ -260,7 +260,7 @@ void StatsManager::CommitStatsToProfiles( const StageStats *pSS ) auto_ptr xml( new XNode("Stats") ); xml->AppendChild( "MachineGuid", PROFILEMAN->GetMachineProfile()->m_sGuid ); - XNode *recent = NULL; + XNode *recent = nullptr; if( GAMESTATE->IsCourseMode() ) recent = xml->AppendChild( new XNode("RecentCourseScores") ); else diff --git a/src/StepMania.cpp b/src/StepMania.cpp index 7d52109646..5dac70f954 100644 --- a/src/StepMania.cpp +++ b/src/StepMania.cpp @@ -732,7 +732,7 @@ RageDisplay *CreateDisplay() if( asRenderers.empty() ) RageException::Throw( "%s", ERROR_NO_VIDEO_RENDERERS.GetValue().c_str() ); - RageDisplay *pRet = NULL; + RageDisplay *pRet = nullptr; for( unsigned i=0; iSetProcessedTimingData(NULL); + GAMESTATE->SetProcessedTimingData(nullptr); } void Steps::Decompress() const @@ -444,7 +444,7 @@ void Steps::DeAutogen( bool bCopyNoteData ) m_iMeter = Real()->m_iMeter; copy( Real()->m_CachedRadarValues, Real()->m_CachedRadarValues + NUM_PLAYERS, m_CachedRadarValues ); m_sCredit = Real()->m_sCredit; - parent = NULL; + parent = nullptr; if( bCopyNoteData ) Compress(); @@ -463,7 +463,7 @@ void Steps::CopyFrom( Steps* pSource, StepsType ntTo, float fMusicLengthSeconds NoteData noteData; pSource->GetNoteData( noteData ); noteData.SetNumTracks( GAMEMAN->GetStepsTypeInfo(ntTo).iNumTracks ); - parent = NULL; + parent = nullptr; m_Timing = pSource->m_Timing; this->m_pSong = pSource->m_pSong; this->m_Attacks = pSource->m_Attacks; diff --git a/src/StepsDisplay.cpp b/src/StepsDisplay.cpp index 97832c59fb..ea17f4ffac 100644 --- a/src/StepsDisplay.cpp +++ b/src/StepsDisplay.cpp @@ -293,7 +293,7 @@ public: { if( lua_isnil(L,1) ) { - p->SetFromSteps( NULL ); + p->SetFromSteps(nullptr); } else { @@ -306,7 +306,7 @@ public: { if( lua_isnil(L,1) ) { - p->SetFromTrail( NULL ); + p->SetFromTrail(nullptr); } else { diff --git a/src/StepsUtil.cpp b/src/StepsUtil.cpp index 3a8b87ed70..ab427d187a 100644 --- a/src/StepsUtil.cpp +++ b/src/StepsUtil.cpp @@ -248,7 +248,7 @@ Steps *StepsID::ToSteps( const Song *p, bool bAllowNull ) const SongID songID; songID.FromSong( p ); - Steps *pRet = NULL; + Steps *pRet = nullptr; if( dc == Difficulty_Edit ) { pRet = SongUtil::GetOneSteps( p, st, dc, -1, -1, sDescription, "", uHash, true ); diff --git a/src/StepsUtil.h b/src/StepsUtil.h index fa61a61900..f22d988f00 100644 --- a/src/StepsUtil.h +++ b/src/StepsUtil.h @@ -90,7 +90,7 @@ public: Steps *pSteps; /** @brief Set up a blank Song and * Step. */ - SongAndSteps() : pSong(NULL), pSteps(NULL) { } + SongAndSteps() : pSong(nullptr), pSteps(nullptr) { } /** * @brief Set up the specified Song and * Step. @@ -170,7 +170,7 @@ public: * the same thing. */ StepsID(): st(StepsType_Invalid), dc(Difficulty_Invalid), sDescription(""), uHash(0), m_Cache() {} - void Unset() { FromSteps(NULL); } + void Unset() { FromSteps(nullptr); } void FromSteps( const Steps *p ); Steps *ToSteps( const Song *p, bool bAllowNull ) const; bool operator<( const StepsID &rhs ) const; diff --git a/src/StyleUtil.h b/src/StyleUtil.h index 6051d17617..ee102a9707 100644 --- a/src/StyleUtil.h +++ b/src/StyleUtil.h @@ -12,7 +12,7 @@ class StyleID public: StyleID(): sGame(""), sStyle("") { } - void Unset() { FromStyle(NULL); } + void Unset() { FromStyle(nullptr); } void FromStyle( const Style *p ); const Style *ToStyle() const; bool operator<( const StyleID &rhs ) const; diff --git a/src/ThemeManager.cpp b/src/ThemeManager.cpp index 4ec59bf5ee..a6f95925ea 100644 --- a/src/ThemeManager.cpp +++ b/src/ThemeManager.cpp @@ -26,7 +26,7 @@ #include "XmlFileUtil.h" #include -ThemeManager* THEME = NULL; // global object accessable from anywhere in the program +ThemeManager* THEME = nullptr; // global object accessable from anywhere in the program static const RString THEME_INFO_INI = "ThemeInfo.ini"; @@ -58,7 +58,7 @@ public: iniStrings.Clear(); } }; -LoadedThemeData *g_pLoadedThemeData = NULL; +LoadedThemeData *g_pLoadedThemeData = nullptr; // For self-registering metrics diff --git a/src/ThemeMetric.h b/src/ThemeMetric.h index ff5decaaf5..2cae4edcfe 100644 --- a/src/ThemeMetric.h +++ b/src/ThemeMetric.h @@ -219,7 +219,7 @@ class ThemeMetric2D : public IThemeMetric vector m_metric; public: - ThemeMetric2D( const RString& sGroup = "", MetricName2D pfn = NULL, size_t N = 0, size_t M = 0 ) + ThemeMetric2D( const RString& sGroup = "", MetricName2D pfn = nullptr, size_t N = 0, size_t M = 0 ) { Load( sGroup, pfn, N, M ); } @@ -260,7 +260,7 @@ class ThemeMetricMap : public IThemeMetric map m_metric; public: - ThemeMetricMap( const RString& sGroup = "", MetricNameMap pfn = NULL, const vector vsValueNames = vector() ) + ThemeMetricMap( const RString& sGroup = "", MetricNameMap pfn = nullptr, const vector vsValueNames = vector() ) { Load( sGroup, pfn, vsValueNames ); } diff --git a/src/Trail.cpp b/src/Trail.cpp index 3b0ae9ff90..53cb69fbd2 100644 --- a/src/Trail.cpp +++ b/src/Trail.cpp @@ -125,7 +125,7 @@ const RadarValues &Trail::GetRadarValues() const NoteDataUtil::TransformNoteData( nd, e.Attacks, pSteps->m_StepsType, e.pSong ); RadarValues transformed_rv; NoteDataUtil::CalculateRadarValues( nd, e.pSong->m_fMusicLengthSeconds, transformed_rv ); - GAMESTATE->SetProcessedTimingData(NULL); + GAMESTATE->SetProcessedTimingData(nullptr); rv += transformed_rv; } else diff --git a/src/Trail.h b/src/Trail.h index 8c9b8a1095..e447496216 100644 --- a/src/Trail.h +++ b/src/Trail.h @@ -1,129 +1,129 @@ -#ifndef TRAIL_H -#define TRAIL_H - -#include "Attack.h" -#include "RadarValues.h" -#include "Difficulty.h" -#include "RageUtil_CachedObject.h" - -class Song; -class Steps; -struct lua_State; - -/** @brief One such Song and - * Step in the entire Trail. */ -struct TrailEntry -{ - TrailEntry(): - pSong(NULL), - pSteps(NULL), - Modifiers(""), - Attacks(), - bSecret(false), - iLowMeter(-1), - iHighMeter(-1), - dc(Difficulty_Invalid) - { - } - void GetAttackArray( AttackArray &out ) const; - - /** @brief The Song involved in the entry. */ - Song* pSong; - /** @brief The Step involved in the entry. */ - Steps* pSteps; - /** @brief The Modifiers applied for the whole Song. */ - RString Modifiers; - /** @brief The Attacks that will take place durring the Song. */ - AttackArray Attacks; - /** - * @brief Is this Song and its Step meant to be a secret? - * If so, it will show text such as "???" to indicate that it's a mystery. */ - bool bSecret; - - /* These represent the meter and difficulty used by the course to pick the - * steps; if you want the real difficulty and meter, look at pSteps. */ - int iLowMeter; - int iHighMeter; - Difficulty dc; - bool operator== ( const TrailEntry &rhs ) const; - bool operator!= ( const TrailEntry &rhs ) const { return !(*this==rhs); } - bool ContainsTransformOrTurn() const; - - // Lua - void PushSelf( lua_State *L ); -}; - -/** @brief A queue of Songs and Steps that are generated from a Course. */ -class Trail -{ -public: - StepsType m_StepsType; - CourseType m_CourseType; - CourseDifficulty m_CourseDifficulty; - vector m_vEntries; - int m_iSpecifiedMeter; // == -1 if no meter specified - mutable bool m_bRadarValuesCached; - mutable RadarValues m_CachedRadarValues; - - /** - * @brief Set up the Trail with default values. - * - * This used to call Init(), which is still available. */ - Trail(): m_StepsType(StepsType_Invalid), - m_CourseType(CourseType_Invalid), - m_CourseDifficulty(Difficulty_Invalid), - m_vEntries(), m_iSpecifiedMeter(-1), - m_bRadarValuesCached(false), m_CachedRadarValues(), - m_CachedObject() {} - void Init() - { - m_StepsType = StepsType_Invalid; - m_CourseDifficulty = Difficulty_Invalid; - m_iSpecifiedMeter = -1; - m_vEntries.clear(); - m_bRadarValuesCached = false; - } - - const RadarValues &GetRadarValues() const; - void SetRadarValues( const RadarValues &rv ); // for pre-populating cache - int GetMeter() const; - int GetTotalMeter() const; - float GetLengthSeconds() const; - void GetDisplayBpms( DisplayBpms &AddTo ) const; - bool IsSecret() const; - bool ContainsSong( const Song *pSong ) const; - - CachedObject m_CachedObject; - - // Lua - void PushSelf( lua_State *L ); -}; - -#endif - -/** - * @file - * @author Chris Danford, Glenn Maynard (c) 2001-2004 - * @section LICENSE - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef TRAIL_H +#define TRAIL_H + +#include "Attack.h" +#include "RadarValues.h" +#include "Difficulty.h" +#include "RageUtil_CachedObject.h" + +class Song; +class Steps; +struct lua_State; + +/** @brief One such Song and + * Step in the entire Trail. */ +struct TrailEntry +{ + TrailEntry(): + pSong(nullptr), + pSteps(nullptr), + Modifiers(""), + Attacks(), + bSecret(false), + iLowMeter(-1), + iHighMeter(-1), + dc(Difficulty_Invalid) + { + } + void GetAttackArray( AttackArray &out ) const; + + /** @brief The Song involved in the entry. */ + Song* pSong; + /** @brief The Step involved in the entry. */ + Steps* pSteps; + /** @brief The Modifiers applied for the whole Song. */ + RString Modifiers; + /** @brief The Attacks that will take place durring the Song. */ + AttackArray Attacks; + /** + * @brief Is this Song and its Step meant to be a secret? + * If so, it will show text such as "???" to indicate that it's a mystery. */ + bool bSecret; + + /* These represent the meter and difficulty used by the course to pick the + * steps; if you want the real difficulty and meter, look at pSteps. */ + int iLowMeter; + int iHighMeter; + Difficulty dc; + bool operator== ( const TrailEntry &rhs ) const; + bool operator!= ( const TrailEntry &rhs ) const { return !(*this==rhs); } + bool ContainsTransformOrTurn() const; + + // Lua + void PushSelf( lua_State *L ); +}; + +/** @brief A queue of Songs and Steps that are generated from a Course. */ +class Trail +{ +public: + StepsType m_StepsType; + CourseType m_CourseType; + CourseDifficulty m_CourseDifficulty; + vector m_vEntries; + int m_iSpecifiedMeter; // == -1 if no meter specified + mutable bool m_bRadarValuesCached; + mutable RadarValues m_CachedRadarValues; + + /** + * @brief Set up the Trail with default values. + * + * This used to call Init(), which is still available. */ + Trail(): m_StepsType(StepsType_Invalid), + m_CourseType(CourseType_Invalid), + m_CourseDifficulty(Difficulty_Invalid), + m_vEntries(), m_iSpecifiedMeter(-1), + m_bRadarValuesCached(false), m_CachedRadarValues(), + m_CachedObject() {} + void Init() + { + m_StepsType = StepsType_Invalid; + m_CourseDifficulty = Difficulty_Invalid; + m_iSpecifiedMeter = -1; + m_vEntries.clear(); + m_bRadarValuesCached = false; + } + + const RadarValues &GetRadarValues() const; + void SetRadarValues( const RadarValues &rv ); // for pre-populating cache + int GetMeter() const; + int GetTotalMeter() const; + float GetLengthSeconds() const; + void GetDisplayBpms( DisplayBpms &AddTo ) const; + bool IsSecret() const; + bool ContainsSong( const Song *pSong ) const; + + CachedObject m_CachedObject; + + // Lua + void PushSelf( lua_State *L ); +}; + +#endif + +/** + * @file + * @author Chris Danford, Glenn Maynard (c) 2001-2004 + * @section LICENSE + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/TrailUtil.cpp b/src/TrailUtil.cpp index 72f8b90011..3aed7df390 100644 --- a/src/TrailUtil.cpp +++ b/src/TrailUtil.cpp @@ -39,7 +39,7 @@ Trail *TrailID::ToTrail( const Course *p, bool bAllowNull ) const { ASSERT( p != nullptr ); - Trail *pRet = NULL; + Trail *pRet = nullptr; if( !m_Cache.Get(&pRet) ) { if( st != StepsType_Invalid && cd != Difficulty_Invalid ) diff --git a/src/TrailUtil.h b/src/TrailUtil.h index 12c4a7dd76..3dfd97c5fc 100644 --- a/src/TrailUtil.h +++ b/src/TrailUtil.h @@ -35,7 +35,7 @@ class TrailID public: TrailID(): st(StepsType_Invalid), cd(Difficulty_Invalid), m_Cache() { m_Cache.Unset(); } - void Unset() { FromTrail(NULL); } + void Unset() { FromTrail(nullptr); } void FromTrail( const Trail *p ); Trail *ToTrail( const Course *p, bool bAllowNull ) const; bool operator<( const TrailID &rhs ) const; diff --git a/src/UnlockManager.cpp b/src/UnlockManager.cpp index d7411ca9a7..7825a8ab5b 100644 --- a/src/UnlockManager.cpp +++ b/src/UnlockManager.cpp @@ -19,7 +19,7 @@ #include "GameManager.h" #include "Style.h" -UnlockManager* UNLOCKMAN = NULL; // global and accessable from anywhere in our program +UnlockManager* UNLOCKMAN = nullptr; // global and accessable from anywhere in our program #define UNLOCK_NAMES THEME->GetMetric ("UnlockManager","UnlockNames") #define UNLOCK(x) THEME->GetMetricR("UnlockManager", ssprintf("Unlock%sCommand",x.c_str())); @@ -91,7 +91,7 @@ void UnlockManager::UnlockSong( const Song *song ) RString UnlockManager::FindEntryID( const RString &sName ) const { - const UnlockEntry *pEntry = NULL; + const UnlockEntry *pEntry = nullptr; const Song *pSong = SONGMAN->FindSong( sName ); if( pSong != nullptr ) diff --git a/src/WheelBase.cpp b/src/WheelBase.cpp index b22f5edd15..0f394e055e 100644 --- a/src/WheelBase.cpp +++ b/src/WheelBase.cpp @@ -39,7 +39,7 @@ WheelBase::~WheelBase() SAFE_DELETE( i ); } m_WheelBaseItems.clear(); - m_LastSelection = NULL; + m_LastSelection = nullptr; } void WheelBase::Load( RString sType ) @@ -48,7 +48,7 @@ void WheelBase::Load( RString sType ) ASSERT( this->GetNumChildren() == 0 ); // only load once m_bEmpty = false; - m_LastSelection = NULL; + m_LastSelection = nullptr; m_iSelection = 0; m_fTimeLeftInState = 0; m_fPositionOffsetFromSelection = 0; diff --git a/src/WheelItemBase.cpp b/src/WheelItemBase.cpp index a198a36f87..5534067205 100644 --- a/src/WheelItemBase.cpp +++ b/src/WheelItemBase.cpp @@ -38,9 +38,9 @@ WheelItemBase::WheelItemBase( const WheelItemBase &cpy ): WheelItemBase::WheelItemBase(RString sType) { SetName( sType ); - m_pData = NULL; + m_pData = nullptr; m_bExpanded = false; - m_pGrayBar = NULL; + m_pGrayBar = nullptr; Load(sType); } diff --git a/src/XmlFile.h b/src/XmlFile.h index 5dee45490f..69a5071585 100644 --- a/src/XmlFile.h +++ b/src/XmlFile.h @@ -67,14 +67,14 @@ typedef vector XNodes; ++Var ) /** @brief Loop through each child. */ #define FOREACH_Child( pNode, Var ) \ - XNode *Var = NULL; \ + XNode *Var = nullptr; \ for( XNodes::iterator Var##Iter = (pNode)->m_childs.begin(); \ Var = (Var##Iter != (pNode)->m_childs.end())? *Var##Iter:NULL, \ Var##Iter != (pNode)->m_childs.end(); \ ++Var##Iter ) /** @brief Loop through each child, using a constant iterator. */ #define FOREACH_CONST_Child( pNode, Var ) \ - const XNode *Var = NULL; \ + const XNode *Var = nullptr; \ for( XNodes::const_iterator Var##Iter = (pNode)->m_childs.begin(); \ Var = (Var##Iter != (pNode)->m_childs.end())? *Var##Iter:NULL, \ Var##Iter != (pNode)->m_childs.end(); \ diff --git a/src/arch/ArchHooks/ArchHooks.cpp b/src/arch/ArchHooks/ArchHooks.cpp index 514f272cbb..6b56ee37d8 100644 --- a/src/arch/ArchHooks/ArchHooks.cpp +++ b/src/arch/ArchHooks/ArchHooks.cpp @@ -1,117 +1,117 @@ -#include "global.h" -#include "ArchHooks.h" -#include "LuaReference.h" -#include "RageLog.h" -#include "RageThreads.h" -#include "arch/arch_default.h" - -bool ArchHooks::g_bQuitting = false; -bool ArchHooks::g_bToggleWindowed = false; -// Keep from pulling RageThreads.h into ArchHooks.h -static RageMutex g_Mutex( "ArchHooks" ); -ArchHooks *HOOKS = NULL; - -ArchHooks::ArchHooks(): m_bHasFocus(true), m_bFocusChanged(false) -{ - -} - -bool ArchHooks::GetAndClearToggleWindowed() -{ - LockMut( g_Mutex ); - bool bToggle = g_bToggleWindowed; - - g_bToggleWindowed = false; - return bToggle; -} - -void ArchHooks::SetToggleWindowed() -{ - LockMut( g_Mutex ); - g_bToggleWindowed = true; -} - -void ArchHooks::SetHasFocus( bool bHasFocus ) -{ - if( bHasFocus == m_bHasFocus ) - return; - m_bHasFocus = bHasFocus; - - LOG->Trace( "App %s focus", bHasFocus? "has":"doesn't have" ); - LockMut( g_Mutex ); - m_bFocusChanged = true; -} - -bool ArchHooks::AppFocusChanged() -{ - LockMut( g_Mutex ); - bool bFocusChanged = m_bFocusChanged; - - m_bFocusChanged = false; - return bFocusChanged; -} - -bool ArchHooks::GoToURL( RString sUrl ) -{ - return false; -} - -ArchHooks *ArchHooks::Create() -{ - return new ARCH_HOOKS; -} - -// lua start -#include "LuaBinding.h" -#include "LuaReference.h" - -class LunaArchHooks: public Luna -{ -public: - DEFINE_METHOD( AppHasFocus, AppHasFocus() ); - DEFINE_METHOD( GetArchName, GetArchName() ); - - LunaArchHooks() - { - ADD_METHOD( AppHasFocus ); - ADD_METHOD( GetArchName ); - } -}; -LUA_REGISTER_CLASS( ArchHooks ); - -/* XXX: ArchHooks is instantiated before Lua, so we encounter a dependency problem when - * trying to register HOOKS. Work around it by registering HOOKS in a static function, - * which LuaManager will call when it is instantiated. */ -void LuaFunc_Register_Hooks( lua_State *L ) -{ - lua_pushstring( L, "HOOKS" ); - HOOKS->PushSelf( L ); - lua_settable( L, LUA_GLOBALSINDEX ); -} - -REGISTER_WITH_LUA_FUNCTION( LuaFunc_Register_Hooks ); - -/* - * (c) 2003-2004 Glenn Maynard, Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "ArchHooks.h" +#include "LuaReference.h" +#include "RageLog.h" +#include "RageThreads.h" +#include "arch/arch_default.h" + +bool ArchHooks::g_bQuitting = false; +bool ArchHooks::g_bToggleWindowed = false; +// Keep from pulling RageThreads.h into ArchHooks.h +static RageMutex g_Mutex( "ArchHooks" ); +ArchHooks *HOOKS = nullptr; + +ArchHooks::ArchHooks(): m_bHasFocus(true), m_bFocusChanged(false) +{ + +} + +bool ArchHooks::GetAndClearToggleWindowed() +{ + LockMut( g_Mutex ); + bool bToggle = g_bToggleWindowed; + + g_bToggleWindowed = false; + return bToggle; +} + +void ArchHooks::SetToggleWindowed() +{ + LockMut( g_Mutex ); + g_bToggleWindowed = true; +} + +void ArchHooks::SetHasFocus( bool bHasFocus ) +{ + if( bHasFocus == m_bHasFocus ) + return; + m_bHasFocus = bHasFocus; + + LOG->Trace( "App %s focus", bHasFocus? "has":"doesn't have" ); + LockMut( g_Mutex ); + m_bFocusChanged = true; +} + +bool ArchHooks::AppFocusChanged() +{ + LockMut( g_Mutex ); + bool bFocusChanged = m_bFocusChanged; + + m_bFocusChanged = false; + return bFocusChanged; +} + +bool ArchHooks::GoToURL( RString sUrl ) +{ + return false; +} + +ArchHooks *ArchHooks::Create() +{ + return new ARCH_HOOKS; +} + +// lua start +#include "LuaBinding.h" +#include "LuaReference.h" + +class LunaArchHooks: public Luna +{ +public: + DEFINE_METHOD( AppHasFocus, AppHasFocus() ); + DEFINE_METHOD( GetArchName, GetArchName() ); + + LunaArchHooks() + { + ADD_METHOD( AppHasFocus ); + ADD_METHOD( GetArchName ); + } +}; +LUA_REGISTER_CLASS( ArchHooks ); + +/* XXX: ArchHooks is instantiated before Lua, so we encounter a dependency problem when + * trying to register HOOKS. Work around it by registering HOOKS in a static function, + * which LuaManager will call when it is instantiated. */ +void LuaFunc_Register_Hooks( lua_State *L ) +{ + lua_pushstring( L, "HOOKS" ); + HOOKS->PushSelf( L ); + lua_settable( L, LUA_GLOBALSINDEX ); +} + +REGISTER_WITH_LUA_FUNCTION( LuaFunc_Register_Hooks ); + +/* + * (c) 2003-2004 Glenn Maynard, Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/arch/ArchHooks/ArchHooks_MacOSX.cpp b/src/arch/ArchHooks/ArchHooks_MacOSX.cpp index 6376fc161e..d2eed89460 100644 --- a/src/arch/ArchHooks/ArchHooks_MacOSX.cpp +++ b/src/arch/ArchHooks/ArchHooks_MacOSX.cpp @@ -88,12 +88,12 @@ void ArchHooks_MacOSX::Init() CFPropertyListRef old = CFPreferencesCopyAppValue( key, appID ); CFURLRef path = CFBundleCopyBundleURL( bundle ); CFPropertyListRef value = CFURLCopyFileSystemPath( path, kCFURLPOSIXPathStyle ); - CFMutableDictionaryRef newDict = NULL; + CFMutableDictionaryRef newDict = nullptr; if( old && CFGetTypeID(old) != CFDictionaryGetTypeID() ) { CFRelease( old ); - old = NULL; + old = nullptr; } if( !old ) @@ -289,7 +289,7 @@ void ArchHooks_MacOSX::DumpDebugInfo() if( urlRef == nullptr ) break; - CFDataRef dataRef = NULL; + CFDataRef dataRef = nullptr; SInt32 error; CFURLCreateDataAndPropertiesFromResource( NULL, urlRef, &dataRef, NULL, NULL, &error ); CFRelease( urlRef ); diff --git a/src/arch/ArchHooks/ArchHooks_Win32.cpp b/src/arch/ArchHooks/ArchHooks_Win32.cpp index acdd58424f..9bac75cb04 100644 --- a/src/arch/ArchHooks/ArchHooks_Win32.cpp +++ b/src/arch/ArchHooks/ArchHooks_Win32.cpp @@ -110,7 +110,7 @@ bool ArchHooks_Win32::CheckForMultipleInstances(int argc, char* argv[]) * not the main window. */ CallbackData data; data.hParent = hWnd; - data.hResult = NULL; + data.hResult = nullptr; EnumWindows( GetEnabledPopup, (LPARAM) &data ); if( data.hResult != nullptr ) diff --git a/src/arch/Dialog/Dialog.cpp b/src/arch/Dialog/Dialog.cpp index 7cce1f8467..446a5952c7 100644 --- a/src/arch/Dialog/Dialog.cpp +++ b/src/arch/Dialog/Dialog.cpp @@ -23,7 +23,7 @@ DialogDriver *MakeDialogDriver() ASSERT( asDriversToTry.size() != 0 ); RString sDriver; - DialogDriver *pRet = NULL; + DialogDriver *pRet = nullptr; for( unsigned i = 0; pRet == nullptr && i < asDriversToTry.size(); ++i ) { @@ -56,7 +56,7 @@ DialogDriver *MakeDialogDriver() return pRet; } -static DialogDriver *g_pImpl = NULL; +static DialogDriver *g_pImpl = nullptr; static DialogDriver_Null g_NullDriver; static bool g_bWindowed = true; // Start out true so that we'll show errors before DISPLAY is init'd. @@ -79,7 +79,7 @@ void Dialog::Init() void Dialog::Shutdown() { delete g_pImpl; - g_pImpl = NULL; + g_pImpl = nullptr; } static bool MessageIsIgnored( RString sID ) diff --git a/src/arch/Dialog/DialogDriver_MacOSX.cpp b/src/arch/Dialog/DialogDriver_MacOSX.cpp index 3b6e186a51..7bdfb47ff3 100644 --- a/src/arch/Dialog/DialogDriver_MacOSX.cpp +++ b/src/arch/Dialog/DialogDriver_MacOSX.cpp @@ -9,7 +9,7 @@ REGISTER_DIALOG_DRIVER_CLASS( MacOSX ); static CFOptionFlags ShowAlert( CFOptionFlags flags, const RString& sMessage, CFStringRef OK, - CFStringRef alt = NULL, CFStringRef other = NULL) + CFStringRef alt = nullptr, CFStringRef other = nullptr) { CFOptionFlags result; CFStringRef text = CFStringCreateWithCString( NULL, sMessage, kCFStringEncodingUTF8 ); diff --git a/src/arch/Dialog/DialogDriver_Win32.cpp b/src/arch/Dialog/DialogDriver_Win32.cpp index 967cd7c1f0..74291f1f01 100644 --- a/src/arch/Dialog/DialogDriver_Win32.cpp +++ b/src/arch/Dialog/DialogDriver_Win32.cpp @@ -1,306 +1,306 @@ -#include "global.h" -#include "DialogDriver_Win32.h" -#include "RageUtil.h" -#if !defined(SMPACKAGE) -#include "LocalizedString.h" -#endif -#include "ThemeManager.h" -#include "ProductInfo.h" - -#include "archutils/win32/AppInstance.h" -#include "archutils/win32/ErrorStrings.h" -#include "archutils/win32/GotoURL.h" -#include "archutils/win32/RestartProgram.h" -#include "archutils/Win32/SpecialDirs.h" -#if !defined(SMPACKAGE) -#include "archutils/win32/WindowsResources.h" -#include "archutils/win32/GraphicsWindow.h" -#endif -#include "archutils/win32/DialogUtil.h" - -#if defined(SMPACKAGE) -int __stdcall AfxMessageBox(LPCTSTR lpszText, UINT nType, UINT nIDHelp); -#endif - -REGISTER_DIALOG_DRIVER_CLASS( Win32 ); - -static bool g_bHush; -static RString g_sMessage; -static bool g_bAllowHush; - -#if !defined(SMPACKAGE) -static BOOL CALLBACK OKWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) -{ - switch( msg ) - { - case WM_INITDIALOG: - { - // Disable the parent window, like a modal MessageBox does. - EnableWindow( GetParent(hWnd), FALSE ); - - DialogUtil::LocalizeDialogAndContents( hWnd ); - - // Hide or display "Don't show this message." - g_bHush = false; - HWND hHushButton = GetDlgItem( hWnd, IDC_HUSH ); - int iStyle = GetWindowLong( hHushButton, GWL_STYLE ); - - if( g_bAllowHush ) - iStyle |= WS_VISIBLE; - else - iStyle &= ~WS_VISIBLE; - SetWindowLong( hHushButton, GWL_STYLE, iStyle ); - - // Set static text. - RString sMessage = g_sMessage; - sMessage.Replace( "\n", "\r\n" ); - SetWindowText( GetDlgItem(hWnd, IDC_MESSAGE), sMessage ); - - // Focus is on any of the controls in the dialog by default. - // I'm not sure why. Set focus to the button manually. -Chris - SetFocus( GetDlgItem(hWnd, IDOK) ); - } - break; - - case WM_DESTROY: - // Re-enable the parent window. - EnableWindow( GetParent(hWnd), TRUE ); - break; - - case WM_COMMAND: - switch( LOWORD(wParam) ) - { - case IDOK: - g_bHush = !!IsDlgButtonChecked( hWnd, IDC_HUSH ); - // fall through - case IDCANCEL: - EndDialog( hWnd, 0 ); - break; - } - } - return FALSE; -} -#endif - -#if !defined(SMPACKAGE) -static HWND GetHwnd() -{ - return GraphicsWindow::GetHwnd(); -} -#endif - -#if !defined(SMPACKAGE) -static LocalizedString ERROR_WINDOW_TITLE("Dialog-Prompt", "Error"); -static RString GetWindowTitle() -{ - RString s = ERROR_WINDOW_TITLE.GetValue(); - return s; -} -#endif - -void DialogDriver_Win32::OK( RString sMessage, RString sID ) -{ - g_bAllowHush = sID != ""; - g_sMessage = sMessage; - AppInstance handle; -#if !defined(SMPACKAGE) - DialogBox( handle.Get(), MAKEINTRESOURCE(IDD_OK), ::GetHwnd(), OKWndProc ); -#else - ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_OK, 0 ); -#endif - if( g_bAllowHush && g_bHush ) - Dialog::IgnoreMessage( sID ); -} - -Dialog::Result DialogDriver_Win32::OKCancel( RString sMessage, RString sID ) -{ - g_bAllowHush = sID != ""; - g_sMessage = sMessage; - AppInstance handle; - -#if !defined(SMPACKAGE) - //DialogBox( handle.Get(), MAKEINTRESOURCE(IDD_OK), ::GetHwnd(), OKWndProc ); - int result = ::MessageBox( NULL, sMessage, GetWindowTitle(), MB_OKCANCEL ); -#else - int result = ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_OKCANCEL, 0 ); -#endif - if( g_bAllowHush && g_bHush ) - Dialog::IgnoreMessage( sID ); - - switch( result ) - { - case IDOK: - return Dialog::ok; - default: - return Dialog::cancel; - } -} - -#if !defined(SMPACKAGE) -static RString g_sErrorString; - -static BOOL CALLBACK ErrorWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) -{ - switch( msg ) - { - case WM_INITDIALOG: - { - DialogUtil::SetHeaderFont( hWnd, IDC_STATIC_HEADER_TEXT ); - - // Set static text - RString sMessage = g_sErrorString; - sMessage.Replace( "\n", "\r\n" ); - SetWindowText( GetDlgItem(hWnd, IDC_EDIT_ERROR), sMessage ); - } - break; - case WM_COMMAND: - switch( LOWORD(wParam) ) - { - case IDC_BUTTON_VIEW_LOG: - { - PROCESS_INFORMATION pi; - STARTUPINFO si; - ZeroMemory( &si, sizeof(si) ); - - RString sAppDataDir = SpecialDirs::GetAppDataDir(); - RString sCommand = "notepad \"" + sAppDataDir + PRODUCT_ID + "/Logs/log.txt\""; - CreateProcess( - NULL, // pointer to name of executable module - sCommand.GetBuffer(), // pointer to command line string - NULL, // process security attributes - NULL, // thread security attributes - false, // handle inheritance flag - 0, // creation flags - NULL, // pointer to new environment block - NULL, // pointer to current directory name - &si, // pointer to STARTUPINFO - &pi // pointer to PROCESS_INFORMATION - ); - } - break; - case IDC_BUTTON_REPORT: - GotoURL( REPORT_BUG_URL ); - break; - case IDC_BUTTON_RESTART: - Win32RestartProgram(); - // Possibly make W32RP a NORETURN call? - FAIL_M("Win32RestartProgram failed?"); - case IDOK: - EndDialog( hWnd, 0 ); - break; - } - break; - case WM_CTLCOLORSTATIC: - { - HDC hdc = (HDC)wParam; - HWND hwndStatic = (HWND)lParam; - HBRUSH hbr = NULL; - - // TODO: Change any attributes of the DC here - switch( GetDlgCtrlID(hwndStatic) ) - { - case IDC_STATIC_HEADER_TEXT: - case IDC_STATIC_ICON: - hbr = (HBRUSH)::GetStockObject(WHITE_BRUSH); - SetBkMode( hdc, OPAQUE ); - SetBkColor( hdc, RGB(255,255,255) ); - break; - } - - // TODO: Return a different brush if the default is not desired - return (BOOL)hbr; - } - } - return FALSE; -} -#endif - -void DialogDriver_Win32::Error( RString sError, RString sID ) -{ -#if !defined(SMPACKAGE) - g_sErrorString = sError; - - // throw up a pretty error dialog - AppInstance handle; - DialogBox( handle.Get(), MAKEINTRESOURCE(IDD_ERROR_DIALOG), NULL, ErrorWndProc ); -#else - ::AfxMessageBox( ConvertUTF8ToACP(sError).c_str(), MB_OK, 0 ); -#endif -} - -Dialog::Result DialogDriver_Win32::AbortRetryIgnore( RString sMessage, RString ID ) -{ - int iRet = 0; -#if !defined(SMPACKAGE) - iRet = ::MessageBox(::GetHwnd(), ConvertUTF8ToACP(sMessage).c_str(), ConvertUTF8ToACP(::GetWindowTitle()).c_str(), MB_ABORTRETRYIGNORE|MB_DEFBUTTON3 ); -#else - iRet = ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_ABORTRETRYIGNORE|MB_DEFBUTTON3, 0 ); -#endif - switch( iRet ) - { - case IDABORT: return Dialog::abort; - case IDRETRY: return Dialog::retry; - case IDIGNORE: return Dialog::ignore; - default: - FAIL_M(ssprintf("Unexpected response to Abort/Retry/Ignore dialog: %i", iRet)); - } -} - -Dialog::Result DialogDriver_Win32::AbortRetry( RString sMessage, RString sID ) -{ - int iRet = 0; -#if !defined(SMPACKAGE) - iRet = ::MessageBox(::GetHwnd(), ConvertUTF8ToACP(sMessage).c_str(), ConvertUTF8ToACP(::GetWindowTitle()).c_str(), MB_RETRYCANCEL); -#else - iRet = ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_RETRYCANCEL, 0 ); -#endif - switch( iRet ) - { - case IDRETRY: return Dialog::retry; - case IDCANCEL: return Dialog::abort; - default: - FAIL_M(ssprintf("Unexpected response to Retry/Cancel dialog: %i", iRet)); - } -} - -Dialog::Result DialogDriver_Win32::YesNo( RString sMessage, RString sID ) -{ - int iRet = 0; -#if !defined(SMPACKAGE) - iRet = ::MessageBox(::GetHwnd(), ConvertUTF8ToACP(sMessage).c_str(), ConvertUTF8ToACP(::GetWindowTitle()).c_str(), MB_YESNO); -#else - iRet = ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_RETRYCANCEL, 0 ); -#endif - switch( iRet ) - { - case IDYES: return Dialog::yes; - case IDNO: return Dialog::no; - default: - FAIL_M(ssprintf("Unexpected response to Yes/No dialog: %i", iRet)); - } -} - -/* - * (c) 2003-2004 Glenn Maynard, Chris Danford - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "DialogDriver_Win32.h" +#include "RageUtil.h" +#if !defined(SMPACKAGE) +#include "LocalizedString.h" +#endif +#include "ThemeManager.h" +#include "ProductInfo.h" + +#include "archutils/win32/AppInstance.h" +#include "archutils/win32/ErrorStrings.h" +#include "archutils/win32/GotoURL.h" +#include "archutils/win32/RestartProgram.h" +#include "archutils/Win32/SpecialDirs.h" +#if !defined(SMPACKAGE) +#include "archutils/win32/WindowsResources.h" +#include "archutils/win32/GraphicsWindow.h" +#endif +#include "archutils/win32/DialogUtil.h" + +#if defined(SMPACKAGE) +int __stdcall AfxMessageBox(LPCTSTR lpszText, UINT nType, UINT nIDHelp); +#endif + +REGISTER_DIALOG_DRIVER_CLASS( Win32 ); + +static bool g_bHush; +static RString g_sMessage; +static bool g_bAllowHush; + +#if !defined(SMPACKAGE) +static BOOL CALLBACK OKWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) +{ + switch( msg ) + { + case WM_INITDIALOG: + { + // Disable the parent window, like a modal MessageBox does. + EnableWindow( GetParent(hWnd), FALSE ); + + DialogUtil::LocalizeDialogAndContents( hWnd ); + + // Hide or display "Don't show this message." + g_bHush = false; + HWND hHushButton = GetDlgItem( hWnd, IDC_HUSH ); + int iStyle = GetWindowLong( hHushButton, GWL_STYLE ); + + if( g_bAllowHush ) + iStyle |= WS_VISIBLE; + else + iStyle &= ~WS_VISIBLE; + SetWindowLong( hHushButton, GWL_STYLE, iStyle ); + + // Set static text. + RString sMessage = g_sMessage; + sMessage.Replace( "\n", "\r\n" ); + SetWindowText( GetDlgItem(hWnd, IDC_MESSAGE), sMessage ); + + // Focus is on any of the controls in the dialog by default. + // I'm not sure why. Set focus to the button manually. -Chris + SetFocus( GetDlgItem(hWnd, IDOK) ); + } + break; + + case WM_DESTROY: + // Re-enable the parent window. + EnableWindow( GetParent(hWnd), TRUE ); + break; + + case WM_COMMAND: + switch( LOWORD(wParam) ) + { + case IDOK: + g_bHush = !!IsDlgButtonChecked( hWnd, IDC_HUSH ); + // fall through + case IDCANCEL: + EndDialog( hWnd, 0 ); + break; + } + } + return FALSE; +} +#endif + +#if !defined(SMPACKAGE) +static HWND GetHwnd() +{ + return GraphicsWindow::GetHwnd(); +} +#endif + +#if !defined(SMPACKAGE) +static LocalizedString ERROR_WINDOW_TITLE("Dialog-Prompt", "Error"); +static RString GetWindowTitle() +{ + RString s = ERROR_WINDOW_TITLE.GetValue(); + return s; +} +#endif + +void DialogDriver_Win32::OK( RString sMessage, RString sID ) +{ + g_bAllowHush = sID != ""; + g_sMessage = sMessage; + AppInstance handle; +#if !defined(SMPACKAGE) + DialogBox( handle.Get(), MAKEINTRESOURCE(IDD_OK), ::GetHwnd(), OKWndProc ); +#else + ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_OK, 0 ); +#endif + if( g_bAllowHush && g_bHush ) + Dialog::IgnoreMessage( sID ); +} + +Dialog::Result DialogDriver_Win32::OKCancel( RString sMessage, RString sID ) +{ + g_bAllowHush = sID != ""; + g_sMessage = sMessage; + AppInstance handle; + +#if !defined(SMPACKAGE) + //DialogBox( handle.Get(), MAKEINTRESOURCE(IDD_OK), ::GetHwnd(), OKWndProc ); + int result = ::MessageBox( NULL, sMessage, GetWindowTitle(), MB_OKCANCEL ); +#else + int result = ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_OKCANCEL, 0 ); +#endif + if( g_bAllowHush && g_bHush ) + Dialog::IgnoreMessage( sID ); + + switch( result ) + { + case IDOK: + return Dialog::ok; + default: + return Dialog::cancel; + } +} + +#if !defined(SMPACKAGE) +static RString g_sErrorString; + +static BOOL CALLBACK ErrorWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) +{ + switch( msg ) + { + case WM_INITDIALOG: + { + DialogUtil::SetHeaderFont( hWnd, IDC_STATIC_HEADER_TEXT ); + + // Set static text + RString sMessage = g_sErrorString; + sMessage.Replace( "\n", "\r\n" ); + SetWindowText( GetDlgItem(hWnd, IDC_EDIT_ERROR), sMessage ); + } + break; + case WM_COMMAND: + switch( LOWORD(wParam) ) + { + case IDC_BUTTON_VIEW_LOG: + { + PROCESS_INFORMATION pi; + STARTUPINFO si; + ZeroMemory( &si, sizeof(si) ); + + RString sAppDataDir = SpecialDirs::GetAppDataDir(); + RString sCommand = "notepad \"" + sAppDataDir + PRODUCT_ID + "/Logs/log.txt\""; + CreateProcess( + NULL, // pointer to name of executable module + sCommand.GetBuffer(), // pointer to command line string + NULL, // process security attributes + NULL, // thread security attributes + false, // handle inheritance flag + 0, // creation flags + NULL, // pointer to new environment block + NULL, // pointer to current directory name + &si, // pointer to STARTUPINFO + &pi // pointer to PROCESS_INFORMATION + ); + } + break; + case IDC_BUTTON_REPORT: + GotoURL( REPORT_BUG_URL ); + break; + case IDC_BUTTON_RESTART: + Win32RestartProgram(); + // Possibly make W32RP a NORETURN call? + FAIL_M("Win32RestartProgram failed?"); + case IDOK: + EndDialog( hWnd, 0 ); + break; + } + break; + case WM_CTLCOLORSTATIC: + { + HDC hdc = (HDC)wParam; + HWND hwndStatic = (HWND)lParam; + HBRUSH hbr = nullptr; + + // TODO: Change any attributes of the DC here + switch( GetDlgCtrlID(hwndStatic) ) + { + case IDC_STATIC_HEADER_TEXT: + case IDC_STATIC_ICON: + hbr = (HBRUSH)::GetStockObject(WHITE_BRUSH); + SetBkMode( hdc, OPAQUE ); + SetBkColor( hdc, RGB(255,255,255) ); + break; + } + + // TODO: Return a different brush if the default is not desired + return (BOOL)hbr; + } + } + return FALSE; +} +#endif + +void DialogDriver_Win32::Error( RString sError, RString sID ) +{ +#if !defined(SMPACKAGE) + g_sErrorString = sError; + + // throw up a pretty error dialog + AppInstance handle; + DialogBox( handle.Get(), MAKEINTRESOURCE(IDD_ERROR_DIALOG), NULL, ErrorWndProc ); +#else + ::AfxMessageBox( ConvertUTF8ToACP(sError).c_str(), MB_OK, 0 ); +#endif +} + +Dialog::Result DialogDriver_Win32::AbortRetryIgnore( RString sMessage, RString ID ) +{ + int iRet = 0; +#if !defined(SMPACKAGE) + iRet = ::MessageBox(::GetHwnd(), ConvertUTF8ToACP(sMessage).c_str(), ConvertUTF8ToACP(::GetWindowTitle()).c_str(), MB_ABORTRETRYIGNORE|MB_DEFBUTTON3 ); +#else + iRet = ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_ABORTRETRYIGNORE|MB_DEFBUTTON3, 0 ); +#endif + switch( iRet ) + { + case IDABORT: return Dialog::abort; + case IDRETRY: return Dialog::retry; + case IDIGNORE: return Dialog::ignore; + default: + FAIL_M(ssprintf("Unexpected response to Abort/Retry/Ignore dialog: %i", iRet)); + } +} + +Dialog::Result DialogDriver_Win32::AbortRetry( RString sMessage, RString sID ) +{ + int iRet = 0; +#if !defined(SMPACKAGE) + iRet = ::MessageBox(::GetHwnd(), ConvertUTF8ToACP(sMessage).c_str(), ConvertUTF8ToACP(::GetWindowTitle()).c_str(), MB_RETRYCANCEL); +#else + iRet = ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_RETRYCANCEL, 0 ); +#endif + switch( iRet ) + { + case IDRETRY: return Dialog::retry; + case IDCANCEL: return Dialog::abort; + default: + FAIL_M(ssprintf("Unexpected response to Retry/Cancel dialog: %i", iRet)); + } +} + +Dialog::Result DialogDriver_Win32::YesNo( RString sMessage, RString sID ) +{ + int iRet = 0; +#if !defined(SMPACKAGE) + iRet = ::MessageBox(::GetHwnd(), ConvertUTF8ToACP(sMessage).c_str(), ConvertUTF8ToACP(::GetWindowTitle()).c_str(), MB_YESNO); +#else + iRet = ::AfxMessageBox( ConvertUTF8ToACP(sMessage).c_str(), MB_RETRYCANCEL, 0 ); +#endif + switch( iRet ) + { + case IDYES: return Dialog::yes; + case IDNO: return Dialog::no; + default: + FAIL_M(ssprintf("Unexpected response to Yes/No dialog: %i", iRet)); + } +} + +/* + * (c) 2003-2004 Glenn Maynard, Chris Danford + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/arch/InputHandler/InputHandler_DirectInput.cpp b/src/arch/InputHandler/InputHandler_DirectInput.cpp index 70b010c79b..95d4430e08 100644 --- a/src/arch/InputHandler/InputHandler_DirectInput.cpp +++ b/src/arch/InputHandler/InputHandler_DirectInput.cpp @@ -184,7 +184,7 @@ InputHandler_DInput::~InputHandler_DInput() Devices.clear(); g_dinput->Release(); - g_dinput = NULL; + g_dinput = nullptr; } void InputHandler_DInput::WindowReset() @@ -782,7 +782,7 @@ void InputHandler_DInput::InputThreadMain() continue; Devices[i].Device->Unacquire(); - Devices[i].Device->SetEventNotification( NULL ); + Devices[i].Device->SetEventNotification(nullptr); } CloseHandle(Handle); diff --git a/src/arch/InputHandler/InputHandler_DirectInputHelper.cpp b/src/arch/InputHandler/InputHandler_DirectInputHelper.cpp index e5747864a3..7b14852c45 100644 --- a/src/arch/InputHandler/InputHandler_DirectInputHelper.cpp +++ b/src/arch/InputHandler/InputHandler_DirectInputHelper.cpp @@ -12,7 +12,7 @@ #pragma comment(lib, "dxguid.lib") #endif #endif -LPDIRECTINPUT8 g_dinput = NULL; +LPDIRECTINPUT8 g_dinput = nullptr; static int ConvertScancodeToKey( int scancode ); static BOOL CALLBACK DIJoystick_EnumDevObjectsProc(LPCDIDEVICEOBJECTINSTANCE dev, LPVOID data); @@ -24,7 +24,7 @@ DIDevice::DIDevice() dev = InputDevice_Invalid; buffered = true; memset(&JoystickInst, 0, sizeof(JoystickInst)); - Device = NULL; + Device = nullptr; } bool DIDevice::Open() @@ -136,7 +136,7 @@ void DIDevice::Close() Device->Unacquire(); Device->Release(); - Device = NULL; + Device = nullptr; buttons = axes = hats = 0; Inputs.clear(); } diff --git a/src/arch/InputHandler/InputHandler_Linux_tty.cpp b/src/arch/InputHandler/InputHandler_Linux_tty.cpp index 88015caa08..1c3f127bf7 100644 --- a/src/arch/InputHandler/InputHandler_Linux_tty.cpp +++ b/src/arch/InputHandler/InputHandler_Linux_tty.cpp @@ -31,14 +31,14 @@ static int saved_kbd_mode; /* This is normally a singleton. Keep track of it, so we can access it * from our signal handler. */ -static InputHandler_Linux_tty *handler = NULL; +static InputHandler_Linux_tty *handler = nullptr; void InputHandler_Linux_tty::OnCrash(int signo) { /* Make sure we delete the input handler if we crash, so we don't leave * the terminal in raw mode. */ delete handler; - handler = NULL; + handler = nullptr; } @@ -159,7 +159,7 @@ InputHandler_Linux_tty::~InputHandler_Linux_tty() tcsetattr(fd, TCSAFLUSH, &saved_kbd_termios); close(fd); - handler = NULL; + handler = nullptr; } void InputHandler_Linux_tty::Update() diff --git a/src/arch/InputHandler/InputHandler_MacOSX_HID.cpp b/src/arch/InputHandler/InputHandler_MacOSX_HID.cpp index bc9849fb4f..46b418235e 100644 --- a/src/arch/InputHandler/InputHandler_MacOSX_HID.cpp +++ b/src/arch/InputHandler/InputHandler_MacOSX_HID.cpp @@ -455,7 +455,7 @@ wchar_t InputHandler_MacOSX_HID::DeviceButtonToChar( DeviceButton button, bool b { // Fall back on the 'KCHR' resource. static unsigned long state = 0; - static Ptr keymap = NULL; + static Ptr keymap = nullptr; Ptr new_keymap; new_keymap = (Ptr)GetScriptManagerVariable(smKCHRCache); diff --git a/src/arch/InputHandler/InputHandler_Win32_MIDI.cpp b/src/arch/InputHandler/InputHandler_Win32_MIDI.cpp index 1cb056a812..f2ee13fb82 100644 --- a/src/arch/InputHandler/InputHandler_Win32_MIDI.cpp +++ b/src/arch/InputHandler/InputHandler_Win32_MIDI.cpp @@ -24,7 +24,7 @@ InputHandler_Win32_MIDI::InputHandler_Win32_MIDI() { int device_id = 0; - g_device = NULL; + g_device = nullptr; if( device_id >= (int) midiInGetNumDevs() ) { diff --git a/src/arch/Lights/LightsDriver_Win32Parallel.cpp b/src/arch/Lights/LightsDriver_Win32Parallel.cpp index 5118704f2c..7df7cbc247 100644 --- a/src/arch/Lights/LightsDriver_Win32Parallel.cpp +++ b/src/arch/Lights/LightsDriver_Win32Parallel.cpp @@ -5,12 +5,12 @@ REGISTER_SOUND_DRIVER_CLASS(Win32Parallel); -HINSTANCE hDLL = NULL; +HINSTANCE hDLL = nullptr; typedef void (WINAPI PORTOUT)(short int Port, char Data); -PORTOUT* PortOut = NULL; +PORTOUT* PortOut = nullptr; typedef short int (WINAPI ISDRIVERINSTALLED)(); -ISDRIVERINSTALLED* IsDriverInstalled = NULL; +ISDRIVERINSTALLED* IsDriverInstalled = nullptr; const int LIGHTS_PER_PARALLEL_PORT = 8; // xxx: don't hardcode the port addresses. -aj diff --git a/src/arch/LoadingWindow/LoadingWindow.cpp b/src/arch/LoadingWindow/LoadingWindow.cpp index 859f52222e..d85ea8bd94 100644 --- a/src/arch/LoadingWindow/LoadingWindow.cpp +++ b/src/arch/LoadingWindow/LoadingWindow.cpp @@ -19,7 +19,7 @@ LoadingWindow *LoadingWindow::Create() ASSERT( DriversToTry.size() != 0 ); RString Driver; - LoadingWindow *ret = NULL; + LoadingWindow *ret = nullptr; for( unsigned i = 0; ret == nullptr && i < DriversToTry.size(); ++i ) { diff --git a/src/arch/LoadingWindow/LoadingWindow_Gtk.cpp b/src/arch/LoadingWindow/LoadingWindow_Gtk.cpp index 82f9ca8ffa..4fb976fc98 100644 --- a/src/arch/LoadingWindow/LoadingWindow_Gtk.cpp +++ b/src/arch/LoadingWindow/LoadingWindow_Gtk.cpp @@ -7,7 +7,7 @@ #include -static void *Handle = NULL; +static void *Handle = nullptr; static INIT Module_Init; static SHUTDOWN Module_Shutdown; static SETTEXT Module_SetText; @@ -71,11 +71,11 @@ LoadingWindow_Gtk::~LoadingWindow_Gtk() { if( Module_Shutdown != nullptr ) Module_Shutdown(); - Module_Shutdown = NULL; + Module_Shutdown = nullptr; if( Handle ) dlclose( Handle ); - Handle = NULL; + Handle = nullptr; } void LoadingWindow_Gtk::SetText( RString s ) diff --git a/src/arch/LoadingWindow/LoadingWindow_GtkModule.cpp b/src/arch/LoadingWindow/LoadingWindow_GtkModule.cpp index fcaab8c0a1..646f301d46 100644 --- a/src/arch/LoadingWindow/LoadingWindow_GtkModule.cpp +++ b/src/arch/LoadingWindow/LoadingWindow_GtkModule.cpp @@ -33,7 +33,7 @@ extern "C" const char *Init( int *argc, char ***argv ) splash = gtk_image_new_from_file(splash_image_path); - label = gtk_label_new(NULL); + label = gtk_label_new(nullptr); gtk_label_set_justify(GTK_LABEL(label),GTK_JUSTIFY_CENTER); gtk_label_set_ellipsize(GTK_LABEL(label),PANGO_ELLIPSIZE_END); gtk_label_set_line_wrap(GTK_LABEL(label),FALSE); diff --git a/src/arch/LoadingWindow/LoadingWindow_Win32.cpp b/src/arch/LoadingWindow/LoadingWindow_Win32.cpp index d4183f5876..184f5ea27b 100644 --- a/src/arch/LoadingWindow/LoadingWindow_Win32.cpp +++ b/src/arch/LoadingWindow/LoadingWindow_Win32.cpp @@ -17,7 +17,7 @@ #include "LocalizedString.h" #include "RageSurfaceUtils_Zoom.h" -static HBITMAP g_hBitmap = NULL; +static HBITMAP g_hBitmap = nullptr; /* Load a RageSurface into a GDI surface. */ static HBITMAP LoadWin32Surface( const RageSurface *pSplash, HWND hWnd ) @@ -39,7 +39,7 @@ static HBITMAP LoadWin32Surface( const RageSurface *pSplash, HWND hWnd ) RageSurfaceUtils::Zoom( s, iWidth, iHeight ); } - HDC hScreen = GetDC(NULL); + HDC hScreen = GetDC(nullptr); ASSERT_M( hScreen != nullptr, werr_ssprintf(GetLastError(), "hScreen") ); HBITMAP bitmap = CreateCompatibleBitmap( hScreen, s->w, s->h ); @@ -104,7 +104,7 @@ BOOL CALLBACK LoadingWindow_Win32::WndProc( HWND hWnd, UINT msg, WPARAM wParam, case WM_DESTROY: DeleteObject( g_hBitmap ); - g_hBitmap = NULL; + g_hBitmap = nullptr; break; } @@ -126,7 +126,7 @@ void LoadingWindow_Win32::SetSplash( const RageSurface *pSplash ) if( g_hBitmap != nullptr ) { DeleteObject( g_hBitmap ); - g_hBitmap = NULL; + g_hBitmap = nullptr; } g_hBitmap = LoadWin32Surface( pSplash, hwnd ); @@ -143,7 +143,7 @@ void LoadingWindow_Win32::SetSplash( const RageSurface *pSplash ) LoadingWindow_Win32::LoadingWindow_Win32() { - m_hIcon = NULL; + m_hIcon = nullptr; hwnd = CreateDialog( handle.Get(), MAKEINTRESOURCE(IDD_LOADING_DIALOG), NULL, WndProc ); for( unsigned i = 0; i < 3; ++i ) text[i] = "ABC"; /* always set on first call */ diff --git a/src/arch/LowLevelWindow/LowLevelWindow_MacOSX.mm b/src/arch/LowLevelWindow/LowLevelWindow_MacOSX.mm index 71a0d8cf4f..47b9afe388 100644 --- a/src/arch/LowLevelWindow/LowLevelWindow_MacOSX.mm +++ b/src/arch/LowLevelWindow/LowLevelWindow_MacOSX.mm @@ -293,7 +293,7 @@ void RenderTarget_MacOSX::FinishRenderingTo() } -LowLevelWindow_MacOSX::LowLevelWindow_MacOSX() : m_Context(nil), m_BGContext(nil), m_CurrentDisplayMode(NULL), m_DisplayID(0) +LowLevelWindow_MacOSX::LowLevelWindow_MacOSX() : m_Context(nil), m_BGContext(nil), m_CurrentDisplayMode(nullptr), m_DisplayID(0) { POOL; m_WindowDelegate = [[SMWindowDelegate alloc] init]; @@ -323,7 +323,7 @@ void *LowLevelWindow_MacOSX::GetProcAddress( RString s ) // Both functions mentioned in there are deprecated in 10.4. const RString& symbolName( '_' + s ); const uint32_t count = _dyld_image_count(); - NSSymbol symbol = NULL; + NSSymbol symbol = nullptr; const uint32_t options = NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR; for( uint32_t i = 0; i < count && !symbol; ++i ) @@ -462,13 +462,13 @@ void LowLevelWindow_MacOSX::ShutDownFullScreen() ASSERT( err == kCGErrorSuccess ); SetActualParamsFromMode( m_CurrentDisplayMode ); // We don't own this so we cannot release it. - m_CurrentDisplayMode = NULL; + m_CurrentDisplayMode = nullptr; m_CurrentParams.windowed = true; } int LowLevelWindow_MacOSX::ChangeDisplayMode( const VideoModeParams& p ) { - CFDictionaryRef mode = NULL; + CFDictionaryRef mode = nullptr; CFDictionaryRef newMode; CGDisplayErr err; diff --git a/src/arch/LowLevelWindow/LowLevelWindow_Win32.cpp b/src/arch/LowLevelWindow/LowLevelWindow_Win32.cpp index f4cbae92ef..0ff5024681 100644 --- a/src/arch/LowLevelWindow/LowLevelWindow_Win32.cpp +++ b/src/arch/LowLevelWindow/LowLevelWindow_Win32.cpp @@ -13,8 +13,8 @@ #include static PIXELFORMATDESCRIPTOR g_CurrentPixelFormat; -static HGLRC g_HGLRC = NULL; -static HGLRC g_HGLRC_Background = NULL; +static HGLRC g_HGLRC = nullptr; +static HGLRC g_HGLRC_Background = nullptr; static void DestroyGraphicsWindowAndOpenGLContext() { @@ -22,13 +22,13 @@ static void DestroyGraphicsWindowAndOpenGLContext() { wglMakeCurrent( NULL, NULL ); wglDeleteContext( g_HGLRC ); - g_HGLRC = NULL; + g_HGLRC = nullptr; } if( g_HGLRC_Background != nullptr ) { wglDeleteContext( g_HGLRC_Background ); - g_HGLRC_Background = NULL; + g_HGLRC_Background = nullptr; } ZERO( g_CurrentPixelFormat ); @@ -42,7 +42,7 @@ void *LowLevelWindow_Win32::GetProcAddress( RString s ) if( pRet != nullptr ) return pRet; - return ::GetProcAddress( GetModuleHandle(NULL), s ); + return ::GetProcAddress( GetModuleHandle(nullptr), s ); } LowLevelWindow_Win32::LowLevelWindow_Win32() @@ -186,9 +186,9 @@ RString LowLevelWindow_Win32::TryVideoMode( const VideoModeParams &p, bool &bNew { wglMakeCurrent( NULL, NULL ); wglDeleteContext( g_HGLRC ); - g_HGLRC = NULL; + g_HGLRC = nullptr; wglDeleteContext( g_HGLRC_Background ); - g_HGLRC_Background = NULL; + g_HGLRC_Background = nullptr; } bNewDeviceOut = true; @@ -234,7 +234,7 @@ RString LowLevelWindow_Win32::TryVideoMode( const VideoModeParams &p, bool &bNew { LOG->Warn( werr_ssprintf(GetLastError(), "wglShareLists failed") ); wglDeleteContext( g_HGLRC_Background ); - g_HGLRC_Background = NULL; + g_HGLRC_Background = nullptr; } if( !wglMakeCurrent( GraphicsWindow::GetHDC(), g_HGLRC ) ) @@ -323,8 +323,8 @@ RenderTarget_Win32::RenderTarget_Win32(LowLevelWindow_Win32 *pWind) { m_pWind = pWind; m_texHandle = 0; - m_hOldDeviceContext = NULL; - m_hOldRenderContext = NULL; + m_hOldDeviceContext = nullptr; + m_hOldRenderContext = nullptr; } RenderTarget_Win32::~RenderTarget_Win32() diff --git a/src/arch/LowLevelWindow/LowLevelWindow_X11.cpp b/src/arch/LowLevelWindow/LowLevelWindow_X11.cpp index c6026d17c3..d509818fae 100644 --- a/src/arch/LowLevelWindow/LowLevelWindow_X11.cpp +++ b/src/arch/LowLevelWindow/LowLevelWindow_X11.cpp @@ -24,12 +24,12 @@ using namespace X11Helper; #include #endif -static GLXContext g_pContext = NULL; -static GLXContext g_pBackgroundContext = NULL; +static GLXContext g_pContext = nullptr; +static GLXContext g_pBackgroundContext = nullptr; static Window g_AltWindow = None; static Rotation g_OldRotation; static int g_iOldSize; -XRRScreenConfiguration *g_pScreenConfig = NULL; +XRRScreenConfiguration *g_pScreenConfig = nullptr; static LocalizedString FAILED_CONNECTION_XSERVER( "LowLevelWindow_X11", "Failed to establish a connection with the X server" ); LowLevelWindow_X11::LowLevelWindow_X11() @@ -65,15 +65,15 @@ LowLevelWindow_X11::~LowLevelWindow_X11() if( g_pContext ) { glXDestroyContext( Dpy, g_pContext ); - g_pContext = NULL; + g_pContext = nullptr; } if( g_pBackgroundContext ) { glXDestroyContext( Dpy, g_pBackgroundContext ); - g_pBackgroundContext = NULL; + g_pBackgroundContext = nullptr; } XRRFreeScreenConfigInfo( g_pScreenConfig ); - g_pScreenConfig = NULL; + g_pScreenConfig = nullptr; XDestroyWindow( Dpy, Win ); Win = None; @@ -379,9 +379,9 @@ RenderTarget_X11::RenderTarget_X11( LowLevelWindow_X11 *pWind ) { m_pWind = pWind; m_iPbuffer = 0; - m_pPbufferContext = NULL; + m_pPbufferContext = nullptr; m_iTexHandle = 0; - m_pOldContext = NULL; + m_pOldContext = nullptr; m_pOldDrawable = 0; } @@ -496,7 +496,7 @@ void RenderTarget_X11::FinishRenderingTo() glBindTexture( GL_TEXTURE_2D, 0 ); glXMakeCurrent( Dpy, m_pOldDrawable, m_pOldContext ); - m_pOldContext = NULL; + m_pOldContext = nullptr; m_pOldDrawable = 0; } diff --git a/src/arch/MemoryCard/MemoryCardDriver.cpp b/src/arch/MemoryCard/MemoryCardDriver.cpp index fddb59cb5a..dce9556b59 100644 --- a/src/arch/MemoryCard/MemoryCardDriver.cpp +++ b/src/arch/MemoryCard/MemoryCardDriver.cpp @@ -124,7 +124,7 @@ bool MemoryCardDriver::DoOneUpdate( bool bMount, vector& vStor #include "arch/arch_default.h" MemoryCardDriver *MemoryCardDriver::Create() { - MemoryCardDriver *ret = NULL; + MemoryCardDriver *ret = nullptr; #ifdef ARCH_MEMORY_CARD_DRIVER ret = new ARCH_MEMORY_CARD_DRIVER; diff --git a/src/arch/MovieTexture/MovieTexture.cpp b/src/arch/MovieTexture/MovieTexture.cpp index fd17848608..1f54e3928e 100644 --- a/src/arch/MovieTexture/MovieTexture.cpp +++ b/src/arch/MovieTexture/MovieTexture.cpp @@ -92,7 +92,7 @@ RageMovieTexture *RageMovieTexture::Create( RageTextureID ID ) if( DriversToTry.empty() ) RageException::Throw( "%s", MOVIE_DRIVERS_EMPTY.GetValue().c_str() ); - RageMovieTexture *ret = NULL; + RageMovieTexture *ret = nullptr; for (RString const &Driver : DriversToTry) { diff --git a/src/arch/MovieTexture/MovieTexture_DShow.cpp b/src/arch/MovieTexture/MovieTexture_DShow.cpp index 04fec360e9..c5be869196 100644 --- a/src/arch/MovieTexture/MovieTexture_DShow.cpp +++ b/src/arch/MovieTexture/MovieTexture_DShow.cpp @@ -150,7 +150,7 @@ MovieTexture_DShow::MovieTexture_DShow( RageTextureID ID ) : m_bPlaying = false; m_uTexHandle = 0; - buffer = NULL; + buffer = nullptr; } RString MovieTexture_DShow::Init() @@ -258,7 +258,7 @@ void MovieTexture_DShow::CheckFrame() delete pFromDShow; - buffer = NULL; + buffer = nullptr; CHECKPOINT; @@ -310,12 +310,12 @@ RString MovieTexture_DShow::GetActiveFilterList() { RString ret; - IEnumFilters *pEnum = NULL; + IEnumFilters *pEnum = nullptr; HRESULT hr = m_pGB->EnumFilters(&pEnum); if (FAILED(hr)) return hr_ssprintf(hr, "EnumFilters"); - IBaseFilter *pF = NULL; + IBaseFilter *pF = nullptr; while( S_OK == pEnum->Next(1, &pF, 0) ) { FILTER_INFO FilterInfo; @@ -341,7 +341,7 @@ RString MovieTexture_DShow::Create() actualID.iAlphaBits = 0; - if( FAILED( hr=CoInitialize(NULL) ) ) + if( FAILED( hr=CoInitialize(nullptr) ) ) RageException::Throw( hr_ssprintf(hr, "Could not CoInitialize") ); // Create the filter graph diff --git a/src/arch/MovieTexture/MovieTexture_DShowHelper.cpp b/src/arch/MovieTexture/MovieTexture_DShowHelper.cpp index 95273c11fb..ce2dcbd03b 100644 --- a/src/arch/MovieTexture/MovieTexture_DShowHelper.cpp +++ b/src/arch/MovieTexture/MovieTexture_DShowHelper.cpp @@ -19,7 +19,7 @@ CTextureRenderer::CTextureRenderer(): if( FAILED(CBV_ret) ) RageException::Throw( hr_ssprintf(CBV_ret, "Could not create texture renderer object!") ); - m_pTexture = NULL; + m_pTexture = nullptr; } CTextureRenderer::~CTextureRenderer() diff --git a/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp b/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp index 9f496981a6..964d40885c 100644 --- a/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp +++ b/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp @@ -294,8 +294,8 @@ MovieDecoder_FFMpeg::MovieDecoder_FFMpeg() { FixLilEndian(); - m_fctx = NULL; - m_pStream = NULL; + m_fctx = nullptr; + m_pStream = nullptr; m_iCurrentPacketOffset = -1; m_fLastFrame = 0; @@ -313,7 +313,7 @@ MovieDecoder_FFMpeg::~MovieDecoder_FFMpeg() if (m_swsctx) { avcodec::sws_freeContext(m_swsctx); - m_swsctx = NULL; + m_swsctx = nullptr; } if (m_avioContext != nullptr ) { @@ -337,9 +337,9 @@ void MovieDecoder_FFMpeg::Init() m_fPTS = -1; m_iFrameNumber = -1; /* decode one frame and you're on the 0th */ m_fTimestampOffset = 0; - m_swsctx = NULL; - m_avioContext = NULL; - m_buffer = NULL; + m_swsctx = nullptr; + m_avioContext = nullptr; + m_buffer = nullptr; if( m_iCurrentPacketOffset != -1 ) { @@ -695,13 +695,13 @@ void MovieDecoder_FFMpeg::Close() if( m_pStream && m_pStream->codec->codec ) { avcodec::avcodec_close( m_pStream->codec ); - m_pStream = NULL; + m_pStream = nullptr; } if( m_fctx ) { avcodec::avformat_close_input( &m_fctx ); - m_fctx = NULL; + m_fctx = nullptr; } Init(); diff --git a/src/arch/MovieTexture/MovieTexture_Generic.cpp b/src/arch/MovieTexture/MovieTexture_Generic.cpp index 58773e76d3..6d6307ee08 100644 --- a/src/arch/MovieTexture/MovieTexture_Generic.cpp +++ b/src/arch/MovieTexture/MovieTexture_Generic.cpp @@ -25,11 +25,11 @@ MovieTexture_Generic::MovieTexture_Generic( RageTextureID ID, MovieDecoder *pDec m_pDecoder = pDecoder; m_uTexHandle = 0; - m_pRenderTarget = NULL; - m_pTextureIntermediate = NULL; + m_pRenderTarget = nullptr; + m_pTextureIntermediate = nullptr; m_bLoop = true; - m_pSurface = NULL; - m_pTextureLock = NULL; + m_pSurface = nullptr; + m_pTextureLock = nullptr; m_ImageWaiting = FRAME_NONE; m_fRate = 1; m_bWantRewind = false; @@ -88,10 +88,10 @@ MovieTexture_Generic::~MovieTexture_Generic() void MovieTexture_Generic::DestroyTexture() { delete m_pSurface; - m_pSurface = NULL; + m_pSurface = nullptr; delete m_pTextureLock; - m_pTextureLock = NULL; + m_pTextureLock = nullptr; if( m_uTexHandle ) { @@ -100,9 +100,9 @@ void MovieTexture_Generic::DestroyTexture() } delete m_pRenderTarget; - m_pRenderTarget = NULL; + m_pRenderTarget = nullptr; delete m_pTextureIntermediate; - m_pTextureIntermediate = NULL; + m_pTextureIntermediate = nullptr; } class RageMovieTexture_Generic_Intermediate : public RageTexture @@ -217,7 +217,7 @@ void MovieTexture_Generic::CreateTexture() if( m_pTextureLock != nullptr ) { delete [] m_pSurface->pixels; - m_pSurface->pixels = NULL; + m_pSurface->pixels = nullptr; } } diff --git a/src/arch/Sound/ALSA9Dynamic.cpp b/src/arch/Sound/ALSA9Dynamic.cpp index a41d8a5a3e..12b83a6452 100644 --- a/src/arch/Sound/ALSA9Dynamic.cpp +++ b/src/arch/Sound/ALSA9Dynamic.cpp @@ -6,13 +6,13 @@ #define ALSA_PCM_NEW_SW_PARAMS_API #include -static void *Handle = NULL; +static void *Handle = nullptr; #include "RageUtil.h" #include "ALSA9Dynamic.h" -/* foo_f dfoo = NULL */ -#define FUNC(ret, name, proto) name##_f d##name = NULL +/* foo_f dfoo = nullptr */ +#define FUNC(ret, name, proto) name##_f d##name = nullptr #include "ALSA9Functions.h" #undef FUNC @@ -62,8 +62,8 @@ void UnloadALSA() { if( Handle ) dlclose( Handle ); - Handle = NULL; -#define FUNC(ret, name, proto) d##name = NULL; + Handle = nullptr; +#define FUNC(ret, name, proto) d##name = nullptr; #include "ALSA9Functions.h" #undef FUNC } diff --git a/src/arch/Sound/ALSA9Helpers.cpp b/src/arch/Sound/ALSA9Helpers.cpp index b04fe696d2..4199e81427 100644 --- a/src/arch/Sound/ALSA9Helpers.cpp +++ b/src/arch/Sound/ALSA9Helpers.cpp @@ -212,7 +212,7 @@ Alsa9Buf::Alsa9Buf() last_cursor_pos = 0; preferred_writeahead = 8192; preferred_chunksize = 1024; - pcm = NULL; + pcm = nullptr; } RString Alsa9Buf::Init( int channels_, diff --git a/src/arch/Sound/DSoundHelpers.cpp b/src/arch/Sound/DSoundHelpers.cpp index 8438ecdd14..ec720172c8 100644 --- a/src/arch/Sound/DSoundHelpers.cpp +++ b/src/arch/Sound/DSoundHelpers.cpp @@ -43,7 +43,7 @@ void DSound::SetPrimaryBufferMode() format.dwSize = sizeof(format); format.dwFlags = DSBCAPS_PRIMARYBUFFER; format.dwBufferBytes = 0; - format.lpwfxFormat = NULL; + format.lpwfxFormat = nullptr; IDirectSoundBuffer *pBuffer; HRESULT hr = this->GetDS()->CreateSoundBuffer( &format, &pBuffer, NULL ); @@ -98,9 +98,9 @@ void DSound::SetPrimaryBufferMode() DSound::DSound() { HRESULT hr; - if( FAILED( hr = CoInitialize(NULL) ) ) + if( FAILED( hr = CoInitialize(nullptr) ) ) RageException::Throw( hr_ssprintf(hr, "CoInitialize") ); - m_pDS = NULL; + m_pDS = nullptr; } RString DSound::Init() @@ -163,8 +163,8 @@ bool DSound::IsEmulated() const DSoundBuf::DSoundBuf() { - m_pBuffer = NULL; - m_pTempBuffer = NULL; + m_pBuffer = nullptr; + m_pTempBuffer = nullptr; } RString DSoundBuf::Init( DSound &ds, DSoundBuf::hw hardware, diff --git a/src/arch/Sound/RageSoundDriver_ALSA9_Software.cpp b/src/arch/Sound/RageSoundDriver_ALSA9_Software.cpp index b53df0c358..aedf9f75ef 100644 --- a/src/arch/Sound/RageSoundDriver_ALSA9_Software.cpp +++ b/src/arch/Sound/RageSoundDriver_ALSA9_Software.cpp @@ -53,12 +53,12 @@ bool RageSoundDriver_ALSA9_Software::GetData() if( frames_to_fill <= 0 ) return false; - static int16_t *buf = NULL; + static int16_t *buf = nullptr; static int bufsize = 0; if( buf && bufsize < frames_to_fill ) { delete[] buf; - buf = NULL; + buf = nullptr; } if( !buf ) { @@ -89,7 +89,7 @@ void RageSoundDriver_ALSA9_Software::SetupDecodingThread() RageSoundDriver_ALSA9_Software::RageSoundDriver_ALSA9_Software() { - m_pPCM = NULL; + m_pPCM = nullptr; m_bShutdown = false; } diff --git a/src/arch/Sound/RageSoundDriver_AU.cpp b/src/arch/Sound/RageSoundDriver_AU.cpp index a68bf9e73d..eeedaab075 100644 --- a/src/arch/Sound/RageSoundDriver_AU.cpp +++ b/src/arch/Sound/RageSoundDriver_AU.cpp @@ -40,8 +40,8 @@ static inline RString FourCCToString( uint32_t num ) return s; } -RageSoundDriver_AU::RageSoundDriver_AU() : m_OutputUnit(NULL), m_iSampleRate(0), m_bDone(false), m_bStarted(false), - m_pIOThread(NULL), m_pNotificationThread(NULL), m_Semaphore("Sound") +RageSoundDriver_AU::RageSoundDriver_AU() : m_OutputUnit(nullptr), m_iSampleRate(0), m_bDone(false), m_bStarted(false), + m_pIOThread(nullptr), m_pNotificationThread(nullptr), m_Semaphore("Sound") { } diff --git a/src/arch/Sound/RageSoundDriver_DSound_Software.cpp b/src/arch/Sound/RageSoundDriver_DSound_Software.cpp index 1366f45fec..ffdc822b8d 100644 --- a/src/arch/Sound/RageSoundDriver_DSound_Software.cpp +++ b/src/arch/Sound/RageSoundDriver_DSound_Software.cpp @@ -1,169 +1,169 @@ -#include "global.h" -#include "RageSoundDriver_DSound_Software.h" -#include "DSoundHelpers.h" - -#include "RageLog.h" -#include "RageUtil.h" -#include "RageSoundManager.h" -#include "PrefsManager.h" -#include "archutils/Win32/ErrorStrings.h" - -REGISTER_SOUND_DRIVER_CLASS2( DirectSound-sw, DSound_Software ); - -static const int channels = 2; -static const int bytes_per_frame = channels*2; /* 16-bit */ -static const int safe_writeahead = 1024*4; /* in frames */ -static int g_iMaxWriteahead; - -/* We'll fill the buffer in chunks this big. */ -static const int num_chunks = 8; -static int chunksize() { return g_iMaxWriteahead / num_chunks; } - -void RageSoundDriver_DSound_Software::MixerThread() -{ - if( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) ) - if( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) ) - LOG->Warn(werr_ssprintf(GetLastError(), "Failed to set sound thread priority")); - - /* Fill a buffer before we start playing, so we don't play whatever junk is - * in the buffer. */ - char *locked_buf; - unsigned len; - while( m_pPCM->get_output_buf(&locked_buf, &len, chunksize()) ) - { - memset( locked_buf, 0, len ); - m_pPCM->release_output_buf(locked_buf, len); - } - - /* Start playing. */ - m_pPCM->Play(); - - while( !m_bShutdownMixerThread ) - { - char *pLockedBuf; - unsigned iLen; - const int64_t iPlayPos = m_pPCM->GetOutputPosition(); /* must be called before get_output_buf */ - - if( !m_pPCM->get_output_buf(&pLockedBuf, &iLen, chunksize()) ) - { - Sleep( chunksize()*1000 / m_iSampleRate ); - continue; - } - - this->Mix( (int16_t *) pLockedBuf, iLen/bytes_per_frame, iPlayPos, m_pPCM->GetPosition() ); - - m_pPCM->release_output_buf( pLockedBuf, iLen ); - } - - /* I'm not sure why, but if we don't stop the stream now, then the thread will take - * 90ms (our buffer size) longer to close. */ - m_pPCM->Stop(); -} - -int64_t RageSoundDriver_DSound_Software::GetPosition() const -{ - return m_pPCM->GetPosition(); -} - -int RageSoundDriver_DSound_Software::MixerThread_start(void *p) -{ - ((RageSoundDriver_DSound_Software *) p)->MixerThread(); - return 0; -} - -RageSoundDriver_DSound_Software::RageSoundDriver_DSound_Software() -{ - m_bShutdownMixerThread = false; - m_pPCM = NULL; -} - -RString RageSoundDriver_DSound_Software::Init() -{ - RString sError = ds.Init(); - if( sError != "" ) - return sError; - - /* If we're emulated, we're better off with the WaveOut driver; DS - * emulation tends to be desynced. */ - if( ds.IsEmulated() ) - return "Driver unusable (emulated device)"; - - g_iMaxWriteahead = safe_writeahead; - if( PREFSMAN->m_iSoundWriteAhead ) - g_iMaxWriteahead = PREFSMAN->m_iSoundWriteAhead; - - /* Create a DirectSound stream, but don't force it into hardware. */ - m_pPCM = new DSoundBuf; - m_iSampleRate = PREFSMAN->m_iSoundPreferredSampleRate; - if( m_iSampleRate == 0 ) - m_iSampleRate = 44100; - sError = m_pPCM->Init( ds, DSoundBuf::HW_DONT_CARE, channels, m_iSampleRate, 16, g_iMaxWriteahead ); - if( sError != "" ) - return sError; - - LOG->Info( "Software mixing at %i hz", m_iSampleRate ); - - StartDecodeThread(); - - m_MixingThread.SetName("Mixer thread"); - m_MixingThread.Create( MixerThread_start, this ); - - return RString(); -} - -RageSoundDriver_DSound_Software::~RageSoundDriver_DSound_Software() -{ - /* Signal the mixing thread to quit. */ - if( m_MixingThread.IsCreated() ) - { - m_bShutdownMixerThread = true; - LOG->Trace("Shutting down mixer thread ..."); - LOG->Flush(); - m_MixingThread.Wait(); - LOG->Trace("Mixer thread shut down."); - LOG->Flush(); - } - - delete m_pPCM; -} - -void RageSoundDriver_DSound_Software::SetupDecodingThread() -{ - if( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) ) - LOG->Warn( werr_ssprintf(GetLastError(), "Failed to set decoding thread priority") ); -} - -float RageSoundDriver_DSound_Software::GetPlayLatency() const -{ - return (1.0f / m_iSampleRate) * g_iMaxWriteahead; -} - -int RageSoundDriver_DSound_Software::GetSampleRate() const -{ - return m_iSampleRate; -} - -/* - * (c) 2002-2004 Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "RageSoundDriver_DSound_Software.h" +#include "DSoundHelpers.h" + +#include "RageLog.h" +#include "RageUtil.h" +#include "RageSoundManager.h" +#include "PrefsManager.h" +#include "archutils/Win32/ErrorStrings.h" + +REGISTER_SOUND_DRIVER_CLASS2( DirectSound-sw, DSound_Software ); + +static const int channels = 2; +static const int bytes_per_frame = channels*2; /* 16-bit */ +static const int safe_writeahead = 1024*4; /* in frames */ +static int g_iMaxWriteahead; + +/* We'll fill the buffer in chunks this big. */ +static const int num_chunks = 8; +static int chunksize() { return g_iMaxWriteahead / num_chunks; } + +void RageSoundDriver_DSound_Software::MixerThread() +{ + if( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) ) + if( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) ) + LOG->Warn(werr_ssprintf(GetLastError(), "Failed to set sound thread priority")); + + /* Fill a buffer before we start playing, so we don't play whatever junk is + * in the buffer. */ + char *locked_buf; + unsigned len; + while( m_pPCM->get_output_buf(&locked_buf, &len, chunksize()) ) + { + memset( locked_buf, 0, len ); + m_pPCM->release_output_buf(locked_buf, len); + } + + /* Start playing. */ + m_pPCM->Play(); + + while( !m_bShutdownMixerThread ) + { + char *pLockedBuf; + unsigned iLen; + const int64_t iPlayPos = m_pPCM->GetOutputPosition(); /* must be called before get_output_buf */ + + if( !m_pPCM->get_output_buf(&pLockedBuf, &iLen, chunksize()) ) + { + Sleep( chunksize()*1000 / m_iSampleRate ); + continue; + } + + this->Mix( (int16_t *) pLockedBuf, iLen/bytes_per_frame, iPlayPos, m_pPCM->GetPosition() ); + + m_pPCM->release_output_buf( pLockedBuf, iLen ); + } + + /* I'm not sure why, but if we don't stop the stream now, then the thread will take + * 90ms (our buffer size) longer to close. */ + m_pPCM->Stop(); +} + +int64_t RageSoundDriver_DSound_Software::GetPosition() const +{ + return m_pPCM->GetPosition(); +} + +int RageSoundDriver_DSound_Software::MixerThread_start(void *p) +{ + ((RageSoundDriver_DSound_Software *) p)->MixerThread(); + return 0; +} + +RageSoundDriver_DSound_Software::RageSoundDriver_DSound_Software() +{ + m_bShutdownMixerThread = false; + m_pPCM = nullptr; +} + +RString RageSoundDriver_DSound_Software::Init() +{ + RString sError = ds.Init(); + if( sError != "" ) + return sError; + + /* If we're emulated, we're better off with the WaveOut driver; DS + * emulation tends to be desynced. */ + if( ds.IsEmulated() ) + return "Driver unusable (emulated device)"; + + g_iMaxWriteahead = safe_writeahead; + if( PREFSMAN->m_iSoundWriteAhead ) + g_iMaxWriteahead = PREFSMAN->m_iSoundWriteAhead; + + /* Create a DirectSound stream, but don't force it into hardware. */ + m_pPCM = new DSoundBuf; + m_iSampleRate = PREFSMAN->m_iSoundPreferredSampleRate; + if( m_iSampleRate == 0 ) + m_iSampleRate = 44100; + sError = m_pPCM->Init( ds, DSoundBuf::HW_DONT_CARE, channels, m_iSampleRate, 16, g_iMaxWriteahead ); + if( sError != "" ) + return sError; + + LOG->Info( "Software mixing at %i hz", m_iSampleRate ); + + StartDecodeThread(); + + m_MixingThread.SetName("Mixer thread"); + m_MixingThread.Create( MixerThread_start, this ); + + return RString(); +} + +RageSoundDriver_DSound_Software::~RageSoundDriver_DSound_Software() +{ + /* Signal the mixing thread to quit. */ + if( m_MixingThread.IsCreated() ) + { + m_bShutdownMixerThread = true; + LOG->Trace("Shutting down mixer thread ..."); + LOG->Flush(); + m_MixingThread.Wait(); + LOG->Trace("Mixer thread shut down."); + LOG->Flush(); + } + + delete m_pPCM; +} + +void RageSoundDriver_DSound_Software::SetupDecodingThread() +{ + if( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) ) + LOG->Warn( werr_ssprintf(GetLastError(), "Failed to set decoding thread priority") ); +} + +float RageSoundDriver_DSound_Software::GetPlayLatency() const +{ + return (1.0f / m_iSampleRate) * g_iMaxWriteahead; +} + +int RageSoundDriver_DSound_Software::GetSampleRate() const +{ + return m_iSampleRate; +} + +/* + * (c) 2002-2004 Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/arch/Sound/RageSoundDriver_Generic_Software.cpp b/src/arch/Sound/RageSoundDriver_Generic_Software.cpp index 67b9ef729c..216ffb5e0a 100644 --- a/src/arch/Sound/RageSoundDriver_Generic_Software.cpp +++ b/src/arch/Sound/RageSoundDriver_Generic_Software.cpp @@ -18,7 +18,7 @@ static int underruns = 0, logged_underruns = 0; RageSoundDriver::Sound::Sound() { - m_pSound = NULL; + m_pSound = nullptr; m_State = AVAILABLE; m_bPaused = false; } @@ -273,7 +273,7 @@ void RageSoundDriver::Update() // LOG->Trace("finishing sound %i", i); m_Sounds[i].m_pSound->SoundIsFinishedPlaying(); - m_Sounds[i].m_pSound = NULL; + m_Sounds[i].m_pSound = nullptr; /* This sound is done. Set it to HALTING, since the mixer thread might * be accessing it; it'll change it back to STOPPED once it's ready to @@ -382,7 +382,7 @@ void RageSoundDriver::StopMixing( RageSoundBase *pSound ) /* Invalidate the m_pSound pointer to guarantee we don't make any further references to * it. Once this call returns, the sound may no longer exist. */ - m_Sounds[i].m_pSound = NULL; + m_Sounds[i].m_pSound = nullptr; // LOG->Trace("end StopMixing"); m_Mutex.Unlock(); diff --git a/src/arch/Sound/RageSoundDriver_OSS.cpp b/src/arch/Sound/RageSoundDriver_OSS.cpp index 1c75d5454e..b30b38d6be 100644 --- a/src/arch/Sound/RageSoundDriver_OSS.cpp +++ b/src/arch/Sound/RageSoundDriver_OSS.cpp @@ -77,7 +77,7 @@ bool RageSoundDriver_OSS::GetData() const int chunksize = ab.fragsize; - static int16_t *buf = NULL; + static int16_t *buf = nullptr; if(!buf) buf = new int16_t[chunksize / sizeof(int16_t)]; diff --git a/src/arch/Sound/RageSoundDriver_PulseAudio.cpp b/src/arch/Sound/RageSoundDriver_PulseAudio.cpp index 5a19c73ed1..fd147665b8 100644 --- a/src/arch/Sound/RageSoundDriver_PulseAudio.cpp +++ b/src/arch/Sound/RageSoundDriver_PulseAudio.cpp @@ -16,9 +16,9 @@ REGISTER_SOUND_DRIVER_CLASS2( Pulse, PulseAudio ); /* Constructor */ RageSoundDriver_PulseAudio::RageSoundDriver_PulseAudio() : RageSoundDriver(), -m_LastPosition(0), m_SampleRate(0), m_Error(NULL), +m_LastPosition(0), m_SampleRate(0), m_Error(nullptr), m_Sem("Pulseaudio Synchronization Semaphore"), -m_PulseMainLoop(NULL), m_PulseCtx(NULL), m_PulseStream(NULL) +m_PulseMainLoop(nullptr), m_PulseCtx(nullptr), m_PulseStream(nullptr) { m_SampleRate = PREFSMAN->m_iSoundPreferredSampleRate; if( m_SampleRate == 0 ) @@ -137,7 +137,7 @@ void RageSoundDriver_PulseAudio::m_InitStream(void) { if(asprintf(&m_Error, "invalid sample spec!") == -1) { - m_Error = NULL; + m_Error = nullptr; } m_Sem.Post(); return; @@ -155,7 +155,7 @@ void RageSoundDriver_PulseAudio::m_InitStream(void) { if(asprintf(&m_Error, "pa_stream_new(): %s", pa_strerror(pa_context_errno(m_PulseCtx))) == -1) { - m_Error = NULL; + m_Error = nullptr; } m_Sem.Post(); return; @@ -231,7 +231,7 @@ void RageSoundDriver_PulseAudio::m_InitStream(void) if(asprintf(&m_Error, "pa_stream_connect_playback(): %s", pa_strerror(pa_context_errno(m_PulseCtx))) == -1) { - m_Error = NULL; + m_Error = nullptr; } m_Sem.Post(); return; @@ -261,7 +261,7 @@ void RageSoundDriver_PulseAudio::CtxStateCb(pa_context *c) case PA_CONTEXT_FAILED: if(asprintf(&m_Error, "context connection failed: %s", pa_strerror(pa_context_errno(m_PulseCtx))) == -1) { - m_Error = NULL; + m_Error = nullptr; } m_Sem.Post(); return; diff --git a/src/arch/Sound/RageSoundDriver_WDMKS.cpp b/src/arch/Sound/RageSoundDriver_WDMKS.cpp index 4745d7ef4c..21f8b07108 100644 --- a/src/arch/Sound/RageSoundDriver_WDMKS.cpp +++ b/src/arch/Sound/RageSoundDriver_WDMKS.cpp @@ -38,7 +38,7 @@ struct WinWdmPin { WinWdmPin( WinWdmFilter *pParentFilter, int iPinId ) { - m_hHandle = NULL; + m_hHandle = nullptr; m_pParentFilter = pParentFilter; m_iPinId = iPinId; } @@ -92,7 +92,7 @@ struct WinWdmFilter WinWdmFilter() { - m_hHandle = NULL; + m_hHandle = nullptr; m_iUsageCount = 0; } @@ -129,8 +129,8 @@ static RString GUIDToString( const GUID *pGuid ) pGuid->Data4[4], pGuid->Data4[5], pGuid->Data4[6], pGuid->Data4[7] ); } -static HMODULE DllKsUser = NULL; -static KSCREATEPIN *FunctionKsCreatePin = NULL; +static HMODULE DllKsUser = nullptr; +static KSCREATEPIN *FunctionKsCreatePin = nullptr; /* Low level pin/filter access functions */ static bool WdmSyncIoctl( @@ -313,7 +313,7 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) /* Get the INTERFACE property list */ { - KSMULTIPLE_ITEM *pItem = NULL; + KSMULTIPLE_ITEM *pItem = nullptr; if( !WdmGetPinPropertyMulti(m_hHandle, iPinId, &KSPROPSETID_Pin, KSPROPERTY_PIN_INTERFACES, &pItem, sError) ) { sError = "KSPROPERTY_PIN_INTERFACES: " + sError; @@ -342,7 +342,7 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) /* Get the MEDIUM properties list */ { - KSMULTIPLE_ITEM *pItem = NULL; + KSMULTIPLE_ITEM *pItem = nullptr; if( !WdmGetPinPropertyMulti( m_hHandle, iPinId, &KSPROPSETID_Pin, KSPROPERTY_PIN_MEDIUMS, &pItem, sError) ) { sError = "KSPROPERTY_PIN_MEDIUMS: " + sError; @@ -405,7 +405,7 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) } } free( pDataRangesItem ); - pDataRangesItem = NULL; + pDataRangesItem = nullptr; if( pPin->m_dataRangesItem.size() == 0 ) { @@ -433,7 +433,7 @@ void WinWdmPin::Close() SetState( KSSTATE_PAUSE, sError ); SetState( KSSTATE_STOP, sError ); CloseHandle( m_hHandle ); - m_hHandle = NULL; + m_hHandle = nullptr; m_pParentFilter->Release(); } @@ -465,7 +465,7 @@ bool WinWdmPin::Instantiate( const WAVEFORMATEX *pFormat, RString &sError ) sError = werr_ssprintf( iRet, "FunctionKsCreatePin" ); m_pParentFilter->Release(); - m_hHandle = NULL; + m_hHandle = nullptr; return false; } @@ -613,7 +613,7 @@ void WinWdmFilter::Release() if( m_hHandle != nullptr ) { CloseHandle( m_hHandle ); - m_hHandle = NULL; + m_hHandle = nullptr; } } } @@ -885,7 +885,7 @@ static bool PaWinWdm_Initialize( RString &sError ) { sError = "no KsCreatePin in ksuser.dll"; FreeLibrary( DllKsUser ); - DllKsUser = NULL; + DllKsUser = nullptr; return false; } @@ -900,7 +900,7 @@ struct WinWdmStream memset( this, 0, sizeof(*this) ); for( int i = 0; i < MAX_CHUNKS; ++i ) m_Signal[i].hEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); - m_pPlaybackPin = NULL; + m_pPlaybackPin = nullptr; } ~WinWdmStream() @@ -920,11 +920,11 @@ struct WinWdmStream { if( m_pPlaybackPin ) m_pPlaybackPin->Close(); - m_pPlaybackPin = NULL; + m_pPlaybackPin = nullptr; for( int i = 0; i < 2; ++i ) { VirtualFree( m_Packets[i].Data, 0, MEM_RELEASE ); - m_Packets[i].Data = NULL; + m_Packets[i].Data = nullptr; } } @@ -1263,8 +1263,8 @@ int64_t RageSoundDriver_WDMKS::GetPosition() const RageSoundDriver_WDMKS::RageSoundDriver_WDMKS() { - m_pStream = NULL; - m_pFilter = NULL; + m_pStream = nullptr; + m_pFilter = nullptr; m_bShutdown = false; m_iLastCursorPos = 0; m_hSignal = CreateEvent( NULL, FALSE, FALSE, NULL ); /* abort event */ diff --git a/src/arch/Sound/RageSoundDriver_WaveOut.cpp b/src/arch/Sound/RageSoundDriver_WaveOut.cpp index 20718ea2d9..fdde71198c 100644 --- a/src/arch/Sound/RageSoundDriver_WaveOut.cpp +++ b/src/arch/Sound/RageSoundDriver_WaveOut.cpp @@ -106,7 +106,7 @@ RageSoundDriver_WaveOut::RageSoundDriver_WaveOut() m_hSoundEvent = CreateEvent( NULL, false, true, NULL ); - m_hWaveOut = NULL; + m_hWaveOut = nullptr; } RString RageSoundDriver_WaveOut::Init() diff --git a/src/arch/Threads/Threads_Pthreads.cpp b/src/arch/Threads/Threads_Pthreads.cpp index 71c81a4fc9..dfd696ff1b 100644 --- a/src/arch/Threads/Threads_Pthreads.cpp +++ b/src/arch/Threads/Threads_Pthreads.cpp @@ -215,7 +215,7 @@ static const clockid_t CLOCK_MONOTONIC = 1; namespace { typedef int (* CONDATTR_SET_CLOCK)( pthread_condattr_t *attr, clockid_t clock_id ); - CONDATTR_SET_CLOCK g_CondattrSetclock = NULL; + CONDATTR_SET_CLOCK g_CondattrSetclock = nullptr; bool bInitialized = false; #if defined(UNIX) @@ -230,7 +230,7 @@ namespace return; bInitialized = true; - void *pLib = NULL; + void *pLib = nullptr; do { { @@ -260,10 +260,10 @@ namespace return; } while(0); - g_CondattrSetclock = NULL; + g_CondattrSetclock = nullptr; if( pLib != nullptr ) dlclose( pLib ); - pLib = NULL; + pLib = nullptr; } #elif defined(MACOSX) void InitMonotonic() { bInitialized = true; } diff --git a/src/arch/Threads/Threads_Win32.cpp b/src/arch/Threads/Threads_Win32.cpp index ecc154e583..b529b554e0 100644 --- a/src/arch/Threads/Threads_Win32.cpp +++ b/src/arch/Threads/Threads_Win32.cpp @@ -7,12 +7,12 @@ const int MAX_THREADS=128; -static MutexImpl_Win32 *g_pThreadIdMutex = NULL; +static MutexImpl_Win32 *g_pThreadIdMutex = nullptr; static void InitThreadIdMutex() { if( g_pThreadIdMutex != nullptr ) return; - g_pThreadIdMutex = new MutexImpl_Win32(NULL); + g_pThreadIdMutex = new MutexImpl_Win32(nullptr); } static uint64_t g_ThreadIds[MAX_THREADS]; @@ -55,7 +55,7 @@ int ThreadImpl_Win32::Wait() GetExitCodeThread( ThreadHandle, &ret ); CloseHandle( ThreadHandle ); - ThreadHandle = NULL; + ThreadHandle = nullptr; return ret; } @@ -97,7 +97,7 @@ static DWORD WINAPI StartThread( LPVOID pData ) { if( g_ThreadIds[i] == RageThread::GetCurrentThreadID() ) { - g_ThreadHandles[i] = NULL; + g_ThreadHandles[i] = nullptr; g_ThreadIds[i] = 0; break; } @@ -140,7 +140,7 @@ ThreadImpl *MakeThisThread() // LOG->Warn( werr_ssprintf( GetLastError(), "DuplicateHandle(%p, %p) failed", // CurProc, GetCurrentThread() ) ); - thread->ThreadHandle = NULL; + thread->ThreadHandle = nullptr; } thread->ThreadId = GetCurrentThreadId(); diff --git a/src/arch/arch.cpp b/src/arch/arch.cpp index 92371b12b8..ccf6cda03d 100644 --- a/src/arch/arch.cpp +++ b/src/arch/arch.cpp @@ -25,7 +25,7 @@ void MakeInputHandlers( const RString &drivers, vector &Add ) for (RString const &s: DriversToTry) { - InputHandler *ret = NULL; + InputHandler *ret = nullptr; #ifdef USE_INPUT_HANDLER_DIRECTINPUT if( !s.CompareNoCase("DirectInput") ) ret = new InputHandler_DInput; @@ -74,7 +74,7 @@ void MakeLightsDrivers( const RString &driver, vector &Add ) { LOG->Trace( "Initializing lights driver: %s", driver.c_str() ); - LightsDriver *ret = NULL; + LightsDriver *ret = nullptr; #ifdef USE_LIGHTS_DRIVER_LINUX_PIUIO if( !driver.CompareNoCase("PIUIO") ) ret = new LightsDriver_Linux_PIUIO; @@ -113,7 +113,7 @@ LoadingWindow *MakeLoadingWindow() ASSERT( DriversToTry.size() != 0 ); RString Driver; - LoadingWindow *ret = NULL; + LoadingWindow *ret = nullptr; for( unsigned i = 0; ret == nullptr && i < DriversToTry.size(); ++i ) { @@ -161,7 +161,7 @@ LowLevelWindow *MakeLowLevelWindow() #include "MemoryCard/Selector_MemoryCardDriver.h" MemoryCardDriver *MakeMemoryCardDriver() { - MemoryCardDriver *ret = NULL; + MemoryCardDriver *ret = nullptr; #ifdef ARCH_MEMORY_CARD_DRIVER ret = new ARCH_MEMORY_CARD_DRIVER; @@ -194,7 +194,7 @@ RageMovieTexture *MakeRageMovieTexture( RageTextureID ID ) RageException::Throw( MOVIE_DRIVERS_EMPTY.GetValue() ); RString Driver; - RageMovieTexture *ret = NULL; + RageMovieTexture *ret = nullptr; for( unsigned i=0; ret== nullptr && iWarn( "Couldn't get device interface from plugin interface." ); - m_Interface = NULL; + m_Interface = nullptr; return false; } @@ -117,7 +117,7 @@ bool HIDDevice::Open( io_object_t device ) { PrintIOErr( ret, "Failed to open the interface." ); CALL( m_Interface, Release ); - m_Interface = NULL; + m_Interface = nullptr; return false; } @@ -133,9 +133,9 @@ bool HIDDevice::Open( io_object_t device ) { PrintIOErr( ret, "Failed to create the queue." ); CALL( m_Queue, Release ); - m_Queue = NULL; + m_Queue = nullptr; CALL( m_Interface, Release ); - m_Interface = NULL; + m_Interface = nullptr; return false; } diff --git a/src/archutils/Unix/Backtrace.cpp b/src/archutils/Unix/Backtrace.cpp index 50d4e1ff17..865f155ee1 100644 --- a/src/archutils/Unix/Backtrace.cpp +++ b/src/archutils/Unix/Backtrace.cpp @@ -137,8 +137,8 @@ static int get_readable_ranges( const void **starts, const void **ends, int size close(fd); - *starts++ = NULL; - *ends++ = NULL; + *starts++ = nullptr; + *ends++ = nullptr; return got; } @@ -157,7 +157,7 @@ static int find_address( const void *p, const void **starts, const void **ends ) return -1; } -static void *SavedStackPointer = NULL; +static void *SavedStackPointer = nullptr; void InitializeBacktrace() { @@ -364,7 +364,7 @@ static void do_backtrace( const void **buf, size_t size, const BacktraceContext frame = frame->link; } - buf[i] = NULL; + buf[i] = nullptr; } #if defined(CPU_X86) @@ -396,7 +396,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) { ctx = &CurrentCtx; - CurrentCtx.ip = NULL; + CurrentCtx.ip = nullptr; CurrentCtx.bp = __builtin_frame_address(0); CurrentCtx.sp = __builtin_frame_address(0); CurrentCtx.pid = GetCurrentThreadId(); @@ -523,7 +523,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) if( g_StackPointer == 0 ) { buf[0] = BACKTRACE_METHOD_NOT_AVAILABLE; - buf[1] = NULL; + buf[1] = nullptr; return; } @@ -532,7 +532,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) { ctx = &CurrentCtx; - CurrentCtx.ip = NULL; + CurrentCtx.ip = nullptr; CurrentCtx.bp = __builtin_frame_address(0); CurrentCtx.sp = __builtin_frame_address(0); } @@ -562,7 +562,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) { /* There isn't much we can do if this is the case. The stack should be read/write * and since it isn't, give up. */ - buf[i] = NULL; + buf[i] = nullptr; return; } const Frame *frame = (Frame *)ctx->sp; @@ -620,7 +620,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) frame = frame->link; } - buf[i] = NULL; + buf[i] = nullptr; } #undef PROT_RW #undef PROT_EXE @@ -656,7 +656,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) /* __builtin_frame_address is broken on OS X; it sometimes returns bogus results. */ register void *r1 __asm__ ("r1"); CurrentCtx.FramePtr = (const Frame *) r1; - CurrentCtx.PC = NULL; + CurrentCtx.PC = nullptr; } const Frame *frame = ctx->FramePtr; @@ -673,7 +673,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) frame = frame->stackPointer; } - buf[i] = NULL; + buf[i] = nullptr; } #elif defined(BACKTRACE_METHOD_PPC_LINUX) @@ -704,7 +704,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) register void *r1 __asm__("1"); CurrentCtx.FramePtr = (const Frame *)r1; - CurrentCtx.PC = NULL; + CurrentCtx.PC = nullptr; } const Frame *frame = (const Frame *)ctx->FramePtr; @@ -718,7 +718,7 @@ void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) if( frame->linkReg ) buf[i++] = frame->linkReg; } - buf[i] = NULL; + buf[i] = nullptr; } #else @@ -729,7 +729,7 @@ void InitializeBacktrace() { } void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx ) { buf[0] = BACKTRACE_METHOD_NOT_AVAILABLE; - buf[1] = NULL; + buf[1] = nullptr; } #endif diff --git a/src/archutils/Unix/Backtrace.h b/src/archutils/Unix/Backtrace.h index 0d9261b739..0646c7bd50 100644 --- a/src/archutils/Unix/Backtrace.h +++ b/src/archutils/Unix/Backtrace.h @@ -34,7 +34,7 @@ void InitializeBacktrace(); * null-terminated. If ctx is NULL, retrieve the current backtrace; otherwise * retrieve a backtrace for the given context. (Not all backtracers may * support contexts.) */ -void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx = NULL ); +void GetBacktrace( const void **buf, size_t size, const BacktraceContext *ctx = nullptr ); /* Set up a BacktraceContext to get a backtrace for a thread. ThreadID may * not be the current thread. True is returned on success, false on failure. */ diff --git a/src/archutils/Unix/BacktraceNames.cpp b/src/archutils/Unix/BacktraceNames.cpp index 8bb9298742..f5d586d35c 100644 --- a/src/archutils/Unix/BacktraceNames.cpp +++ b/src/archutils/Unix/BacktraceNames.cpp @@ -242,8 +242,8 @@ void BacktraceNames::FromAddr( const void *p ) const struct load_command *cmd = (struct load_command *) &header[1]; unsigned long diff = 0xffffffff; - const char *dli_sname = NULL; - void *dli_saddr = NULL; + const char *dli_sname = nullptr; + void *dli_saddr = nullptr; for( unsigned long i = 0; i < header->ncmds; i++, cmd = next_load_command(cmd) ) { diff --git a/src/archutils/Unix/CrashHandlerChild.cpp b/src/archutils/Unix/CrashHandlerChild.cpp index 754efb4de3..40a971d75f 100644 --- a/src/archutils/Unix/CrashHandlerChild.cpp +++ b/src/archutils/Unix/CrashHandlerChild.cpp @@ -30,7 +30,7 @@ extern const char *const version_time; bool child_read( int fd, void *p, int size ); -const char *g_pCrashHandlerArgv0 = NULL; +const char *g_pCrashHandlerArgv0 = nullptr; static void output_stack_trace( FILE *out, const void **BacktracePointers ) diff --git a/src/archutils/Unix/SignalHandler.cpp b/src/archutils/Unix/SignalHandler.cpp index 4e30c229c5..f9f2011413 100644 --- a/src/archutils/Unix/SignalHandler.cpp +++ b/src/archutils/Unix/SignalHandler.cpp @@ -115,7 +115,7 @@ static void *CreateStack( int size ) * * mmap entries always show up individually in /proc/#/maps. We could use posix_memalign as * a fallback, but we'd have to put a barrier page on both sides to guarantee that. */ - char *p = NULL; + char *p = nullptr; p = (char *) mmap( NULL, size+PageSize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0 ); if( p == (void *) -1 ) @@ -156,7 +156,7 @@ void SignalHandler::OnClose( handler h ) /* Allocate a separate signal stack. This makes the crash handler work * if we run out of stack space. */ const int AltStackSize = 1024*64; - void *p = NULL; + void *p = nullptr; if( bUseAltSigStack ) p = CreateStack( AltStackSize ); @@ -169,7 +169,7 @@ void SignalHandler::OnClose( handler h ) if( sigaltstack( &ss, NULL ) == -1 ) { LOG->Info( "sigaltstack failed: %s", strerror(errno) ); - p = NULL; /* no SA_ONSTACK */ + p = nullptr; /* no SA_ONSTACK */ } } diff --git a/src/archutils/Unix/X11Helper.cpp b/src/archutils/Unix/X11Helper.cpp index 8711da0f97..5ff09dccc0 100644 --- a/src/archutils/Unix/X11Helper.cpp +++ b/src/archutils/Unix/X11Helper.cpp @@ -5,7 +5,7 @@ #include "Preference.h" #include "PrefsManager.h" // XXX: only used for m_bShowMouseCursor -aj -Display *X11Helper::Dpy = NULL; +Display *X11Helper::Dpy = nullptr; Window X11Helper::Win = None; static int ErrorCallback( Display*, XErrorEvent* ); @@ -31,7 +31,7 @@ void X11Helper::CloseXConnection() DEBUG_ASSERT( Dpy != nullptr ); DEBUG_ASSERT( Win == None ); XCloseDisplay( Dpy ); - Dpy = NULL; + Dpy = nullptr; } bool X11Helper::MakeWindow( Window &win, int screenNum, int depth, Visual *visual, int width, int height, bool overrideRedirect ) diff --git a/src/archutils/Win32/CommandLine.cpp b/src/archutils/Win32/CommandLine.cpp index 903534da79..7dcbe706d6 100644 --- a/src/archutils/Win32/CommandLine.cpp +++ b/src/archutils/Win32/CommandLine.cpp @@ -9,7 +9,7 @@ int GetWin32CmdLine( char** &argv ) { char *pCmdLine = GetCommandLine(); int argc = 0; - argv = NULL; + argv = nullptr; int i = 0; while( pCmdLine[i] ) diff --git a/src/archutils/Win32/Crash.cpp b/src/archutils/Win32/Crash.cpp index a0cf183004..0985291def 100644 --- a/src/archutils/Win32/Crash.cpp +++ b/src/archutils/Win32/Crash.cpp @@ -73,7 +73,7 @@ static void GetReason( const EXCEPTION_RECORD *pRecord, CrashInfo *crash ) strcpy( crash->m_CrashReason, reason ); } -static HWND g_hForegroundWnd = NULL; +static HWND g_hForegroundWnd = nullptr; void CrashHandler::SetForegroundWindow( HWND hWnd ) { g_hForegroundWnd = hWnd; @@ -105,7 +105,7 @@ bool StartChild( HANDLE &hProcess, HANDLE &hToStdin, HANDLE &hFromStdout ) SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = true; - sa.lpSecurityDescriptor = NULL; + sa.lpSecurityDescriptor = nullptr; CreatePipe( &si.hStdInput, &hToStdin, &sa, 0 ); CreatePipe( &hFromStdout, &si.hStdOutput, &sa, 0 ); @@ -166,7 +166,7 @@ static const char *CrashGetModuleBaseName(HMODULE hmod, char *pszBaseName) pszFile = pszBaseName; - char *period = NULL; + char *period = nullptr; while( *pszFile++ ) if( pszFile[-1]=='.' ) period = pszFile-1; @@ -299,7 +299,7 @@ static long MainExceptionHandler( EXCEPTION_POINTERS *pExc ) /* If we get here, then we've been called recursively, which means we * crashed. If InHere is greater than 1, then we crashed after writing * the crash dump; say so. */ - SetUnhandledExceptionFilter(NULL); + SetUnhandledExceptionFilter(nullptr); MessageBox( NULL, InHere == 1? "The error reporting interface has crashed.\n": @@ -345,7 +345,7 @@ static long MainExceptionHandler( EXCEPTION_POINTERS *pExc ) InHere = false; - SetUnhandledExceptionFilter( NULL ); + SetUnhandledExceptionFilter(nullptr); /* Forcibly terminate; if we keep going, we'll try to shut down threads and * do other things that may deadlock, which is confusing for users. */ @@ -474,7 +474,7 @@ void CrashHandler::do_backtrace( const void **buf, size_t size, LDT_ENTRY sel; if( !GetThreadSelectorEntry( hThread, pContext->SegFs, &sel ) ) { - *buf = NULL; + *buf = nullptr; return; } @@ -523,7 +523,7 @@ void CrashHandler::do_backtrace( const void **buf, size_t size, lpAddr += 4; } while( ReadProcessMemory(hProcess, lpAddr-4, &data, 4, NULL)); - *buf = NULL; + *buf = nullptr; } // Trigger the crash handler. This works even in the debugger. diff --git a/src/archutils/Win32/CrashHandlerChild.cpp b/src/archutils/Win32/CrashHandlerChild.cpp index 63272a3713..7930d66681 100644 --- a/src/archutils/Win32/CrashHandlerChild.cpp +++ b/src/archutils/Win32/CrashHandlerChild.cpp @@ -84,7 +84,7 @@ namespace VDDebugInfo const unsigned char *src = (const unsigned char *) pctx->sRawBlock.data(); - pctx->pRVAHeap = NULL; + pctx->pRVAHeap = nullptr; static const char *header = "symbolic debug information"; if( memcmp(src, header, strlen(header)) ) @@ -119,7 +119,7 @@ namespace VDDebugInfo return true; pctx->sRawBlock = RString(); - pctx->pRVAHeap = NULL; + pctx->pRVAHeap = nullptr; GetVDIPath( pctx->sFilename, ARRAYLEN(pctx->sFilename) ); pctx->sError = RString(); @@ -623,7 +623,7 @@ CrashDialog::CrashDialog( const RString &sCrashReport, const CompleteCrashData & m_CrashData( CrashData ) { LoadLocalizedStrings(); - m_pPost = NULL; + m_pPost = nullptr; } CrashDialog::~CrashDialog() @@ -656,7 +656,7 @@ BOOL CrashDialog::HandleMessage( UINT msg, WPARAM wParam, LPARAM lParam ) { HDC hdc = (HDC)wParam; HWND hwndStatic = (HWND)lParam; - HBRUSH hbr = NULL; + HBRUSH hbr = nullptr; // TODO: Change any attributes of the DC here switch( GetDlgCtrlID(hwndStatic) ) @@ -839,7 +839,7 @@ void ChildProcess() // Now that we've done that, the process is gone. Don't use g_hParent. CloseHandle( SymbolLookup::g_hParent ); - SymbolLookup::g_hParent = NULL; + SymbolLookup::g_hParent = nullptr; CrashDialog cd( sCrashReport, Data ); #if defined(AUTOMATED_CRASH_REPORTS) diff --git a/src/archutils/Win32/CrashHandlerInternal.h b/src/archutils/Win32/CrashHandlerInternal.h index 895d5aa043..905b7e7a93 100644 --- a/src/archutils/Win32/CrashHandlerInternal.h +++ b/src/archutils/Win32/CrashHandlerInternal.h @@ -18,7 +18,7 @@ struct CrashInfo m_CrashReason[0] = 0; memset( m_AlternateThreadBacktrace, 0, sizeof(m_AlternateThreadBacktrace) ); memset( m_AlternateThreadName, 0, sizeof(m_AlternateThreadName) ); - m_BacktracePointers[0] = NULL; + m_BacktracePointers[0] = nullptr; } }; diff --git a/src/archutils/Win32/CrashHandlerNetworking.cpp b/src/archutils/Win32/CrashHandlerNetworking.cpp index f83ca962f9..6b18c4aa8e 100644 --- a/src/archutils/Win32/CrashHandlerNetworking.cpp +++ b/src/archutils/Win32/CrashHandlerNetworking.cpp @@ -172,8 +172,8 @@ NetworkStream_Win32::NetworkStream_Win32(): m_State = STATE_IDLE; m_Socket = NULL; #if defined(WINDOWS) - m_hResolve = NULL; - m_hResolveHwnd = NULL; + m_hResolve = nullptr; + m_hResolveHwnd = nullptr; m_hCompletionEvent = CreateEvent( NULL, true, false, NULL ); #endif } @@ -355,7 +355,7 @@ void NetworkStream_Win32::Open( const RString &sHost, int iPort, ConnectionType m_iPort = iPort; // Look up the hostname. - hostent *pHost = NULL; + hostent *pHost = nullptr; char pBuf[MAXGETHOSTSTRUCT]; { pHost = (hostent *) pBuf; @@ -374,8 +374,8 @@ void NetworkStream_Win32::Open( const RString &sHost, int iPort, ConnectionType mw.Run(); m_Mutex.Lock(); - m_hResolve = NULL; - m_hResolveHwnd = NULL; + m_hResolve = nullptr; + m_hResolveHwnd = nullptr; if( m_State == STATE_CANCELLED ) { m_Mutex.Unlock(); diff --git a/src/archutils/Win32/DialogUtil.cpp b/src/archutils/Win32/DialogUtil.cpp index 3b741ae16c..ed11e30b83 100644 --- a/src/archutils/Win32/DialogUtil.cpp +++ b/src/archutils/Win32/DialogUtil.cpp @@ -9,7 +9,7 @@ // pLogFont->nHeight is interpreted as PointSize * 10 static HFONT CreatePointFontIndirect(const LOGFONT* lpLogFont) { - HDC hDC = ::GetDC(NULL); + HDC hDC = ::GetDC(nullptr); // convert nPointSize to logical units based on pDC LOGFONT logFont = *lpLogFont; diff --git a/src/archutils/Win32/GetFileInformation.cpp b/src/archutils/Win32/GetFileInformation.cpp index 880c8f42b3..dd2b5a398f 100644 --- a/src/archutils/Win32/GetFileInformation.cpp +++ b/src/archutils/Win32/GetFileInformation.cpp @@ -118,9 +118,9 @@ bool GetProcessFileName( uint32_t iProcessID, RString &sName ) // This method only works in NT/2K/XP. do { - static HINSTANCE hPSApi = NULL; + static HINSTANCE hPSApi = nullptr; typedef DWORD (WINAPI* pfnGetProcessImageFileNameA)(HANDLE hProcess, LPSTR lpImageFileName, DWORD nSize); - static pfnGetProcessImageFileNameA pGetProcessImageFileName = NULL; + static pfnGetProcessImageFileNameA pGetProcessImageFileName = nullptr; static bool bTried = false; if( !bTried ) diff --git a/src/archutils/Win32/GraphicsWindow.cpp b/src/archutils/Win32/GraphicsWindow.cpp index f6d245a536..c12a5500ec 100644 --- a/src/archutils/Win32/GraphicsWindow.cpp +++ b/src/archutils/Win32/GraphicsWindow.cpp @@ -22,7 +22,7 @@ static HDC g_HDC; static VideoModeParams g_CurrentParams; static bool g_bResolutionChanged = false; static bool g_bHasFocus = true; -static HICON g_hIcon = NULL; +static HICON g_hIcon = nullptr; static bool m_bWideWindowClass; static bool g_bD3D = false; @@ -36,7 +36,7 @@ static RString GetNewWindow() { HWND h = GetForegroundWindow(); if( h == nullptr ) - return "(NULL)"; + return "(nullptr)"; DWORD iProcessID; GetWindowThreadProcessId( h, &iProcessID ); @@ -110,7 +110,7 @@ static LRESULT CALLBACK GraphicsWindow_WndProc( HWND hWnd, UINT msg, WPARAM wPar case WM_SETCURSOR: if( !g_CurrentParams.windowed ) { - SetCursor( NULL ); + SetCursor(nullptr); return 1; } break; @@ -322,7 +322,7 @@ void GraphicsWindow::CreateGraphicsWindow( const VideoModeParams &p, bool bForce { SetClassLong( g_hWndMain, GCL_HICON, (LONG) LoadIcon(NULL,IDI_APPLICATION) ); DestroyIcon( g_hIcon ); - g_hIcon = NULL; + g_hIcon = nullptr; } g_hIcon = IconFromFile( p.sIconFile ); if( g_hIcon != nullptr ) @@ -376,7 +376,7 @@ void GraphicsWindow::DestroyGraphicsWindow() if( g_HDC != nullptr ) { ReleaseDC( g_hWndMain, g_HDC ); - g_HDC = NULL; + g_HDC = nullptr; } CHECKPOINT; @@ -384,7 +384,7 @@ void GraphicsWindow::DestroyGraphicsWindow() if( g_hWndMain != nullptr ) { DestroyWindow( g_hWndMain ); - g_hWndMain = NULL; + g_hWndMain = nullptr; CrashHandler::SetForegroundWindow( g_hWndMain ); } @@ -393,7 +393,7 @@ void GraphicsWindow::DestroyGraphicsWindow() if( g_hIcon != nullptr ) { DestroyIcon( g_hIcon ); - g_hIcon = NULL; + g_hIcon = nullptr; } CHECKPOINT; diff --git a/src/archutils/Win32/USB.cpp b/src/archutils/Win32/USB.cpp index ab02bda84a..fac00e8c08 100644 --- a/src/archutils/Win32/USB.cpp +++ b/src/archutils/Win32/USB.cpp @@ -1,246 +1,246 @@ -#include "global.h" -#include "USB.h" -#include "RageLog.h" -#include "RageUtil.h" -#include "archutils/Win32/ErrorStrings.h" - -#if defined(_MSC_VER) -#pragma comment(lib, "archutils/Win32/ddk/setupapi.lib") -#pragma comment(lib, "archutils/Win32/ddk/hid.lib") -#endif - -extern "C" { -#include "archutils/Win32/ddk/setupapi.h" -/* Quiet header warning: */ -#include "archutils/Win32/ddk/hidsdi.h" -} - -static RString GetUSBDevicePath( int iNum ) -{ - GUID guid; - HidD_GetHidGuid( &guid ); - - HDEVINFO DeviceInfo = SetupDiGetClassDevs( &guid, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE) ); - - SP_DEVICE_INTERFACE_DATA DeviceInterface; - DeviceInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - - if( !SetupDiEnumDeviceInterfaces (DeviceInfo, - NULL, &guid, iNum, &DeviceInterface) ) - { - SetupDiDestroyDeviceInfoList( DeviceInfo ); - return RString(); - } - - unsigned long iSize; - SetupDiGetDeviceInterfaceDetail( DeviceInfo, &DeviceInterface, NULL, 0, &iSize, 0 ); - - PSP_INTERFACE_DEVICE_DETAIL_DATA DeviceDetail = (PSP_INTERFACE_DEVICE_DETAIL_DATA) malloc( iSize ); - DeviceDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA); - - RString sRet; - if( SetupDiGetDeviceInterfaceDetail(DeviceInfo, &DeviceInterface, - DeviceDetail, iSize, &iSize, NULL) ) - sRet = DeviceDetail->DevicePath; - free( DeviceDetail ); - - SetupDiDestroyDeviceInfoList( DeviceInfo ); - return sRet; -} - -bool USBDevice::Open( int iVID, int iPID, int iBlockSize, int iNum, void (*pfnInit)(HANDLE) ) -{ - DWORD iIndex = 0; - - RString path; - while( (path = GetUSBDevicePath(iIndex++)) != "" ) - { - HANDLE h = CreateFile( path, GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); - - if( h == INVALID_HANDLE_VALUE ) - continue; - - HIDD_ATTRIBUTES attr; - if( !HidD_GetAttributes(h, &attr) ) - { - CloseHandle( h ); - continue; - } - - if( (iVID != -1 && attr.VendorID != iVID) || - (iPID != -1 && attr.ProductID != iPID) ) - { - CloseHandle( h ); - continue; /* This isn't it. */ - } - - /* The VID and PID match. */ - if( iNum-- > 0 ) - { - CloseHandle( h ); - continue; - } - - if( pfnInit ) - pfnInit( h ); - CloseHandle(h); - - m_IO.Open( path, iBlockSize ); - return true; - } - - return false; -} - -bool USBDevice::IsOpen() const -{ - return m_IO.IsOpen(); -} - - -int USBDevice::GetPadEvent() -{ - if( !IsOpen() ) - return -1; - - long iBuf; - if( m_IO.read(&iBuf) <= 0 ) - return -1; - - return iBuf; -} - -WindowsFileIO::WindowsFileIO() -{ - ZeroMemory( &m_Overlapped, sizeof(m_Overlapped) ); - m_Handle = INVALID_HANDLE_VALUE; - m_pBuffer = NULL; -} - -WindowsFileIO::~WindowsFileIO() -{ - if( m_Handle != INVALID_HANDLE_VALUE ) - CloseHandle( m_Handle ); - delete[] m_pBuffer; -} - -bool WindowsFileIO::Open( RString path, int iBlockSize ) -{ - LOG->Trace( "WindowsFileIO::open(%s)", path.c_str() ); - m_iBlockSize = iBlockSize; - - if( m_pBuffer ) - delete[] m_pBuffer; - m_pBuffer = new char[m_iBlockSize]; - - if( m_Handle != INVALID_HANDLE_VALUE ) - CloseHandle( m_Handle ); - - m_Handle = CreateFile( path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL ); - - if( m_Handle == INVALID_HANDLE_VALUE ) - return false; - - queue_read(); - - return true; -} - -void WindowsFileIO::queue_read() -{ - /* Request feedback from the device. */ - unsigned long iRead; - ReadFile( m_Handle, m_pBuffer, m_iBlockSize, &iRead, &m_Overlapped ); -} - -int WindowsFileIO::finish_read( void *p ) -{ - LOG->Trace( "this %p, %p", this, p ); - /* We do; get the result. It'll go into the original m_pBuffer - * we supplied on the original call; that's why m_pBuffer is a - * member instead of a local. */ - unsigned long iCnt; - int iRet = GetOverlappedResult( m_Handle, &m_Overlapped, &iCnt, FALSE ); - - if( iRet == 0 && (GetLastError() == ERROR_IO_PENDING || GetLastError() == ERROR_IO_INCOMPLETE) ) - return -1; - - queue_read(); - - if( iRet == 0 ) - { - LOG->Warn( werr_ssprintf(GetLastError(), "Error reading USB device") ); - return -1; - } - - memcpy( p, m_pBuffer, iCnt ); - return iCnt; -} - -int WindowsFileIO::read( void *p ) -{ - LOG->Trace( "WindowsFileIO::read()" ); - - /* See if we have a response for our request (which we may - * have made on a previous call): */ - if( WaitForSingleObjectEx(m_Handle, 0, TRUE) == WAIT_TIMEOUT ) - return -1; - - return finish_read(p); -} - -int WindowsFileIO::read_several(const vector &sources, void *p, int &actual, float timeout) -{ - HANDLE *Handles = new HANDLE[sources.size()]; - for( unsigned i = 0; i < sources.size(); ++i ) - Handles[i] = sources[i]->m_Handle; - - int ret = WaitForMultipleObjectsEx( sources.size(), Handles, false, int(timeout * 1000), true); - delete[] Handles; - - if( ret == -1 ) - { - LOG->Trace( werr_ssprintf(GetLastError(), "WaitForMultipleObjectsEx failed") ); - return -1; - } - - if( ret >= int(WAIT_OBJECT_0) && ret < int(WAIT_OBJECT_0+sources.size()) ) - { - actual = ret - WAIT_OBJECT_0; - return sources[actual]->finish_read(p); - } - - return 0; -} - -bool WindowsFileIO::IsOpen() const -{ - return m_Handle != INVALID_HANDLE_VALUE; -} - -/* - * (c) 2002-2005 Glenn Maynard - * All rights reserved. - * - * 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, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "USB.h" +#include "RageLog.h" +#include "RageUtil.h" +#include "archutils/Win32/ErrorStrings.h" + +#if defined(_MSC_VER) +#pragma comment(lib, "archutils/Win32/ddk/setupapi.lib") +#pragma comment(lib, "archutils/Win32/ddk/hid.lib") +#endif + +extern "C" { +#include "archutils/Win32/ddk/setupapi.h" +/* Quiet header warning: */ +#include "archutils/Win32/ddk/hidsdi.h" +} + +static RString GetUSBDevicePath( int iNum ) +{ + GUID guid; + HidD_GetHidGuid( &guid ); + + HDEVINFO DeviceInfo = SetupDiGetClassDevs( &guid, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE) ); + + SP_DEVICE_INTERFACE_DATA DeviceInterface; + DeviceInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); + + if( !SetupDiEnumDeviceInterfaces (DeviceInfo, + NULL, &guid, iNum, &DeviceInterface) ) + { + SetupDiDestroyDeviceInfoList( DeviceInfo ); + return RString(); + } + + unsigned long iSize; + SetupDiGetDeviceInterfaceDetail( DeviceInfo, &DeviceInterface, NULL, 0, &iSize, 0 ); + + PSP_INTERFACE_DEVICE_DETAIL_DATA DeviceDetail = (PSP_INTERFACE_DEVICE_DETAIL_DATA) malloc( iSize ); + DeviceDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA); + + RString sRet; + if( SetupDiGetDeviceInterfaceDetail(DeviceInfo, &DeviceInterface, + DeviceDetail, iSize, &iSize, NULL) ) + sRet = DeviceDetail->DevicePath; + free( DeviceDetail ); + + SetupDiDestroyDeviceInfoList( DeviceInfo ); + return sRet; +} + +bool USBDevice::Open( int iVID, int iPID, int iBlockSize, int iNum, void (*pfnInit)(HANDLE) ) +{ + DWORD iIndex = 0; + + RString path; + while( (path = GetUSBDevicePath(iIndex++)) != "" ) + { + HANDLE h = CreateFile( path, GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); + + if( h == INVALID_HANDLE_VALUE ) + continue; + + HIDD_ATTRIBUTES attr; + if( !HidD_GetAttributes(h, &attr) ) + { + CloseHandle( h ); + continue; + } + + if( (iVID != -1 && attr.VendorID != iVID) || + (iPID != -1 && attr.ProductID != iPID) ) + { + CloseHandle( h ); + continue; /* This isn't it. */ + } + + /* The VID and PID match. */ + if( iNum-- > 0 ) + { + CloseHandle( h ); + continue; + } + + if( pfnInit ) + pfnInit( h ); + CloseHandle(h); + + m_IO.Open( path, iBlockSize ); + return true; + } + + return false; +} + +bool USBDevice::IsOpen() const +{ + return m_IO.IsOpen(); +} + + +int USBDevice::GetPadEvent() +{ + if( !IsOpen() ) + return -1; + + long iBuf; + if( m_IO.read(&iBuf) <= 0 ) + return -1; + + return iBuf; +} + +WindowsFileIO::WindowsFileIO() +{ + ZeroMemory( &m_Overlapped, sizeof(m_Overlapped) ); + m_Handle = INVALID_HANDLE_VALUE; + m_pBuffer = nullptr; +} + +WindowsFileIO::~WindowsFileIO() +{ + if( m_Handle != INVALID_HANDLE_VALUE ) + CloseHandle( m_Handle ); + delete[] m_pBuffer; +} + +bool WindowsFileIO::Open( RString path, int iBlockSize ) +{ + LOG->Trace( "WindowsFileIO::open(%s)", path.c_str() ); + m_iBlockSize = iBlockSize; + + if( m_pBuffer ) + delete[] m_pBuffer; + m_pBuffer = new char[m_iBlockSize]; + + if( m_Handle != INVALID_HANDLE_VALUE ) + CloseHandle( m_Handle ); + + m_Handle = CreateFile( path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL ); + + if( m_Handle == INVALID_HANDLE_VALUE ) + return false; + + queue_read(); + + return true; +} + +void WindowsFileIO::queue_read() +{ + /* Request feedback from the device. */ + unsigned long iRead; + ReadFile( m_Handle, m_pBuffer, m_iBlockSize, &iRead, &m_Overlapped ); +} + +int WindowsFileIO::finish_read( void *p ) +{ + LOG->Trace( "this %p, %p", this, p ); + /* We do; get the result. It'll go into the original m_pBuffer + * we supplied on the original call; that's why m_pBuffer is a + * member instead of a local. */ + unsigned long iCnt; + int iRet = GetOverlappedResult( m_Handle, &m_Overlapped, &iCnt, FALSE ); + + if( iRet == 0 && (GetLastError() == ERROR_IO_PENDING || GetLastError() == ERROR_IO_INCOMPLETE) ) + return -1; + + queue_read(); + + if( iRet == 0 ) + { + LOG->Warn( werr_ssprintf(GetLastError(), "Error reading USB device") ); + return -1; + } + + memcpy( p, m_pBuffer, iCnt ); + return iCnt; +} + +int WindowsFileIO::read( void *p ) +{ + LOG->Trace( "WindowsFileIO::read()" ); + + /* See if we have a response for our request (which we may + * have made on a previous call): */ + if( WaitForSingleObjectEx(m_Handle, 0, TRUE) == WAIT_TIMEOUT ) + return -1; + + return finish_read(p); +} + +int WindowsFileIO::read_several(const vector &sources, void *p, int &actual, float timeout) +{ + HANDLE *Handles = new HANDLE[sources.size()]; + for( unsigned i = 0; i < sources.size(); ++i ) + Handles[i] = sources[i]->m_Handle; + + int ret = WaitForMultipleObjectsEx( sources.size(), Handles, false, int(timeout * 1000), true); + delete[] Handles; + + if( ret == -1 ) + { + LOG->Trace( werr_ssprintf(GetLastError(), "WaitForMultipleObjectsEx failed") ); + return -1; + } + + if( ret >= int(WAIT_OBJECT_0) && ret < int(WAIT_OBJECT_0+sources.size()) ) + { + actual = ret - WAIT_OBJECT_0; + return sources[actual]->finish_read(p); + } + + return 0; +} + +bool WindowsFileIO::IsOpen() const +{ + return m_Handle != INVALID_HANDLE_VALUE; +} + +/* + * (c) 2002-2005 Glenn Maynard + * All rights reserved. + * + * 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, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * 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 OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/archutils/Win32/WindowIcon.cpp b/src/archutils/Win32/WindowIcon.cpp index cd52b87bb0..fcaff50846 100644 --- a/src/archutils/Win32/WindowIcon.cpp +++ b/src/archutils/Win32/WindowIcon.cpp @@ -77,7 +77,7 @@ HICON IconFromSurface( const RageSurface *pSrcImg ) HICON icon = CreateIconFromResourceEx( (BYTE *) pBitmap, iSize + iSizeImage, TRUE, 0x00030000, pImg->w, pImg->h, LR_DEFAULTCOLOR ); delete pImg; - pImg = NULL; + pImg = nullptr; free( pBitmap ); if( icon == nullptr ) diff --git a/src/archutils/Win32/WindowsDialogBox.cpp b/src/archutils/Win32/WindowsDialogBox.cpp index 0fe1714eca..8a7928f5d3 100644 --- a/src/archutils/Win32/WindowsDialogBox.cpp +++ b/src/archutils/Win32/WindowsDialogBox.cpp @@ -3,7 +3,7 @@ WindowsDialogBox::WindowsDialogBox() { - m_hWnd = NULL; + m_hWnd = nullptr; } void WindowsDialogBox::Run( int iDialog )