networking

This commit is contained in:
2025-07-13 15:47:42 +03:00
parent f5b26be510
commit a9c28b8940
345 changed files with 142130 additions and 174 deletions
+16
View File
@@ -0,0 +1,16 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Base class for various game menu screens
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "BaseMenu.h"
// Static data
HGAMEFONT g_hMenuFont = 0;
uint64 g_ulLastReturnKeyTick = 0;
uint64 g_ulLastKeyDownTick = 0;
uint64 g_ulLastKeyUpTick = 0;
+248
View File
@@ -0,0 +1,248 @@
//========= Copyright (c) 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Base class for various game menu screens
//
// $NoKeywords: $
//=============================================================================
#ifndef BASEMENU_H
#define BASEMENU_H
#include <string>
#include <vector>
#include "GameEngine.h"
#include "SpaceWar.h"
#include "SpaceWarClient.h"
#include "steam/isteamcontroller.h"
#define MENU_FONT_HEIGHT 24
#define MENU_ITEM_PADDING 12
extern HGAMEFONT g_hMenuFont;
extern uint64 g_ulLastReturnKeyTick;
extern uint64 g_ulLastKeyDownTick;
extern uint64 g_ulLastKeyUpTick;
template <class T> class CBaseMenu
{
public:
// Typedef for menu items
typedef std::pair<std::string, T> MenuItem_t;
// Constructor
CBaseMenu( IGameEngine *pGameEngine )
{
m_pGameEngine = pGameEngine;
m_uSelectedItem = 0;
m_bSelectionPushed = false;
if ( !g_hMenuFont )
{
g_hMenuFont = pGameEngine->HCreateFont( MENU_FONT_HEIGHT, FW_BOLD, false, "Arial" );
if ( !g_hMenuFont )
OutputDebugString( "Menu font was not created properly, text won't draw\n" );
}
}
// Destructor
virtual ~CBaseMenu() { }
// Sets a heading for the menu
void SetHeading( const char *pchHeading )
{
m_sHeading = pchHeading;
}
// Clear all menu entries
void ClearMenuItems()
{
m_VecMenuItems.clear();
m_uSelectedItem = 0;
}
// Add a menu item to the menu
void AddMenuItem( MenuItem_t item )
{
m_VecMenuItems.push_back( item );
}
void PushSelectedItem()
{
if ( m_VecMenuItems.size() )
{
m_bSelectionPushed = true;
m_selection = m_VecMenuItems[m_uSelectedItem].second;
}
}
void PopSelectedItem()
{
if ( m_bSelectionPushed )
{
m_bSelectionPushed = false;
// find the item and set it as selected if it exists
for ( unsigned int i = 0; i < m_VecMenuItems.size(); i++ )
{
if ( !memcmp( &m_VecMenuItems[i].second, &m_selection, sizeof( m_selection ) ) )
{
m_uSelectedItem = i;
break;
}
}
}
}
// Run a frame + render
void RunFrame()
{
// Note: The below code uses globals that are shared across all menus to avoid double
// key press registration, this is so that when you do something like hit return in the pause
// menu to "go back to main menu" you don't end up immediately registering a return in the
// main menu afterwards.
// check if the enter key is down, if it is take action
if ( m_pGameEngine->BIsKeyDown( VK_RETURN ) ||
m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_MenuSelect ) )
{
uint64 ulCurrentTickCount = m_pGameEngine->GetGameTickCount();
if ( ulCurrentTickCount - 220 > g_ulLastReturnKeyTick )
{
g_ulLastReturnKeyTick = ulCurrentTickCount;
if ( m_uSelectedItem < m_VecMenuItems.size() )
{
SpaceWarClient()->OnMenuSelection( m_VecMenuItems[m_uSelectedItem].second );
return;
}
}
}
// Check if we need to change the selected menu item
else if ( m_pGameEngine->BIsKeyDown( VK_DOWN ) ||
m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_MenuDown ) )
{
uint64 ulCurrentTickCount = m_pGameEngine->GetGameTickCount();
if ( ulCurrentTickCount - 140 > g_ulLastKeyDownTick )
{
g_ulLastKeyDownTick = ulCurrentTickCount;
if ( m_uSelectedItem < m_VecMenuItems.size() - 1 )
m_uSelectedItem++;
else
m_uSelectedItem = 0;
}
}
else if ( m_pGameEngine->BIsKeyDown( VK_UP ) ||
m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_MenuUp ) )
{
uint64 ulCurrentTickCount = m_pGameEngine->GetGameTickCount();
if ( ulCurrentTickCount - 140 > g_ulLastKeyUpTick )
{
g_ulLastKeyUpTick = ulCurrentTickCount;
if ( m_uSelectedItem > 0 )
m_uSelectedItem--;
else
m_uSelectedItem = (uint32)m_VecMenuItems.size() - 1;
}
}
Render();
}
// Render the menu
virtual void Render()
{
const int32 iMaxMenuItems = 14;
int32 iNumItems = (int32)m_VecMenuItems.size();
uint32 uBoxHeight = MIN( iNumItems, iMaxMenuItems ) * ( MENU_FONT_HEIGHT + MENU_ITEM_PADDING );
uint32 yPos = m_pGameEngine->GetViewportHeight()/2 - uBoxHeight/2;
RECT rect;
rect.top = yPos;
rect.bottom = yPos + MENU_FONT_HEIGHT + MENU_ITEM_PADDING;
rect.left = 0;
rect.right = m_pGameEngine->GetViewportWidth();
char rgchBuffer[256];
if ( m_sHeading.length() )
{
DWORD dwColor = D3DCOLOR_ARGB( 255, 255, 128, 128 );
RECT rectHeader;
rectHeader.top = 10;
rectHeader.bottom = rectHeader.top + MENU_FONT_HEIGHT + ( MENU_ITEM_PADDING * 2 );
rectHeader.left = 0;
rectHeader.right = m_pGameEngine->GetViewportWidth();
m_pGameEngine->BDrawString( g_hMenuFont, rectHeader, dwColor, TEXTPOS_CENTER|TEXTPOS_VCENTER, m_sHeading.c_str() );
}
int32 iStartItem = 0;
int32 iEndItem = iNumItems;
if ( iNumItems > iMaxMenuItems )
{
iStartItem = MAX( (int32)m_uSelectedItem - iMaxMenuItems/2, 0 );
iEndItem = MIN( iStartItem + iMaxMenuItems, iNumItems );
}
if ( iStartItem > 0 )
{
// Draw ... Scroll Up ...
DWORD dwColor = D3DCOLOR_ARGB( 255, 255, 255, 255 );
m_pGameEngine->BDrawString( g_hMenuFont, rect, dwColor, TEXTPOS_CENTER|TEXTPOS_VCENTER, "... Scroll Up ..." );
rect.top = rect.bottom;
rect.bottom += MENU_FONT_HEIGHT + MENU_ITEM_PADDING;
}
for( int32 i=iStartItem; i<iEndItem; ++i )
{
// Empty strings can be used to space menus, they don't get drawn or selected
if ( strlen( m_VecMenuItems[i].first.c_str() ) > 0 )
{
DWORD dwColor;
if ( i == m_uSelectedItem )
{
dwColor = D3DCOLOR_ARGB( 255, 25, 200, 25 );
sprintf_safe( rgchBuffer, "{ %s }", m_VecMenuItems[i].first.c_str() );
}
else
{
dwColor = D3DCOLOR_ARGB( 255, 255, 255, 255 );
sprintf_safe( rgchBuffer, "%s", m_VecMenuItems[i].first.c_str() );
}
m_pGameEngine->BDrawString( g_hMenuFont, rect, dwColor, TEXTPOS_CENTER|TEXTPOS_VCENTER, rgchBuffer );
}
rect.top = rect.bottom;
rect.bottom += MENU_FONT_HEIGHT + MENU_ITEM_PADDING;
}
if ( iNumItems > iEndItem )
{
// Draw ... Scroll Down ...
DWORD dwColor = D3DCOLOR_ARGB( 255, 255, 255, 255 );
m_pGameEngine->BDrawString( g_hMenuFont, rect, dwColor, TEXTPOS_CENTER|TEXTPOS_VCENTER, "... Scroll Down ..." );
rect.top = rect.bottom;
rect.bottom += MENU_FONT_HEIGHT + MENU_ITEM_PADDING;
}
}
private:
// Game engine instance
IGameEngine *m_pGameEngine;
// Heading
std::string m_sHeading;
// Vector of menu options
std::vector< MenuItem_t > m_VecMenuItems;
// Currently selected item index
uint32 m_uSelectedItem;
// pushed selection
bool m_bSelectionPushed;
T m_selection;
};
#endif // MAINMENU_H
Binary file not shown.
Binary file not shown.
+58
View File
@@ -0,0 +1,58 @@
This package was debianized by Peter Cernak <pce@users.sourceforge.net> on
Sun, 5 Sep 2004 17:10:26 +0200.
It was downloaded from http://dejavu.sourceforge.net/
Upstream Authors: Stepan Roh <src@users.sourceforge.net> (original author),
see /usr/share/doc/ttf-dejavu/AUTHORS for full list
Copyright:
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
+168
View File
@@ -0,0 +1,168 @@
//========= Copyright 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking friends list
//
//=============================================================================
#include "stdafx.h"
#include "Friends.h"
#include "BaseMenu.h"
#include <math.h>
#include <vector>
#include <algorithm>
//-----------------------------------------------------------------------------
// Purpose: Menu that shows your friends
//-----------------------------------------------------------------------------
class CFriendsListMenu : public CBaseMenu<FriendsListMenuItem_t>
{
static const FriendsListMenuItem_t k_menuItemEmpty;
public:
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CFriendsListMenu( IGameEngine *pGameEngine ) : CBaseMenu<FriendsListMenuItem_t>( pGameEngine )
{
}
//-----------------------------------------------------------------------------
// Purpose: Creates friends list menu
//-----------------------------------------------------------------------------
void Rebuild()
{
PushSelectedItem();
ClearMenuItems();
AddMenuItem( CFriendsListMenu::MenuItem_t( "Friends List", k_menuItemEmpty ) );
// First add pending incoming requests
AddFriendsByFlag( k_EFriendFlagFriendshipRequested, "Incoming Friend Requests" );
// Add each Tag group and record the users with tags
std::vector<CSteamID> vecTaggedSteamIDs;
int nFriendsGroups = SteamFriends()->GetFriendsGroupCount();
for ( int iFG = 0; iFG < nFriendsGroups; iFG++ )
{
FriendsGroupID_t friendsGroupID = SteamFriends()->GetFriendsGroupIDByIndex( iFG );
if ( friendsGroupID == k_FriendsGroupID_Invalid )
continue;
int nFriendsGroupMemberCount = SteamFriends()->GetFriendsGroupMembersCount( friendsGroupID );
if ( !nFriendsGroupMemberCount )
continue;
const char *pszFriendsGroupName = SteamFriends()->GetFriendsGroupName( friendsGroupID );
if ( pszFriendsGroupName == NULL )
pszFriendsGroupName = "";
AddMenuItem( CFriendsListMenu::MenuItem_t( "", k_menuItemEmpty ) );
AddMenuItem( CFriendsListMenu::MenuItem_t( pszFriendsGroupName, k_menuItemEmpty ) );
std::vector<CSteamID> vecSteamIDMembers( nFriendsGroupMemberCount );
SteamFriends()->GetFriendsGroupMembersList( friendsGroupID, &vecSteamIDMembers[0], nFriendsGroupMemberCount );
for ( int iMember = 0; iMember < nFriendsGroupMemberCount; iMember++ )
{
const CSteamID &steamIDMember = vecSteamIDMembers[iMember];
AddFriendToMenu( steamIDMember );
vecTaggedSteamIDs.push_back( steamIDMember );
}
}
// Add the "normal" Friends category, filtering out the ones with tags
AddFriendsByFlag( k_EFriendFlagImmediate, "Friends", &vecTaggedSteamIDs );
// Finally add the pending outgoing requests
AddFriendsByFlag( k_EFriendFlagRequestingFriendship, "Outgoing Friend Requests" );
PopSelectedItem();
}
private:
void AddFriendsByFlag( int iFriendFlag, const char *pszName, std::vector<CSteamID> *pVecIgnoredSteamIDs = NULL )
{
int iFriendCount = SteamFriends()->GetFriendCount( iFriendFlag );
if ( !iFriendCount )
return;
AddMenuItem( CFriendsListMenu::MenuItem_t( "", k_menuItemEmpty ) );
AddMenuItem( CFriendsListMenu::MenuItem_t( pszName, k_menuItemEmpty ) );
for ( int iFriend = 0; iFriend < iFriendCount; iFriend++ )
{
CSteamID steamIDFriend = SteamFriends()->GetFriendByIndex( iFriend, iFriendFlag );
// This mimicks the Steam client's feature where it only shows
// untagged friends in the canonical Friends section by default
if ( pVecIgnoredSteamIDs && ( std::find( pVecIgnoredSteamIDs->begin(), pVecIgnoredSteamIDs->end(), steamIDFriend ) != pVecIgnoredSteamIDs->end() ) )
continue;
AddFriendToMenu( steamIDFriend );
}
}
void AddFriendToMenu( CSteamID steamIDFriend )
{
if ( !steamIDFriend.IsValid() )
return;
FriendsListMenuItem_t menuItemFriend = { steamIDFriend };
char szFriendNameBuffer[512] = { '\0' };
const char *pszFriendName = SteamFriends()->GetFriendPersonaName( steamIDFriend );
sprintf_safe( szFriendNameBuffer, "%s", pszFriendName );
const char *pszFriendNickname = SteamFriends()->GetPlayerNickname( steamIDFriend );
if ( pszFriendNickname )
{
sprintf_safe( szFriendNameBuffer, "%s (%s)", szFriendNameBuffer, pszFriendNickname );
}
AddMenuItem( CFriendsListMenu::MenuItem_t( szFriendNameBuffer, menuItemFriend ) );
}
};
const FriendsListMenuItem_t CFriendsListMenu::k_menuItemEmpty = { k_steamIDNil };
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CFriendsList::CFriendsList( IGameEngine *pGameEngine ) : m_pGameEngine( pGameEngine )
{
m_pFriendsListMenu = new CFriendsListMenu( pGameEngine );
Show();
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame for the CFriendsList
//-----------------------------------------------------------------------------
void CFriendsList::RunFrame()
{
m_pFriendsListMenu->RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Handles menu actions when viewing a friends list
//-----------------------------------------------------------------------------
void CFriendsList::OnMenuSelection( FriendsListMenuItem_t selection )
{
// Do nothing (yet)
}
//-----------------------------------------------------------------------------
// Purpose: Shows / Refreshes the friends list
//-----------------------------------------------------------------------------
void CFriendsList::Show()
{
m_pFriendsListMenu->Rebuild();
}
+40
View File
@@ -0,0 +1,40 @@
//========= Copyright © 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking friends list
//
//=============================================================================
#ifndef FRIENDS_H
#define FRIENDS_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "SpaceWarClient.h"
class CSpaceWarClient;
class CFriendsListMenu;
class CFriendsList
{
public:
// Constructor
CFriendsList( IGameEngine *pGameEngine );
// Run a frame
void RunFrame();
// shows / refreshes friends list
void Show();
// handles input from friends list menu
void OnMenuSelection( FriendsListMenuItem_t selection );
private:
// Engine
IGameEngine *m_pGameEngine;
CFriendsListMenu *m_pFriendsListMenu;
};
#endif // FRIENDS_H
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+224
View File
@@ -0,0 +1,224 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Main class for the game engine
//
// $NoKeywords: $
//=============================================================================
#ifndef GAMEENGINE_H
#define GAMEENGINE_H
#include <set>
#include <map>
// Typedef for font handles
typedef int HGAMEFONT;
// Typedef for vertex buffer handles
typedef int HGAMEVERTBUF;
// Typedef for texture handles
typedef int HGAMETEXTURE;
// Typedef for voice channels
typedef int HGAMEVOICECHANNEL;
// BDrawText position flags
#define TEXTPOS_TOP 0x00000000
#define TEXTPOS_LEFT 0x00000000
#define TEXTPOS_CENTER 0x00000001
#define TEXTPOS_RIGHT 0x00000002
#define TEXTPOS_VCENTER 0x00000004
#define TEXTPOS_BOTTOM 0x00000008
#define VOICE_OUTPUT_SAMPLE_RATE 11000 // real sample rate is 11025 but for XAudio2 it must be a multiple of XAUDIO2_QUANTUM_DENOMINATOR
#define VOICE_OUTPUT_SAMPLE_RATE_IDEAL 11025
#define BYTES_PER_SAMPLE 2
// Texture formats we support for upload to textures
enum ETEXTUREFORMAT
{
eTextureFormat_RGBA, // 8 bits per channel
eTextureFormat_BGRA, // 8 bits per channel
eTextureFormat_BGRA16, // 16 bits per channel
};
#define MAX_CONTROLLERS 4
enum ECONTROLLERDIGITALACTION
{
eControllerDigitalAction_TurnLeft,
eControllerDigitalAction_TurnRight,
eControllerDigitalAction_ForwardThrust,
eControllerDigitalAction_ReverseThrust,
eControllerDigitalAction_FireLasers,
eControllerDigitalAction_PauseMenu,
eControllerDigitalAction_MenuUp,
eControllerDigitalAction_MenuDown,
eControllerDigitalAction_MenuLeft,
eControllerDigitalAction_MenuRight,
eControllerDigitalAction_MenuSelect,
eControllerDigitalAction_MenuCancel,
eControllerDigitalAction_NumActions
};
enum ECONTROLLERANALOGACTION
{
eControllerAnalogAction_AnalogControls,
eControllerAnalogAction_NumActions
};
enum ECONTROLLERACTIONSET
{
eControllerActionSet_ShipControls,
eControllerActionSet_MenuControls,
eControllerActionSet_Layer_Thrust,
eControllerActionSet_NumSets
};
// used for VR support
namespace vr { class IVRSystem; }
//
// Interface that needs to be implemented for game engines on all platforms
//
class IGameEngine
{
public:
// Just here to stop warnings on non-virtual destructor in gcc builds
virtual ~IGameEngine() {};
// Check if the game engine is initialized ok and ready for use
virtual bool BReadyForUse() = 0;
// Check if the engine is shutting down
virtual bool BShuttingDown() = 0;
// Set the background color
virtual void SetBackgroundColor( short a, short r, short g, short b ) = 0;
// Start a frame, clear(), beginscene(), etc
virtual bool StartFrame() = 0;
// Finish a frame, endscene(), present(), etc.
virtual void EndFrame() = 0;
// Shutdown the game engine
virtual void Shutdown() = 0;
// Pump messages from the OS
virtual void MessagePump() = 0;
// Accessors for game screen size
virtual int32 GetViewportWidth() = 0;
virtual int32 GetViewportHeight() = 0;
// Function for drawing text to the screen, dwFormat is a combination of flags like DT_LEFT, TEXTPOS_VCENTER etc...
virtual bool BDrawString( HGAMEFONT hFont, RECT rect, DWORD dwColor, DWORD dwFormat, const char *pchText ) = 0;
// Create a new font returning our internal handle value for it (0 means failure)
virtual HGAMEFONT HCreateFont( int nHeight, int nFontWeight, bool bItalic, const char * pchFont ) = 0;
// Create a new texture returning our internal handle value for it (0 means failure), texture type specifies the type of data contained in pData
virtual HGAMETEXTURE HCreateTexture( byte *pData, uint32 uWidth, uint32 uHeight, ETEXTUREFORMAT eTextureFormat = eTextureFormat_RGBA ) = 0;
// update an existing texture, texture type specifies the type of data contained in pData
virtual bool UpdateTexture( HGAMETEXTURE texture, byte *pData, uint32 uWidth, uint32 uHeight, ETEXTUREFORMAT eTextureFormat = eTextureFormat_RGBA ) = 0;
// Draw a line, the engine itself will manage batching these (although you can explicitly flush if you need to)
virtual bool BDrawLine( float xPos0, float yPos0, DWORD dwColor0, float xPos1, float yPos1, DWORD dwColor1 ) = 0;
// Flush the line buffer
virtual bool BFlushLineBuffer() = 0;
// Draw a point, the engine itself will manage batching these (although you can explicitly flush if you need to)
virtual bool BDrawPoint( float xPos, float yPos, DWORD dwColor ) = 0;
// Flush the point buffer
virtual bool BFlushPointBuffer() = 0;
// Draw a filled quad
virtual bool BDrawFilledRect( float xPos0, float yPos0, float xPos1, float yPos1, DWORD dwColor ) = 0;
// Draw a textured rectangle
virtual bool BDrawTexturedRect( float xPos0, float yPos0, float xPos1, float yPos1,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture ) = 0;
// Draw a textured arbitrary quad
virtual bool BDrawTexturedQuad( float xPos0, float yPos0, float xPos1, float yPos1, float xPos2, float yPos2, float xPos3, float yPos3,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture ) = 0;
// Flush any still cached quad buffers
virtual bool BFlushQuadBuffer() = 0;
// Get the current state of a key
virtual bool BIsKeyDown( DWORD dwVK ) = 0;
// Get the first (in some arbitrary order) key down, if any
virtual bool BGetFirstKeyDown( DWORD *pdwVK ) = 0;
// Return true if there is an active Steam Controller
virtual bool BIsSteamInputDeviceActive() = 0;
// Get the current state of a controller action
virtual bool BIsControllerActionActive( ECONTROLLERDIGITALACTION dwAction ) = 0;
// Find an active Steam controller
virtual void FindActiveSteamInputDevice() = 0;
// Get the current state of a controller analog action
virtual void GetControllerAnalogAction( ECONTROLLERANALOGACTION dwAction, float *x, float *y ) = 0;
// Set the current Steam Controller Action set
virtual void SetSteamControllerActionSet( ECONTROLLERACTIONSET dwActionSet ) = 0;
// Set an Action Set Layer for Steam Input
virtual void ActivateSteamControllerActionSetLayer( ECONTROLLERACTIONSET dwActionSet ) = 0;
virtual void DeactivateSteamControllerActionSetLayer( ECONTROLLERACTIONSET dwActionSet ) = 0;
// Returns whether a given action set layer is active
virtual bool BIsActionSetLayerActive( ECONTROLLERACTIONSET dwActionSetLayer ) = 0;
// These calls return a string describing which controller button the action is currently bound to
virtual const char *GetTextStringForControllerOriginDigital( ECONTROLLERACTIONSET dwActionSet, ECONTROLLERDIGITALACTION dwDigitalAction ) = 0;
virtual const char *GetTextStringForControllerOriginAnalog( ECONTROLLERACTIONSET dwActionSet, ECONTROLLERANALOGACTION dwDigitalAction ) = 0;
virtual void SetControllerColor( uint8 nColorR, uint8 nColorG, uint8 nColorB, unsigned int nFlags ) = 0;
virtual void SetTriggerEffect( bool bEnabled ) = 0;
virtual void TriggerControllerVibration( unsigned short nLeftSpeed, unsigned short nRightSpeed ) = 0;
virtual void TriggerControllerHaptics( ESteamControllerPad ePad, unsigned short usOnMicroSec, unsigned short usOffMicroSec, unsigned short usRepeat ) = 0;
// Get current tick count for the game engine
virtual uint64 GetGameTickCount() = 0;
// Tell the game engine to update current tick count
virtual void UpdateGameTickCount() = 0;
// Tell the game engine to sleep for a bit if needed to limit frame rate. Returns
// true if you need to keep calling it to sleep more to reach your limit, returns
// false when you should proceed to the next frame.
virtual bool BSleepForFrameRateLimit( uint32 ulMaxFrameRate ) = 0;
// Get the tick count elapsed since the previous frame
// bugbug - We use this time to compute things like thrust and acceleration in the game,
// so it's important in doesn't jump ahead by large increments... Need a better
// way to handle that.
virtual uint64 GetGameTicksFrameDelta() = 0;
// Check if the game engine hwnd currently has focus (and a working d3d device)
virtual bool BGameEngineHasFocus() = 0;
// Voice chat functions
virtual HGAMEVOICECHANNEL HCreateVoiceChannel() = 0;
virtual void DestroyVoiceChannel( HGAMEVOICECHANNEL hChannel ) = 0;
virtual bool AddVoiceData( HGAMEVOICECHANNEL hChannel, const uint8 *pVoiceData, uint32 uLength ) = 0;
};
#endif // GAMEENGINE_H
+363
View File
@@ -0,0 +1,363 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking inventory
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "Inventory.h"
#include "SpaceWarClient.h"
//-----------------------------------------------------------------------------
// Purpose: singleton instance of CSpaceWarLocalInventory
//-----------------------------------------------------------------------------
CSpaceWarLocalInventory *SpaceWarLocalInventory()
{
static CSpaceWarLocalInventory inv;
return &inv;
}
CSpaceWarLocalInventory::CSpaceWarLocalInventory()
: m_SteamInventoryResult( this, &CSpaceWarLocalInventory::OnSteamInventoryResult ),
m_SteamInventoryFullUpdate( this, &CSpaceWarLocalInventory::OnSteamInventoryFullUpdate )
{
m_hPlaytimeRequestResult = k_SteamInventoryResultInvalid;
m_hPromoRequestResult = k_SteamInventoryResultInvalid;
m_hLastFullUpdate = k_SteamInventoryResultInvalid;
m_hExchangeRequestResult = k_SteamInventoryResultInvalid;
m_LastDropInstanceID = k_SteamItemInstanceIDInvalid;
// Indicate that this game has a use for item definition properties (we look up "name").
// If your game hardcodes the complete set of items, then you can probably skip this call.
SteamInventory()->LoadItemDefinitions();
// If there are any promotional items which your game offers (or may offer in the future)
// then this is the call that will grant them. Promotional items are a result of meeting
// some external criteria like owning another specific game. These criteria are specified
// in your Steamworks item definitions.
SteamInventory()->GrantPromoItems( &m_hPromoRequestResult );
#ifdef _DEBUG
GrantTestItems();
#endif
// We could pass a variable to receive the result handle, for
// comparison to the handle in SteamInventoryResultReady_t,
// but this simple example does not bother to keep track of
// multiple in-flight API calls.
SteamInventory()->GetAllItems( NULL ); // this will fire off FullUpdate and then ResultReady
}
//-----------------------------------------------------------------------------
// Purpose: Handles notification that GetAllItems has refreshed the local inventory
//-----------------------------------------------------------------------------
void CSpaceWarLocalInventory::OnSteamInventoryFullUpdate( SteamInventoryFullUpdate_t *callback )
{
// This callback triggers immediately before the ResultReady callback. We shouldn't
// free the result handle here, as we wil always free it at the end of ResultReady.
bool bGotResult = false;
std::vector<SteamItemDetails_t> vecDetails;
uint32 count = 0;
if ( SteamInventory()->GetResultItems( callback->m_handle, NULL, &count ) )
{
vecDetails.resize( count );
bGotResult = SteamInventory()->GetResultItems( callback->m_handle, vecDetails.data(), &count );
}
if ( bGotResult )
{
// For everything already in the inventory, check for update (exists in result) or removal (does not exist)
std::list<CSpaceWarItem *>::iterator iter;
for ( iter = m_listPlayerItems.begin(); iter != m_listPlayerItems.end(); /*incr at end of loop*/ )
{
bool bFound = false;
for ( size_t i = 0; i < vecDetails.size(); i++ )
{
if ( (*iter)->GetItemId() == vecDetails[i].m_itemId )
{
// Update item with matching item id
(*iter)->m_Details = vecDetails[i];
// Remove elements from the result vector as we process updates (fast swap-and-pop removal)
if ( i < vecDetails.size() - 1 )
vecDetails[i] = vecDetails.back();
vecDetails.pop_back();
bFound = true;
break;
}
}
if ( !bFound )
{
// No items in the full update match the existing item. Delete current iterator and advance.
delete *iter;
iter = m_listPlayerItems.erase( iter );
}
else
{
// Increment iterator without deleting.
++iter;
}
}
// Anything remaining in the result vector is a new item, since we removed all the updates.
for ( size_t i = 0; i < vecDetails.size(); ++i )
{
CSpaceWarItem *item = new CSpaceWarItem();
item->m_Details = vecDetails[i];
m_listPlayerItems.push_back( item );
}
}
// Remember that we just processed this full update to avoid doing work in ResultReady
m_hLastFullUpdate = callback->m_handle;
}
//-----------------------------------------------------------------------------
// Purpose: Handles notification that the inventory is updated
//-----------------------------------------------------------------------------
void CSpaceWarLocalInventory::OnSteamInventoryResult( SteamInventoryResultReady_t *callback )
{
// Ignore results that belong to some other SteamID - this normally won't happen, unless you start
// calling SerializeResult/DeserializeResult, but it is better to be safe. Also ignore anything that
// we just processed in OnSteamInventoryFullUpdate to avoid duplicate work.
if ( callback->m_result == k_EResultOK && m_hLastFullUpdate != callback->m_handle &&
SteamInventory()->CheckResultSteamID( callback->m_handle, SpaceWarClient()->GetLocalSteamID() ) )
{
bool bGotResult = false;
std::vector<SteamItemDetails_t> vecDetails;
uint32 count = 0;
if ( SteamInventory()->GetResultItems( callback->m_handle, NULL, &count ) )
{
vecDetails.resize( count );
bGotResult = SteamInventory()->GetResultItems( callback->m_handle, vecDetails.data(), &count );
}
if ( bGotResult )
{
// For everything already in the inventory, check for update or removal
std::list<CSpaceWarItem *>::iterator iter;
for ( iter = m_listPlayerItems.begin(); iter != m_listPlayerItems.end(); /*incr at end of loop*/ )
{
bool bDestroy = false;
for ( size_t i = 0; i < vecDetails.size(); i++ )
{
if ( (*iter)->GetItemId() == vecDetails[i].m_itemId )
{
// If flagged for removal by a partial update, remove it
if ( vecDetails[i].m_unFlags & k_ESteamItemRemoved )
{
bDestroy = true;
}
else
{
(*iter)->m_Details = vecDetails[i];
}
// Remove elements from the result vector as we process updates (fast swap-and-pop removal)
if ( i < vecDetails.size() - 1 )
vecDetails[i] = vecDetails.back();
vecDetails.pop_back();
break;
}
}
if ( bDestroy )
{
// Delete list element at current iterator and advance.
delete *iter;
iter = m_listPlayerItems.erase( iter );
}
else
{
// Increment iterator without deleting.
++iter;
}
}
// Anything remaining in the result vector is a new item, unless flagged for removal by an operation result.
for ( size_t i = 0; i < vecDetails.size(); ++i )
{
if ( !( vecDetails[i].m_unFlags & k_ESteamItemRemoved ) )
{
CSpaceWarItem *item = new CSpaceWarItem();
item->m_Details = vecDetails[i];
m_listPlayerItems.push_back( item );
}
}
}
}
// Clear out any pending handles.
if ( callback->m_handle == m_hPlaytimeRequestResult )
m_hPlaytimeRequestResult = -1;
if ( callback->m_handle == m_hExchangeRequestResult )
m_hExchangeRequestResult = -1;
if ( callback->m_handle == m_hPromoRequestResult )
m_hPromoRequestResult = -1;
if ( callback->m_handle == m_hLastFullUpdate )
m_hLastFullUpdate = -1;
// We're not hanging on the the result after processing it.
SteamInventory()->DestroyResult( callback->m_handle );
}
void CSpaceWarLocalInventory::CheckForItemDrops()
{
SteamInventory()->TriggerItemDrop( &m_hPlaytimeRequestResult, k_SpaceWarItem_TimedDropList );
}
void CSpaceWarLocalInventory::ModifyItemProperties()
{
const CSpaceWarItem *item100 = GetInstanceOf( k_SpaceWarItem_ShipDecoration1 );
if ( item100 )
{
SteamInventoryUpdateHandle_t updateHandle = SteamInventory()->StartUpdateProperties();
SteamInventory()->SetProperty( updateHandle, item100->GetItemId(), "string_value", "blah" );
SteamInventory()->SetProperty( updateHandle, item100->GetItemId(), "bool_value", true );
SteamInventory()->SetProperty( updateHandle, item100->GetItemId(), "int64_value", (int64)55 );
SteamInventory()->SetProperty( updateHandle, item100->GetItemId(), "float_value", 123.456f );
SteamInventoryResult_t resultHandle;
SteamInventory()->SubmitUpdateProperties( updateHandle, &resultHandle );
}
}
void CSpaceWarLocalInventory::DoExchange()
{
const CSpaceWarItem *item100 = GetInstanceOf( k_SpaceWarItem_ShipDecoration1 );
const CSpaceWarItem *item101 = GetInstanceOf( k_SpaceWarItem_ShipDecoration2 );
const CSpaceWarItem *item102 = GetInstanceOf( k_SpaceWarItem_ShipDecoration3 );
const CSpaceWarItem *item103 = GetInstanceOf( k_SpaceWarItem_ShipDecoration4 );
if ( item100 && item101 && item102 && item103 )
{
SteamItemInstanceID_t inputItems[4];
uint32 inputQuantities[4];
inputItems[0] = item100->GetItemId();
inputQuantities[0] = 1;
inputItems[1] = item101->GetItemId();
inputQuantities[1] = 1;
inputItems[2] = item102->GetItemId();
inputQuantities[2] = 1;
inputItems[3] = item103->GetItemId();
inputQuantities[3] = 1;
SteamItemDef_t outputItems[1];
outputItems[0] = 110;
uint32 outputQuantity[1];
outputQuantity[0] = 1;
SteamInventory()->ExchangeItems( &m_hExchangeRequestResult, outputItems, outputQuantity, 1, inputItems, inputQuantities, 4 );
}
}
void CSpaceWarLocalInventory::GrantTestItems()
{
std::vector<SteamItemDef_t> newItems;
newItems.push_back( k_SpaceWarItem_ShipDecoration1 );
newItems.push_back( k_SpaceWarItem_ShipDecoration2 );
SteamInventory()->GenerateItems( NULL, newItems.data(), NULL, (uint32) newItems.size() );
}
const CSpaceWarItem * CSpaceWarLocalInventory::GetItem( SteamItemInstanceID_t nItemId ) const
{
std::list<CSpaceWarItem *>::const_iterator iter;
for ( iter = m_listPlayerItems.begin(); iter != m_listPlayerItems.end(); ++iter )
{
if ( (*iter)->GetItemId() == nItemId )
return (*iter);
}
return NULL;
}
bool CSpaceWarLocalInventory::HasInstanceOf( SteamItemDef_t nDefinition ) const
{
std::list<CSpaceWarItem *>::const_iterator iter;
for ( iter = m_listPlayerItems.begin(); iter != m_listPlayerItems.end(); ++iter )
{
if ( ( *iter )->GetDefinition() == nDefinition )
return true;
}
return false;
}
uint32 CSpaceWarLocalInventory::GetNumOf( SteamItemDef_t nDefinition ) const
{
uint32 unQuantity = 0;
std::list<CSpaceWarItem *>::const_iterator iter;
for ( iter = m_listPlayerItems.begin(); iter != m_listPlayerItems.end(); ++iter )
{
if ( ( *iter )->GetDefinition() == nDefinition )
{
unQuantity += (*iter)->GetQuantity();
}
}
return unQuantity;
}
const CSpaceWarItem * CSpaceWarLocalInventory::GetInstanceOf( SteamItemDef_t nDefinition ) const
{
std::list<CSpaceWarItem *>::const_iterator iter;
for ( iter = m_listPlayerItems.begin(); iter != m_listPlayerItems.end(); ++iter )
{
if ( ( *iter )->GetDefinition() == nDefinition )
return (*iter);
}
return NULL;
}
void CSpaceWarLocalInventory::RefreshFromServer()
{
// This will trigger the SteamInventoryResultReady_t callback,
// and possibly the SteamInventoryFullUpdate_t callback first.
// We could pass a variable to receive the result handle, for
// comparison to the handle in SteamInventoryResultReady_t,
// but this simple example does not bother to keep track of
// multiple in-flight API calls.
SteamInventory()->GetAllItems( NULL );
}
std::string CSpaceWarItem::GetLocalizedName() const
{
std::string ret;
char buf[512];
uint32 bufSize = sizeof(buf);
if ( SteamInventory()->GetItemDefinitionProperty( GetDefinition(), "name", buf, &bufSize ) && bufSize <= sizeof(buf) )
{
ret = buf;
}
else
{
ret = "(unknown)";
}
return ret;
}
std::string CSpaceWarItem::GetLocalizedDescription() const
{
std::string ret;
char buf[2048];
uint32 bufSize = sizeof(buf);
if ( SteamInventory()->GetItemDefinitionProperty( GetDefinition(), "description", buf, &bufSize ) && bufSize <= sizeof(buf) )
{
ret = buf;
}
return ret;
}
std::string CSpaceWarItem::GetIconURL() const
{
std::string ret;
char buf[512];
uint32 bufSize = sizeof(buf);
if ( SteamInventory()->GetItemDefinitionProperty( GetDefinition(), "icon_url", buf, &bufSize ) && bufSize <= sizeof(buf) )
{
ret = buf;
}
return ret;
}
+87
View File
@@ -0,0 +1,87 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking stats and achievements
//
// $NoKeywords: $
//=============================================================================
#ifndef INVENTORY_H
#define INVENTORY_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include <list>
#include <string>
class CSpaceWarItem;
// These are hardcoded in the game and match the item definition IDs which were uploaded to Steam.
enum ESpaceWarItemDefIDs
{
k_SpaceWarItem_TimedDropList = 10,
k_SpaceWarItem_ShipDecoration1 = 100,
k_SpaceWarItem_ShipDecoration2 = 101,
k_SpaceWarItem_ShipDecoration3 = 102,
k_SpaceWarItem_ShipDecoration4 = 103,
k_SpaceWarItem_ShipWeapon1 = 110,
k_SpaceWarItem_ShipWeapon2 = 111,
k_SpaceWarItem_ShipSpecial1 = 120,
k_SpaceWarItem_ShipSpecial2 = 121
};
class CSpaceWarLocalInventory
{
public:
void RefreshFromServer();
void GrantTestItems();
void CheckForItemDrops();
void DoExchange();
void ModifyItemProperties();
const std::list<CSpaceWarItem *>& GetItemList() const { return m_listPlayerItems; }
const CSpaceWarItem * GetItem( SteamItemInstanceID_t nItemId ) const;
const CSpaceWarItem * GetInstanceOf( SteamItemDef_t nDefinition ) const;
bool HasInstanceOf( SteamItemDef_t nDefinition ) const;
uint32 GetNumOf( SteamItemDef_t nDefinition ) const;
bool IsWaitingForDropResults() const { return m_hPlaytimeRequestResult != k_SteamInventoryResultInvalid; }
const CSpaceWarItem * GetLastDroppedItem() const { return GetItem( m_LastDropInstanceID ); }
private:
friend CSpaceWarLocalInventory *SpaceWarLocalInventory();
CSpaceWarLocalInventory();
STEAM_CALLBACK( CSpaceWarLocalInventory, OnSteamInventoryResult, SteamInventoryResultReady_t, m_SteamInventoryResult );
STEAM_CALLBACK( CSpaceWarLocalInventory, OnSteamInventoryFullUpdate, SteamInventoryFullUpdate_t, m_SteamInventoryFullUpdate );
private:
SteamInventoryResult_t m_hPlaytimeRequestResult;
SteamInventoryResult_t m_hPromoRequestResult;
SteamInventoryResult_t m_hLastFullUpdate;
SteamInventoryResult_t m_hExchangeRequestResult;
std::list<CSpaceWarItem *> m_listPlayerItems;
SteamItemInstanceID_t m_LastDropInstanceID;
};
CSpaceWarLocalInventory *SpaceWarLocalInventory();
class CSpaceWarItem
{
public:
SteamItemInstanceID_t GetItemId() const { return m_Details.m_itemId; }
SteamItemDef_t GetDefinition() const { return m_Details.m_iDefinition; }
uint16 GetQuantity() const { return m_Details.m_unQuantity; }
std::string GetLocalizedName() const;
std::string GetLocalizedDescription() const;
std::string GetIconURL() const;
private:
friend class CSpaceWarLocalInventory;
SteamItemDetails_t m_Details;
};
#endif // INVENTORY_H
+158
View File
@@ -0,0 +1,158 @@
//========= Copyright © Valve LLC, All rights reserved. ============
//
// Purpose: Class for interacting with the Item Store
//
//=============================================================================
#include "stdafx.h"
#include "ItemStore.h"
#include "BaseMenu.h"
#include <math.h>
#include <vector>
#include <algorithm>
//-----------------------------------------------------------------------------
// Purpose: Menu that shows purchaseable items
//-----------------------------------------------------------------------------
class CItemStoreMenu : public CBaseMenu<PurchaseableItem_t>
{
public:
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CItemStoreMenu( IGameEngine *pGameEngine, CItemStore *pItemStore ) : CBaseMenu<PurchaseableItem_t>( pGameEngine ), m_pItemStore( pItemStore )
{
}
//-----------------------------------------------------------------------------
// Purpose: Creates menu
//-----------------------------------------------------------------------------
void Rebuild()
{
PushSelectedItem();
ClearMenuItems();
const std::vector<PurchaseableItem_t> &vecPurchaseableItems = m_pItemStore->GetPurchaseableItems();
for ( uint32 i = 0; i < vecPurchaseableItems.size(); ++i )
{
const PurchaseableItem_t &t = vecPurchaseableItems[i];
AddItemToMenu( t );
}
PurchaseableItem_t menuItemBack = { 0, 0 };
AddMenuItem( CItemStoreMenu::MenuItem_t( "Return to main menu", menuItemBack ) );
PopSelectedItem();
}
private:
void AddItemToMenu( const PurchaseableItem_t &item )
{
char bufName[512];
uint32 bufNameSize = sizeof( bufName );
if ( !SteamInventory()->GetItemDefinitionProperty( item.m_nItemDefID, "name", bufName, &bufNameSize ) && bufNameSize <= sizeof( bufName ) )
{
return;
}
uint32 unQuantity = SpaceWarLocalInventory()->GetNumOf( item.m_nItemDefID );
char rgchBuffer[1024];
sprintf_safe( rgchBuffer, "%u. Purchase %-25s %s %0.2f (own %u)", item.m_nItemDefID, bufName, m_pItemStore->GetCurrency(), float( item.m_ulPrice ) / 100, unQuantity );
AddMenuItem( CItemStoreMenu::MenuItem_t( rgchBuffer, item ) );
}
CItemStore *m_pItemStore;
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CItemStore::CItemStore( IGameEngine *pGameEngine ) : m_pGameEngine( pGameEngine )
{
m_pItemStoreMenu = new CItemStoreMenu( pGameEngine, this );
Show();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemStore::RunFrame()
{
m_pItemStoreMenu->RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Handles menu actions when viewing purchaseable items
//-----------------------------------------------------------------------------
void CItemStore::OnMenuSelection( PurchaseableItem_t selection )
{
if ( selection.m_nItemDefID == 0 )
{
SpaceWarClient()->SetGameState( k_EClientGameMenu );
return;
}
uint32 rgQuantity[1] = {1};
SteamInventory()->StartPurchase( &selection.m_nItemDefID, rgQuantity, 1 );
}
//-----------------------------------------------------------------------------
// Purpose: load all all purchaseable items
//-----------------------------------------------------------------------------
void CItemStore::LoadItemsWithPrices()
{
m_vecPurchaseableItems.clear();
SteamAPICall_t hSteamAPICall = SteamInventory()->RequestPrices();
m_SteamCallResultRequestPrices.Set( hSteamAPICall, this, &CItemStore::OnRequestPricesResult );
}
//-----------------------------------------------------------------------------
// Purpose: Request prices from the Steam Inventory Service
//-----------------------------------------------------------------------------
void CItemStore::OnRequestPricesResult( SteamInventoryRequestPricesResult_t *pParam, bool bIOFailure )
{
if ( pParam->m_result == k_EResultOK )
{
strncpy( m_rgchCurrency, pParam->m_rgchCurrency, sizeof( m_rgchCurrency ) );
uint32 unItems = SteamInventory()->GetNumItemsWithPrices();
std::vector<SteamItemDef_t> vecItemDefs;
vecItemDefs.resize( unItems );
std::vector<uint64> vecPrices;
vecPrices.resize( unItems );
if ( SteamInventory()->GetItemsWithPrices( vecItemDefs.data(), vecPrices.data(), NULL, unItems ) )
{
m_vecPurchaseableItems.reserve( unItems );
for ( uint32 i = 0; i < unItems; ++i )
{
PurchaseableItem_t t;
t.m_nItemDefID = vecItemDefs[i];
t.m_ulPrice = vecPrices[i];
m_vecPurchaseableItems.push_back( t );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Shows / Refreshes the friends list
//-----------------------------------------------------------------------------
void CItemStore::Show()
{
m_pItemStoreMenu->Rebuild();
}
+53
View File
@@ -0,0 +1,53 @@
//========= Copyright © Valve LLC, All rights reserved. ============
//
// Purpose: Class for interacting with in-game store
//
//=============================================================================
#ifndef ITEMSTORE_H
#define ITEMSTORE_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "SpaceWarClient.h"
class CSpaceWarClient;
class CItemStoreMenu;
class CItemStore
{
public:
// Constructor
CItemStore( IGameEngine *pGameEngine );
// Run a frame
void RunFrame();
// shows / refreshes item store
void Show();
// handles input from item store menu
void OnMenuSelection( PurchaseableItem_t selection );
// ask the inventory service for things to purchase
void LoadItemsWithPrices();
const std::vector<PurchaseableItem_t> &GetPurchaseableItems() const { return m_vecPurchaseableItems; }
const char *GetCurrency() const { return m_rgchCurrency; }
private:
// callback when we ask the Inventory Service for prices
void OnRequestPricesResult( SteamInventoryRequestPricesResult_t *pParam, bool bIOFailure );
CCallResult<CItemStore, SteamInventoryRequestPricesResult_t> m_SteamCallResultRequestPrices;
char m_rgchCurrency[4];
std::vector<PurchaseableItem_t> m_vecPurchaseableItems;
// Engine
IGameEngine *m_pGameEngine;
CItemStoreMenu *m_pItemStoreMenu;
};
#endif // ITEMSTORE_H
+321
View File
@@ -0,0 +1,321 @@
//========= Copyright 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking leaderboards
//
//=============================================================================
#include "stdafx.h"
#include "Leaderboards.h"
#include "BaseMenu.h"
#include <math.h>
//-----------------------------------------------------------------------------
// Purpose: Menu that shows a leaderboard
//-----------------------------------------------------------------------------
class CLeaderboardMenu : public CBaseMenu<LeaderboardMenuItem_t>
{
static const int k_nMaxLeaderboardEntries = 10; // maximum number of leaderboard entries we can display
LeaderboardEntry_t m_leaderboardEntries[k_nMaxLeaderboardEntries]; // leaderboard entries we received from DownloadLeaderboardEntries
int m_nLeaderboardEntries; // number of leaderboard entries we received
SteamLeaderboard_t m_hSteamLeaderboard; // handle to the leaderboard we are displaying
ELeaderboardDataRequest m_eLeaderboardData; // type of data we are displaying
bool m_bLoading; // waiting to receive leaderboard results
bool m_bIOFailure; // last attempt to retrieve the leaderboard failed
CCallResult<CLeaderboardMenu, LeaderboardScoresDownloaded_t> m_callResultDownloadEntries;
public:
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CLeaderboardMenu( IGameEngine *pGameEngine ) : CBaseMenu<LeaderboardMenuItem_t>( pGameEngine )
{
m_hSteamLeaderboard = 0;
m_nLeaderboardEntries = 0;
m_bLoading = false;
m_bIOFailure = false;
}
//-----------------------------------------------------------------------------
// Purpose: Menu that shows a leaderboard
//-----------------------------------------------------------------------------
void ShowLeaderboard( SteamLeaderboard_t hLeaderboard, ELeaderboardDataRequest eLeaderboardData, int offset )
{
m_hSteamLeaderboard = hLeaderboard;
m_eLeaderboardData = eLeaderboardData;
m_bLoading = true;
m_bIOFailure = false;
if ( hLeaderboard )
{
// load the specified leaderboard data. We only display k_nMaxLeaderboardEntries entries at a time
SteamAPICall_t hSteamAPICall = SteamUserStats()->DownloadLeaderboardEntries( hLeaderboard, eLeaderboardData,
offset, offset + k_nMaxLeaderboardEntries );
// Register for the async callback
m_callResultDownloadEntries.Set( hSteamAPICall, this, &CLeaderboardMenu::OnLeaderboardDownloadedEntries );
}
Rebuild();
}
//-----------------------------------------------------------------------------
// Purpose: Creates leaderboard menu
//-----------------------------------------------------------------------------
void Rebuild()
{
PushSelectedItem();
ClearMenuItems();
LeaderboardMenuItem_t menuItemBack = { true, false };
LeaderboardMenuItem_t menuItemNextLeaderboard = { false, true };
LeaderboardMenuItem_t menuItemEmpty = { 0 };
if ( m_hSteamLeaderboard )
{
// create a header for the leaderboard
std::string strName = "Leaderboard: ";
strName += SteamUserStats()->GetLeaderboardName( m_hSteamLeaderboard );
if ( m_eLeaderboardData == k_ELeaderboardDataRequestGlobal )
strName += ", Top 10";
else if ( m_eLeaderboardData == k_ELeaderboardDataRequestGlobalAroundUser )
strName += ", Around User";
else if ( m_eLeaderboardData == k_ELeaderboardDataRequestFriends )
strName += ", Friends of User";
AddMenuItem( CLeaderboardMenu::MenuItem_t( strName, menuItemEmpty ) );
}
// create leaderboard
if ( !m_hSteamLeaderboard || m_bLoading )
{
AddMenuItem( CLeaderboardMenu::MenuItem_t( "Loading...", menuItemEmpty ) );
}
else if ( m_bIOFailure )
{
AddMenuItem( CLeaderboardMenu::MenuItem_t( "Network failure!", menuItemEmpty ) );
}
else
{
if ( m_nLeaderboardEntries == 0 )
{
// Requesting for global scores around the user will return successfully with 0 results if the
// user does not have an entry on the leaderboard
std::string strText;
if ( m_eLeaderboardData != k_ELeaderboardDataRequestGlobalAroundUser )
{
strText = "No scores for this leaderboard";
}
else
{
strText = SteamFriends()->GetPersonaName();
strText += " does not have a score for this leaderboard";
}
AddMenuItem( CLeaderboardMenu::MenuItem_t( strText, menuItemEmpty ) );
}
for ( int index = 0; index < m_nLeaderboardEntries; index++ )
{
char rgchMenuText[256];
const char *pchName = SteamFriends()->GetFriendPersonaName( m_leaderboardEntries[index].m_steamIDUser );
sprintf_safe( rgchMenuText, "(%d) %s - %d", m_leaderboardEntries[index].m_nGlobalRank,
pchName, m_leaderboardEntries[index].m_nScore );
AddMenuItem( MenuItem_t( std::string( rgchMenuText ), menuItemEmpty ) );
}
}
// navigation buttons
AddMenuItem( CLeaderboardMenu::MenuItem_t( "Next leaderboard", menuItemNextLeaderboard ) );
AddMenuItem( CLeaderboardMenu::MenuItem_t( "Return to main menu", menuItemBack ) );
PopSelectedItem();
}
//-----------------------------------------------------------------------------
// Purpose: Called when SteamUserStats()->DownloadLeaderboardEntries() returns asynchronously
//-----------------------------------------------------------------------------
void OnLeaderboardDownloadedEntries( LeaderboardScoresDownloaded_t *pLeaderboardScoresDownloaded, bool bIOFailure )
{
m_bLoading = false;
m_bIOFailure = bIOFailure;
// leaderboard entries handle will be invalid once we return from this function. Copy all data now.
m_nLeaderboardEntries = MIN( pLeaderboardScoresDownloaded->m_cEntryCount, k_nMaxLeaderboardEntries );
for ( int index = 0; index < m_nLeaderboardEntries; index++ )
{
SteamUserStats()->GetDownloadedLeaderboardEntry( pLeaderboardScoresDownloaded->m_hSteamLeaderboardEntries,
index, &m_leaderboardEntries[ index ], NULL, 0 );
}
// show our new data
Rebuild();
}
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CLeaderboards::CLeaderboards( IGameEngine *pGameEngine ) : m_pGameEngine( pGameEngine )
{
m_hQuickestWinLeaderboard = 0;
m_hFeetTraveledLeaderboard = 0;
m_nCurrentLeaderboard = 0;
m_bLoading = false;
m_pLeaderboardMenu = new CLeaderboardMenu( pGameEngine );
FindLeaderboards();
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame for the CLeaderboards
//-----------------------------------------------------------------------------
void CLeaderboards::RunFrame()
{
m_pLeaderboardMenu->RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Handles menu actions when viewing a leaderboard
//-----------------------------------------------------------------------------
void CLeaderboards::OnMenuSelection( LeaderboardMenuItem_t selection )
{
if ( selection.m_bBack )
{
SpaceWarClient()->SetGameState( k_EClientGameMenu );
}
else if ( selection.m_bNextLeaderboard )
{
m_nCurrentLeaderboard = (m_nCurrentLeaderboard+1) % 2;
Show();
}
}
//-----------------------------------------------------------------------------
// Purpose: Shows / Refreshes the leaderboard
//-----------------------------------------------------------------------------
void CLeaderboards::Show()
{
if ( m_nCurrentLeaderboard == 0 )
{
// we want to show the top 10. To do so, we request global score data beginning at 0
m_pLeaderboardMenu->ShowLeaderboard( m_hQuickestWinLeaderboard, k_ELeaderboardDataRequestGlobal, 0 );
}
else if ( m_nCurrentLeaderboard == 1 )
{
// we want to show the 10 users around us
m_pLeaderboardMenu->ShowLeaderboard( m_hFeetTraveledLeaderboard, k_ELeaderboardDataRequestGlobalAroundUser, -5 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Gets handles for our leaderboards. If the leaderboards don't exist, creates them.
// Each time this is called, we look up another leaderboard.
//-----------------------------------------------------------------------------
void CLeaderboards::FindLeaderboards()
{
if ( m_bLoading )
return;
SteamAPICall_t hSteamAPICall = 0;
if ( !m_hQuickestWinLeaderboard )
{
// find/create a leaderboard for the quickest win
hSteamAPICall = SteamUserStats()->FindOrCreateLeaderboard( LEADERBOARD_QUICKEST_WIN,
k_ELeaderboardSortMethodAscending, k_ELeaderboardDisplayTypeTimeSeconds );
}
else if ( !m_hFeetTraveledLeaderboard )
{
// find/create a leaderboard for the most feet traveled in 1 round
hSteamAPICall = SteamUserStats()->FindOrCreateLeaderboard( LEADERBOARD_FEET_TRAVELED,
k_ELeaderboardSortMethodDescending, k_ELeaderboardDisplayTypeNumeric );
}
if ( hSteamAPICall != 0 )
{
// set the function to call when this API call has completed
m_SteamCallResultCreateLeaderboard.Set( hSteamAPICall, this, &CLeaderboards::OnFindLeaderboard );
m_bLoading = true;
}
}
//-----------------------------------------------------------------------------
// Purpose: Called when SteamUserStats()->FindOrCreateLeaderboard() returns asynchronously
//-----------------------------------------------------------------------------
void CLeaderboards::OnFindLeaderboard( LeaderboardFindResult_t *pFindLeaderboardResult, bool bIOFailure )
{
m_bLoading = false;
// see if we encountered an error during the call
if ( !pFindLeaderboardResult->m_bLeaderboardFound || bIOFailure )
return;
// check to see which leaderboard handle we just retrieved
const char *pchName = SteamUserStats()->GetLeaderboardName( pFindLeaderboardResult->m_hSteamLeaderboard );
if ( strcmp( pchName, LEADERBOARD_QUICKEST_WIN ) == 0 )
m_hQuickestWinLeaderboard = pFindLeaderboardResult->m_hSteamLeaderboard;
else if ( strcmp( pchName, LEADERBOARD_FEET_TRAVELED ) == 0 )
m_hFeetTraveledLeaderboard = pFindLeaderboardResult->m_hSteamLeaderboard;
// look up any other leaderboards
FindLeaderboards();
// if the user is currently looking at a leaderboard, it might be one we didn't have a handle for yet. Update the leaderboard.
if ( SpaceWarClient()->GetGameState() == k_EClientLeaderboards )
Show();
}
//-----------------------------------------------------------------------------
// Purpose: Updates leaderboards with stats from our just finished game
//-----------------------------------------------------------------------------
void CLeaderboards::UpdateLeaderboards( CStatsAndAchievements *pStats )
{
// if the user won, update the leaderboard with the time it took. If the user's previous time was faster, this time will be thrown out.
if ( m_hQuickestWinLeaderboard && SpaceWarClient()->BLocalPlayerWonLastGame() )
{
SteamAPICall_t hSteamAPICall = SteamUserStats()->UploadLeaderboardScore( m_hQuickestWinLeaderboard, k_ELeaderboardUploadScoreMethodKeepBest, (int)pStats->GetGameDurationSeconds(), NULL, 0 );
m_SteamCallResultUploadScore.Set( hSteamAPICall, this, &CLeaderboards::OnUploadScore );
}
// update the leaderboard for the most feet traveled in 1 round. If the user previously traveled farther in a round than this one,
// this value will be thrown out
if ( m_hFeetTraveledLeaderboard )
{
SteamUserStats()->UploadLeaderboardScore( m_hFeetTraveledLeaderboard, k_ELeaderboardUploadScoreMethodKeepBest, (int)pStats->GetGameFeetTraveled(), NULL, 0 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Called when SteamUserStats()->UploadLeaderboardScore() returns asynchronously
//-----------------------------------------------------------------------------
void CLeaderboards::OnUploadScore( LeaderboardScoreUploaded_t *pScoreUploadedResult, bool bIOFailure )
{
if ( !pScoreUploadedResult->m_bSuccess )
{
// error
}
if ( pScoreUploadedResult->m_bScoreChanged )
{
// could display new rank
}
}
+64
View File
@@ -0,0 +1,64 @@
//========= Copyright © 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking leaderboards
//
//=============================================================================
#ifndef LEADERBOARDS_H
#define LEADERBOARDS_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "StatsAndAchievements.h"
#include "SpaceWarClient.h"
class ISteamUser;
class CSpaceWarClient;
class CLeaderboardMenu;
class CLeaderboards
{
public:
// Constructor
CLeaderboards( IGameEngine *pGameEngine );
// Run a frame
void RunFrame();
// shows / refreshes leaderboard
void Show();
// Updates leaderboards with stats from our just finished game
void UpdateLeaderboards( CStatsAndAchievements *pStats );
// handles input from leaderboard menu
void OnMenuSelection( LeaderboardMenuItem_t selection );
private:
void FindLeaderboards();
// Engine
IGameEngine *m_pGameEngine;
// Called when SteamUserStats()->FindOrCreateLeaderboard() returns asynchronously
void OnFindLeaderboard( LeaderboardFindResult_t *pFindLearderboardResult, bool bIOFailure );
CCallResult<CLeaderboards, LeaderboardFindResult_t> m_SteamCallResultCreateLeaderboard;
// Called when SteamUserStats()->UploadLeaderboardScore() returns asynchronously
void OnUploadScore( LeaderboardScoreUploaded_t *pFindLearderboardResult, bool bIOFailure );
CCallResult<CLeaderboards, LeaderboardScoreUploaded_t> m_SteamCallResultUploadScore;
// handles to our leaderboards
SteamLeaderboard_t m_hQuickestWinLeaderboard;
SteamLeaderboard_t m_hFeetTraveledLeaderboard;
int m_bLoading; // true if we looking up a leaderboard handle
CLeaderboardMenu *m_pLeaderboardMenu; // Displays the current leaderboard
int m_nCurrentLeaderboard; // Index for leaderboard the user is currently viewing
};
#endif // LEADERBOARDS_H
+382
View File
@@ -0,0 +1,382 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for handling finding & creating lobbies, getting their details,
// and seeing other users in the current lobby
//
//=============================================================================
#include "stdafx.h"
#include "Lobby.h"
#include "SpaceWarClient.h"
#include "p2pauth.h"
//-----------------------------------------------------------------------------
// Purpose: Menu that shows a list of other users in a lobby
//-----------------------------------------------------------------------------
class CLobbyMenu : public CBaseMenu<LobbyMenuItem_t>
{
public:
// Constructor
CLobbyMenu( IGameEngine *pGameEngine ) : CBaseMenu<LobbyMenuItem_t>( pGameEngine ) {}
void Rebuild( const CSteamID &steamIDLobby )
{
PushSelectedItem();
ClearMenuItems();
if ( !steamIDLobby.IsValid() )
{
LobbyMenuItem_t menuItem = { CSteamID(), LobbyMenuItem_t::k_ELobbyMenuItemLeaveLobby };
AddMenuItem( CLobbyMenu::MenuItem_t( "Lobby Disconnected - Return to main menu", menuItem ) );
return;
}
// list of users in lobby
// iterate all the users in the lobby and show their details
int cLobbyMembers = SteamMatchmaking()->GetNumLobbyMembers( steamIDLobby );
for ( int i = 0; i < cLobbyMembers; i++ )
{
CSteamID steamIDLobbyMember = SteamMatchmaking()->GetLobbyMemberByIndex( steamIDLobby, i ) ;
// we get the details of a user from the ISteamFriends interface
const char *pchName = SteamFriends()->GetFriendPersonaName( steamIDLobbyMember );
// we may not know the name of the other users in the lobby immediately; but we'll receive
// a PersonaStateUpdate_t callback when they do, and we'll rebuild the list then
if ( pchName && *pchName )
{
const char *pchReady = SteamMatchmaking()->GetLobbyMemberData( steamIDLobby, steamIDLobbyMember, "ready" );
bool bReady = ( pchReady && atoi( pchReady ) == 1);
LobbyMenuItem_t menuItem = { steamIDLobbyMember, LobbyMenuItem_t::k_ELobbyMenuItemUser };
char rgchMenuText[256];
sprintf_safe( rgchMenuText, "%s %s", pchName, bReady ? "(READY)" : "" );
AddMenuItem( MenuItem_t( std::string( rgchMenuText ), menuItem ) );
}
}
// ready/not ready toggle
{
const char *pchReady = SteamMatchmaking()->GetLobbyMemberData( steamIDLobby, SteamUser()->GetSteamID(), "ready" );
bool bReady = ( pchReady && atoi( pchReady ) == 1 );
LobbyMenuItem_t menuItem = { CSteamID(), LobbyMenuItem_t::k_ELobbyMenuItemToggleReadState };
if ( bReady )
AddMenuItem( CLobbyMenu::MenuItem_t( "Set myself as Not Ready", menuItem ) );
else
AddMenuItem( CLobbyMenu::MenuItem_t( "Set myself as Ready", menuItem ) );
}
// see if the local user is the owner of this lobby
bool bLobbyOwner = false;
if ( SteamUser()->GetSteamID() == SteamMatchmaking()->GetLobbyOwner( steamIDLobby ) )
{
bLobbyOwner = true;
}
// start game
if ( bLobbyOwner )
{
LobbyMenuItem_t menuItem = { CSteamID(), LobbyMenuItem_t::k_ELobbyMenuItemStartGame };
AddMenuItem( CLobbyMenu::MenuItem_t( "Start game", menuItem ) );
}
// invite friend
{
LobbyMenuItem_t menuItem = { CSteamID(), LobbyMenuItem_t::k_ELobbyMenuItemInviteToLobby, steamIDLobby };
AddMenuItem( CLobbyMenu::MenuItem_t( "Invite Friend", menuItem ) );
}
// exit lobby
{
LobbyMenuItem_t menuItem = { CSteamID(), LobbyMenuItem_t::k_ELobbyMenuItemLeaveLobby };
AddMenuItem( CLobbyMenu::MenuItem_t( "Return to main menu", menuItem ) );
}
// reset selection
PopSelectedItem();
}
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CLobby::CLobby( IGameEngine *pGameEngine ) :
m_pGameEngine( pGameEngine ),
m_CallbackPersonaStateChange( this, &CLobby::OnPersonaStateChange ),
m_CallbackLobbyDataUpdate( this, &CLobby::OnLobbyDataUpdate ),
m_CallbackChatDataUpdate( this, &CLobby::OnLobbyChatUpdate )
{
m_pMenu = new CLobbyMenu( pGameEngine );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CLobby::~CLobby()
{
}
//-----------------------------------------------------------------------------
// Purpose: Sets the ID of the lobby to display
//-----------------------------------------------------------------------------
void CLobby::SetLobbySteamID( const CSteamID &steamIDLobby )
{
m_steamIDLobby = steamIDLobby;
m_pMenu->Rebuild( m_steamIDLobby );
}
//-----------------------------------------------------------------------------
// Purpose: Draws the lobby
//-----------------------------------------------------------------------------
void CLobby::RunFrame()
{
m_pMenu->RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Handles a user in the lobby changing their name or details
// ( note: joining and leaving is handled below by CLobby::OnLobbyChatUpdate() )
//-----------------------------------------------------------------------------
void CLobby::OnPersonaStateChange( PersonaStateChange_t *pCallback )
{
// callbacks are broadcast to all listeners, so we'll get this for every friend who changes state
// so make sure the user is in the lobby before acting
if ( !SteamFriends()->IsUserInSource( pCallback->m_ulSteamID, m_steamIDLobby ) )
return;
// rebuild the menu
m_pMenu->Rebuild( m_steamIDLobby );
}
//-----------------------------------------------------------------------------
// Purpose: Handles lobby data changing
//-----------------------------------------------------------------------------
void CLobby::OnLobbyDataUpdate( LobbyDataUpdate_t *pCallback )
{
// callbacks are broadcast to all listeners, so we'll get this for every lobby we're requesting
if ( m_steamIDLobby != pCallback->m_ulSteamIDLobby )
return;
// set the heading
m_pMenu->SetHeading( SteamMatchmaking()->GetLobbyData( m_steamIDLobby, "name" ) );
// rebuild the menu
m_pMenu->Rebuild( m_steamIDLobby );
}
//-----------------------------------------------------------------------------
// Purpose: Handles users in the lobby joining or leaving
//-----------------------------------------------------------------------------
void CLobby::OnLobbyChatUpdate( LobbyChatUpdate_t *pCallback )
{
// callbacks are broadcast to all listeners, so we'll get this for every lobby we're requesting
if ( m_steamIDLobby != pCallback->m_ulSteamIDLobby )
return;
if ( pCallback->m_ulSteamIDUserChanged == SteamUser()->GetSteamID().ConvertToUint64() &&
( pCallback->m_rgfChatMemberStateChange &
( k_EChatMemberStateChangeLeft|
k_EChatMemberStateChangeDisconnected|
k_EChatMemberStateChangeKicked|
k_EChatMemberStateChangeBanned ) ) )
{
// we've left the lobby, so it is now invalid
m_steamIDLobby = CSteamID();
}
// rebuild the menu
m_pMenu->Rebuild( m_steamIDLobby );
int cLobbyMembers = SteamMatchmaking()->GetNumLobbyMembers( m_steamIDLobby );
for ( int i = 0; i < cLobbyMembers; i++ )
{
CSteamID steamIDLobbyMember = SteamMatchmaking()->GetLobbyMemberByIndex( m_steamIDLobby, i ) ;
// ignore yourself.
if ( SteamUser()->GetSteamID() == steamIDLobbyMember )
continue;
}
}
//-----------------------------------------------------------------------------
// Purpose: Menu that shows a list of lobbies to choose from
//-----------------------------------------------------------------------------
class CLobbyBrowserMenu : public CBaseMenu<LobbyBrowserMenuItem_t>
{
public:
// Constructor
CLobbyBrowserMenu( IGameEngine *pGameEngine ) : CBaseMenu<LobbyBrowserMenuItem_t>( pGameEngine ) {}
void ShowSearching()
{
PushSelectedItem();
ClearMenuItems();
LobbyBrowserMenuItem_t data;
data.m_eStateToTransitionTo = k_EClientGameMenu;
AddMenuItem( CLobbyBrowserMenu::MenuItem_t( "Searching...", data ) );
data.m_eStateToTransitionTo = k_EClientGameMenu;
AddMenuItem( CLobbyBrowserMenu::MenuItem_t( "Return to main menu", data ) );
PopSelectedItem();
}
void Rebuild( std::list<Lobby_t> &listLobbies )
{
PushSelectedItem();
ClearMenuItems();
LobbyBrowserMenuItem_t data;
std::list<Lobby_t>::iterator iter;
for( iter = listLobbies.begin(); iter != listLobbies.end(); ++iter )
{
data.m_eStateToTransitionTo = k_EClientJoiningLobby;
data.m_steamIDLobby = iter->m_steamIDLobby;
if ( iter->m_rgchName[0] )
{
AddMenuItem( MenuItem_t( std::string( iter->m_rgchName ), data ) );
}
}
data.m_eStateToTransitionTo = k_EClientGameMenu;
AddMenuItem( CLobbyBrowserMenu::MenuItem_t( "Return to main menu", data ) );
// reset selection
PopSelectedItem();
}
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
// just initializes base data
//-----------------------------------------------------------------------------
CLobbyBrowser::CLobbyBrowser( IGameEngine *pGameEngine )
: m_CallbackLobbyDataUpdated( this, &CLobbyBrowser::OnLobbyDataUpdatedCallback )
{
m_pGameEngine = pGameEngine;
m_pMenu = new CLobbyBrowserMenu( pGameEngine );
m_pMenu->Rebuild( m_ListLobbies );
m_pMenu->SetHeading( "Lobby browser" );
m_bRequestingLobbies = false;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CLobbyBrowser::~CLobbyBrowser()
{
delete m_pMenu;
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame (to handle KB input and such as well as render)
//-----------------------------------------------------------------------------
void CLobbyBrowser::RunFrame()
{
m_pMenu->RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Starts rebuilding the lobby list
//-----------------------------------------------------------------------------
void CLobbyBrowser::Refresh()
{
if ( !m_bRequestingLobbies )
{
m_bRequestingLobbies = true;
// request all lobbies for this game
SteamAPICall_t hSteamAPICall = SteamMatchmaking()->RequestLobbyList();
// set the function to call when this API call has completed
m_SteamCallResultLobbyMatchList.Set( hSteamAPICall, this, &CLobbyBrowser::OnLobbyMatchListCallback );
m_pMenu->ShowSearching();
}
}
//-----------------------------------------------------------------------------
// Purpose: Callback, on a list of lobbies being received from the Steam back-end
//-----------------------------------------------------------------------------
void CLobbyBrowser::OnLobbyMatchListCallback( LobbyMatchList_t *pCallback, bool bIOFailure )
{
m_ListLobbies.clear();
m_bRequestingLobbies = false;
if ( bIOFailure )
{
// we had a Steam I/O failure - we probably timed out talking to the Steam back-end servers
// doesn't matter in this case, we can just act if no lobbies were received
}
// lobbies are returned in order of closeness to the user, so add them to the list in that order
for ( uint32 iLobby = 0; iLobby < pCallback->m_nLobbiesMatching; iLobby++ )
{
CSteamID steamIDLobby = SteamMatchmaking()->GetLobbyByIndex( iLobby );
// add the lobby to the list
Lobby_t lobby;
lobby.m_steamIDLobby = steamIDLobby;
// pull the name from the lobby metadata
const char *pchLobbyName = SteamMatchmaking()->GetLobbyData( steamIDLobby, "name" );
if ( pchLobbyName && pchLobbyName[0] )
{
// set the lobby name
sprintf_safe( lobby.m_rgchName, "%s", pchLobbyName );
}
else
{
// we don't have info about the lobby yet, request it
SteamMatchmaking()->RequestLobbyData( steamIDLobby );
// results will be returned via LobbyDataUpdate_t callback
sprintf_safe( lobby.m_rgchName, "Lobby %d", steamIDLobby.GetAccountID() );
}
m_ListLobbies.push_back( lobby );
}
m_pMenu->Rebuild( m_ListLobbies );
}
//-----------------------------------------------------------------------------
// Purpose: Callback, on a list of lobbies being received from the Steam back-end
//-----------------------------------------------------------------------------
void CLobbyBrowser::OnLobbyDataUpdatedCallback( LobbyDataUpdate_t *pCallback )
{
// find the lobby in our local list
std::list<Lobby_t>::iterator iter;
for( iter = m_ListLobbies.begin(); iter != m_ListLobbies.end(); ++iter )
{
// update the name of the lobby
if ( iter->m_steamIDLobby == pCallback->m_ulSteamIDLobby )
{
// extract the display name from the lobby metadata
const char *pchLobbyName = SteamMatchmaking()->GetLobbyData( iter->m_steamIDLobby, "name" );
if ( pchLobbyName[0] )
{
sprintf_safe( iter->m_rgchName, "%s", pchLobbyName );
// update the menu
m_pMenu->Rebuild( m_ListLobbies );
}
return;
}
}
}
+95
View File
@@ -0,0 +1,95 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for handling finding & creating lobbies, getting their details,
// and seeing other users in the current lobby
//
//=============================================================================
#ifndef LOBBY_H
#define LOBBY_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "BaseMenu.h"
#include <list>
class CSpaceWarClient;
class CLobbyBrowserMenu;
class CLobbyMenu;
//-----------------------------------------------------------------------------
// Purpose: Displays the other users in a lobby and allows the game to be started
//-----------------------------------------------------------------------------
class CLobby
{
public:
CLobby( IGameEngine *pGameEngine );
~CLobby();
// sets which lobby to display
void SetLobbySteamID( const CSteamID &steamIDLobby );
// Run a frame (to handle KB input and such as well as render)
void RunFrame();
private:
CSteamID m_steamIDLobby;
// Pointer to engine instance (so we can draw stuff)
IGameEngine *m_pGameEngine;
// Menu object
CLobbyMenu *m_pMenu;
// user state change handler
STEAM_CALLBACK( CLobby, OnPersonaStateChange, PersonaStateChange_t, m_CallbackPersonaStateChange );
// lobby state change handler
STEAM_CALLBACK( CLobby, OnLobbyDataUpdate, LobbyDataUpdate_t, m_CallbackLobbyDataUpdate );
STEAM_CALLBACK( CLobby, OnLobbyChatUpdate, LobbyChatUpdate_t, m_CallbackChatDataUpdate );
};
// an item in the list of lobbies we've found to display
struct Lobby_t
{
CSteamID m_steamIDLobby;
char m_rgchName[256];
};
//-----------------------------------------------------------------------------
// Purpose: Displaying and allows selection from a list of lobbies
//-----------------------------------------------------------------------------
class CLobbyBrowser
{
public:
CLobbyBrowser( IGameEngine *pGameEngine );
~CLobbyBrowser();
// rebuild the list
void Refresh();
// Run a frame (to handle KB input and such as well as render)
void RunFrame();
private:
// Pointer to engine instance (so we can draw stuff)
IGameEngine *m_pGameEngine;
// Track whether we are in the middle of a refresh or not
bool m_bRequestingLobbies;
// Menu object
CLobbyBrowserMenu *m_pMenu;
CCallResult<CLobbyBrowser, LobbyMatchList_t> m_SteamCallResultLobbyMatchList;
void OnLobbyMatchListCallback( LobbyMatchList_t *pLobbyMatchList, bool bIOFailure );
STEAM_CALLBACK( CLobbyBrowser, OnLobbyDataUpdatedCallback, LobbyDataUpdate_t, m_CallbackLobbyDataUpdated );
std::list< Lobby_t > m_ListLobbies;
};
#endif //LOBBY_H
+377
View File
@@ -0,0 +1,377 @@
//====== Copyright 1996-2008, Valve Corporation, All rights reserved. =======
//
// Purpose: Main file for the SteamworksExample app
//
//=============================================================================
#include "stdafx.h"
#include "steam/steam_api.h"
#ifdef WIN32
#include <direct.h>
#else
#define MAX_PATH PATH_MAX
#include <unistd.h>
#define _getcwd getcwd
#define _snprintf snprintf
#endif
#if defined(WIN32)
#include "gameenginewin32.h"
#define atoll _atoi64
#elif defined(OSX)
#include "GameEngine.h"
extern IGameEngine *CreateGameEngineOSX();
#elif defined(SDL)
#include "GameEngine.h"
extern IGameEngine *CreateGameEngineSDL();
#endif
#include "SpaceWarClient.h"
//-----------------------------------------------------------------------------
// Purpose: Wrapper around SteamAPI_WriteMiniDump which can be used directly
// as a se translator
//-----------------------------------------------------------------------------
#ifdef _WIN32
void MiniDumpFunction( unsigned int nExceptionCode, EXCEPTION_POINTERS *pException )
{
MessageBox( nullptr, "Spacewar is crashing now!", "Unhandled Exception", MB_OK );
// You can build and set an arbitrary comment to embed in the minidump here,
// maybe you want to put what level the user was playing, how many players on the server,
// how much memory is free, etc...
SteamAPI_SetMiniDumpComment( "Minidump comment: SteamworksExample.exe\n" );
// The 0 here is a build ID, we don't set it
SteamAPI_WriteMiniDump( nExceptionCode, pException, 0 );
}
#endif
//-----------------------------------------------------------------------------
// Purpose: Helper to display critical errors
//-----------------------------------------------------------------------------
int Alert( const char *lpCaption, const char *lpText )
{
#ifndef _WIN32
fprintf( stderr, "Message: '%s', Detail: '%s'\n", lpCaption, lpText );
return 0;
#else
return ::MessageBox( NULL, lpText, lpCaption, MB_OK );
#endif
}
//-----------------------------------------------------------------------------
// Purpose: callback hook for debug text emitted from the Steam API
//-----------------------------------------------------------------------------
extern "C" void __cdecl SteamAPIDebugTextHook( int nSeverity, const char *pchDebugText )
{
// if you're running in the debugger, only warnings (nSeverity >= 1) will be sent
// if you add -debug_steamapi to the command-line, a lot of extra informational messages will also be sent
::OutputDebugString( pchDebugText );
if ( nSeverity >= 1 )
{
// place to set a breakpoint for catching API errors
int x = 3;
(void)x;
}
}
//-----------------------------------------------------------------------------
// Purpose: Extracts some feature from the command line
//-----------------------------------------------------------------------------
bool ParseCommandLine( const char *pchCmdLine, const char **ppchServerAddress, const char **ppchLobbyID )
{
// Look for the +connect ipaddress:port parameter in the command line,
// Steam will pass this when a user has used the Steam Server browser to find
// a server for our game and is trying to join it.
const char *pchConnectParam = "+connect ";
const char *pchConnect = strstr( pchCmdLine, pchConnectParam );
*ppchServerAddress = NULL;
if ( pchConnect && strlen( pchCmdLine ) > (pchConnect - pchCmdLine) + strlen( pchConnectParam ) )
{
// Address should be right after the +connect
*ppchServerAddress = pchCmdLine + ( pchConnect - pchCmdLine ) + strlen( pchConnectParam );
}
// look for +connect_lobby lobbyid paramter on the command line
// Steam will pass this in if a user taken up an invite to a lobby
const char *pchConnectLobbyParam = "+connect_lobby ";
const char *pchConnectLobby = strstr( pchCmdLine, pchConnectLobbyParam );
*ppchLobbyID = NULL;
if ( pchConnectLobby && strlen( pchCmdLine ) > (pchConnectLobby - pchCmdLine) + strlen( pchConnectLobbyParam ) )
{
// lobby ID should be right after the +connect_lobby
*ppchLobbyID = pchCmdLine + ( pchConnectLobby - pchCmdLine ) + strlen( pchConnectLobbyParam );
}
return *ppchServerAddress || *ppchLobbyID;
}
//-----------------------------------------------------------------------------
// Purpose: Main loop code shared between all platforms
//-----------------------------------------------------------------------------
void RunGameLoop( IGameEngine *pGameEngine, const char *pchServerAddress, const char *pchLobbyID, bool bShowTimer )
{
// Make sure it initialized ok
if ( pGameEngine->BReadyForUse() )
{
// Initialize the game
CSpaceWarClient *pGameClient = new CSpaceWarClient( pGameEngine );
pGameClient->SetShowTimer( bShowTimer );
// Black background
pGameEngine->SetBackgroundColor( 0, 0, 0, 0 );
// If +connect was used to specify a server address, connect now
pGameClient->ExecCommandLineConnect( pchServerAddress, pchLobbyID );
// test a user specific secret before entering main loop
Steamworks_TestSecret();
pGameClient->RetrieveEncryptedAppTicket();
while( !pGameEngine->BShuttingDown() )
{
if ( pGameEngine->StartFrame() )
{
pGameEngine->UpdateGameTickCount();
// Run a game frame
pGameClient->RunFrame();
pGameEngine->EndFrame();
// Sleep to limit frame rate
while( pGameEngine->BSleepForFrameRateLimit( MAX_CLIENT_AND_SERVER_FPS ) )
{
// Keep running the network on the client at a faster rate than the FPS limit
pGameClient->ReceiveNetworkData();
}
}
}
delete pGameClient;
}
// Cleanup the game engine
delete pGameEngine;
}
//-----------------------------------------------------------------------------
// Purpose: Real main entry point for the program
//-----------------------------------------------------------------------------
static int RealMain( const char *pchCmdLine, HINSTANCE hInstance, int nCmdShow )
{
if ( SteamAPI_RestartAppIfNecessary( k_uAppIdInvalid ) )
{
// if Steam is not running or the game wasn't started through Steam, SteamAPI_RestartAppIfNecessary starts the
// local Steam client and also launches this game again.
// Once you get a public Steam AppID assigned for this game, you need to replace k_uAppIdInvalid with it and
// removed steam_appid.txt from the game depot.
return EXIT_FAILURE;
}
// Init Steam CEG
if ( !Steamworks_InitCEGLibrary() )
{
OutputDebugString( "Steamworks_InitCEGLibrary() failed\n" );
Alert( "Fatal Error", "Steam must be running to play this game (InitDrmLibrary() failed).\n" );
return EXIT_FAILURE;
}
// Initialize SteamAPI, if this fails we bail out since we depend on Steam for lots of stuff.
// You don't necessarily have to though if you write your code to check whether all the Steam
// interfaces are NULL before using them and provide alternate paths when they are unavailable.
//
// This will also load the in-game steam overlay dll into your process. That dll is normally
// injected by steam when it launches games, but by calling this you cause it to always load,
// even when not launched via steam.
SteamErrMsg errMsg = { 0 };
if ( SteamAPI_InitEx( &errMsg ) != k_ESteamAPIInitResult_OK )
{
OutputDebugString( "SteamAPI_Init() failed: " );
OutputDebugString( errMsg );
OutputDebugString( "\n" );
Alert( "Fatal Error", "Steam must be running to play this game (SteamAPI_Init() failed).\n" );
return EXIT_FAILURE;
}
// set our debug handler
SteamClient()->SetWarningMessageHook( &SteamAPIDebugTextHook );
// Ensure that the user has logged into Steam. This will always return true if the game is launched
// from Steam, but if Steam is at the login prompt when you run your game from the debugger, it
// will return false.
if ( !SteamUser()->BLoggedOn() )
{
OutputDebugString( "Steam user is not logged in\n" );
Alert( "Fatal Error", "Steam user must be logged in to play this game (SteamUser()->BLoggedOn() returned false).\n" );
return EXIT_FAILURE;
}
const char *pchServerAddress, *pchLobbyID;
if ( !ParseCommandLine( pchCmdLine, &pchServerAddress, &pchLobbyID ) )
{
// no connect string on process command line. If app was launched via a Steam URL, the extra command line parameters in that URL
// get be retrieved with GetLaunchCommandLine. This way an attacker can't put malicious parameters in the process command line
// which might allow much more functionality then indented.
char szCommandLine[1024] = {};
if ( SteamApps()->GetLaunchCommandLine( szCommandLine, sizeof( szCommandLine ) ) > 0 )
{
ParseCommandLine( szCommandLine, &pchServerAddress, &pchLobbyID );
}
}
bool bShowTimer = !!strstr( pchCmdLine, "-timer" );
// do a DRM self check
Steamworks_SelfCheck();
// Construct a new instance of the game engine
// bugbug jmccaskey - make screen resolution dynamic, maybe take it on command line?
IGameEngine *pGameEngine =
#if defined(_WIN32)
new CGameEngineWin32( hInstance, nCmdShow, 1024, 768 );
#elif defined(OSX)
CreateGameEngineOSX();
#elif defined(SDL)
CreateGameEngineSDL( );
#else
#error Need CreateGameEngine()
#endif
if ( !SteamInput()->Init( false ) )
{
OutputDebugString( "SteamInput()->Init failed.\n" );
Alert( "Fatal Error", "SteamInput()->Init failed.\n" );
return EXIT_FAILURE;
}
char rgchCWD[1024];
if ( !_getcwd( rgchCWD, sizeof( rgchCWD ) ) )
{
strcpy( rgchCWD, "." );
}
char rgchFullPath[1024];
#if defined(OSX)
// hack for now, because we do not have utility functions available for finding the resource path
// alternatively we could disable the SteamController init on OS X
_snprintf( rgchFullPath, sizeof( rgchFullPath ), "%s/steamworksexample.app/Contents/Resources/%s", rgchCWD, "steam_input_manifest.vdf" );
#else
_snprintf( rgchFullPath, sizeof( rgchFullPath ), "%s\\%s", rgchCWD, "steam_input_manifest.vdf" );
#endif
SteamInput()->SetInputActionManifestFilePath( rgchFullPath );
// This call will block and run until the game exits
RunGameLoop( pGameEngine, pchServerAddress, pchLobbyID, bShowTimer );
// Shutdown the SteamAPI
SteamAPI_Shutdown();
// Shutdown Steam CEG
Steamworks_TermCEGLibrary();
// exit
return EXIT_SUCCESS;
}
//-----------------------------------------------------------------------------
// Purpose: Main entry point for the program -- win32
//-----------------------------------------------------------------------------
#ifdef WIN32
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// All we do here is call the real main function after setting up our se translator
// this allows us to catch exceptions and report errors to Steam.
//
// Note that you must set your compiler flags correctly to enable structured exception
// handling in order for this particular setup method to work.
if ( IsDebuggerPresent() )
{
// We don't want to mask exceptions (or report them to Steam!) when debugging.
// If you would like to step through the exception handler, attach a debugger
// after running the game outside of the debugger.
return RealMain( lpCmdLine, hInstance, nCmdShow );
}
_set_se_translator( MiniDumpFunction );
try // this try block allows the SE translator to work
{
return RealMain( lpCmdLine, hInstance, nCmdShow );
}
catch( ... )
{
return -1;
}
}
#endif
#ifdef OSX
int main(int argc, const char **argv)
{
char szCmdLine[1024];
char *pszStart = szCmdLine;
char * const pszEnd = szCmdLine + V_ARRAYSIZE(szCmdLine);
*szCmdLine = '\0';
for ( int i = 1; i < argc; i++ )
{
const char *parm = argv[i];
while ( *parm && (pszStart < pszEnd) )
{
*pszStart++ = *parm++;
}
if ( pszStart >= pszEnd )
break;
if ( i < argc-1 )
*pszStart++ = ' ';
}
szCmdLine[V_ARRAYSIZE(szCmdLine) - 1] = '\0';
return RealMain( szCmdLine, 0, 0 );
}
#endif
#ifdef SDL
int main(int argc, const char **argv)
{
char szCmdLine[1024];
char *pszStart = szCmdLine;
char * const pszEnd = szCmdLine + V_ARRAYSIZE(szCmdLine);
*szCmdLine = '\0';
for ( int i = 1; i < argc; i++ )
{
const char *parm = argv[i];
while ( *parm && (pszStart < pszEnd) )
{
*pszStart++ = *parm++;
}
if ( pszStart >= pszEnd )
break;
if ( i < argc-1 )
*pszStart++ = ' ';
}
szCmdLine[V_ARRAYSIZE(szCmdLine) - 1] = '\0';
return RealMain( szCmdLine, 0, 0 );
}
#endif
+82
View File
@@ -0,0 +1,82 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class to define the main game menu
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "MainMenu.h"
#include "SpaceWar.h"
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMainMenu::CMainMenu( IGameEngine *pGameEngine ) : CBaseMenu<EClientGameState>( pGameEngine )
{
SetupMenu();
}
//-----------------------------------------------------------------------------
// Purpose: Add relevant menu entries, honoring parental settings
//-----------------------------------------------------------------------------
void CMainMenu::SetupMenu()
{
ISteamParentalSettings *pSettings = SteamParentalSettings();
AddMenuItem( MenuItem_t( "Start New Server", k_EClientGameStartServer ) );
AddMenuItem( MenuItem_t( "Find LAN Servers", k_EClientFindLANServers ) );
AddMenuItem( MenuItem_t( "Find Internet Servers", k_EClientFindInternetServers ) );
AddMenuItem( MenuItem_t( "Create Lobby", k_EClientCreatingLobby ) );
AddMenuItem( MenuItem_t( "Find Lobby", k_EClientFindLobby ) );
AddMenuItem( MenuItem_t( "Instructions", k_EClientGameInstructions ) );
if ( !pSettings->BIsFeatureBlocked( k_EFeatureProfile ) )
{
AddMenuItem( MenuItem_t( "Stats and Achievements", k_EClientStatsAchievements ) );
}
AddMenuItem( MenuItem_t( "Leaderboards", k_EClientLeaderboards ) );
if ( !pSettings->BIsFeatureBlocked( k_EFeatureFriends ) )
{
AddMenuItem( MenuItem_t( "Friends List", k_EClientFriendsList ) );
AddMenuItem( MenuItem_t( "Group chat room", k_EClientClanChatRoom ) );
}
AddMenuItem( MenuItem_t( "Remote Play Invite", k_EClientRemotePlayInvite ) );
AddMenuItem( MenuItem_t( "Remote Play Sessions", k_EClientRemotePlaySessions ) );
AddMenuItem( MenuItem_t( "Remote Storage", k_EClientRemoteStorage ) );
AddMenuItem( MenuItem_t( "Write Minidump", k_EClientMinidump ) );
if ( !pSettings->BIsFeatureBlocked( k_EFeatureBrowser ) )
{
AddMenuItem( MenuItem_t( "Web Callback", k_EClientWebCallback ) );
}
AddMenuItem( MenuItem_t( "Music Player", k_EClientMusic ) );
if ( !pSettings->BIsFeatureBlocked( k_EFeatureCommunity ) )
{
AddMenuItem( MenuItem_t( "Workshop Items", k_EClientWorkshop ) );
}
if ( !pSettings->BIsFeatureBlocked( k_EFeatureBrowser ) )
{
AddMenuItem( MenuItem_t( "HTML Page", k_EClientHTMLSurface ) );
}
AddMenuItem( MenuItem_t( "In-game Store", k_EClientInGameStore ) );
AddMenuItem( MenuItem_t( "OverlayAPI", k_EClientOverlayAPI ) );
AddMenuItem( MenuItem_t( "Exit Game", k_EClientGameExiting ) );
}
//-----------------------------------------------------------------------------
// Purpose: Callback for a change in parental settings. Rebuild menu.
//-----------------------------------------------------------------------------
void CMainMenu::OnParentalSettingsChanged( SteamParentalSettingsChanged_t *pParam )
{
ClearMenuItems();
SetupMenu();
}
+30
View File
@@ -0,0 +1,30 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class to define the main game menu
//
// $NoKeywords: $
//=============================================================================
#ifndef MAINMENU_H
#define MAINMENU_H
#include <string>
#include <vector>
#include "GameEngine.h"
#include "SpaceWar.h"
#include "BaseMenu.h"
#include "SpaceWarClient.h"
class CMainMenu : public CBaseMenu<EClientGameState>
{
public:
// Constructor
CMainMenu( IGameEngine *pGameEngine );
void SetupMenu();
private:
STEAM_CALLBACK( CMainMenu, OnParentalSettingsChanged, SteamParentalSettingsChanged_t );
};
#endif // MAINMENU_H
+186
View File
@@ -0,0 +1,186 @@
SOURCEFILES := \
BaseMenu.cpp \
Friends.cpp \
Inventory.cpp \
ItemStore.cpp \
Leaderboards.cpp \
Lobby.cpp \
Main.cpp \
MainMenu.cpp \
OverlayExamples.cpp \
PhotonBeam.cpp \
QuitMenu.cpp \
RemotePlay.cpp \
RemoteStorage.cpp \
ServerBrowser.cpp \
Ship.cpp \
SimpleProtobuf.cpp \
SpaceWarClient.cpp \
SpaceWarEntity.cpp \
SpaceWarServer.cpp \
StarField.cpp \
StatsAndAchievements.cpp \
Sun.cpp \
timeline.cpp \
VectorEntity.cpp \
clanchatroom.cpp \
gameenginesdl.cpp \
htmlsurface.cpp \
musicplayer.cpp \
p2pauth.cpp \
stdafx.cpp \
voicechat.cpp \
glew.c
TARGETNAME := SteamworksExampleLinux
#TARGETTYPE can be APP, STATIC or SHARED
TARGETTYPE := APP
include flags.mak
CONFIG ?= RELEASE
ALL_MACROS := $(COMMON_MACROS)
ifeq ($(CONFIG),DEBUG)
BINARYDIR = debug
CFLAGS += $(DEBUG_CFLAGS)
CXXFLAGS += $(DEBUG_CXXFLAGS)
LDFLAGS += $(DEBUG_LDFLAGS)
ALL_MACROS += $(DEBUG_MACROS)
endif
ifeq ($(CONFIG),RELEASE)
BINARYDIR = release
CFLAGS += $(RELEASE_CFLAGS)
CXXFLAGS += $(RELEASE_CXXFLAGS)
LDFLAGS += $(RELEASE_LDFLAGS)
ALL_MACROS += $(RELEASE_MACROS)
endif
ifeq ($(BINARYDIR),)
error:
$(error Please specify CONFIG=DEBUG/RELEASE)
endif
ARCH ?= 64
ifeq ($(ARCH), 32)
CFLAGS += -m32
CXXFLAGS += -m32
LDFLAGS += -m32
else
ifneq ($(ARCH), 64)
$(error Please specify ARCH=32/64)
endif
endif
EXTERNAL_LIBS :=
EXTERNAL_LIBS_COPIED := $(foreach lib, $(EXTERNAL_LIBS),$(BINARYDIR)/$(notdir $(lib)))
CXXFLAGS += -Wno-invalid-offsetof
CFLAGS += $(addprefix -I,$(INCLUDE_DIRS))
CXXFLAGS += $(addprefix -I,$(INCLUDE_DIRS))
CFLAGS += $(addprefix -D,$(ALL_MACROS))
CXXFLAGS += $(addprefix -D,$(ALL_MACROS))
CXXFLAGS += $(addprefix -framework ,$(MACOS_FRAMEWORKS))
CFLAGS += $(addprefix -framework ,$(MACOS_FRAMEWORKS))
LDFLAGS += $(addprefix -framework ,$(MACOS_FRAMEWORKS))
LDFLAGS += $(addprefix -L,$(LIBRARY_DIRS))
LIBRARY_LDFLAGS = $(addprefix -l,$(LIBRARY_NAMES))
ifeq ($(IS_LINUX_PROJECT),1)
RPATH_PREFIX := -Wl,--rpath='$$ORIGIN/../
LIBRARY_LDFLAGS += $(EXTERNAL_LIBS)
LIBRARY_LDFLAGS += -Wl,--rpath='$$ORIGIN'
LIBRARY_LDFLAGS += $(addsuffix ',$(addprefix $(RPATH_PREFIX),$(dir $(EXTERNAL_LIBS))))
ifeq ($(TARGETTYPE),SHARED)
LIBRARY_LDFLAGS += -Wl,-soname,$(TARGETNAME)
endif
else
LIBRARY_LDFLAGS += $(EXTERNAL_LIBS)
endif
CFLAGS += $(MCUFLAGS)
CXXFLAGS += $(MCUFLAGS)
LDFLAGS += $(MCUFLAGS)
all_make_files := Makefile flags.mak $(ADDITIONAL_MAKE_FILES)
ifeq ($(STARTUPFILES),)
all_source_files := $(SOURCEFILES)
else
all_source_files := $(STARTUPFILES) $(filter-out $(STARTUPFILES),$(SOURCEFILES))
endif
source_obj1 := $(all_source_files:.cpp=.o)
source_obj2 := $(source_obj1:.c=.o)
source_objs := $(source_obj2:.S=.o)
all_objs := $(addprefix $(BINARYDIR)/, $(notdir $(source_objs)))
ifeq ($(GENERATE_BIN_FILE),1)
all: $(BINARYDIR)/$(basename $(TARGETNAME)).bin
$(BINARYDIR)/$(basename $(TARGETNAME)).bin: $(BINARYDIR)/$(TARGETNAME)
$(OBJCOPY) -O binary $< $@
else
all: $(BINARYDIR)/$(TARGETNAME)
endif
ifeq ($(TARGETTYPE),APP)
$(BINARYDIR)/$(TARGETNAME): $(all_objs) $(EXTERNAL_LIBS) $(BINARYDIR)/$(STEAM_API) $(BINARYDIR)/SteamworksExample.sh $(BINARYDIR)/DejaVuSans.ttf
$(LD) -o $@ $(START_GROUP) $(all_objs) $(LIBRARY_LDFLAGS) $(LDFLAGS) $(END_GROUP)
@echo "You can start the game by running $(BINARYDIR)/SteamworksExample.sh"
endif
ifeq ($(TARGETTYPE),SHARED)
$(BINARYDIR)/$(TARGETNAME): $(all_objs) $(EXTERNAL_LIBS)
$(LD) -shared -o $@ $(START_GROUP) $(all_objs) $(LIBRARY_LDFLAGS) $(LDFLAGS) $(END_GROUP)
endif
ifeq ($(TARGETTYPE),STATIC)
$(BINARYDIR)/$(TARGETNAME): $(all_objs)
$(AR) -r $@ $^
endif
-include $(all_objs:.o=.dep)
clean:
ifeq ($(USE_DEL_TO_CLEAN),1)
del /S /Q $(BINARYDIR)
else
rm -f $(BINARYDIR)/*.o $(BINARYDIR)/*.dep $(BINARYDIR)/$(TARGETNAME) $(BINARYDIR)/SteamworksExample.sh
endif
$(BINARYDIR):
mkdir $(BINARYDIR)
$(BINARYDIR)/$(STEAM_API): $(LIBRARY_DIRS)/$(STEAM_API)
chmod +w $@ || true
cp -v $< $@
chmod +x $@
$(BINARYDIR)/SteamworksExample.sh: SteamworksExample.sh
cp -v $< $@
chmod +x $@
$(BINARYDIR)/DejaVuSans.ttf: DejaVuSans.ttf
cp -v $< $@
$(BINARYDIR)/%.o : %.cpp $(all_make_files) |$(BINARYDIR)
$(CXX) $(CXXFLAGS) -c $< -o $@ -MD -MF $(@:.o=.dep)
$(BINARYDIR)/%.o : %.c $(all_make_files) |$(BINARYDIR)
$(CC) $(CFLAGS) -c $< -o $@ -MD -MF $(@:.o=.dep)
$(BINARYDIR)/%.o : %.S $(all_make_files) |$(BINARYDIR)
$(CC) $(CFLAGS) $(ASFLAGS) -c $< -o $@ -MD -MF $(@:.o=.dep)
+224
View File
@@ -0,0 +1,224 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Defines the wire protocol for the game
//
// $NoKeywords: $
//=============================================================================
#ifndef MESSAGES_H
#define MESSAGES_H
#include <map>
#pragma pack( push, 1 )
// Network message types
enum EMessage
{
// Server messages
k_EMsgServerBegin = 0,
k_EMsgServerSendInfo = k_EMsgServerBegin+1,
k_EMsgServerFailAuthentication = k_EMsgServerBegin+2,
k_EMsgServerPassAuthentication = k_EMsgServerBegin+3,
k_EMsgServerUpdateWorld = k_EMsgServerBegin+4,
k_EMsgServerExiting = k_EMsgServerBegin+5,
k_EMsgServerPingResponse = k_EMsgServerBegin+6,
k_EMsgServerPlayerHitSun = k_EMsgServerBegin+7,
// Client messages
k_EMsgClientBegin = 500,
k_EMsgClientBeginAuthentication = k_EMsgClientBegin+2,
k_EMsgClientSendLocalUpdate = k_EMsgClientBegin+3,
// P2P authentication messages
k_EMsgP2PBegin = 600,
k_EMsgP2PSendingTicket = k_EMsgP2PBegin+1,
// voice chat messages
k_EMsgVoiceChatBegin = 700,
//k_EMsgVoiceChatPing = k_EMsgVoiceChatBegin+1, // deprecated keep alive message
k_EMsgVoiceChatData = k_EMsgVoiceChatBegin+2, // voice data from another player
// force 32-bit size enum so the wire protocol doesn't get outgrown later
k_EForceDWORD = 0x7fffffff,
};
// enums for use in
enum EDisconnectReason
{
k_EDRClientDisconnect = k_ESteamNetConnectionEnd_App_Min + 1,
k_EDRServerClosed = k_ESteamNetConnectionEnd_App_Min + 2,
k_EDRServerReject = k_ESteamNetConnectionEnd_App_Min + 3,
k_EDRServerFull = k_ESteamNetConnectionEnd_App_Min + 4,
k_EDRClientKicked = k_ESteamNetConnectionEnd_App_Min + 5
};
// Msg from the server to the client which is sent right after communications are established
// and tells the client what SteamID the game server is using as well as whether the server is secure
struct MsgServerSendInfo_t
{
MsgServerSendInfo_t() : m_dwMessageType( LittleDWord( k_EMsgServerSendInfo ) ) {}
DWORD GetMessageType() { return LittleDWord( m_dwMessageType ); }
void SetSteamIDServer( uint64 SteamID ) { m_ulSteamIDServer = LittleQWord( SteamID ); }
uint64 GetSteamIDServer() { return LittleQWord( m_ulSteamIDServer ); }
void SetSecure( bool bSecure ) { m_bIsVACSecure = bSecure; }
bool GetSecure() { return m_bIsVACSecure; }
void SetServerName( const char *pchName ) { strncpy_safe( m_rgchServerName, pchName, sizeof( m_rgchServerName ) ); }
const char *GetServerName() { return m_rgchServerName; }
private:
const DWORD m_dwMessageType;
uint64 m_ulSteamIDServer;
bool m_bIsVACSecure;
char m_rgchServerName[128];
};
// Msg from the server to the client when refusing a connection
struct MsgServerFailAuthentication_t
{
MsgServerFailAuthentication_t() : m_dwMessageType( LittleDWord( k_EMsgServerFailAuthentication ) ) {}
DWORD GetMessageType() { return LittleDWord( m_dwMessageType ); }
private:
const DWORD m_dwMessageType;
};
// Msg from the server to client when accepting a pending connection
struct MsgServerPassAuthentication_t
{
MsgServerPassAuthentication_t() : m_dwMessageType( LittleDWord( k_EMsgServerPassAuthentication ) ) {}
DWORD GetMessageType() { return LittleDWord( m_dwMessageType ); }
void SetPlayerPosition ( uint32 pos ) { m_uPlayerPosition = LittleDWord( pos ); }
uint32 GetPlayerPosition() { return LittleDWord( m_uPlayerPosition ); }
private:
const DWORD m_dwMessageType;
uint32 m_uPlayerPosition;
};
// Msg from the server to clients when updating the world state
struct MsgServerUpdateWorld_t
{
MsgServerUpdateWorld_t() : m_dwMessageType( LittleDWord( k_EMsgServerUpdateWorld ) ) {}
DWORD GetMessageType() { return LittleDWord( m_dwMessageType ); }
ServerSpaceWarUpdateData_t *AccessUpdateData() { return &m_ServerUpdateData; }
private:
const DWORD m_dwMessageType;
ServerSpaceWarUpdateData_t m_ServerUpdateData;
};
// Msg from server to clients when it is exiting
struct MsgServerExiting_t
{
MsgServerExiting_t() : m_dwMessageType( LittleDWord( k_EMsgServerExiting ) ) {}
DWORD GetMessageType() { return LittleDWord( m_dwMessageType ); }
private:
const DWORD m_dwMessageType;
};
// Msg from client to server when initiating authentication
struct MsgClientBeginAuthentication_t
{
MsgClientBeginAuthentication_t() : m_dwMessageType( LittleDWord( k_EMsgClientBeginAuthentication ) ) {}
DWORD GetMessageType() { return LittleDWord( m_dwMessageType ); }
void SetToken( const char *pchToken, uint32 unLen ) { m_uTokenLen = LittleDWord( unLen ); memcpy( m_rgchToken, pchToken, MIN( unLen, sizeof( m_rgchToken ) ) ); }
uint32 GetTokenLen() { return LittleDWord( m_uTokenLen ); }
const char *GetTokenPtr() { return m_rgchToken; }
void SetSteamID( uint64 ulSteamID ) { m_ulSteamID = LittleQWord( ulSteamID ); }
uint64 GetSteamID() { return LittleQWord( m_ulSteamID ); }
private:
const DWORD m_dwMessageType;
uint32 m_uTokenLen;
#ifdef USE_GS_AUTH_API
char m_rgchToken[1024];
#endif
uint64 m_ulSteamID;
};
// Msg from client to server when sending state update
struct MsgClientSendLocalUpdate_t
{
MsgClientSendLocalUpdate_t() : m_dwMessageType( LittleDWord( k_EMsgClientSendLocalUpdate ) ) {}
DWORD GetMessageType() { return LittleDWord( m_dwMessageType ); }
void SetShipPosition( uint32 uPos ) { m_uShipPosition = LittleDWord( uPos ); }
ClientSpaceWarUpdateData_t *AccessUpdateData() { return &m_ClientUpdateData; }
private:
const DWORD m_dwMessageType;
uint32 m_uShipPosition;
ClientSpaceWarUpdateData_t m_ClientUpdateData;
};
// Message sent from one peer to another, so peers authenticate directly with each other.
// (In this example, the server is responsible for relaying the messages, but peers
// are directly authenticating each other.)
struct MsgP2PSendingTicket_t
{
MsgP2PSendingTicket_t() : m_dwMessageType( LittleDWord( k_EMsgP2PSendingTicket ) ) {}
DWORD GetMessageType() { return LittleDWord( m_dwMessageType ); }
void SetToken( const void *pToken, uint32 unLen ) { m_uTokenLen = LittleDWord( unLen ); memcpy( m_rgchToken, pToken, MIN( unLen, sizeof( m_rgchToken ) ) ); }
uint32 GetTokenLen() const { return LittleDWord( m_uTokenLen ); }
const char *GetTokenPtr() const { return m_rgchToken; }
// Sender or receiver (depending on context)
void SetSteamID( uint64 ulSteamID ) { m_ulSteamID = LittleQWord( ulSteamID ); }
uint64 GetSteamID() const { return LittleQWord( m_ulSteamID ); }
private:
DWORD m_dwMessageType;
uint32 m_uTokenLen;
char m_rgchToken[1024];
uint64 m_ulSteamID;
};
// voice chat data. This is relayed through the server
struct MsgVoiceChatData_t
{
MsgVoiceChatData_t() : m_dwMessageType( LittleDWord( k_EMsgVoiceChatData ) ) {}
DWORD GetMessageType() const { return LittleDWord( m_dwMessageType ); }
void SetDataLength( uint32 unLength ) { m_uDataLength = LittleDWord( unLength ); }
uint32 GetDataLength() const { return LittleDWord( m_uDataLength ); }
void SetSteamID(CSteamID steamID) { from_steamID = steamID; }
CSteamID GetSteamID() const { return from_steamID; }
private:
const DWORD m_dwMessageType;
uint32 m_uDataLength;
CSteamID from_steamID;
};
// A notification to the client that this player collided with the sun
struct MsgServerPlayerHitSun_t
{
MsgServerPlayerHitSun_t() : m_dwMessageType( LittleDWord( k_EMsgServerPlayerHitSun ) ) {}
DWORD GetMessageType() const { return LittleDWord( m_dwMessageType ); }
void SetSteamID( CSteamID steamID ) { from_steamID = steamID; }
CSteamID GetSteamID() const { return from_steamID; }
private:
const DWORD m_dwMessageType;
CSteamID from_steamID;
};
#pragma pack( pop )
#endif // MESSAGES_H
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 318 B

@@ -0,0 +1,289 @@
//========= Copyright Valve LLC, All rights reserved. ============
//
// Purpose: Examples for interacting with Overlay
//
//=============================================================================
#include "stdafx.h"
#include "OverlayExamples.h"
#include "BaseMenu.h"
#include <math.h>
#include <vector>
#include <algorithm>
//-----------------------------------------------------------------------------
// Purpose: Menu that shows your friends
//-----------------------------------------------------------------------------
class COverlayExamplesMenu : public CBaseMenu<OverlayExample_t>
{
public:
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
COverlayExamplesMenu( IGameEngine *pGameEngine, COverlayExamples *pOverlayExamples ) : CBaseMenu<OverlayExample_t>( pGameEngine ), m_pOverlayExamples( pOverlayExamples )
{
}
//-----------------------------------------------------------------------------
// Purpose: Creates menu
//-----------------------------------------------------------------------------
void Rebuild()
{
PushSelectedItem();
ClearMenuItems();
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlay - Friends", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlay, "Friends" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlay - Community", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlay, "Community" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlay - Settings", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlay, "Settings" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlay - LobbyInvite", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlay, "LobbyInvite" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlay - OfficialGameGroup", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlay, "OfficialGameGroup" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlay - Leaderboards", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlay, "Leaderboards" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - steamid", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "steamid" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - chat", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "chat" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - jointrade", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "jointrade" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - stats", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "stats" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - achievements", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "achievements" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - friendadd", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "friendadd" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - friendremove", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "friendremove" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - friendrequestaccept", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "friendrequestaccept" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToUser - friendrequestignore", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser, "friendrequestignore" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToWebPage", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToWebPage, "https://steamcommunity.com/" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToWebPageModal", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToWebPageModal, "https://steamcommunity.com/" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToStore", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToStore, "" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToStore - Add to Cart", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToStore, "addtocart" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayToStore - Add to Cart & Show", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToStore, "addtocartandshow" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "ActivateGameOverlayInviteDialogConnectString", { OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayInviteDialogConnectString, NULL } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( SteamScreenshots()->IsScreenshotsHooked() ? "Screenshots Hooked!" : "Hook Screenshots", { OverlayExample_t::k_EOverlayExampleItem_HookScreenshots, NULL } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Request Keyboard", { OverlayExample_t::k_EOverlayExampleItem_RequestKeyboard, NULL } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Set Notification Inset", { OverlayExample_t::k_EOverlayExampleItem_Notification_SetInset, "100" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Reset Notification Inset", { OverlayExample_t::k_EOverlayExampleItem_Notification_SetInset, "0" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Set Notification Position: Top Left", { OverlayExample_t::k_EOverlayExampleItem_Notification_SetPosition, "0" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Set Notification Position: Top Right", { OverlayExample_t::k_EOverlayExampleItem_Notification_SetPosition, "1" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Set Notification Position: Bottom Left", { OverlayExample_t::k_EOverlayExampleItem_Notification_SetPosition, "2" } ) );
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Set Notification Position: Bottom Right", { OverlayExample_t::k_EOverlayExampleItem_Notification_SetPosition, "3" } ) );
if ( m_pOverlayExamples->BHasLastGamePhase() )
{
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Show last match", { OverlayExample_t::k_EOverlayExampleItem_Timeline_OpenOverlayToGamePhase } ) );
}
if ( m_pOverlayExamples->BHasLastTimelineEvent() )
{
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Show last crash into sun", { OverlayExample_t::k_EOverlayExampleItem_Timeline_OpenOverlayToTimelineEvent } ) );
}
AddMenuItem( COverlayExamplesMenu::MenuItem_t( "Return to main menu", { OverlayExample_t::k_EOverlayExampleItem_BackToMenu, NULL } ) );
PopSelectedItem();
}
private:
COverlayExamples *m_pOverlayExamples;
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
COverlayExamples::COverlayExamples( IGameEngine *pGameEngine )
: m_pGameEngine( pGameEngine )
{
m_pMenu = new COverlayExamplesMenu( pGameEngine, this );
m_delayedCommand = { OverlayExample_t::k_EOverlayExampleItem_Invalid, NULL };
Show();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COverlayExamples::RunFrame()
{
m_pMenu->RunFrame();
if ( !m_pGameEngine->BIsKeyDown( VK_RETURN ) && !m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_MenuSelect ) )
{
switch ( m_delayedCommand.m_eItem )
{
case OverlayExample_t::k_EOverlayExampleItem_BackToMenu:
{
SpaceWarClient()->SetGameState( k_EClientGameMenu );
}
break;
case OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlay:
{
SteamFriends()->ActivateGameOverlay( m_delayedCommand.m_pchExtraCommandData );
}
break;
case OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToUser:
{
// pick first friend
if ( SteamFriends()->GetFriendCount( k_EFriendFlagImmediate ) != 0 )
{
CSteamID steamID = SteamFriends()->GetFriendByIndex( 0, k_EFriendFlagImmediate );
SteamFriends()->ActivateGameOverlayToUser( m_delayedCommand.m_pchExtraCommandData, steamID );
}
}
break;
case OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToWebPage:
{
SteamFriends()->ActivateGameOverlayToWebPage( m_delayedCommand.m_pchExtraCommandData );
}
break;
case OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToWebPageModal:
{
SteamFriends()->ActivateGameOverlayToWebPage( m_delayedCommand.m_pchExtraCommandData, k_EActivateGameOverlayToWebPageMode_Modal );
}
break;
case OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayToStore:
{
if ( !strcmp( m_delayedCommand.m_pchExtraCommandData, "addtocart" ) )
{
SteamFriends()->ActivateGameOverlayToStore( 440, k_EOverlayToStoreFlag_AddToCart );
}
else if ( !strcmp( m_delayedCommand.m_pchExtraCommandData, "addtocartandshow" ) )
{
SteamFriends()->ActivateGameOverlayToStore( 440, k_EOverlayToStoreFlag_AddToCartAndShow );
}
else
{
SteamFriends()->ActivateGameOverlayToStore( 440, k_EOverlayToStoreFlag_None );
}
}
break;
/*
case OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayRemotePlayTogetherInviteDialog:
{
SteamFriends()->ActivateGameOverlayRemotePlayTogetherInviteDialog( steamIDLobby );
}
break;
*/
case OverlayExample_t::k_EOverlayExampleItem_ActivateGameOverlayInviteDialogConnectString:
{
const char *pConnectString = SteamFriends()->GetFriendRichPresence( SteamUser()->GetSteamID(), "connect" );
SteamFriends()->ActivateGameOverlayInviteDialogConnectString( pConnectString );
}
break;
case OverlayExample_t::k_EOverlayExampleItem_HookScreenshots:
{
SteamScreenshots()->HookScreenshots( !SteamScreenshots()->IsScreenshotsHooked() );
m_pMenu->Rebuild();
}
break;
case OverlayExample_t::k_EOverlayExampleItem_RequestKeyboard:
{
EGamepadTextInputMode eInputMode = k_EGamepadTextInputModeNormal;
EGamepadTextInputLineMode eLineInputMode = k_EGamepadTextInputLineModeSingleLine;
const char *pchDescription = "Enter Text Here";
uint32 unCharMax = 20;
const char *pchExistingText = "Placeholder";
SteamUtils()->ShowGamepadTextInput( eInputMode , eLineInputMode, pchDescription, unCharMax, pchExistingText );
}
break;
case OverlayExample_t::k_EOverlayExampleItem_Notification_SetInset:
SteamUtils()->SetOverlayNotificationInset( atoi( m_delayedCommand.m_pchExtraCommandData ), atoi( m_delayedCommand.m_pchExtraCommandData ) );
break;
case OverlayExample_t::k_EOverlayExampleItem_Notification_SetPosition:
SteamUtils()->SetOverlayNotificationPosition( (ENotificationPosition)atoi( m_delayedCommand.m_pchExtraCommandData ) );
break;
case OverlayExample_t::k_EOverlayExampleItem_Timeline_OpenOverlayToGamePhase:
SteamTimeline()->OpenOverlayToGamePhase( m_strLastGamePhaseIDToShow.c_str() );
break;
case OverlayExample_t::k_EOverlayExampleItem_Timeline_OpenOverlayToTimelineEvent:
SteamTimeline()->OpenOverlayToTimelineEvent( m_ulLastCrashIntoSunEventIDToShow );
break;
default:
break;
}
m_delayedCommand.m_eItem = OverlayExample_t::k_EOverlayExampleItem_Invalid;
}
}
//-----------------------------------------------------------------------------
// Purpose: Handles menu actions when viewing a friends list
//-----------------------------------------------------------------------------
void COverlayExamples::OnMenuSelection( OverlayExample_t selection )
{
m_delayedCommand = selection;
}
//-----------------------------------------------------------------------------
// Purpose: Shows / Refreshes the friends list
//-----------------------------------------------------------------------------
void COverlayExamples::Show()
{
if ( SpaceWarClient()->GetLastGamePhaseID() )
{
SteamAPICall_t hSteamAPICall = SteamTimeline()->DoesGamePhaseRecordingExist( std::to_string( SpaceWarClient()->GetLastGamePhaseID() ).c_str() );
m_SteamCallResultDoesGamePhaseRecordingExist.Set( hSteamAPICall, this, &COverlayExamples::OnDoesGamePhaseRecordingExist );
}
m_strLastGamePhaseIDToShow.erase();
if ( SpaceWarClient()->GetLastCrashIntoSunEvent() )
{
SteamAPICall_t hSteamAPICall = SteamTimeline()->DoesEventRecordingExist( SpaceWarClient()->GetLastCrashIntoSunEvent() );
m_SteamCallResultDoesEventRecordingExist.Set( hSteamAPICall, this, &COverlayExamples::OnDoesEventRecordingExist );
}
m_pMenu->Rebuild();
}
void COverlayExamples::OnScreenshotRequested( ScreenshotRequested_t *pCallback )
{
SteamFriends()->ActivateGameOverlayToWebPage( "google.com" );
}
void COverlayExamples::OnSteamScreenshotReady( ScreenshotReady_t *pCallback )
{
}
void COverlayExamples::OnDoesEventRecordingExist( SteamTimelineEventRecordingExists_t *pCallback, bool bIOFailure )
{
if ( bIOFailure || !pCallback->m_bRecordingExists )
{
// nothing to do here. We didn't show these items when showing the menu
return;
}
m_ulLastCrashIntoSunEventIDToShow = pCallback->m_ulEventID;
m_pMenu->Rebuild();
}
void COverlayExamples::OnDoesGamePhaseRecordingExist( SteamTimelineGamePhaseRecordingExists_t *pCallback, bool bIOFailure )
{
if ( bIOFailure || ( pCallback->m_ulRecordingMS == 0 && pCallback->m_unClipCount == 0 ) )
{
// nothing to do here. We didn't show these items when showing the menu
return;
}
m_strLastGamePhaseIDToShow = pCallback->m_rgchPhaseID;
m_pMenu->Rebuild();
}
+58
View File
@@ -0,0 +1,58 @@
//========= Copyright © Valve LLC, All rights reserved. ============
//
// Purpose: Class that shows some examples for bringing up the Steam Overlay
//
//=============================================================================
#ifndef OVERLAYEXAMPLES_H
#define OVERLAYEXAMPLES_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "SpaceWarClient.h"
class CSpaceWarClient;
class COverlayExamplesMenu;
class COverlayExamples
{
public:
// Constructor
COverlayExamples( IGameEngine *pGameEngine );
// Run a frame
void RunFrame();
// shows / refreshes item store
void Show();
// handles input from menu
void OnMenuSelection( OverlayExample_t selection );
bool BHasLastGamePhase() const { return !m_strLastGamePhaseIDToShow.empty(); }
bool BHasLastTimelineEvent() const { return m_ulLastCrashIntoSunEventIDToShow != 0; }
private:
// Engine
IGameEngine *m_pGameEngine;
COverlayExamplesMenu *m_pMenu;
OverlayExample_t m_delayedCommand;
std::string m_strLastGamePhaseIDToShow;
uint64 m_ulLastCrashIntoSunEventIDToShow = 0;
STEAM_CALLBACK( COverlayExamples, OnScreenshotRequested, ScreenshotRequested_t );
STEAM_CALLBACK( COverlayExamples, OnSteamScreenshotReady, ScreenshotReady_t );
// callback for when we ask about an event having recordings
void OnDoesEventRecordingExist( SteamTimelineEventRecordingExists_t *pCallback, bool bIOFailure );
CCallResult<COverlayExamples, SteamTimelineEventRecordingExists_t> m_SteamCallResultDoesEventRecordingExist;
// callback for when we ask about a phase having recordings
void OnDoesGamePhaseRecordingExist( SteamTimelineGamePhaseRecordingExists_t *pCallback, bool bIOFailure );
CCallResult<COverlayExamples, SteamTimelineGamePhaseRecordingExists_t> m_SteamCallResultDoesGamePhaseRecordingExist;
};
#endif // OVERLAYEXAMPLES_H
+40
View File
@@ -0,0 +1,40 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for rendering photon beams
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "PhotonBeam.h"
#include "SpaceWar.h"
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CPhotonBeam::CPhotonBeam( IGameEngine *pGameEngine, float xPos, float yPos, DWORD dwBeamColor, float flInitialRotation, float flInitialXVelocity, float flInitialYVelocity )
: CSpaceWarEntity( pGameEngine, 3, true )
{
// Beams only have a lifetime of 1 second
m_ulTickCountToDieAt = m_pGameEngine->GetGameTickCount()+PHOTON_BEAM_LIFETIME_IN_TICKS;
// Set a really high max velocity for photon beams
SetMaximumVelocity( 500 );
AddLine( -2.0f, -3.0f, -2.0f, 3.0f, dwBeamColor );
AddLine( 2.0f, -3.0f, 2.0f, 3.0f, dwBeamColor );
SetPosition( xPos, yPos );
SetRotationDeltaNextFrame( flInitialRotation );
SetVelocity( flInitialXVelocity, flInitialYVelocity );
}
//-----------------------------------------------------------------------------
// Purpose: Update with data from server
//-----------------------------------------------------------------------------
void CPhotonBeam::OnReceiveServerUpdate( ServerPhotonBeamUpdateData_t *pUpdateData )
{
SetPosition( pUpdateData->GetXPosition()*m_pGameEngine->GetViewportWidth(), pUpdateData->GetYPosition()*m_pGameEngine->GetViewportHeight() );
SetVelocity( pUpdateData->GetXVelocity(), pUpdateData->GetYVelocity() );
SetAccumulatedRotation( pUpdateData->GetRotation() );
}
+31
View File
@@ -0,0 +1,31 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for rendering photon beams
//
// $NoKeywords: $
//=============================================================================
#ifndef PHOTONBEAM_H
#define PHOTONBEAM_H
#include "GameEngine.h"
#include "SpaceWarEntity.h"
#include "SpaceWar.h"
class CPhotonBeam : public CSpaceWarEntity
{
public:
// Constructor
CPhotonBeam( IGameEngine *pGameEngine, float xPos, float yPos, DWORD dwBeamColor, float flInitialRotation, float flInitialXVelocity, float flInitialYVelocity );
// Check if the photon beam needs to die
bool BIsBeamExpired() { return m_pGameEngine->GetGameTickCount() > m_ulTickCountToDieAt; }
// Update with new data from server
void OnReceiveServerUpdate( ServerPhotonBeamUpdateData_t *pUpdateData );
private:
uint64 m_ulTickCountToDieAt;
};
#endif // PHOTONBEAM_H
+21
View File
@@ -0,0 +1,21 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class to define the pause menu
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "QuitMenu.h"
#include "SpaceWar.h"
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CQuitMenu::CQuitMenu( IGameEngine *pGameEngine ) : CBaseMenu<EClientGameState>( pGameEngine )
{
AddMenuItem( MenuItem_t( "Resume Game", k_EClientGameActive ) );
AddMenuItem( MenuItem_t( "Exit To Menu", k_EClientGameMenu ) );
AddMenuItem( MenuItem_t( "Exit To Desktop", k_EClientGameExiting ) );
}
+25
View File
@@ -0,0 +1,25 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class to define the pause game menu
//
// $NoKeywords: $
//=============================================================================
#ifndef QUITMENU_H
#define QUITMENU_H
#include <string>
#include <vector>
#include "GameEngine.h"
#include "SpaceWar.h"
#include "BaseMenu.h"
#include "SpaceWarClient.h"
class CQuitMenu : public CBaseMenu<EClientGameState>
{
public:
// Constructor
CQuitMenu( IGameEngine *pGameEngine );
};
#endif // QUITMENU_H
+180
View File
@@ -0,0 +1,180 @@
//========= Copyright 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for Remote Play session list
//
//=============================================================================
#include "stdafx.h"
#include "RemotePlay.h"
#include "BaseMenu.h"
//-----------------------------------------------------------------------------
// Purpose: Menu that shows your Remote Play session
//-----------------------------------------------------------------------------
class CRemotePlayListMenu : public CBaseMenu<RemotePlayListMenuItem_t>
{
static const RemotePlayListMenuItem_t k_menuItemEmpty;
public:
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CRemotePlayListMenu( IGameEngine *pGameEngine ) : CBaseMenu<RemotePlayListMenuItem_t>( pGameEngine )
{
}
//-----------------------------------------------------------------------------
// Purpose: Creates Remote Play session list menu
//-----------------------------------------------------------------------------
void Rebuild()
{
PushSelectedItem();
ClearMenuItems();
AddMenuItem( CRemotePlayListMenu::MenuItem_t( "Remote Play Session List", k_menuItemEmpty ) );
InputHandle_t arrInputHandles[ STEAM_INPUT_MAX_COUNT ];
int nNumControllers = SteamInput()->GetConnectedControllers( arrInputHandles );
uint32 unSessionCount = SteamRemotePlay()->GetSessionCount();
for ( uint32 iIndex = 0; iIndex < unSessionCount; iIndex++ )
{
RemotePlaySessionID_t unSessionID = SteamRemotePlay()->GetSessionID( iIndex );
if ( !unSessionID )
{
continue;
}
RemotePlayListMenuItem_t item;
item.m_unSessionID = unSessionID;
const char *pszSessionPersonaName = SteamFriends()->GetFriendPersonaName( SteamRemotePlay()->GetSessionSteamID( unSessionID ) );
const char *pszSessionClientName = SteamRemotePlay()->GetSessionClientName( unSessionID );
const char *pszSessionClientFormFactor = GetFormFactor( SteamRemotePlay()->GetSessionClientFormFactor( unSessionID ) );
int nResolutionX, nResolutionY;
SteamRemotePlay()->BGetSessionClientResolution( unSessionID, &nResolutionX, &nResolutionY );
char szLabel[ 1024 ];
snprintf( szLabel, sizeof( szLabel ), "%s streaming to %s: %s %dx%d", pszSessionPersonaName, pszSessionClientName, pszSessionClientFormFactor, nResolutionX, nResolutionY );
for ( int iController = 0; iController < nNumControllers; ++iController )
{
if ( SteamInput()->GetRemotePlaySessionID( arrInputHandles[ iController ] ) == unSessionID )
{
strncat( szLabel, ", has ", sizeof( szLabel ) - strlen( szLabel ) - 1 );
strncat( szLabel, GetControllerType( SteamInput()->GetInputTypeForHandle( arrInputHandles[ iController ] ) ), sizeof( szLabel ) - strlen( szLabel ) - 1 );
}
}
AddMenuItem( CRemotePlayListMenu::MenuItem_t( szLabel, item ) );
}
PopSelectedItem();
}
private:
const char *GetFormFactor( ESteamDeviceFormFactor eFormFactor )
{
switch ( eFormFactor )
{
case k_ESteamDeviceFormFactorPhone:
return "[PHONE]";
case k_ESteamDeviceFormFactorTablet:
return "[TABLET]";
case k_ESteamDeviceFormFactorComputer:
return "[COMPUTER]";
case k_ESteamDeviceFormFactorTV:
return "[TV]";
default:
return "[UNKNOWN]";
}
}
const char *GetControllerType( ESteamInputType eInputType )
{
switch ( eInputType )
{
case k_ESteamInputType_SteamController:
return "Steam Controller";
case k_ESteamInputType_XBox360Controller:
return "XBox 360 Controller";
case k_ESteamInputType_XBoxOneController:
return "XBox One Controller";
case k_ESteamInputType_PS4Controller:
return "PS4 Controller";
case k_ESteamInputType_MobileTouch:
return "Touch Controller";
default:
return "Game Controller";
}
}
};
const RemotePlayListMenuItem_t CRemotePlayListMenu::k_menuItemEmpty = { 0 };
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CRemotePlayList::CRemotePlayList( IGameEngine *pGameEngine ) : m_pGameEngine( pGameEngine )
{
m_pRemotePlayListMenu = new CRemotePlayListMenu( pGameEngine );
m_nNumControllers = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame for the CRemotePlayList
//-----------------------------------------------------------------------------
void CRemotePlayList::RunFrame()
{
InputHandle_t arrInputHandles[ STEAM_INPUT_MAX_COUNT ];
int nNumControllers = SteamInput()->GetConnectedControllers( arrInputHandles );
if ( nNumControllers != m_nNumControllers )
{
m_nNumControllers = nNumControllers;
m_pRemotePlayListMenu->Rebuild();
}
m_pRemotePlayListMenu->RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Handles menu actions when viewing a Remote Play session list
//-----------------------------------------------------------------------------
void CRemotePlayList::OnMenuSelection( RemotePlayListMenuItem_t selection )
{
// Do nothing (yet)
}
//-----------------------------------------------------------------------------
// Purpose: Shows / Refreshes the Remote Play session list
//-----------------------------------------------------------------------------
void CRemotePlayList::Show()
{
m_pRemotePlayListMenu->Rebuild();
}
//-----------------------------------------------------------------------------
// Purpose: Handle Remote Play session connected
//-----------------------------------------------------------------------------
void CRemotePlayList::OnRemotePlaySessionConnected( SteamRemotePlaySessionConnected_t *pParam )
{
m_pRemotePlayListMenu->Rebuild();
}
//-----------------------------------------------------------------------------
// Purpose: Handle Remote Play session disconnected
//-----------------------------------------------------------------------------
void CRemotePlayList::OnRemotePlaySessionDisconnected( SteamRemotePlaySessionDisconnected_t *pParam )
{
m_pRemotePlayListMenu->Rebuild();
}
+45
View File
@@ -0,0 +1,45 @@
//========= Copyright © 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for Remote Play session list
//
//=============================================================================
#ifndef REMOTEPLAY_H
#define REMOTEPLAY_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "SpaceWarClient.h"
class CSpaceWarClient;
class CRemotePlayListMenu;
class CRemotePlayList
{
public:
// Constructor
CRemotePlayList( IGameEngine *pGameEngine );
// Run a frame
void RunFrame();
// shows / refreshes Remote Play session list
void Show();
// handles input from Remote Play session list menu
void OnMenuSelection( RemotePlayListMenuItem_t selection );
private:
STEAM_CALLBACK( CRemotePlayList, OnRemotePlaySessionConnected, SteamRemotePlaySessionConnected_t );
STEAM_CALLBACK( CRemotePlayList, OnRemotePlaySessionDisconnected, SteamRemotePlaySessionDisconnected_t );
private:
// Engine
IGameEngine *m_pGameEngine;
CRemotePlayListMenu *m_pRemotePlayListMenu;
int m_nNumControllers;
};
#endif // REMOTEPLAY_H
+365
View File
@@ -0,0 +1,365 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking stats and achievements
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "RemoteStorage.h"
#include "BaseMenu.h"
#include <assert.h>
#define CLOUDDISP_FONT_HEIGHT 20
#define CLOUDDISP_COLUMN_WIDTH 600
#define CLOUDDISP_TEXT_HEIGHT 20
#define CLOUDDISP_VERT_SPACING 4
#define MESSAGE_FILE_NAME "message.dat"
extern uint64 g_ulLastReturnKeyTick;
//-----------------------------------------------------------------------------
// NOTE
//
// The Steam program is normally responsible for synchronizing an App's files
// to the Steam Cloud before launch and after the program exits.
//
// This means that, if you build this example app and run it directly,
// the Remote Storage page may appear to work (it will save the file changes
// to disk, locally), however nothing will actually get pulled down from
// or sent up to the Steam Cloud.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CRemoteStorage::CRemoteStorage( IGameEngine *pGameEngine ) : m_pGameEngine( pGameEngine )
{
m_pRemoteStorageScreen = new CRemoteStorageScreen( pGameEngine );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CRemoteStorage::~CRemoteStorage()
{
delete m_pRemoteStorageScreen;
}
//-----------------------------------------------------------------------------
// Purpose: Called when the user selects view remote storage files
//-----------------------------------------------------------------------------
void CRemoteStorage::Show()
{
m_pRemoteStorageScreen->Show();
}
//-----------------------------------------------------------------------------
// Purpose: Called once per frame
//-----------------------------------------------------------------------------
void CRemoteStorage::Render()
{
m_pRemoteStorageScreen->Render();
if ( m_pRemoteStorageScreen->BFinished() )
SpaceWarClient()->SetGameState( k_EClientGameMenu );
}
//-----------------------------------------------------------------------------
// Purpose: A sync menu item has been selected
//-----------------------------------------------------------------------------
void CRemoteStorage::OnMenuSelection( ERemoteStorageSyncMenuCommand selection )
{
}
//-----------------------------------------------------------------------------
// Purpose: CRemoteStorageScreen implementation
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CRemoteStorageScreen::CRemoteStorageScreen( IGameEngine *pGameEngine ) : m_pGameEngine( pGameEngine )
{
m_rgchGreeting[0] = 0;
strncpy( m_rgchGreeting, "<none>", sizeof( m_rgchGreeting ) );
m_rgchGreetingNext[0] = 0;
m_pSteamRemoteStorage = SteamRemoteStorage();
m_hDisplayFont = pGameEngine->HCreateFont( CLOUDDISP_FONT_HEIGHT, FW_MEDIUM, false, "Arial" );
if ( !m_hDisplayFont )
OutputDebugString( "RemoteStorage font was not created properly, text won't draw\n" );
GetFileStats();
}
//-----------------------------------------------------------------------------
// Purpose: Load the user's saved message
//-----------------------------------------------------------------------------
void CRemoteStorageScreen::LoadMessage()
{
if ( !m_pSteamRemoteStorage->FileExists( MESSAGE_FILE_NAME ) )
return;
int32 cubFile = m_pSteamRemoteStorage->GetFileSize( MESSAGE_FILE_NAME );
if ( cubFile >= sizeof( m_rgchGreeting ) )
{
// ?? too big, nuke it
char c = 0;
OutputDebugString( "RemoteStorage: File was larger than expected. . .\n" );
m_pSteamRemoteStorage->FileWrite( MESSAGE_FILE_NAME, &c, 1 );
}
else
{
int32 cubRead = m_pSteamRemoteStorage->FileRead( MESSAGE_FILE_NAME, m_rgchGreeting, sizeof( m_rgchGreeting ) - 1 );
m_rgchGreeting[cubRead] = 0; // null-terminate
}
}
//-----------------------------------------------------------------------------
// Purpose: Update stats on our files in the Cloud
//-----------------------------------------------------------------------------
void CRemoteStorageScreen::GetFileStats()
{
m_ulBytesQuota = 0;
m_ulAvailableBytes = 0;
m_nNumFilesInCloud = m_pSteamRemoteStorage->GetFileCount();
m_pSteamRemoteStorage->GetQuota( &m_ulBytesQuota, &m_ulAvailableBytes );
}
//-----------------------------------------------------------------------------
// Purpose: Called when the user selects view remote storage files
//-----------------------------------------------------------------------------
void CRemoteStorageScreen::Show()
{
GetFileStats();
LoadMessage();
if ( m_pGameEngine->BIsSteamInputDeviceActive() )
{
const int32 width = m_pGameEngine->GetViewportWidth();
const int32 pxColumn1Left = width / 2 - CLOUDDISP_COLUMN_WIDTH / 2;
int32 pxVertOffset = 8 * CLOUDDISP_TEXT_HEIGHT + 4 * ( CLOUDDISP_TEXT_HEIGHT + CLOUDDISP_VERT_SPACING );
SteamUtils()->ShowFloatingGamepadTextInput( k_EFloatingGamepadTextInputModeModeSingleLine, pxColumn1Left, pxVertOffset, CLOUDDISP_COLUMN_WIDTH, CLOUDDISP_TEXT_HEIGHT );
}
}
bool CRemoteStorageScreen::BHandleCancel()
{
// always cancel
m_rgchGreetingNext[0] = 0;
if( m_pGameEngine->BIsSteamInputDeviceActive() )
{
SteamUtils()->DismissFloatingGamepadTextInput();
}
m_bFinished = true;
return true;
}
bool CRemoteStorageScreen::BHandleSelect()
{
int nGreetingNextLength = (int)strlen( m_rgchGreetingNext );
bool bQuotaExceeded = nGreetingNextLength > m_ulBytesQuota;
if ( !bQuotaExceeded )
{
uint64 ulCurrentTickCount = m_pGameEngine->GetGameTickCount();
if ( ulCurrentTickCount - 150 > g_ulLastReturnKeyTick )
{
// global from BaseMenu.h!
g_ulLastReturnKeyTick = ulCurrentTickCount;
// Do it
{
m_bFinished = true;
strncpy( m_rgchGreeting, m_rgchGreetingNext, sizeof( m_rgchGreeting ) );
m_rgchGreetingNext[0] = 0;
// Note: not writing the NULL termination, so won't read it back later either.
bool bRet = m_pSteamRemoteStorage->FileWrite( MESSAGE_FILE_NAME, m_rgchGreeting, (int)strlen( m_rgchGreeting ) );
// Update our stats on stuff
GetFileStats();
if ( !bRet )
{
OutputDebugString( "RemoteStorage: Failed to write file!\n" );
}
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Render the Remote Storage page
//-----------------------------------------------------------------------------
void CRemoteStorageScreen::Render()
{
m_bFinished = false;
// Update key press information
int nGreetingNextLength = (int) strlen( m_rgchGreetingNext );
DWORD dwVKDown = 0;
bool bQuotaExceeded = nGreetingNextLength > m_ulBytesQuota;
if ( m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_MenuCancel ) )
{
if ( BHandleCancel() )
return;
}
else if ( m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_MenuSelect ) )
{
if ( BHandleSelect() )
return;
}
while ( m_pGameEngine->BGetFirstKeyDown( &dwVKDown ) )
{
if ( VK_ESCAPE == dwVKDown )
{
if ( BHandleCancel() )
return;
}
else if ( VK_RETURN == dwVKDown )
{
if ( BHandleSelect() )
return;
}
else if ( VK_BACK == dwVKDown )
{
if ( nGreetingNextLength )
{
m_rgchGreetingNext[--nGreetingNextLength] = 0;
}
}
else if ( ( dwVKDown >= 0x30 && dwVKDown <= 0x39 )
|| ( dwVKDown >= 0x41 && dwVKDown <= 0x5A )
|| dwVKDown == VK_SPACE )
{
// Add the key pressed
if ( nGreetingNextLength + 1 < sizeof( m_rgchGreetingNext ) )
{
m_rgchGreetingNext[nGreetingNextLength++] = (char) dwVKDown;
m_rgchGreetingNext[nGreetingNextLength] = 0;
}
}
}
const int32 width = m_pGameEngine->GetViewportWidth();
//const int32 height = m_pGameEngine->GetViewportHeight();
const int32 pxColumn1Left = width / 2 - CLOUDDISP_COLUMN_WIDTH / 2;
RECT rect;
{
int32 pxVertOffset = 8 * ( CLOUDDISP_TEXT_HEIGHT );
rect.top = pxVertOffset;
rect.bottom = rect.top + CLOUDDISP_TEXT_HEIGHT;
rect.left = pxColumn1Left;
rect.right = rect.left + CLOUDDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + CLOUDDISP_VERT_SPACING;
char rgchBuffer[256];
sprintf_safe( rgchBuffer, "Num Files In Cloud: %d", m_nNumFilesInCloud );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, rgchBuffer );
rect.top = pxVertOffset;
rect.bottom = rect.top + CLOUDDISP_TEXT_HEIGHT;
rect.left = pxColumn1Left;
rect.right = rect.left + CLOUDDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + CLOUDDISP_TEXT_HEIGHT + CLOUDDISP_VERT_SPACING;
sprintf_safe( rgchBuffer, "Quota: %llu bytes, %llu bytes remaining", m_ulBytesQuota, m_ulAvailableBytes );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, rgchBuffer );
rect.top = pxVertOffset;
rect.bottom = rect.top + CLOUDDISP_TEXT_HEIGHT;
rect.left = pxColumn1Left;
rect.right = rect.left + CLOUDDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + CLOUDDISP_VERT_SPACING;
sprintf_safe( rgchBuffer, "Current Message:" );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, rgchBuffer );
rect.top = pxVertOffset;
rect.bottom = rect.top + CLOUDDISP_TEXT_HEIGHT;
rect.left = pxColumn1Left;
rect.right = rect.left + CLOUDDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + CLOUDDISP_TEXT_HEIGHT + CLOUDDISP_VERT_SPACING;
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, m_rgchGreeting );
rect.top = pxVertOffset;
rect.bottom = rect.top + CLOUDDISP_TEXT_HEIGHT;
rect.left = pxColumn1Left;
rect.right = rect.left + CLOUDDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + CLOUDDISP_VERT_SPACING;
sprintf_safe( rgchBuffer, "Type in a new message below:" );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, rgchBuffer );
rect.top = pxVertOffset;
rect.bottom = rect.top + CLOUDDISP_TEXT_HEIGHT;
rect.left = pxColumn1Left;
rect.right = rect.left + CLOUDDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + CLOUDDISP_TEXT_HEIGHT + CLOUDDISP_VERT_SPACING;
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, m_rgchGreetingNext );
rect.top = pxVertOffset;
rect.bottom = rect.top + CLOUDDISP_TEXT_HEIGHT;
rect.left = pxColumn1Left;
rect.right = rect.left + CLOUDDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + CLOUDDISP_TEXT_HEIGHT + CLOUDDISP_VERT_SPACING;
if ( m_pGameEngine->BIsSteamInputDeviceActive() )
{
const char *rgchSaveActionOrigin = m_pGameEngine->GetTextStringForControllerOriginDigital( eControllerActionSet_MenuControls, eControllerDigitalAction_MenuSelect );
const char *rgchCancelActionOrigin = m_pGameEngine->GetTextStringForControllerOriginDigital( eControllerActionSet_MenuControls, eControllerDigitalAction_MenuCancel );
if ( strcmp( rgchSaveActionOrigin, "None" ) == 0 || strcmp( rgchCancelActionOrigin, "None" ) == 0 )
{
sprintf_safe( rgchBuffer, "Hit <ENTER> to save, <ESC> to cancel. Controller bindings are not setup properly" );
}
else
{
sprintf_safe( rgchBuffer, "Hit <ENTER> or %s to save, <ESC> or %s to cancel", rgchSaveActionOrigin, rgchCancelActionOrigin );
}
}
else
{
sprintf_safe( rgchBuffer, "Hit <ENTER> to save, <ESC> to cancel" );
}
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, rgchBuffer );
if ( bQuotaExceeded )
{
rect.top = pxVertOffset;
rect.bottom = rect.top + CLOUDDISP_TEXT_HEIGHT;
rect.left = pxColumn1Left;
rect.right = rect.left + CLOUDDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + CLOUDDISP_TEXT_HEIGHT + CLOUDDISP_VERT_SPACING;
sprintf_safe( rgchBuffer, "!! QUOTA EXCEEDED !!" );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, rgchBuffer );
}
}
}
+100
View File
@@ -0,0 +1,100 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for manipulating Steam Cloud
//
// $NoKeywords: $
//=============================================================================
#ifndef REMOTE_STORAGE_H
#define REMOTE_STORAGE_H
#include "SpaceWar.h"
#include "GameEngine.h"
class ISteamUser;
class CSpaceWarClient;
class IRemoteStorageSync;
class CRemoteStorageScreen;
enum ERemoteStorageSyncMenuCommand
{
k_EMenuCommandNone = 0,
k_EMenuCommandProgress = 1,
k_EMenuCommandSyncComplete = 2,
};
//-----------------------------------------------------------------------------
// Purpose: Example of Steam Cloud
//-----------------------------------------------------------------------------
class CRemoteStorage
{
public:
// Constructor
CRemoteStorage( IGameEngine *pGameEngine );
~CRemoteStorage();
// call when user changes to this menu
void Show();
// Display the remote storage screen
void Render();
// A sync menu item has been selected
void OnMenuSelection( ERemoteStorageSyncMenuCommand selection );
private:
IGameEngine *m_pGameEngine;
CRemoteStorageScreen *m_pRemoteStorageScreen;
};
//-----------------------------------------------------------------------------
// Purpose: Screen where user can enter their custom message
//-----------------------------------------------------------------------------
class CRemoteStorageScreen
{
public:
CRemoteStorageScreen( IGameEngine *pGameEngine );
// call when user changes to this menu
void Show();
// Display the remote storage screen
void Render();
// Done showing this page?
bool BFinished() { return m_bFinished; }
private:
void GetFileStats();
void LoadMessage();
bool BHandleSelect();
bool BHandleCancel();
// Game engine
IGameEngine *m_pGameEngine;
// Display font
HGAMEFONT m_hDisplayFont;
// Steam User interface
ISteamUser *m_pSteamUser;
// Steam RemoteStorage interface
ISteamRemoteStorage *m_pSteamRemoteStorage;
// Greeting message
char m_rgchGreeting[40];
char m_rgchGreetingNext[40];
bool m_bFinished;
int32 m_nNumFilesInCloud;
uint64 m_ulBytesQuota;
uint64 m_ulAvailableBytes;
};
#endif
+202
View File
@@ -0,0 +1,202 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for handling finding servers, getting their details, and displaying
// them inside the game
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "ServerBrowser.h"
#include "ServerBrowserMenu.h"
//-----------------------------------------------------------------------------
// Purpose: Constructor -- initialize from steam gameserveritem_t
//-----------------------------------------------------------------------------
CGameServer::CGameServer( gameserveritem_t *pGameServerItem )
{
m_unIPAddress = pGameServerItem->m_NetAdr.GetIP();
m_nConnectionPort = pGameServerItem->m_NetAdr.GetConnectionPort();
m_nPing = pGameServerItem->m_nPing;
strncpy_safe( m_szMap, pGameServerItem->m_szMap, ARRAYSIZE( m_szMap ) );
strncpy_safe( m_szGameDescription, pGameServerItem->m_szGameDescription, ARRAYSIZE( m_szGameDescription ) );
m_nPlayers = pGameServerItem->m_nPlayers;
m_nMaxPlayers = pGameServerItem->m_nMaxPlayers;
m_nBotPlayers = pGameServerItem->m_nBotPlayers;
m_bPassword = pGameServerItem->m_bPassword;
m_bSecure = pGameServerItem->m_bSecure;
m_nServerVersion = pGameServerItem->m_nServerVersion;
strncpy_safe( m_szServerName, pGameServerItem->GetName(), ARRAYSIZE( m_szServerName ) );
sprintf_safe( m_szServerString, "%s (%i/%i) at %s ping(%d)", pGameServerItem->GetName(), pGameServerItem->m_nPlayers, pGameServerItem->m_nMaxPlayers, pGameServerItem->m_NetAdr.GetConnectionAddressString(), pGameServerItem->m_nPing );
m_steamID = pGameServerItem->m_steamID;
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CServerBrowser::CServerBrowser( IGameEngine *pGameEngine )
{
m_pMenu = new CServerBrowserMenu( pGameEngine );
m_pGameEngine = pGameEngine;
m_nServers = 0;
m_bRequestingServers = false;
m_hServerListRequest = NULL;
m_pMenu->Rebuild( m_ListGameServers, m_bRequestingServers );
m_pMenu->SetHeading( "Internet Server browser" );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CServerBrowser::~CServerBrowser()
{
if ( m_hServerListRequest )
{
SteamMatchmakingServers()->ReleaseRequest( m_hServerListRequest );
m_hServerListRequest = NULL;
}
if ( m_pMenu )
delete m_pMenu;
// ...
}
//-----------------------------------------------------------------------------
// Purpose: Initiate a refresh of internet servers
//-----------------------------------------------------------------------------
void CServerBrowser::RefreshInternetServers()
{
// If we are still finishing the previous refresh, then ignore this new request
if ( m_bRequestingServers )
return;
// If another request is outstanding, make sure we release it properly
if ( m_hServerListRequest )
{
SteamMatchmakingServers()->ReleaseRequest( m_hServerListRequest );
m_hServerListRequest = NULL;
}
OutputDebugString( "Refreshing internet servers\n" );
// Track that we are now in a refresh, what type of refresh, and reset our server count
m_bRequestingServers = true;
m_nServers = 0;
m_ListGameServers.clear();
m_pMenu->SetHeading( "Internet Server browser" );
m_pMenu->Rebuild( m_ListGameServers, m_bRequestingServers );
Steamworks_TestSecret();
// Allocate some filters, there are some common pre-defined values that can be used:
//
// "gamedir" -- this is used to specify mods inside or a single product/appid
// "secure" -- this is used to specify whether anti-cheat is enabled for a server
// "gametype" -- this is used to specify game type and is set to whatever your game server code sets
MatchMakingKeyValuePair_t pFilters[2];
MatchMakingKeyValuePair_t *pFilter = pFilters;
strncpy_safe( pFilters[ 0 ].m_szKey, "gamedir", sizeof(pFilters[ 0 ].m_szKey) );
strncpy_safe( pFilters[ 0 ].m_szValue, "spacewar", sizeof(pFilters[ 0 ].m_szValue) );
strncpy_safe( pFilters[ 1 ].m_szKey, "secure", sizeof(pFilters[ 1 ].m_szKey) );
strncpy_safe( pFilters[ 1 ].m_szValue, "1", sizeof(pFilters[ 1 ].m_szValue) );
//strncpy_safe( pFilters[ 2 ].m_szKey, "gametype", sizeof(pFilters[ 1 ].m_szValue) );
//strncpy_safe( pFilters[ 2 ].m_szValue, "dm", sizeof(pFilters[ 1 ].m_szValue) );
// bugbug jmccaskey - passing just the appid without filters results in getting all servers rather than
// servers filtered by appid alone. So, we'll use the filters to filter the results better.
m_hServerListRequest = SteamMatchmakingServers()->RequestInternetServerList( SteamUtils()->GetAppID(), &pFilter, ARRAYSIZE(pFilters), this );
}
//-----------------------------------------------------------------------------
// Purpose: Initiate a refresh of LAN servers
//-----------------------------------------------------------------------------
void CServerBrowser::RefreshLANServers()
{
// If we are still finishing the previous refresh, then ignore this new request
if ( m_bRequestingServers )
return;
// If another request is outstanding, make sure we release it properly
if ( m_hServerListRequest )
{
SteamMatchmakingServers()->ReleaseRequest( m_hServerListRequest );
m_hServerListRequest = NULL;
}
OutputDebugString( "Refreshing LAN servers\n" );
// Track that we are now in a refresh, what type of refresh, and reset our server count
m_bRequestingServers = true;
m_nServers = 0;
m_ListGameServers.clear();
m_pMenu->SetHeading( "LAN Server browser" );
m_pMenu->Rebuild( m_ListGameServers, m_bRequestingServers );
// LAN refresh doesn't accept filters like internet above does
m_hServerListRequest = SteamMatchmakingServers()->RequestLANServerList( SteamUtils()->GetAppID(), this );
}
//-----------------------------------------------------------------------------
// Purpose: Callback from Steam telling us about a server that has responded
//-----------------------------------------------------------------------------
void CServerBrowser::ServerResponded( HServerListRequest hReq, int iServer )
{
// Assert( hReq == m_hServerListRequest );
gameserveritem_t *pServer = SteamMatchmakingServers()->GetServerDetails( hReq, iServer );
if ( pServer )
{
// Filter out servers that don't match our appid here (might get these in LAN calls since we can't put more filters on it)
if ( pServer->m_nAppID == SteamUtils()->GetAppID() )
{
m_ListGameServers.push_back( CGameServer( pServer ) );
m_nServers++;
}
}
// Rebuild menu
m_pMenu->Rebuild( m_ListGameServers, m_bRequestingServers );
}
//-----------------------------------------------------------------------------
// Purpose: Callback from Steam telling us about a server that has failed to respond
//-----------------------------------------------------------------------------
void CServerBrowser::ServerFailedToRespond( HServerListRequest hReq, int iServer )
{
// Assert( hReq == m_hServerListRequest );
// bugbug jmccaskey - why would we ever need this? Remove servers from our list I guess?
}
//-----------------------------------------------------------------------------
// Purpose: Callback from Steam telling us a refresh is complete
//-----------------------------------------------------------------------------
void CServerBrowser::RefreshComplete( HServerListRequest hReq, EMatchMakingServerResponse response )
{
// Assert( hReq == m_hServerListRequest );
// Doesn't really matter to us whether the response tells us the refresh succeeded or failed,
// we just track whether we are done refreshing or not
m_bRequestingServers = false;
}
//-----------------------------------------------------------------------------
// Purpose: Run a server browser frame (does stuff like checking KB input to change state)
//-----------------------------------------------------------------------------
void CServerBrowser::RunFrame()
{
m_pMenu->RunFrame();
}
+94
View File
@@ -0,0 +1,94 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for handling finding servers, getting their details, and displaying
// them inside the game
//
// $NoKeywords: $
//=============================================================================
#ifndef SERVERBROWSER_H
#define SERVERBROWSER_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "BaseMenu.h"
#include <list>
class CSpaceWarClient;
class CServerBrowserMenu;
// Class to encapsulate game server data
class CGameServer
{
public:
CGameServer( gameserveritem_t *pGameServerItem );
const char* GetName() { return m_szServerName; }
const char* GetDisplayString() { return m_szServerString; }
uint32 GetIP() { return m_unIPAddress; }
int32 GetPort() { return m_nConnectionPort; }
CSteamID GetSteamID() { return m_steamID; }
private:
uint32 m_unIPAddress; // IP address for the server
int32 m_nConnectionPort; // Port for game clients to connect to for this server
int m_nPing; // current ping time in milliseconds
char m_szMap[32]; // current map
char m_szGameDescription[64]; // game description
int m_nPlayers; // current number of players on the server
int m_nMaxPlayers; // Maximum players that can join this server
int m_nBotPlayers; // Number of bots (i.e simulated players) on this server
bool m_bPassword; // true if this server needs a password to join
bool m_bSecure; // Is this server protected by VAC
int m_nServerVersion; // server version as reported to Steam
char m_szServerName[64]; // Game server name
char m_szServerString[128]; // String to show in server browser
CSteamID m_steamID;
};
class CServerBrowser : public ISteamMatchmakingServerListResponse
{
public:
CServerBrowser( IGameEngine *pGameEngine );
~CServerBrowser();
// Initiate a refresh of internet servers
void RefreshInternetServers();
// Initiate a refresh of LAN servers
void RefreshLANServers();
// Run a frame (to handle kb input and such as well as render)
void RunFrame();
// ISteamMatchmakingServerListResponse
void ServerResponded( HServerListRequest hReq, int iServer );
void ServerFailedToRespond( HServerListRequest hReq, int iServer );
void RefreshComplete( HServerListRequest hReq, EMatchMakingServerResponse response );
private:
// Pointer to engine instance (so we can draw stuff)
IGameEngine *m_pGameEngine;
// Track the number of servers we know about
int m_nServers;
// Track whether we are in the middle of a refresh or not
bool m_bRequestingServers;
// Track what server list request is currently running
HServerListRequest m_hServerListRequest;
// Menu object
CServerBrowserMenu *m_pMenu;
// List of game servers
std::list< CGameServer > m_ListGameServers;
};
#endif //SERVERBROWSER_H
@@ -0,0 +1,38 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class to find servers menu
//
//=============================================================================
#ifndef SERVERBROWSERMENU_H
#define SERVERBROWSERMENU_H
#include "BaseMenu.h"
#include "ServerBrowser.h"
class CServerBrowserMenu : public CBaseMenu<ServerBrowserMenuData_t>
{
public:
// Constructor
CServerBrowserMenu( IGameEngine *pGameEngine ) : CBaseMenu<ServerBrowserMenuData_t>( pGameEngine ) {}
void Rebuild( std::list<CGameServer> &List, bool bIsRefreshing )
{
ClearMenuItems();
ServerBrowserMenuData_t data;
std::list<CGameServer>::iterator iter;
for( iter = List.begin(); iter != List.end(); ++iter )
{
data.m_eStateToTransitionTo = k_EClientGameConnecting;
data.m_steamIDGameServer = iter->GetSteamID();
AddMenuItem( MenuItem_t( iter->GetDisplayString(), data ) );
}
data.m_eStateToTransitionTo = k_EClientGameMenu;
AddMenuItem( CServerBrowserMenu::MenuItem_t( "Return to main menu", data ) );
}
};
#endif // SERVERBROWSERMENU_H
+963
View File
@@ -0,0 +1,963 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for rendering the player ships
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "GameEngine.h"
#include "Ship.h"
#include "stdlib.h"
#include "SpaceWarServer.h"
#include "StatsAndAchievements.h"
#include "Inventory.h"
#include <math.h>
#include <string.h>
//-----------------------------------------------------------------------------
// Purpose: Constructor for thrusters
//-----------------------------------------------------------------------------
CForwardThrusters::CForwardThrusters( IGameEngine *pGameEngine, CShip *pShip ) : CVectorEntity( pGameEngine, 0 )
{
DWORD dwColor = D3DCOLOR_ARGB( 255, 255, 255, 102 );
// Initialize our geometry
AddLine( 0.0, 12.0f, 0.0f, 19.0f, dwColor );
AddLine( 1.0, 12.0f, 6.0f, 19.0f, dwColor );
AddLine( 4.0, 12.0f, 11.0f, 19.0f, dwColor );
AddLine( -1.0, 12.0f, -6.0f, 19.0f, dwColor );
AddLine( -4.0, 12.0f, -11.0f, 19.0f, dwColor );
m_pShip = pShip;
}
//-----------------------------------------------------------------------------
// Purpose: Run Frame, updates us to be in the same position/rotation as the ship we belong to
//-----------------------------------------------------------------------------
void CForwardThrusters::RunFrame()
{
SetAccumulatedRotation( m_pShip->GetAccumulatedRotation() );
SetPosition( m_pShip->GetXPos(), m_pShip->GetYPos() );
CVectorEntity::RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Constructor for reverse thrusters
//-----------------------------------------------------------------------------
CReverseThrusters::CReverseThrusters( IGameEngine *pGameEngine, CShip *pShip ) : CVectorEntity( pGameEngine, 0 )
{
DWORD dwColor = D3DCOLOR_ARGB( 255, 255, 255, 102 );
// Initialize our geometry
AddLine( -8.875, 10.5f, -14.85f, 10.5f, dwColor );
AddLine( -8.875, 10.5f, -13.765f, 5.61f, dwColor );
AddLine( -8.875, 10.5f, -7.85f, 3.5f, dwColor );
AddLine( 8.875, 10.5f, 14.85f, 10.5f, dwColor );
AddLine( 8.875, 10.5f, 13.765f, 5.61f, dwColor );
AddLine( 8.875, 10.5f, 7.85f, 3.5f, dwColor );
m_pShip = pShip;
}
//-----------------------------------------------------------------------------
// Purpose: Run Frame, updates us to be in the same position/rotation as the ship we belong to
//-----------------------------------------------------------------------------
void CReverseThrusters::RunFrame()
{
SetAccumulatedRotation( m_pShip->GetAccumulatedRotation() );
SetPosition( m_pShip->GetXPos(), m_pShip->GetYPos() );
CVectorEntity::RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Constructor for ship debris after explosion
//-----------------------------------------------------------------------------
CShipDebris::CShipDebris( IGameEngine *pGameEngine, float xPos, float yPos, DWORD dwDebrisColor ) : CSpaceWarEntity( pGameEngine, 0, true )
{
AddLine( 0.0f, 0.0f, 16.0f, 0.0f, dwDebrisColor );
// Random rotation between 0 and 360 degrees (6.28 radians)
float flRotation = (float)(rand()%628)/100.0f;
SetRotationDeltaNextFrame( flRotation );
// Rotation to apply per second
int nRandRotation = rand()%(157*2) - (157);
m_flRotationPerInterval = nRandRotation/100.0f;
float sinvalue = (float)sin( flRotation );
float cosvalue = (float)cos( flRotation );
float xVelocity = GetXVelocity() + ( sinvalue * 80 );
float yVelocity = GetYVelocity() - ( cosvalue * 80 );
// Offset out a bit from the center of the ship compensating for rotation
float offset = (rand()%12)-6.0f;
float xOffset = xPos + (cosvalue*-offset - sinvalue*-offset);
float yOffset = yPos + (cosvalue*-offset + sinvalue*-offset);
// Set velocity
SetVelocity( xVelocity, yVelocity );
// Set position
SetPosition( xOffset, yOffset );
}
//-----------------------------------------------------------------------------
// Purpose: Run frame for debris (keep it spinning)
//-----------------------------------------------------------------------------
void CShipDebris::RunFrame()
{
SetRotationDeltaNextFrame( m_flRotationPerInterval * MIN( m_pGameEngine->GetGameTicksFrameDelta(), 400.0f )/400.0f );
CSpaceWarEntity::RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
#pragma warning( push )
// warning C4355: 'this' : used in base member initializer list
// This is OK because the thruster classes won't use the ship object in their constructors (where it may still be only partly constructed)
#pragma warning( disable : 4355 )
CShip::CShip( IGameEngine *pGameEngine, bool bIsServerInstance, float xPos, float yPos, DWORD dwShipColor ) :
CSpaceWarEntity( pGameEngine, 11, true ), m_ForwardThrusters( pGameEngine, this ), m_ReverseThrusters( pGameEngine, this )
{
m_bDisabled = false;
m_bExploding = false;
m_ulLastThrustStartedTickCount = 0;
m_dwVKLeft = 0;
m_dwVKRight = 0;
m_nFade = 255;
m_dwVKForwardThrusters = 0;
m_dwVKReverseThrusters = 0;
m_dwVKFire = 0;
m_ulLastPhotonTickCount = 0;
m_dwShipColor = dwShipColor;
m_bForwardThrustersActive = false;
m_bReverseThrustersActive = false;
m_bIsLocalPlayer = false;
m_ulLastClientUpdateTick = 0;
m_bIsServerInstance = bIsServerInstance;
m_nShipDecoration = 0;
m_nShipPower = 0;
m_nShipWeapon = 0;
m_hTextureWhite = 0;
m_nShipShieldStrength = 0;
m_ulExplosionTickCount = 0;
m_bTriggerEffectEnabled = false;
memset( &m_SpaceWarClientUpdateData, 0, sizeof( m_SpaceWarClientUpdateData ) );
for( int i=0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
m_rgPhotonBeams[i] = NULL;
}
BuildGeometry();
SetPosition( xPos, yPos );
// Set Controller color to ship color
m_pGameEngine->SetControllerColor( m_dwShipColor >> 16 & 255, m_dwShipColor >> 8 & 255, m_dwShipColor & 255, k_ESteamControllerLEDFlag_SetColor );
}
#pragma warning( pop )
void CShip::BuildGeometry()
{
ClearVertexes();
// Initialize our geometry
AddLine( -9.0f, 12.0f, 0.0f, -12.0f, m_dwShipColor );
AddLine( 0.0f, -12.0f, 9.0f, 12.0f, m_dwShipColor );
AddLine( 9.0f, 12.0f, -9.0f, 12.0f, m_dwShipColor );
switch ( m_nShipDecoration )
{
case 1:
AddLine( 0.0f, -12.0f, -0.0f, 12.0f, m_dwShipColor );
AddLine( 4.5f, 0.0f, -4.5f, 0.0f, m_dwShipColor );
break;
case 2:
AddLine( 0.0f, -12.0f, -0.0f, 12.0f, m_dwShipColor );
AddLine( 4.5f, 0.0f, -4.5f, 0.0f, m_dwShipColor );
AddLine( 2.5f, -6.0f, -9.0f, 12.0f, m_dwShipColor );
AddLine( 9.0f, 12.0f, -2.5f, -6.0f, m_dwShipColor );
break;
case 3:
AddLine( 0.0f, -12.0f, 0.0f, 12.0f, m_dwShipColor );
AddLine( 2.0f, -8.0f, 2.0f, 12.0f, m_dwShipColor );
AddLine( -2.0f, -8.0f, -2.0f, 12.0f, m_dwShipColor );
break;
case 4:
AddLine( -12.0, 12.0f, -3.0f,-12.0f, m_dwShipColor );
AddLine( -17.0f, 4.0f,-11.0f,-10.0f, m_dwShipColor );
AddLine( -17.0f, 4.0f,-10.0f, 7.0f, m_dwShipColor );
AddLine( -11.0f,-10.0f, -3.0f,-7.0f, m_dwShipColor );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CShip::~CShip()
{
// Cleanup beams
{
for( int i=0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
if ( m_rgPhotonBeams[i] )
delete m_rgPhotonBeams[i];
}
}
// Cleanup debris
{
std::list<CShipDebris *>::iterator iter;
for ( iter = m_ListDebris.begin(); iter != m_ListDebris.end(); ++iter )
{
delete (*iter);
}
m_ListDebris.clear();
}
// Restore Controller Color
m_pGameEngine->SetControllerColor( 0, 0, 0, k_ESteamControllerLEDFlag_RestoreUserDefault );
// Turn off trigger effect
if ( m_bTriggerEffectEnabled )
{
m_pGameEngine->SetTriggerEffect( false );
}
}
//-----------------------------------------------------------------------------
// Purpose: Update entity with updated data from the server
//-----------------------------------------------------------------------------
void CShip::OnReceiveServerUpdate( ServerShipUpdateData_t *pUpdateData )
{
if ( m_bIsServerInstance )
{
OutputDebugString( "Should not be receiving server updates on the server itself\n" );
return;
}
SetDisabled( pUpdateData->GetDisabled() );
SetExploding( pUpdateData->GetExploding() );
SetPosition( pUpdateData->GetXPosition()*m_pGameEngine->GetViewportWidth(), pUpdateData->GetYPosition()*m_pGameEngine->GetViewportHeight() );
SetVelocity( pUpdateData->GetXVelocity(), pUpdateData->GetYVelocity() );
SetAccumulatedRotation( pUpdateData->GetRotation() );
m_nShipPower = pUpdateData->GetPower();
m_nShipWeapon = pUpdateData->GetWeapon();
if ( m_nShipDecoration != pUpdateData->GetDecoration() )
{
m_nShipDecoration = pUpdateData->GetDecoration();
BuildGeometry();
}
if ( !m_bIsLocalPlayer || pUpdateData->GetShieldStrength() == 0 )
{
m_nShipShieldStrength = pUpdateData->GetShieldStrength();
}
m_bForwardThrustersActive = pUpdateData->GetForwardThrustersActive();
m_bReverseThrustersActive = pUpdateData->GetReverseThrustersActive();
// Update the photon beams
for ( int i=0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
ServerPhotonBeamUpdateData_t *pPhotonUpdate = pUpdateData->AccessPhotonBeamData( i );
if ( pPhotonUpdate->GetActive() )
{
if ( !m_rgPhotonBeams[i] )
{
m_rgPhotonBeams[i] = new CPhotonBeam( m_pGameEngine,
pPhotonUpdate->GetXPosition(), pPhotonUpdate->GetYPosition(),
m_dwShipColor, pPhotonUpdate->GetRotation(),
pPhotonUpdate->GetXVelocity(), pPhotonUpdate->GetYVelocity() );
}
else
{
m_rgPhotonBeams[i]->OnReceiveServerUpdate( pPhotonUpdate );
}
}
else
{
if ( m_rgPhotonBeams[i] )
{
delete m_rgPhotonBeams[i];
m_rgPhotonBeams[i] = NULL;
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Update entity with updated data from the client
//-----------------------------------------------------------------------------
void CShip::OnReceiveClientUpdate( ClientSpaceWarUpdateData_t *pUpdateData )
{
if ( !m_bIsServerInstance )
{
OutputDebugString( "Should not be receiving client updates on non-server instances\n" );
return;
}
m_nShipDecoration = pUpdateData->GetDecoration();
m_nShipPower = pUpdateData->GetPower();
m_nShipWeapon = pUpdateData->GetWeapon();
m_nShipShieldStrength = pUpdateData->GetShieldStrength();
memcpy( &m_SpaceWarClientUpdateData, pUpdateData, sizeof( ClientSpaceWarUpdateData_t ) );
}
//-----------------------------------------------------------------------------
// Purpose: Tell the server about any updates we have had client-side
//-----------------------------------------------------------------------------
bool CShip::BGetClientUpdateData( ClientSpaceWarUpdateData_t *pUpdateData )
{
// Limit the rate at which we send updates, even if our internal frame rate is higher
if ( m_pGameEngine->GetGameTickCount() - m_ulLastClientUpdateTick < 1000.0f/CLIENT_UPDATE_SEND_RATE )
return false;
m_ulLastClientUpdateTick = m_pGameEngine->GetGameTickCount();
// Update playername before sending
if ( m_bIsLocalPlayer )
{
m_SpaceWarClientUpdateData.SetPlayerName( SteamFriends()->GetFriendPersonaName( SteamUser()->GetSteamID() ) );
m_SpaceWarClientUpdateData.SetDecoration( m_nShipDecoration );
m_SpaceWarClientUpdateData.SetWeapon( m_nShipWeapon );
m_SpaceWarClientUpdateData.SetPower( m_nShipPower );
m_SpaceWarClientUpdateData.SetShieldStrength( m_nShipShieldStrength );
}
memcpy( pUpdateData, &m_SpaceWarClientUpdateData, sizeof( ClientSpaceWarUpdateData_t ) );
memset( &m_SpaceWarClientUpdateData, 0, sizeof( m_SpaceWarClientUpdateData ) );
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Get the name for this ship (only really works server side)
//-----------------------------------------------------------------------------
const char* CShip::GetPlayerName()
{
return m_SpaceWarClientUpdateData.GetPlayerName();
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame for the ship
//-----------------------------------------------------------------------------
void CShip::RunFrame()
{
if ( m_bDisabled )
return;
const uint64 ulCurrentTickCount = m_pGameEngine->GetGameTickCount();
// Look for expired photon beams
int nNextAvailablePhotonBeamSlot = -1; // Track next available slot for use spawning new beams below
for( int i=0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
if ( m_rgPhotonBeams[i] )
{
if ( m_rgPhotonBeams[i]->BIsBeamExpired() )
{
delete m_rgPhotonBeams[i];
m_rgPhotonBeams[i] = NULL;
}
}
if ( !m_rgPhotonBeams[i] && nNextAvailablePhotonBeamSlot == -1 )
nNextAvailablePhotonBeamSlot = i;
}
// run all the photon beams we have outstanding
for( int i=0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
if ( m_rgPhotonBeams[i] )
m_rgPhotonBeams[i]->RunFrame();
}
// run all the space debris
{
std::list<CShipDebris *>::iterator iter;
for( iter = m_ListDebris.begin(); iter != m_ListDebris.end(); ++iter )
(*iter)->RunFrame();
}
if ( m_bIsLocalPlayer )
{
m_SpaceWarClientUpdateData.SetTurnLeftPressed( false );
m_SpaceWarClientUpdateData.SetTurnRightPressed( false );
if ( m_pGameEngine->BIsKeyDown( m_dwVKLeft )
|| m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_TurnLeft ) )
{
m_SpaceWarClientUpdateData.SetTurnLeftPressed( true );
}
if ( m_pGameEngine->BIsKeyDown( m_dwVKRight )
|| m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_TurnRight ) )
{
m_SpaceWarClientUpdateData.SetTurnRightPressed( true );
}
// The Steam Controller can also map an anlog axis to thrust and steer
float fTurnSpeed, fUnused;
m_pGameEngine->GetControllerAnalogAction( eControllerAnalogAction_AnalogControls, &fTurnSpeed, &fUnused );
if ( fTurnSpeed > 0.0f )
{
m_SpaceWarClientUpdateData.SetTurnRightPressed( true );
m_SpaceWarClientUpdateData.SetTurnSpeed( fTurnSpeed );
}
else if ( fTurnSpeed < 0.0f )
{
m_SpaceWarClientUpdateData.SetTurnLeftPressed( true );
m_SpaceWarClientUpdateData.SetTurnSpeed( fTurnSpeed );
}
}
else if ( m_bIsServerInstance )
{
// Server side
const float fMaxTurnSpeed = (PI_VALUE / 2.0f) * (float)m_pGameEngine->GetGameTicksFrameDelta( ) / 400.0f;
float flRotationDelta = 0.0f;
float fTurnSpeed = m_SpaceWarClientUpdateData.GetTurnSpeed();
if ( fTurnSpeed != 0.0f )
{
flRotationDelta += fMaxTurnSpeed * fTurnSpeed;
}
else
{
if ( m_SpaceWarClientUpdateData.GetTurnLeftPressed( ) )
{
flRotationDelta += -1.0f * fMaxTurnSpeed;
}
if ( m_SpaceWarClientUpdateData.GetTurnRightPressed( ) )
{
flRotationDelta += fMaxTurnSpeed;
}
}
SetRotationDeltaNextFrame( flRotationDelta );
}
// Compute acceleration
if ( m_bIsLocalPlayer )
{
// client side
m_SpaceWarClientUpdateData.SetReverseThrustersPressed( false );
m_SpaceWarClientUpdateData.SetForwardThrustersPressed( false );
bool bForwardThrustActive = false;
if ( m_pGameEngine->BIsKeyDown( m_dwVKForwardThrusters ) ||
m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_ForwardThrust ) )
{
m_SpaceWarClientUpdateData.SetForwardThrustersPressed( true );
bForwardThrustActive = true;
//m_pGameEngine->SetControllerColor( 100, 255, 0, k_ESteamControllerLEDFlag_SetColor );
}
if ( m_pGameEngine->BIsKeyDown( m_dwVKReverseThrusters ) ||
m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_ReverseThrust ) )
{
m_SpaceWarClientUpdateData.SetReverseThrustersPressed( true );
}
// The Steam Controller can also map an analog axis to thrust and steer
float fThrusterLevel, fUnused;
m_pGameEngine->GetControllerAnalogAction( eControllerAnalogAction_AnalogControls, &fUnused, &fThrusterLevel );
if ( fThrusterLevel > 0.0f )
{
m_SpaceWarClientUpdateData.SetForwardThrustersPressed( true );
m_SpaceWarClientUpdateData.SetThrustersLevel( fThrusterLevel );
bForwardThrustActive = true;
}
else if ( fThrusterLevel < 0.0f )
{
m_SpaceWarClientUpdateData.SetReverseThrustersPressed( true );
m_SpaceWarClientUpdateData.SetThrustersLevel( fThrusterLevel );
}
// We can activate action set layers based upon our state.
// This allows action bindings or settings to be changed on an existing action set for contextual usage
if ( bForwardThrustActive )
{
m_pGameEngine->ActivateSteamControllerActionSetLayer( eControllerActionSet_Layer_Thrust );
}
else if ( m_pGameEngine->BIsActionSetLayerActive( eControllerActionSet_Layer_Thrust ) )
{
m_pGameEngine->DeactivateSteamControllerActionSetLayer( eControllerActionSet_Layer_Thrust );
}
// Hardcoded keys to choose various outfits and weapon powerups which require inventory. Note that this is not
// a "secure" multiplayer model - clients can lie about what they own. A more robust solution, if your items
// matter enough to bother, would be to use SerializeResult / DeserializeResult to encode the fact that your
// steamid owns certain items, and then send that encoded result to the server which decodes and verifies it.
if ( m_pGameEngine->BIsKeyDown( 0x30 ) )
{
m_nShipDecoration = 0;
BuildGeometry();
}
else if ( m_pGameEngine->BIsKeyDown( 0x31 ) && SpaceWarLocalInventory()->HasInstanceOf( k_SpaceWarItem_ShipDecoration1 ) )
{
m_nShipDecoration = 1;
BuildGeometry();
}
else if ( m_pGameEngine->BIsKeyDown( 0x32 ) && SpaceWarLocalInventory()->HasInstanceOf( k_SpaceWarItem_ShipDecoration2 ) )
{
m_nShipDecoration = 2;
BuildGeometry();
}
else if ( m_pGameEngine->BIsKeyDown( 0x33 ) && SpaceWarLocalInventory()->HasInstanceOf( k_SpaceWarItem_ShipDecoration3 ) )
{
m_nShipDecoration = 3;
BuildGeometry();
}
else if ( m_pGameEngine->BIsKeyDown( 0x34 ) && SpaceWarLocalInventory()->HasInstanceOf( k_SpaceWarItem_ShipDecoration4 ) )
{
m_nShipDecoration = 4;
BuildGeometry();
}
else if ( m_pGameEngine->BIsKeyDown( 0x35 ) && SpaceWarLocalInventory()->HasInstanceOf( k_SpaceWarItem_ShipWeapon1 ) )
{
m_nShipWeapon = 1;
}
else if ( m_pGameEngine->BIsKeyDown( 0x36 ) && SpaceWarLocalInventory()->HasInstanceOf( k_SpaceWarItem_ShipWeapon2 ) )
{
m_nShipWeapon = 2;
}
else if ( m_pGameEngine->BIsKeyDown( 0x37 ) && SpaceWarLocalInventory()->HasInstanceOf( k_SpaceWarItem_ShipSpecial1 ) )
{
m_nShipPower = 1;
}
else if ( m_pGameEngine->BIsKeyDown( 0x38 ) && SpaceWarLocalInventory()->HasInstanceOf( k_SpaceWarItem_ShipSpecial2 ) )
{
m_nShipPower = 2;
}
}
else if ( m_bIsServerInstance )
{
// Server side
float xThrust = 0;
float yThrust = 0;
m_bReverseThrustersActive = false;
m_bForwardThrustersActive = false;
if ( m_SpaceWarClientUpdateData.GetReverseThrustersPressed() || m_SpaceWarClientUpdateData.GetForwardThrustersPressed() )
{
float flSign = 1.0f;
if ( m_SpaceWarClientUpdateData.GetReverseThrustersPressed() )
{
m_bReverseThrustersActive = true;
flSign = -1.0f;
}
else
{
m_bForwardThrustersActive = true;
}
float fThrusterLevel = m_SpaceWarClientUpdateData.GetThrustersLevel();
if ( fThrusterLevel != 0.0f )
{
flSign = fThrusterLevel;
}
if ( m_ulLastThrustStartedTickCount == 0 )
{
m_ulLastThrustStartedTickCount = ulCurrentTickCount;
m_pGameEngine->TriggerControllerHaptics( k_ESteamControllerPad_Left, 2900, 1200, 4 );
}
// You have to hold the key for a second to reach maximum thrust
float factor = MIN( ((float)(ulCurrentTickCount - m_ulLastThrustStartedTickCount) / 500.0f) + 0.2f, 1.0f );
xThrust = flSign * (float)(MAXIMUM_SHIP_THRUST * factor * sin( GetAccumulatedRotation() ) );
yThrust = flSign * -1.0f * (float)(MAXIMUM_SHIP_THRUST * factor * cos( GetAccumulatedRotation() ) );
}
else
{
m_ulLastThrustStartedTickCount = 0;
}
SetAcceleration( xThrust, yThrust );
}
// We'll use these values in a few places below to compute positions of child objects
// appropriately given our rotation
float sinvalue = (float)sin( GetAccumulatedRotation() );
float cosvalue = (float)cos( GetAccumulatedRotation() );
if ( m_bIsLocalPlayer )
{
// client side
if ( m_pGameEngine->BIsKeyDown( m_dwVKFire ) ||
m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_FireLasers ) )
{
m_SpaceWarClientUpdateData.SetFirePressed( true );
}
}
else if ( m_bIsServerInstance )
{
// server side
if ( nNextAvailablePhotonBeamSlot != -1 && !m_bExploding && m_SpaceWarClientUpdateData.GetFirePressed() && ulCurrentTickCount - PHOTON_BEAM_FIRE_INTERVAL_TICKS > m_ulLastPhotonTickCount )
{
m_ulLastPhotonTickCount = ulCurrentTickCount;
if ( m_nShipWeapon == 1 ) // Item#101
{
float sinvalue1 = (float)sin( GetAccumulatedRotation() - .1f );
float cosvalue1 = (float)cos( GetAccumulatedRotation() - .1f );
float sinvalue2 = (float)sin( GetAccumulatedRotation() + .1f );
float cosvalue2 = (float)cos( GetAccumulatedRotation() + .1f );
float xVelocity = GetXVelocity() + ( sinvalue1 * 275 );
float yVelocity = GetYVelocity() - ( cosvalue1 * 275 );
// Offset 12 points up from the center of the ship, compensating for rotation
float xPos = GetXPos() - sinvalue1*-12.0f;
float yPos = GetYPos() + cosvalue1*-12.0f;
m_rgPhotonBeams[nNextAvailablePhotonBeamSlot] = new CPhotonBeam( m_pGameEngine, xPos, yPos, m_dwShipColor, GetAccumulatedRotation(), xVelocity, yVelocity );
nNextAvailablePhotonBeamSlot = -1; // Track next available slot for use spawning new beams below
for( int i=0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
if ( !m_rgPhotonBeams[i] && nNextAvailablePhotonBeamSlot == -1 )
nNextAvailablePhotonBeamSlot = i;
}
if ( nNextAvailablePhotonBeamSlot != -1 )
{
xVelocity = GetXVelocity() + ( sinvalue2 * 275 );
yVelocity = GetYVelocity() - ( cosvalue2 * 275 );
// Offset 12 points up from the center of the ship, compensating for rotation
xPos = GetXPos() - sinvalue2*-12.0f;
yPos = GetYPos() + cosvalue2*-12.0f;
m_rgPhotonBeams[nNextAvailablePhotonBeamSlot] = new CPhotonBeam( m_pGameEngine, xPos, yPos, m_dwShipColor, GetAccumulatedRotation(), xVelocity, yVelocity );
m_pGameEngine->TriggerControllerHaptics( k_ESteamControllerPad_Right, 1000, 1500, 2 );
}
}
else
{
float speed = 275;
if ( m_nShipWeapon == 2 ) // Item#102
{
speed = 500;
}
float xVelocity = GetXVelocity() + ( sinvalue * speed );
float yVelocity = GetYVelocity() - ( cosvalue * speed );
// Offset 12 points up from the center of the ship, compensating for rotation
float xPos = GetXPos() - sinvalue*-12.0f;
float yPos = GetYPos() + cosvalue*-12.0f;
m_rgPhotonBeams[nNextAvailablePhotonBeamSlot] = new CPhotonBeam( m_pGameEngine, xPos, yPos, m_dwShipColor, GetAccumulatedRotation(), xVelocity, yVelocity );
m_pGameEngine->TriggerControllerHaptics( k_ESteamControllerPad_Right, 1200, 2500, 3 );
}
}
}
CSpaceWarEntity::RunFrame();
// Finally, update the thrusters ( we do this after the base class call as they rely on our data being fully up-to-date)
m_ForwardThrusters.RunFrame();
m_ReverseThrusters.RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Render the ship
//-----------------------------------------------------------------------------
void CShip::Render()
{
int beamCount = 0;
if ( m_bDisabled )
return;
// render all the photon beams we have outstanding
for ( int i = 0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
if ( m_rgPhotonBeams[i] )
{
m_rgPhotonBeams[i]->Render();
beamCount++;
}
}
if ( m_bExploding )
{
// Don't draw actual ship, instead draw the pieces created in the explosion
std::list<CShipDebris *>::iterator iter;
for ( iter = m_ListDebris.begin(); iter != m_ListDebris.end(); ++iter )
( *iter )->Render();
return;
}
// Check if we should be drawing thrusters
if ( m_bForwardThrustersActive )
{
if ( rand() % 3 == 0 )
m_ForwardThrusters.Render();
}
if ( m_bReverseThrustersActive )
{
if ( rand() % 3 == 0 )
m_ReverseThrusters.Render();
}
DWORD actualColor = m_dwShipColor;
if ( m_nShipPower == 1 ) // Item#103 but need to check if the other guy has it sometimes?
{
if ( beamCount > 0 )
{
m_nFade = 255;
}
else if ( m_nFade > 0 )
{
m_nFade -= 5;
if ( m_nFade < 0 )
m_nFade = 0;
if ( m_bIsLocalPlayer && m_nFade < 50 )
{
m_nFade = 128;
}
}
actualColor = (actualColor & 0xffffff) | (m_nFade<<24);
}
DWORD shieldColor = 0x00af8f00;
if ( m_nShipPower == 2 )
{
shieldColor = shieldColor | ((m_nShipShieldStrength / 4)<<24);
if ( m_nShipShieldStrength < 256 )
m_nShipShieldStrength++;
if ( !m_hTextureWhite )
{
byte *pRGBAData = new byte[1 * 1 * 4];
memset( pRGBAData, 255, 1 * 1 * 4 );
m_hTextureWhite = m_pGameEngine->HCreateTexture( pRGBAData, 1, 1 );
delete[] pRGBAData;
}
float rotationClockwise = (m_pGameEngine->GetGameTickCount() / 500.0f);
float rotationCounter = -(m_pGameEngine->GetGameTickCount() / 500.0f);
float x1 = 28.0f * (float)cos( rotationClockwise );
float y1 = 28.0f * (float)sin( rotationClockwise );
float x2 = 28.0f * (float)cos( rotationCounter );
float y2 = 28.0f * (float)sin( rotationCounter );
m_pGameEngine->BDrawTexturedQuad(
this->GetXPos() - x1, this->GetYPos() - y1, this->GetXPos() + y1, this->GetYPos() - x1,
this->GetXPos() - y1, this->GetYPos() + x1, this->GetXPos() + x1, this->GetYPos() + y1,
0, 0, 1, 1, shieldColor, m_hTextureWhite );
m_pGameEngine->BDrawTexturedQuad(
this->GetXPos() - x2, this->GetYPos() - y2, this->GetXPos() + y2, this->GetYPos() - x2,
this->GetXPos() - y2, this->GetYPos() + x2, this->GetXPos() + x2, this->GetYPos() + y2,
0, 0, 1, 1, shieldColor, m_hTextureWhite );
}
else
{
m_nShipShieldStrength = 0;
}
CSpaceWarEntity::Render(actualColor);
}
void CShip::UpdateVibrationEffects()
{
if ( m_ulExplosionTickCount > 0 )
{
float flVibration = MIN( ((float)(m_pGameEngine->GetGameTickCount() - m_ulExplosionTickCount) / 1000.0f), 1.0f );
if ( flVibration == 1.0f )
{
m_pGameEngine->TriggerControllerVibration( 0, 0 );
m_ulExplosionTickCount = 0;
}
else
{
m_pGameEngine->TriggerControllerVibration( (unsigned short)( ( 1.0f - flVibration ) * 48000.0f), (unsigned short)( ( 1.0f - flVibration ) * 24000.0f) );
}
}
bool bTriggerEffectEnabled = !BIsDisabled() && !BIsExploding();
if ( bTriggerEffectEnabled != m_bTriggerEffectEnabled )
{
m_pGameEngine->SetTriggerEffect( bTriggerEffectEnabled );
m_bTriggerEffectEnabled = bTriggerEffectEnabled;
}
}
//-----------------------------------------------------------------------------
// Purpose: Set whether the ship is exploding
//-----------------------------------------------------------------------------
void CShip::SetExploding( bool bExploding )
{
// If we are already in the specified state, no need to do the below work
if ( m_bExploding == bExploding )
{
UpdateVibrationEffects();
return;
}
Steamworks_TestSecret();
// Track that we are exploding, and disable collision detection
m_bExploding = bExploding;
SetCollisionDetectionDisabled( m_bExploding );
if ( bExploding )
{
m_ulExplosionTickCount = m_pGameEngine->GetGameTickCount();
for( int i = 0; i < SHIP_DEBRIS_PIECES; ++i )
{
CShipDebris * pDebris = new CShipDebris( m_pGameEngine, GetXPos(), GetYPos(), m_dwShipColor );
m_ListDebris.push_back( pDebris );
}
}
else
{
m_ulExplosionTickCount = 0;
std::list<CShipDebris *>::iterator iter;
for( iter = m_ListDebris.begin(); iter != m_ListDebris.end(); ++iter )
delete *iter;
m_ListDebris.clear();
}
UpdateVibrationEffects();
}
//-----------------------------------------------------------------------------
// Purpose: Check for photons which have hit the target and remove them
//-----------------------------------------------------------------------------
void CShip::DestroyPhotonsColldingWith( CVectorEntity *pTarget )
{
for( int i=0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
if ( !m_rgPhotonBeams[i] )
continue;
if ( m_rgPhotonBeams[i]->BCollidesWith( pTarget ) )
{
// Photon beam hit the entity, destroy beam
delete m_rgPhotonBeams[i];
m_rgPhotonBeams[i] = NULL;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Check whether any of the photons this ship has fired are colliding with the target
//-----------------------------------------------------------------------------
bool CShip::BCheckForPhotonsCollidingWith( CVectorEntity *pTarget )
{
for( int i=0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
if ( !m_rgPhotonBeams[i] )
continue;
if ( m_rgPhotonBeams[i]->BCollidesWith( pTarget ) )
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Build the update data to send from server to clients
//-----------------------------------------------------------------------------
void CShip::BuildServerUpdate( ServerShipUpdateData_t *pUpdateData )
{
pUpdateData->SetDisabled( BIsDisabled() );
pUpdateData->SetExploding( BIsExploding() );
pUpdateData->SetXAcceleration( GetXAccelerationLastFrame() );
pUpdateData->SetYAcceleration( GetYAccelerationLastFrame() );
pUpdateData->SetXPosition( GetXPos()/(float)m_pGameEngine->GetViewportWidth() );
pUpdateData->SetYPosition( GetYPos()/(float)m_pGameEngine->GetViewportHeight() );
pUpdateData->SetXVelocity( GetXVelocity() );
pUpdateData->SetYVelocity( GetYVelocity() );
pUpdateData->SetRotation( GetAccumulatedRotation() );
pUpdateData->SetRotationDeltaLastFrame( GetRotationDeltaLastFrame() );
pUpdateData->SetForwardThrustersActive( m_bForwardThrustersActive );
pUpdateData->SetReverseThrustersActive( m_bReverseThrustersActive );
pUpdateData->SetDecoration( m_nShipDecoration );
pUpdateData->SetWeapon( m_nShipWeapon );
pUpdateData->SetPower( m_nShipPower );
pUpdateData->SetShieldStrength( m_nShipShieldStrength );
BuildServerPhotonBeamUpdate( pUpdateData );
}
//-----------------------------------------------------------------------------
// Purpose: Build the photon beam update data to send from the server to clients
//-----------------------------------------------------------------------------
void CShip::BuildServerPhotonBeamUpdate( ServerShipUpdateData_t *pUpdateData )
{
for( int i = 0; i < MAX_PHOTON_BEAMS_PER_SHIP; ++i )
{
ServerPhotonBeamUpdateData_t *pPhotonUpdate = pUpdateData->AccessPhotonBeamData( i );
if ( m_rgPhotonBeams[i] )
{
pPhotonUpdate->SetActive( true );
pPhotonUpdate->SetXPosition( m_rgPhotonBeams[i]->GetXPos()/(float)m_pGameEngine->GetViewportWidth() );
pPhotonUpdate->SetYPosition( m_rgPhotonBeams[i]->GetYPos()/(float)m_pGameEngine->GetViewportHeight() );
pPhotonUpdate->SetXVelocity( m_rgPhotonBeams[i]->GetXVelocity() );
pPhotonUpdate->SetYVelocity( m_rgPhotonBeams[i]->GetYVelocity() );
pPhotonUpdate->SetRotation( m_rgPhotonBeams[i]->GetAccumulatedRotation() );
}
else
{
pPhotonUpdate->SetActive( false );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Accumulate stats for this ship
//-----------------------------------------------------------------------------
void CShip::AccumulateStats( CStatsAndAchievements *pStats )
{
if ( m_bIsLocalPlayer )
{
pStats->AddDistanceTraveled( GetDistanceTraveledLastFrame() );
}
}
+230
View File
@@ -0,0 +1,230 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for rendering the player ships
//
// $NoKeywords: $
//=============================================================================
#ifndef SHIP_H
#define SHIP_H
#include <list>
#include "GameEngine.h"
#include "SpaceWarEntity.h"
#include "PhotonBeam.h"
#include "SpaceWar.h"
#define MAXIMUM_SHIP_THRUST 150
#define SHIP_DEBRIS_PIECES 6
// Forward declaration
class CShip;
class CSpaceWarServer;
class CStatsAndAchievements;
// Simple class for the ship thrusters
class CForwardThrusters : public CVectorEntity
{
public:
CForwardThrusters( IGameEngine *pGameEngine, CShip *pShip );
// Run Frame
void RunFrame();
private:
CShip *m_pShip;
};
// Again, but in reverse
class CReverseThrusters : public CVectorEntity
{
public:
CReverseThrusters( IGameEngine *pGameEngine, CShip *pShip );
// Run Frame
void RunFrame();
private:
CShip *m_pShip;
};
// Class to represent debris after explosion
class CShipDebris : public CSpaceWarEntity
{
public:
CShipDebris( IGameEngine *pGameEngine, float xPos, float yPos, DWORD dwDebrisColor );
// Run Frame
void RunFrame();
private:
// We keep the debris spinning
float m_flRotationPerInterval;
};
class CShip : public CSpaceWarEntity
{
public:
// Constructor
CShip( IGameEngine *pGameEngine, bool bIsServerInstance, float xPos, float yPos, DWORD dwShipColor );
// Destructor
~CShip();
// Run a frame
void RunFrame();
// Render a frame
void Render();
// Update ship with data from server
void OnReceiveServerUpdate( ServerShipUpdateData_t *pUpdateData );
// Update the ship with data from a client
void OnReceiveClientUpdate( ClientSpaceWarUpdateData_t *pUpdateData );
// Get the update data for this ship client side (copying into memory passed in)
bool BGetClientUpdateData( ClientSpaceWarUpdateData_t *pUpdatedata );
// Build update data for the ship to send to clients
void BuildServerUpdate( ServerShipUpdateData_t *pUpdateData );
// Build update data for photon beams to send to clients
void BuildServerPhotonBeamUpdate( ServerShipUpdateData_t *pUpdateData );
// Reset vertex data for our object
void ResetVertexData();
// Set whether the ship is exploding
void SetExploding( bool bExploding );
// Rebuild the geometry when we change decoration
void BuildGeometry();
// Set whether the ship is disabled
void SetDisabled( bool bDisabled ) { m_bDisabled = bDisabled; }
// Set the initial rotation for the ship
void SetInitialRotation( float flRotation ) { SetAccumulatedRotation( flRotation ); }
// Setters for key bindings
void SetVKBindingLeft( DWORD dwVKLeft ) { m_dwVKLeft = dwVKLeft; }
void SetVKBindingRight( DWORD dwVKRight ) { m_dwVKRight = dwVKRight; }
void SetVKBindingForwardThrusters( DWORD dwVKForward ) { m_dwVKForwardThrusters = dwVKForward; }
void SetVKBindingReverseThrusters( DWORD dwVKReverse ) { m_dwVKReverseThrusters = dwVKReverse; }
void SetVKBindingFire( DWORD dwVKFire ) { m_dwVKFire = dwVKFire; }
// Check for photons which have hit the entity and destroy the photons
void DestroyPhotonsColldingWith( CVectorEntity *pTarget );
// Check whether any of the photons this ship has fired are colliding with the target
bool BCheckForPhotonsCollidingWith( CVectorEntity *pTarget );
// Check if the ship is currently exploding
bool BIsExploding() { return m_bExploding; }
// Check if the ship is currently disabled
bool BIsDisabled() { return m_bDisabled; }
// Set whether this ship instance is for the local player
// (meaning it should pay attention to key input and such)
void SetIsLocalPlayer( bool bValue ) { m_bIsLocalPlayer = bValue; }
bool BIsLocalPlayer() { return m_bIsLocalPlayer; }
// Accumulate stats for this ship
void AccumulateStats( CStatsAndAchievements *pStats );
// Get the name for this ship (only really works server side)
const char* GetPlayerName();
int GetShieldStrength() { return m_nShipShieldStrength; }
void SetShieldStrength( int strength ) { m_nShipShieldStrength = strength; }
// Update the vibration effects for the ship
void UpdateVibrationEffects();
private:
// Last time we sent an update on our local data to the server
uint64 m_ulLastClientUpdateTick;
// Last time we detected the thrust key go down
uint64 m_ulLastThrustStartedTickCount;
// Last time we fired a photon
uint64 m_ulLastPhotonTickCount;
// When we exploded
uint64 m_ulExplosionTickCount;
// Current trigger effect state
bool m_bTriggerEffectEnabled;
// is this ship our local ship, or a remote player?
bool m_bIsLocalPlayer;
// Is this ship instance running inside the server (otherwise its a client...)
bool m_bIsServerInstance;
// is the ship exploding?
bool m_bExploding;
// is the ship disabled for now?
bool m_bDisabled;
// cloak fade out
int m_nFade;
// vector of beams we have fired (in order of firing time)
CPhotonBeam * m_rgPhotonBeams[MAX_PHOTON_BEAMS_PER_SHIP];
// vector of debris to draw after an explosion
std::list< CShipDebris *> m_ListDebris;
// Color for this ship
DWORD m_dwShipColor;
// Decoration for this ship
int m_nShipDecoration;
// Weapon for this ship
int m_nShipWeapon;
// Power for this ship
int m_nShipPower;
// Power for this ship
int m_nShipShieldStrength;
HGAMETEXTURE m_hTextureWhite;
// Thrusters for this ship
CForwardThrusters m_ForwardThrusters;
// Track whether to draw the thrusters next render call
bool m_bForwardThrustersActive;
// Thrusters for this ship
CReverseThrusters m_ReverseThrusters;
// Thrust and rotation speed can be anlog when using a Steam Controller
float m_fThrusterLevel;
float m_fTurnSpeed;
// Track whether to draw the thrusters next render call
bool m_bReverseThrustersActive;
// This will get populated only if we are the local instance, and then
// sent to the server in response to each server update
ClientSpaceWarUpdateData_t m_SpaceWarClientUpdateData;
// key bindings
DWORD m_dwVKLeft;
DWORD m_dwVKRight;
DWORD m_dwVKForwardThrusters;
DWORD m_dwVKReverseThrusters;
DWORD m_dwVKFire;
};
#endif // SHIP_H
+465
View File
@@ -0,0 +1,465 @@
//====== Copyright 1996-2014, Valve Corporation, All rights reserved. =======
//
// Purpose: Simple C++ protobuf manipulation routines. For a more advanced,
// fully-featured library, see https://developers.google.com/protocol-buffers/
//
//===========================================================================
#include "SimpleProtobuf.h"
//
// NOTE:
// You should probably be using the official protobuf library instead if you
// have any concerns about how this code works, or are planning to modify it.
//
#define CHECK_OVERRUN( ptr, end, len ) ( end < ptr || (size_t)( end - ptr ) < len )
static void ProtobufEncodeVarInt( std::string& strProtobuf, uint64 ulVarInt )
{
for ( ; ulVarInt >= 128; ulVarInt >>= 7 )
strProtobuf.append( 1, ((char)ulVarInt & (char)127) | (char)128 );
strProtobuf.append( 1, (char)ulVarInt );
}
void ProtobufWriteField_Integer( std::string& strProtobuf, uint32 uFieldNumber, uint64 ulVarIntData )
{
ProtobufEncodeVarInt( strProtobuf, PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ) );
ProtobufEncodeVarInt( strProtobuf, ulVarIntData );
}
void ProtobufWriteField_SInteger( std::string& strProtobuf, uint32 uFieldNumber, int64 ulSwizzleVarIntData )
{
ProtobufEncodeVarInt( strProtobuf, PROTOBUF_FIELDTAG_SINTEGER( uFieldNumber ) );
ProtobufEncodeVarInt( strProtobuf, (ulSwizzleVarIntData << 1) ^ (ulSwizzleVarIntData >> 63) );
}
void ProtobufWriteField_Fixed64( std::string& strProtobuf, uint32 uFieldNumber, uint64 ulFixed64Data )
{
ProtobufEncodeVarInt( strProtobuf, PROTOBUF_FIELDTAG_FIXED64( uFieldNumber ) );
#ifdef VALVE_BIG_ENDIAN
ulFixed64Data = QWordSwap( ulFixed64Data );
#endif
strProtobuf.append( reinterpret_cast<char*>(&ulFixed64Data), 8 );
}
void ProtobufWriteField_Fixed64( std::string& strProtobuf, uint32 uFieldNumber, double flFixed64Data )
{
ProtobufEncodeVarInt( strProtobuf, PROTOBUF_FIELDTAG_FIXED64( uFieldNumber ) );
const char *pData = reinterpret_cast<const char*>(&flFixed64Data);
#ifdef VALVE_BIG_ENDIAN
strProtobuf.append( std::const_reverse_iterator<const char*>( pData + 8 ), std::const_reverse_iterator<const char*>( pData ) );
#else
strProtobuf.append( pData, 8 );
#endif
}
void ProtobufWriteField_String( std::string& strProtobuf, uint32 uFieldNumber, const char *pchData, size_t cchData )
{
ProtobufEncodeVarInt( strProtobuf, PROTOBUF_FIELDTAG_STRING( uFieldNumber ) );
ProtobufEncodeVarInt( strProtobuf, cchData );
strProtobuf.append( pchData, cchData );
}
void ProtobufWriteField_String( std::string& strProtobuf, uint32 uFieldNumber, const std::string &strData )
{
ProtobufWriteField_String( strProtobuf, uFieldNumber, strData.data(), strData.size() );
}
void ProtobufWriteField_String( std::string& strProtobuf, uint32 uFieldNumber, const char *pchData )
{
ProtobufWriteField_String( strProtobuf, uFieldNumber, pchData, strlen( pchData ) );
}
void ProtobufWriteField_Fixed32( std::string& strProtobuf, uint32 uFieldNumber, uint32 ulFixed32Data )
{
ProtobufEncodeVarInt( strProtobuf, PROTOBUF_FIELDTAG_FIXED32( uFieldNumber ) );
#ifdef VALVE_BIG_ENDIAN
ulFixed32Data = DWordSwap( ulFixed32Data );
#endif
strProtobuf.append( reinterpret_cast<char*>(&ulFixed32Data), 4 );
}
void ProtobufWriteField_Fixed32( std::string& strProtobuf, uint32 uFieldNumber, float flFixed32Data )
{
ProtobufEncodeVarInt( strProtobuf, PROTOBUF_FIELDTAG_FIXED32( uFieldNumber ) );
const char *pData = reinterpret_cast<const char*>(&flFixed32Data);
#ifdef VALVE_BIG_ENDIAN
strProtobuf.append( std::const_reverse_iterator<const char*>( pData + 4 ), std::const_reverse_iterator<const char*>( pData ) );
#else
strProtobuf.append( pData, 4 );
#endif
}
static bool ProtobufDecodeVarInt( const char * &pParsePosition, const char *pParseEnd, uint64 &ulVarInt )
{
const char * pStart = pParsePosition;
while ( pParsePosition < pParseEnd && (*pParsePosition & 128) )
++pParsePosition;
if ( pParsePosition >= pParseEnd )
return false;
uint64 v = 0;
for ( const char *p = pParsePosition++; p >= pStart; --p )
v = (v << 7) + (*p & 127);
ulVarInt = v;
return true;
}
bool ProtobufReadFieldTag( const char * &pParsePosition, const char *pParseEnd, uint32 &uFieldTag )
{
uint64 v;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, v ) || v == 0 || (v >> 32) != 0 )
{
pParsePosition = pParseEnd;
return false;
}
uFieldTag = (uint32)v;
return true;
}
bool ProtobufSkipFieldValue( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag )
{
switch ( uFieldTag & 7 )
{
case 0: // VARINT
while ( pParsePosition < pParseEnd )
{
char c = *pParsePosition++;
if ( !( c & 128 ) )
return true;
}
return false;
case 1: // FIXED64
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, 8 ) )
{
pParsePosition = pParseEnd;
return false;
}
pParsePosition += 8;
return true;
case 2: // LENGTH DELIM (string, etc)
{
uint64 ulLength = 0;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, ulLength ) )
return false;
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, ulLength ) )
{
pParsePosition = pParseEnd;
return false;
}
pParsePosition += ulLength;
return true;
}
case 5: // FIXED32
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, 4 ) )
{
pParsePosition = pParseEnd;
return false;
}
pParsePosition += 4;
return true;
default: // UNKNOWN
pParsePosition = pParseEnd;
return false;
}
}
bool ProtobufReadFixed32( const char * &pParsePosition, const char *pParseEnd, int32 &nValue )
{
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, 4 ) )
{
pParsePosition = pParseEnd;
return false;
}
memcpy( &nValue, pParsePosition, 4 );
#ifdef VALVE_BIG_ENDIAN
nValue = DWordSwap( nValue );
#endif
pParsePosition += 4;
return true;
}
bool ProtobufReadFixed32( const char * &pParsePosition, const char *pParseEnd, uint32 &uValue )
{
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, 4 ) )
{
pParsePosition = pParseEnd;
return false;
}
memcpy( &uValue, pParsePosition, 4 );
#ifdef VALVE_BIG_ENDIAN
uValue = DWordSwap( uValue );
#endif
pParsePosition += 4;
return true;
}
bool ProtobufReadFixed32( const char * &pParsePosition, const char *pParseEnd, float &flValue )
{
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, 4 ) )
{
pParsePosition = pParseEnd;
return false;
}
#ifdef VALVE_BIG_ENDIAN
std::copy( std::const_reverse_iterator( pParsePosition + 4 ), std::const_reverse_iterator( pParsePosition ), reinterpret_cast<char *>(&flValue) );
#else
memcpy( &flValue, pParsePosition, 4 );
#endif
pParsePosition += 4;
return true;
}
bool ProtobufReadFixed64( const char * &pParsePosition, const char *pParseEnd, int64 &lValue )
{
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, 8 ) )
{
pParsePosition = pParseEnd;
return false;
}
memcpy( &lValue, pParsePosition, 8 );
#ifdef VALVE_BIG_ENDIAN
lValue = QWordSwap( lValue );
#endif
pParsePosition += 8;
return true;
}
bool ProtobufReadFixed64( const char * &pParsePosition, const char *pParseEnd, uint64 &ulValue )
{
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, 8 ) )
{
pParsePosition = pParseEnd;
return false;
}
memcpy( &ulValue, pParsePosition, 8 );
#ifdef VALVE_BIG_ENDIAN
ulValue = QWordSwap( ulValue );
#endif
pParsePosition += 8;
return true;
}
bool ProtobufReadFixed64( const char * &pParsePosition, const char *pParseEnd, double &flValue )
{
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, 8 ) )
{
pParsePosition = pParseEnd;
return false;
}
#ifdef VALVE_BIG_ENDIAN
std::copy( std::const_reverse_iterator( pParsePosition + 8 ), std::const_reverse_iterator( pParsePosition ), reinterpret_cast<char *>(&flValue) );
#else
memcpy( &flValue, pParsePosition, 8 );
#endif
pParsePosition += 8;
return true;
}
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, uint64 &ulVarInt )
{
return ProtobufDecodeVarInt( pParsePosition, pParseEnd, ulVarInt );
}
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, int64 &lVarInt )
{
return ProtobufDecodeVarInt( pParsePosition, pParseEnd, reinterpret_cast<uint64&>(lVarInt) );
}
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, uint32 &uVarInt )
{
uint64 ulVarInt;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, ulVarInt ) )
return false;
uVarInt = (uint32)ulVarInt;
return (uint64)uVarInt == ulVarInt;
}
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, int32 &nVarInt )
{
uint64 ulVarInt;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, ulVarInt ) )
return false;
nVarInt = (int32)ulVarInt;
return (uint64)(int64)nVarInt == ulVarInt;
}
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, bool &bVarInt )
{
uint64 ulVarInt;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, ulVarInt ) )
return false;
bVarInt = ( ulVarInt != 0 );
return true;
}
bool ProtobufReadSInteger( const char * &pParsePosition, const char *pParseEnd, int64 &lVarInt )
{
uint64 v;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, v ) )
return false;
lVarInt = (int64)(v >> 1) ^ -(int64)(v & 1);
return true;
}
bool ProtobufReadSInteger( const char * &pParsePosition, const char *pParseEnd, int32 &nVarInt )
{
uint64 v;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, v ) )
return false;
int64 lVarInt = (int64)(v >> 1) ^ -(int64)(v & 1);
nVarInt = (int32)lVarInt;
return (int64)nVarInt == lVarInt;
}
bool ProtobufReadString( const char * &pParsePosition, const char *pParseEnd, std::string &strValue )
{
uint64 ulLength;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, ulLength ) )
return false;
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, ulLength ) )
{
pParsePosition = pParseEnd;
return false;
}
strValue.assign( pParsePosition, (size_t)ulLength );
pParsePosition += ulLength;
return true;
}
bool ProtobufReadStringAlias( const char * &pParsePosition, const char *pParseEnd, const char * &pStringDataStart, const char * &pStringDataEnd )
{
uint64 ulLength;
if ( !ProtobufDecodeVarInt( pParsePosition, pParseEnd, ulLength ) )
return false;
if ( CHECK_OVERRUN( pParsePosition, pParseEnd, ulLength ) )
{
pParsePosition = pParseEnd;
return false;
}
pStringDataStart = pParsePosition;
pParsePosition += ulLength;
pStringDataEnd = pParsePosition;
return true;
}
template < typename T >
static bool ProtobufReadRepeated_T( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector< T > &vecData, bool( *pfnRead )(const char * &, const char *, T &) )
{
if ( (uFieldTag & 7) == 2 )
{
const char *pStart = NULL, *pEnd = NULL;
if ( !ProtobufReadStringAlias( pParsePosition, pParseEnd, pStart, pEnd ) )
return false;
while ( pStart != pEnd )
{
T v;
if ( !pfnRead( pStart, pEnd, v ) )
return false;
vecData.push_back( v );
}
}
else
{
T v;
if ( !pfnRead( pParsePosition, pParseEnd, v ) )
return false;
vecData.push_back( v );
}
return true;
}
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<uint64> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadInteger ); }
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int64> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadInteger ); }
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<uint32> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadInteger ); }
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int32> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadInteger ); }
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<bool> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadInteger ); }
bool ProtobufReadRepeatedSInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int64> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadSInteger ); }
bool ProtobufReadRepeatedSInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int32> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadSInteger ); }
bool ProtobufReadRepeatedFixed32( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int32> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadFixed32 ); }
bool ProtobufReadRepeatedFixed32( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<uint32> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadFixed32 ); }
bool ProtobufReadRepeatedFixed32( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<float> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadFixed32 ); }
bool ProtobufReadRepeatedFixed64( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int64> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadFixed64 ); }
bool ProtobufReadRepeatedFixed64( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<uint64> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadFixed64 ); }
bool ProtobufReadRepeatedFixed64( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<double> &vec ) { return ProtobufReadRepeated_T( pParsePosition, pParseEnd, uFieldTag, vec, &ProtobufReadFixed64 ); }
bool ProtobufReadRepeatedString( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<std::string> &vec )
{
vec.push_back( std::string() );
if ( !ProtobufReadString( pParsePosition, pParseEnd, vec.back() ) )
{
vec.pop_back();
return false;
}
return true;
}
template < typename T >
static bool ProtobufExtractField_T( const char *pParsePosition, const char *pParseEnd, uint32 uFieldTag, T &value, bool( *pfnRead )(const char * &, const char *, T &) )
{
uint32 uCurrentTag = 0;
bool bOK = false;
while ( ProtobufReadFieldTag( pParsePosition, pParseEnd, uCurrentTag ) )
{
if ( uCurrentTag == uFieldTag )
bOK = pfnRead( pParsePosition, pParseEnd, value );
else
ProtobufSkipFieldValue( pParsePosition, pParseEnd, uCurrentTag );
}
return bOK;
}
template < typename T >
static bool ProtobufExtractField_T( const char *pParsePosition, const char *pParseEnd, uint32 uFieldTag, T &value, bool( *pfnRead )(const char * &, const char *, uint32, T &) )
{
uint32 uCurrentTag = 0;
bool bOK = false;
while ( ProtobufReadFieldTag( pParsePosition, pParseEnd, uCurrentTag ) )
{
if ( uCurrentTag == uFieldTag || uCurrentTag == PROTOBUF_FIELDTAG_STRING( uFieldTag >> 3 ) )
bOK = pfnRead( pParsePosition, pParseEnd, uCurrentTag, value );
else
ProtobufSkipFieldValue( pParsePosition, pParseEnd, uCurrentTag );
}
return bOK;
}
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, uint64 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), value, &ProtobufReadInteger ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, int64 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), value, &ProtobufReadInteger ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, uint32 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), value, &ProtobufReadInteger ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, int32 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), value, &ProtobufReadInteger ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, bool &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), value, &ProtobufReadInteger ); }
bool ProtobufExtractField_SInteger( const std::string &strProtobuf, uint32 uFieldNumber, int64 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_SINTEGER( uFieldNumber ), value, &ProtobufReadSInteger ); }
bool ProtobufExtractField_SInteger( const std::string &strProtobuf, uint32 uFieldNumber, int32 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_SINTEGER( uFieldNumber ), value, &ProtobufReadSInteger ); }
bool ProtobufExtractField_Fixed64( const std::string &strProtobuf, uint32 uFieldNumber, int64 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED64( uFieldNumber ), value, &ProtobufReadFixed64 ); }
bool ProtobufExtractField_Fixed64( const std::string &strProtobuf, uint32 uFieldNumber, uint64 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED64( uFieldNumber ), value, &ProtobufReadFixed64 ); }
bool ProtobufExtractField_Fixed64( const std::string &strProtobuf, uint32 uFieldNumber, double &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED64( uFieldNumber ), value, &ProtobufReadFixed64 ); }
bool ProtobufExtractField_Fixed32( const std::string &strProtobuf, uint32 uFieldNumber, int32 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED32( uFieldNumber ), value, &ProtobufReadFixed32 ); }
bool ProtobufExtractField_Fixed32( const std::string &strProtobuf, uint32 uFieldNumber, uint32 &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED32( uFieldNumber ), value, &ProtobufReadFixed32 ); }
bool ProtobufExtractField_Fixed32( const std::string &strProtobuf, uint32 uFieldNumber, float &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED32( uFieldNumber ), value, &ProtobufReadFixed32 ); }
bool ProtobufExtractField_String( const std::string &strProtobuf, uint32 uFieldNumber, std::string &value ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_STRING( uFieldNumber ), value, &ProtobufReadString ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<uint64> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), vec, &ProtobufReadRepeatedInteger ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<int64> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), vec, &ProtobufReadRepeatedInteger ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<uint32> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), vec, &ProtobufReadRepeatedInteger ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<int32> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), vec, &ProtobufReadRepeatedInteger ); }
bool ProtobufExtractField_Integer( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<bool> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_INTEGER( uFieldNumber ), vec, &ProtobufReadRepeatedInteger ); }
bool ProtobufExtractField_SInteger( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<int64> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_SINTEGER( uFieldNumber ), vec, &ProtobufReadRepeatedSInteger ); }
bool ProtobufExtractField_SInteger( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<int32> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_SINTEGER( uFieldNumber ), vec, &ProtobufReadRepeatedSInteger ); }
bool ProtobufExtractField_Fixed64( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<int64> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED64( uFieldNumber ), vec, &ProtobufReadRepeatedFixed64 ); }
bool ProtobufExtractField_Fixed64( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<uint64> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED64( uFieldNumber ), vec, &ProtobufReadRepeatedFixed64 ); }
bool ProtobufExtractField_Fixed64( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<double> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED64( uFieldNumber ), vec, &ProtobufReadRepeatedFixed64 ); }
bool ProtobufExtractField_Fixed32( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<int32> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED32( uFieldNumber ), vec, &ProtobufReadRepeatedFixed32 ); }
bool ProtobufExtractField_Fixed32( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<uint32> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED32( uFieldNumber ), vec, &ProtobufReadRepeatedFixed32 ); }
bool ProtobufExtractField_Fixed32( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<float> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_FIXED32( uFieldNumber ), vec, &ProtobufReadRepeatedFixed32 ); }
bool ProtobufExtractField_String( const std::string &strProtobuf, uint32 uFieldNumber, std::vector<std::string> &vec ) { return ProtobufExtractField_T( strProtobuf.data(), strProtobuf.data() + strProtobuf.size(), PROTOBUF_FIELDTAG_STRING( uFieldNumber ), vec, &ProtobufReadRepeatedString ); }
+190
View File
@@ -0,0 +1,190 @@
//====== Copyright 1996-2014, Valve Corporation, All rights reserved. =======
//
// Purpose: Simple C++ protobuf manipulation routines. For a more advanced,
// fully-featured library, see https://developers.google.com/protocol-buffers/
//
//===========================================================================
#ifndef SIMPLEPROTOBUF_H
#define SIMPLEPROTOBUF_H
#pragma once
#include "steam/steamtypes.h"
#include <string>
#include <vector>
#include <string.h>
//
// This file contains some quick-and-dirty helpers that can encode and
// decode the protocol-buffer ("protobuf") serialization format. It's
// a reasonable way to communicate with simple protobuf-based services.
//
// However, if you are doing serious work with protobufs, you should
// take the time to understand and use the official C++ library. It
// provides a tool which copmiles protobuf descriptions directly into
// working C++ classes, which will save you time and effort, and help
// with parsing complicated message types.
//
// https://developers.google.com/protocol-buffers/
//
//
// The protobuf serialization format is a simple field-based encoding;
// a complete protobuf is the unordered concatenation of all its fields.
// Unknown or incorrectly-typed fields are ignored by protobuf parsers.
//
// Details: https://developers.google.com/protocol-buffers/docs/encoding
//
// All protobuf value types use one of these five encodings:
// Integer: bool, enum, int32, uint32, int64, uint64
// SInteger: sint32, sint64
// Fixed32: fixed32, float
// Fixed64: fixed64, double
// String: string, bytes, nested message types
//
// Nested protobufs are built up independently, then encoded as string
// fields in the parent protobuf.
//
// Arrays ("repeated" field types) have two possible encodings: simple
// and packed. This utility file can parse both encodings, but only
// emits simple repeated fields (via multiple ProtobufWriteField calls
// with the same field number, one for every array element).
//
//
// Example usage
//
// If this is the protobuf definition of a message...
//
// message TestMessage {
// optional uint32 index = 1;
// optional string text = 2;
// repeated double number = 3;
// optional bool flag = 4;
// }
//
// ...then this is how to compose it:
//
// std::string msg;
// ProtobufWriteField_Integer( msg, 1, iIndex );
// ProtobufWriteField_Integer( msg, 4, true );
// ProtobufWriteField_Fixed64( msg, 3, 1.0 );
// ProtobufWriteField_Fixed64( msg, 3, 2.0 );
// ProtobufWriteField_Fixed64( msg, 3, 3.0 );
// ProtobufWriteField_String( msg, 2, "text field" );
//
// ...and this is how to extract individual fields:
//
// std::string strText;
// ProtobufExtractField_String( msg, 2, strText );
//
// ...and this is how to parse it with optimized low-level operations:
//
// bool bFlag = false;
// uint32 uIndex = 0;
// std::string strText;
// std::vector< double > vecNumbers;
//
// const char *pParse = msg.data(), *pEnd = msg.data() + msg.size();
// for ( uint32 uFieldTag = 0; ProtobufReadFieldTag( pParse, pEnd, uFieldTag ); ) {
// switch ( uFieldTag ) {
// case PROTOBUF_FIELDTAG_INTEGER( 1 ): ProtobufReadInteger( pParse, pEnd, iIndex ); break;
// case PROTOBUF_FIELDTAG_STRING( 2 ): ProtobufReadString( pParse, pEnd, strText ); break;
// case PROTOBUF_FIELDTAG_FIXED64( 3 ): case PROTOBUF_FIELDTAG_REPEATED_FIXED64( 3 ):
// ProtobufReadRepeatedFixed64( pParse, pEnd, uFieldTag, vecNumbers ); break;
// case PROTOBUF_FIELDTAG_STRING( 4 ): ProtobufReadInteger( pParse, pEnd, bFlag ); break;
// default: ProtobufSkipFieldValue( pParse, pEnd, uFieldTag ); break;
// }
// }
//
//
// NOTE: it is important to handle both REPEATED and non-REPEATED cases when
// parsing repeated fields, for all types other than strings! There are two
// different possible encodings for repeated non-string fields, and failing
// to handle both cases can lead to invalid parse results.
//
// Encoding functions
//
// Note: C++ type promotion rules will automatically handle smaller integer types
void ProtobufWriteField_Integer( std::string& strProtobuf, uint32 uFieldNumber, uint64 ulVarIntData );
void ProtobufWriteField_SInteger( std::string& strProtobuf, uint32 uFieldNumber, int64 lSwizzleVarIntData );
void ProtobufWriteField_Fixed64( std::string& strProtobuf, uint32 uFieldNumber, uint64 ulFixed64Data );
void ProtobufWriteField_Fixed64( std::string& strProtobuf, uint32 uFieldNumber, double flFixed64Data );
void ProtobufWriteField_Fixed32( std::string& strProtobuf, uint32 uFieldNumber, uint32 ulFixed32Data );
void ProtobufWriteField_Fixed32( std::string& strProtobuf, uint32 uFieldNumber, float flFixed32Data );
void ProtobufWriteField_String( std::string& strProtobuf, uint32 uFieldNumber, const char *pchData, size_t cchData );
void ProtobufWriteField_String( std::string& strProtobuf, uint32 uFieldNumber, const char *pchData );
void ProtobufWriteField_String( std::string& strProtobuf, uint32 uFieldNumber, const std::string &strData );
// Decoding functions, high-level (not optimized for speed)
//
bool ProtobufExtractField_Integer( const std::string & strProtobuf, uint32 uFieldNumber, uint64 &ulData );
bool ProtobufExtractField_Integer( const std::string & strProtobuf, uint32 uFieldNumber, int64 &lData );
bool ProtobufExtractField_Integer( const std::string & strProtobuf, uint32 uFieldNumber, uint32 &uData );
bool ProtobufExtractField_Integer( const std::string & strProtobuf, uint32 uFieldNumber, int32 &iData );
bool ProtobufExtractField_Integer( const std::string & strProtobuf, uint32 uFieldNumber, bool &bData );
bool ProtobufExtractField_SInteger( const std::string & strProtobuf, uint32 uFieldNumber, int64 &lData );
bool ProtobufExtractField_SInteger( const std::string & strProtobuf, uint32 uFieldNumber, int32 &lData );
bool ProtobufExtractField_Fixed64( const std::string & strProtobuf, uint32 uFieldNumber, uint64 &ulData );
bool ProtobufExtractField_Fixed64( const std::string & strProtobuf, uint32 uFieldNumber, int64 &lData );
bool ProtobufExtractField_Fixed64( const std::string & strProtobuf, uint32 uFieldNumber, double &flData );
bool ProtobufExtractField_Fixed32( const std::string & strProtobuf, uint32 uFieldNumber, uint32 &uData );
bool ProtobufExtractField_Fixed32( const std::string & strProtobuf, uint32 uFieldNumber, int32 &iData );
bool ProtobufExtractField_Fixed32( const std::string & strProtobuf, uint32 uFieldNumber, float &flData );
bool ProtobufExtractField_String( const std::string & strProtobuf, uint32 uFieldNumber, std::string &strData );
// Decoding functions, low-level (see example usage and important NOTE in comments above)
//
bool ProtobufReadFieldTag( const char * &pParsePosition, const char *pParseEnd, uint32 &uFieldTag );
bool ProtobufSkipFieldValue( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag );
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, uint64 &ulVarInt );
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, int64 &lVarInt );
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, uint32 &uVarInt );
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, int32 &nVarInt );
bool ProtobufReadInteger( const char * &pParsePosition, const char *pParseEnd, bool &bVarInt );
bool ProtobufReadSInteger( const char * &pParsePosition, const char *pParseEnd, int64 &lVarInt );
bool ProtobufReadSInteger( const char * &pParsePosition, const char *pParseEnd, int32 &nVarInt );
bool ProtobufReadFixed64( const char * &pParsePosition, const char *pParseEnd, int64 &lValue );
bool ProtobufReadFixed64( const char * &pParsePosition, const char *pParseEnd, uint64 &ulValue );
bool ProtobufReadFixed64( const char * &pParsePosition, const char *pParseEnd, double &flValue );
bool ProtobufReadFixed32( const char * &pParsePosition, const char *pParseEnd, int32 &nValue );
bool ProtobufReadFixed32( const char * &pParsePosition, const char *pParseEnd, uint32 &uValue );
bool ProtobufReadFixed32( const char * &pParsePosition, const char *pParseEnd, float &flValue );
bool ProtobufReadString( const char * &pParsePosition, const char *pParseEnd, std::string &strValue );
bool ProtobufReadStringAlias( const char * &pParsePosition, const char *pParseEnd, const char * &pStringDataStart, const char * &pStringDataEnd );
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<uint64> &vec );
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int64> &vec );
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<uint32> &vec );
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int32> &vec );
bool ProtobufReadRepeatedInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<bool> &vec );
bool ProtobufReadRepeatedSInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int64> &vec );
bool ProtobufReadRepeatedSInteger( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int32> &vec );
bool ProtobufReadRepeatedFixed64( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int64> &vec );
bool ProtobufReadRepeatedFixed64( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<uint64> &vec );
bool ProtobufReadRepeatedFixed64( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<double> &vec );
bool ProtobufReadRepeatedFixed32( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<int32> &vec );
bool ProtobufReadRepeatedFixed32( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<uint32> &vec );
bool ProtobufReadRepeatedFixed32( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<float> &vec );
bool ProtobufReadRepeatedString( const char * &pParsePosition, const char *pParseEnd, uint32 uFieldTag, std::vector<std::string> &vec );
#define PROTOBUF_FIELDTAG_INTEGER( Field ) ( (uint64)( Field ) << 3 )
#define PROTOBUF_FIELDTAG_SINTEGER( Field ) ( (uint64)( Field ) << 3 )
#define PROTOBUF_FIELDTAG_FIXED64( Field ) ( (uint64)( Field ) << 3 | (uint64)1 )
#define PROTOBUF_FIELDTAG_STRING( Field ) ( (uint64)( Field ) << 3 | (uint64)2 )
#define PROTOBUF_FIELDTAG_FIXED32( Field ) ( (uint64)( Field ) << 3 | (uint64)5 )
#define PROTOBUF_FIELDTAG_REPEATED_INTEGER PROTOBUF_FIELDTAG_STRING
#define PROTOBUF_FIELDTAG_REPEATED_SINTEGER PROTOBUF_FIELDTAG_STRING
#define PROTOBUF_FIELDTAG_REPEATED_FIXED32 PROTOBUF_FIELDTAG_STRING
#define PROTOBUF_FIELDTAG_REPEATED_FIXED64 PROTOBUF_FIELDTAG_STRING
#endif
+446
View File
@@ -0,0 +1,446 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Shared definitions for the communication between the server/client
//
// $NoKeywords: $
//=============================================================================
#ifndef SPACEWAR_H
#define SPACEWAR_H
// The Steamworks API's are modular, you can use some subsystems without using others
// When USE_GS_AUTH_API is defined you get the following Steam features:
// - Strong user authentication and authorization
// - Game server matchmaking
// - VAC cheat protection
// - Access to achievement/community API's
// - P2P networking capability
// Remove this define to disable using the native Steam authentication and matchmaking system
// You can use this as a sample of how to integrate your game without replacing an existing matchmaking system
// When you un-define USE_GS_AUTH_API you get:
// - Access to achievement/community API's
// - P2P networking capability
// You CANNOT use:
// - VAC cheat protection
// - Game server matchmaking
// as these function depend on using Steam authentication
#define USE_GS_AUTH_API
// Current game server version
#define SPACEWAR_SERVER_VERSION "1.0.0.0"
// UDP port for the spacewar server to listen on
#define SPACEWAR_SERVER_PORT 27015
// UDP port for the master server updater to listen on
#define SPACEWAR_MASTER_SERVER_UPDATER_PORT 27016
// How long to wait for a response from the server before resending our connection attempt
#define SERVER_CONNECTION_RETRY_MILLISECONDS 350
// How long to wait for a client to send an update before we drop its connection server side
#define SERVER_TIMEOUT_MILLISECONDS 5000
// Maximum packet size in bytes
#define MAX_SPACEWAR_PACKET_SIZE 1024*512
// Maximum number of players who can join a server and play simultaneously
#define MAX_PLAYERS_PER_SERVER 4
// Time to pause wait after a round ends before starting a new one
#define MILLISECONDS_BETWEEN_ROUNDS 4000
// How long photon beams live before expiring
#define PHOTON_BEAM_LIFETIME_IN_TICKS 1750
// How fast can photon beams be fired?
#define PHOTON_BEAM_FIRE_INTERVAL_TICKS 250
// Amount of space needed for beams per ship
#define MAX_PHOTON_BEAMS_PER_SHIP (PHOTON_BEAM_LIFETIME_IN_TICKS/PHOTON_BEAM_FIRE_INTERVAL_TICKS)
// Time to timeout a connection attempt in
#define MILLISECONDS_CONNECTION_TIMEOUT 30000
// How many times a second does the server send world updates to clients
#define SERVER_UPDATE_SEND_RATE 60
// How many times a second do we send our updated client state to the server
#define CLIENT_UPDATE_SEND_RATE 30
// How fast does the server internally run at?
#define MAX_CLIENT_AND_SERVER_FPS 86
template <typename T>
inline T WordSwap( T w )
{
uint16 temp;
temp = ((*((uint16 *)&w) & 0xff00) >> 8);
temp |= ((*((uint16 *)&w) & 0x00ff) << 8);
return *((T*)&temp);
}
template <typename T>
inline T DWordSwap( T dw )
{
uint32 temp;
temp = *((uint32 *)&dw) >> 24;
temp |= ((*((uint32 *)&dw) & 0x00FF0000) >> 8);
temp |= ((*((uint32 *)&dw) & 0x0000FF00) << 8);
temp |= ((*((uint32 *)&dw) & 0x000000FF) << 24);
return *((T*)&temp);
}
template <typename T>
inline T QWordSwap( T dw )
{
uint64 temp;
temp = *((uint64 *)&dw) >> 56;
temp |= ((*((uint64 *)&dw) & 0x00FF000000000000ull) >> 40);
temp |= ((*((uint64 *)&dw) & 0x0000FF0000000000ull) >> 24);
temp |= ((*((uint64 *)&dw) & 0x000000FF00000000ull) >> 8);
temp |= ((*((uint64 *)&dw) & 0x00000000FF000000ull) << 8);
temp |= ((*((uint64 *)&dw) & 0x0000000000FF0000ull) << 24);
temp |= ((*((uint64 *)&dw) & 0x000000000000FF00ull) << 40);
temp |= ((*((uint64 *)&dw) & 0x00000000000000FFull) << 56);
return *((T*)&temp);
}
#define LittleInt16( val ) ( val )
#define LittleWord( val ) ( val )
#define LittleInt32( val ) ( val )
#define LittleDWord( val ) ( val )
#define LittleQWord( val ) ( val )
#define LittleFloat( val ) ( val )
// Leaderboard names
#define LEADERBOARD_QUICKEST_WIN "Quickest Win"
#define LEADERBOARD_FEET_TRAVELED "Feet Traveled"
// Player colors
DWORD const g_rgPlayerColors[ MAX_PLAYERS_PER_SERVER ] =
{
D3DCOLOR_ARGB( 255, 255, 150, 150 ), // red
D3DCOLOR_ARGB( 255, 200, 200, 255 ), // blue
D3DCOLOR_ARGB( 255, 255, 204, 102 ), // orange
D3DCOLOR_ARGB( 255, 153, 255, 153 ), // green
};
// Enum for possible game states on the client
enum EClientGameState
{
k_EClientGameStartServer,
k_EClientGameActive,
k_EClientGameWaitingForPlayers,
k_EClientGameMenu,
k_EClientGameQuitMenu,
k_EClientGameExiting,
k_EClientGameInstructions,
k_EClientGameDraw,
k_EClientGameWinner,
k_EClientGameConnecting,
k_EClientGameConnectionFailure,
k_EClientFindInternetServers,
k_EClientStatsAchievements,
k_EClientCreatingLobby,
k_EClientInLobby,
k_EClientFindLobby,
k_EClientJoiningLobby,
k_EClientFindLANServers,
k_EClientRemoteStorage,
k_EClientLeaderboards,
k_EClientFriendsList,
k_EClientMinidump,
k_EClientClanChatRoom,
k_EClientWebCallback,
k_EClientMusic,
k_EClientWorkshop,
k_EClientHTMLSurface,
k_EClientInGameStore,
k_EClientRemotePlayInvite,
k_EClientRemotePlaySessions,
k_EClientOverlayAPI,
};
// Enum for possible game states on the server
enum EServerGameState
{
k_EServerWaitingForPlayers,
k_EServerActive,
k_EServerDraw,
k_EServerWinner,
k_EServerExiting,
};
#pragma pack( push, 1 )
// Data sent per photon beam from the server to update clients photon beam positions
struct ServerPhotonBeamUpdateData_t
{
void SetActive( bool bIsActive ) { m_bIsActive = bIsActive; }
bool GetActive() { return m_bIsActive; }
void SetRotation( float flRotation ) { m_flCurrentRotation = LittleFloat( flRotation ); }
float GetRotation() { return LittleFloat( m_flCurrentRotation ); }
void SetXVelocity( float flVelocity ) { m_flXVelocity = LittleFloat( flVelocity ); }
float GetXVelocity() { return LittleFloat( m_flXVelocity ); }
void SetYVelocity( float flVelocity ) { m_flYVelocity = LittleFloat( flVelocity ); }
float GetYVelocity() { return LittleFloat( m_flYVelocity ); }
void SetXPosition( float flPosition ) { m_flXPosition = LittleFloat( flPosition ); }
float GetXPosition() { return LittleFloat( m_flXPosition ); }
void SetYPosition( float flPosition ) { m_flYPosition = LittleFloat( flPosition ); }
float GetYPosition() { return LittleFloat( m_flYPosition ); }
private:
// Does the photon beam exist right now?
bool m_bIsActive;
// The current rotation
float m_flCurrentRotation;
// The current velocity
float m_flXVelocity;
float m_flYVelocity;
// The current position
float m_flXPosition;
float m_flYPosition;
};
// This is the data that gets sent per ship in each update, see below for the full update data
struct ServerShipUpdateData_t
{
void SetRotation( float flRotation ) { m_flCurrentRotation = LittleFloat( flRotation ); }
float GetRotation() { return LittleFloat( m_flCurrentRotation ); }
void SetRotationDeltaLastFrame( float flDelta ) { m_flRotationDeltaLastFrame = LittleFloat( flDelta ); }
float GetRotationDeltaLastFrame() { return LittleFloat( m_flRotationDeltaLastFrame ); }
void SetXAcceleration( float flAcceleration ) { m_flXAcceleration = LittleFloat( flAcceleration ); }
float GetXAcceleration() { return LittleFloat( m_flXAcceleration ); }
void SetYAcceleration( float flAcceleration ) { m_flYAcceleration = LittleFloat( flAcceleration ); }
float GetYAcceleration() { return LittleFloat( m_flYAcceleration ); }
void SetXVelocity( float flVelocity ) { m_flXVelocity = LittleFloat( flVelocity ); }
float GetXVelocity() { return LittleFloat( m_flXVelocity ); }
void SetYVelocity( float flVelocity ) { m_flYVelocity = LittleFloat( flVelocity ); }
float GetYVelocity() { return LittleFloat( m_flYVelocity ); }
void SetXPosition( float flPosition ) { m_flXPosition = LittleFloat( flPosition ); }
float GetXPosition() { return LittleFloat( m_flXPosition ); }
void SetYPosition( float flPosition ) { m_flYPosition = LittleFloat( flPosition ); }
float GetYPosition() { return LittleFloat( m_flYPosition ); }
void SetExploding( bool bIsExploding ) { m_bExploding = bIsExploding; }
bool GetExploding() { return m_bExploding; }
void SetDisabled( bool bIsDisabled ) { m_bDisabled = bIsDisabled; }
bool GetDisabled() { return m_bDisabled; }
void SetForwardThrustersActive( bool bActive ) { m_bForwardThrustersActive = bActive; }
bool GetForwardThrustersActive() { return m_bForwardThrustersActive; }
void SetReverseThrustersActive( bool bActive ) { m_bReverseThrustersActive = bActive; }
bool GetReverseThrustersActive() { return m_bReverseThrustersActive; }
void SetDecoration( int nDecoration ) { m_nShipDecoration = nDecoration; }
int GetDecoration() { return m_nShipDecoration; }
void SetWeapon( int nWeapon ) { m_nShipWeapon = nWeapon; }
int GetWeapon() { return m_nShipWeapon; }
void SetPower( int nPower ) { m_nShipPower = nPower; }
int GetPower() { return m_nShipPower; }
void SetShieldStrength( int nShieldStrength ) { m_nShieldStrength = nShieldStrength; }
int GetShieldStrength() { return m_nShieldStrength; }
void SetThrustersLevel( float fLevel ) { m_fThrusterLevel = fLevel; }
float GetThrustersLevel( ) { return m_fThrusterLevel; }
void SetTurnSpeed( float fSpeed ) { m_fTurnSpeed = fSpeed; }
float GetTurnSpeed( ) { return m_fTurnSpeed; }
ServerPhotonBeamUpdateData_t *AccessPhotonBeamData( int iIndex ) { return &m_PhotonBeamData[iIndex]; }
private:
// The current rotation of the ship
float m_flCurrentRotation;
// The delta in rotation for the last frame (client side interpolation will use this)
float m_flRotationDeltaLastFrame;
// The current thrust for the ship
float m_flXAcceleration;
float m_flYAcceleration;
// The current velocity for the ship
float m_flXVelocity;
float m_flYVelocity;
// The current position for the ship
float m_flXPosition;
float m_flYPosition;
// Is the ship exploding?
bool m_bExploding;
// Is the ship disabled?
bool m_bDisabled;
// Are the thrusters to be drawn?
bool m_bForwardThrustersActive;
bool m_bReverseThrustersActive;
// Decoration for this ship
int m_nShipDecoration;
// Weapon for this ship
int m_nShipWeapon;
// Power for this ship
int m_nShipPower;
int m_nShieldStrength;
// Photon beam positions and data
ServerPhotonBeamUpdateData_t m_PhotonBeamData[MAX_PHOTON_BEAMS_PER_SHIP];
// Thrust and rotation speed can be anlog when using a Steam Controller
float m_fThrusterLevel;
float m_fTurnSpeed;
};
// This is the data that gets sent from the server to each client for each update
struct ServerSpaceWarUpdateData_t
{
void SetServerGameState( EServerGameState eState ) { m_eCurrentGameState = LittleDWord( (uint32)eState ); }
EServerGameState GetServerGameState() { return (EServerGameState)LittleDWord( m_eCurrentGameState ); }
void SetPlayerWhoWon( uint32 iIndex ) { m_uPlayerWhoWonGame = LittleDWord( iIndex ); }
uint32 GetPlayerWhoWon() { return LittleDWord( m_uPlayerWhoWonGame ); }
void SetPlayerActive( uint32 iIndex, bool bIsActive ) { m_rgPlayersActive[iIndex] = bIsActive; }
bool GetPlayerActive( uint32 iIndex ) { return m_rgPlayersActive[iIndex]; }
void SetPlayerScore( uint32 iIndex, uint32 unScore ) { m_rgPlayerScores[iIndex] = LittleDWord(unScore); }
uint32 GetPlayerScore( uint32 iIndex ) { return LittleDWord(m_rgPlayerScores[iIndex]); }
void SetPlayerSteamID( uint32 iIndex, uint64 ulSteamID ) { m_rgPlayerSteamIDs[iIndex] = LittleQWord(ulSteamID); }
uint64 GetPlayerSteamID( uint32 iIndex ) { return LittleQWord(m_rgPlayerSteamIDs[iIndex]); }
ServerShipUpdateData_t *AccessShipUpdateData( uint32 iIndex ) { return &m_rgShipData[iIndex];}
private:
// What state the game is in
uint32 m_eCurrentGameState;
// Who just won the game? -- only valid when m_eCurrentGameState == k_EGameWinner
uint32 m_uPlayerWhoWonGame;
// which player slots are in use
bool m_rgPlayersActive[MAX_PLAYERS_PER_SERVER];
// what are the scores for each player?
uint32 m_rgPlayerScores[MAX_PLAYERS_PER_SERVER];
// array of ship data
ServerShipUpdateData_t m_rgShipData[MAX_PLAYERS_PER_SERVER];
// array of players steamids for each slot, serialized to uint64
uint64 m_rgPlayerSteamIDs[MAX_PLAYERS_PER_SERVER];
};
// This is the data that gets sent from each client to the server for each update
struct ClientSpaceWarUpdateData_t
{
void SetPlayerName( const char *pchName ) { strncpy_safe( m_rgchPlayerName, pchName, sizeof( m_rgchPlayerName ) ); }
const char *GetPlayerName() { return m_rgchPlayerName; }
void SetFirePressed( bool bIsPressed ) { m_bFirePressed = bIsPressed; }
bool GetFirePressed() { return m_bFirePressed; }
void SetTurnLeftPressed( bool bIsPressed ) { m_bTurnLeftPressed = bIsPressed; }
bool GetTurnLeftPressed() { return m_bTurnLeftPressed; }
void SetTurnRightPressed( bool bIsPressed ) { m_bTurnRightPressed = bIsPressed; }
bool GetTurnRightPressed() { return m_bTurnRightPressed; }
void SetForwardThrustersPressed( bool bIsPressed ) { m_bForwardThrustersPressed = bIsPressed; }
bool GetForwardThrustersPressed() { return m_bForwardThrustersPressed; }
void SetReverseThrustersPressed( bool bIsPressed ) { m_bReverseThrustersPressed = bIsPressed; }
bool GetReverseThrustersPressed() { return m_bReverseThrustersPressed; }
void SetDecoration( int nDecoration ) { m_nShipDecoration = nDecoration; }
int GetDecoration() { return m_nShipDecoration; }
void SetWeapon( int nWeapon ) { m_nShipWeapon = nWeapon; }
int GetWeapon() { return m_nShipWeapon; }
void SetPower( int nPower ) { m_nShipPower = nPower; }
int GetPower() { return m_nShipPower; }
void SetShieldStrength( int nShieldPower ) { m_nShieldStrength = nShieldPower; }
int GetShieldStrength() { return m_nShieldStrength; }
void SetThrustersLevel( float fLevel ) { m_fThrusterLevel = fLevel; }
float GetThrustersLevel( ) { return m_fThrusterLevel; }
void SetTurnSpeed( float fSpeed ) { m_fTurnSpeed = fSpeed; }
float GetTurnSpeed( ) { return m_fTurnSpeed; }
private:
// Key's which are done
bool m_bFirePressed;
bool m_bTurnLeftPressed;
bool m_bTurnRightPressed;
bool m_bForwardThrustersPressed;
bool m_bReverseThrustersPressed;
// Decoration for this ship
int m_nShipDecoration;
// Weapon for this ship
int m_nShipWeapon;
// Power for this ship
int m_nShipPower;
int m_nShieldStrength;
// Name of the player (needed server side to tell master server about)
// bugbug jmccaskey - Really lame to send this every update instead of event driven...
char m_rgchPlayerName[64];
// Thrust and rotation speed can be anlog when using a Steam Controller
float m_fThrusterLevel;
float m_fTurnSpeed;
};
#pragma pack( pop )
#endif // SPACEWAR_H
File diff suppressed because it is too large Load Diff
+560
View File
@@ -0,0 +1,560 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Main class for the space war game client
//
// $NoKeywords: $
//=============================================================================
#ifndef SPACEWARCLIENT_H
#define SPACEWARCLIENT_H
#include "GameEngine.h"
#include "SpaceWar.h"
#include "Messages.h"
#include "StarField.h"
#include "Sun.h"
#include "Ship.h"
#include "StatsAndAchievements.h"
#include "RemoteStorage.h"
#include "musicplayer.h"
#include "steam/isteamnetworkingsockets.h"
#include "steam/isteamnetworkingutils.h"
// Forward class declaration
class CConnectingMenu;
class CMainMenu;
class CQuitMenu;
class CSpaceWarServer;
class CServerBrowser;
class CLobbyBrowser;
class CLobby;
class CLeaderboards;
class CFriendsList;
class CClanChatRoom;
class CP2PAuthPlayer;
class CP2PAuthedGame;
class CVoiceChat;
class CHTMLSurface;
class CRemotePlayList;
class CItemStore;
class COverlayExamples;
class CTimeline;
// Height of the HUD font
#define HUD_FONT_HEIGHT 18
// Height for the instructions font
#define INSTRUCTIONS_FONT_HEIGHT 24
// Enum for various client connection states
enum EClientConnectionState
{
k_EClientNotConnected, // Initial state, not connected to a server
k_EClientConnectedPendingAuthentication, // We've established communication with the server, but it hasn't authed us yet
k_EClientConnectedAndAuthenticated, // Final phase, server has authed us, we are actually able to play on it
};
// a game server as shown in the find servers menu
struct ServerBrowserMenuData_t
{
EClientGameState m_eStateToTransitionTo;
CSteamID m_steamIDGameServer;
};
// a lobby as shown in the find lobbies menu
struct LobbyBrowserMenuItem_t
{
CSteamID m_steamIDLobby;
EClientGameState m_eStateToTransitionTo;
};
// a user as shown in the lobby screen
struct LobbyMenuItem_t
{
enum ELobbyMenuItemCommand
{
k_ELobbyMenuItemUser,
k_ELobbyMenuItemStartGame,
k_ELobbyMenuItemToggleReadState,
k_ELobbyMenuItemLeaveLobby,
k_ELobbyMenuItemInviteToLobby
};
CSteamID m_steamIDUser; // the user who this is in the lobby
ELobbyMenuItemCommand m_eCommand;
CSteamID m_steamIDLobby; // set if k_ELobbyMenuItemInviteToLobby
};
// a leaderboard item
struct LeaderboardMenuItem_t
{
bool m_bBack;
bool m_bNextLeaderboard;
};
// a friends list item
struct FriendsListMenuItem_t
{
CSteamID m_steamIDFriend;
};
// a Remote Play session list item
struct RemotePlayListMenuItem_t
{
uint32 m_unSessionID;
};
#define MAX_WORKSHOP_ITEMS 16
// a Steam Workshop item
class CWorkshopItem : public CVectorEntity
{
public:
CWorkshopItem( IGameEngine *pGameEngine, uint32 uCollisionRadius ) : CVectorEntity( pGameEngine, uCollisionRadius )
{
memset( &m_ItemDetails, 0, sizeof(m_ItemDetails) );
}
void OnUGCDetailsResult(SteamUGCRequestUGCDetailsResult_t *pCallback, bool bIOFailure)
{
m_ItemDetails = pCallback->m_details;
}
SteamUGCDetails_t m_ItemDetails; // meta data
CCallResult<CWorkshopItem, SteamUGCRequestUGCDetailsResult_t> m_SteamCallResultUGCDetails;
};
struct PurchaseableItem_t
{
SteamItemDef_t m_nItemDefID;
uint64 m_ulPrice;
};
struct OverlayExample_t
{
enum EOverlayExampleItem
{
k_EOverlayExampleItem_BackToMenu,
k_EOverlayExampleItem_Invalid,
k_EOverlayExampleItem_ActivateGameOverlay,
k_EOverlayExampleItem_ActivateGameOverlayToUser,
k_EOverlayExampleItem_ActivateGameOverlayToWebPage,
k_EOverlayExampleItem_ActivateGameOverlayToWebPageModal,
k_EOverlayExampleItem_ActivateGameOverlayToStore,
// k_EOverlayExampleItem_ActivateGameOverlayRemotePlayTogetherInviteDialog,
k_EOverlayExampleItem_ActivateGameOverlayInviteDialogConnectString,
k_EOverlayExampleItem_HookScreenshots,
k_EOverlayExampleItem_RequestKeyboard,
k_EOverlayExampleItem_Notification_SetInset,
k_EOverlayExampleItem_Notification_SetPosition,
k_EOverlayExampleItem_Timeline_OpenOverlayToTimelineEvent,
k_EOverlayExampleItem_Timeline_OpenOverlayToGamePhase,
};
EOverlayExampleItem m_eItem;
const char *m_pchExtraCommandData;
};
class CSpaceWarClient
{
public:
//Constructor
CSpaceWarClient( IGameEngine *pEngine );
// Shared init for all constructors
void Init( IGameEngine *pGameEngine );
// Destructor
~CSpaceWarClient();
// Run a game frame
void RunFrame();
void RenderTimer();
// Service calls that need to happen less frequently than every frame (e.g. every second)
void RunOccasionally();
// Checks for any incoming network data, then dispatches it
void ReceiveNetworkData();
// Connect to a server at a given IP address or game server steamID
void InitiateServerConnection( CSteamID steamIDGameServer );
void InitiateServerConnection( uint32 unServerAddress, const int32 nPort );
// Send data to a client at the given ship index
bool BSendServerData( const void *pData, uint32 nSizeOfData, int nSendFlags );
// Menu callback handler (handles a bunch of menus that just change state with no extra data)
void OnMenuSelection( EClientGameState eState ) { SetGameState( eState ); }
// Menu callback handler (handles server browser selections with extra data)
void OnMenuSelection( ServerBrowserMenuData_t selection )
{
if ( selection.m_eStateToTransitionTo == k_EClientGameConnecting )
{
InitiateServerConnection( selection.m_steamIDGameServer );
}
else
{
SetGameState( selection.m_eStateToTransitionTo );
}
}
void OnMenuSelection( LobbyBrowserMenuItem_t selection )
{
// start joining the lobby
if ( selection.m_eStateToTransitionTo == k_EClientJoiningLobby )
{
SteamAPICall_t hSteamAPICall = SteamMatchmaking()->JoinLobby( selection.m_steamIDLobby );
// set the function to call when this API completes
m_SteamCallResultLobbyEntered.Set( hSteamAPICall, this, &CSpaceWarClient::OnLobbyEntered );
}
SetGameState( selection.m_eStateToTransitionTo );
}
void OnMenuSelection( LobbyMenuItem_t selection );
void OnMenuSelection( LeaderboardMenuItem_t selection );
void OnMenuSelection( FriendsListMenuItem_t selection );
void OnMenuSelection( RemotePlayListMenuItem_t selection );
void OnMenuSelection( ERemoteStorageSyncMenuCommand selection );
void OnMenuSelection( PurchaseableItem_t selection );
void OnMenuSelection( OverlayExample_t selection );
void OnMenuSelection( MusicPlayerMenuItem_t selection ) { m_pMusicPlayer->OnMenuSelection( selection ); }
// Set game state
void SetGameState( EClientGameState eState );
EClientGameState GetGameState() { return m_eGameState; }
// set failure text
void SetConnectionFailureText( const char *pchErrorText );
// Were we the winner?
bool BLocalPlayerWonLastGame();
// Get the steam id for the local user at this client
CSteamID GetLocalSteamID() { return m_SteamIDLocalUser; }
// Get the local players name
const char* GetLocalPlayerName()
{
return SteamFriends()->GetFriendPersonaName( m_SteamIDLocalUser );
}
// Scale screen size to "real" size
float PixelsToFeet( float flPixels );
// Get a Steam-supplied image
HGAMETEXTURE GetSteamImageAsTexture( int iImage );
void RetrieveEncryptedAppTicket();
void ExecCommandLineConnect( const char *pchServerAddress, const char *pchLobbyID );
void SetShowTimer( bool bShowTimer ) { m_bShowTimer = bShowTimer; }
uint32 GetLastGamePhaseID() const { return m_unLastGamePhaseID; }
uint64 GetLastCrashIntoSunEvent() const { return m_ulLastCrashIntoSunEvent; }
private:
// Receive a response from the server for a connection attempt
void OnReceiveServerInfo( CSteamID steamIDGameServer, bool bVACSecure, const char *pchServerName );
// Receive a response from the server for a connection attempt
void OnReceiveServerAuthenticationResponse( bool bSuccess, uint32 uPlayerPosition );
// Recieved a response that the server is full
void OnReceiveServerFullResponse();
// Receive a state update from the server
void OnReceiveServerUpdate( ServerSpaceWarUpdateData_t *pUpdateData );
// Handle the server exiting
void OnReceiveServerExiting();
// Disconnects from a server (telling it so) if we are connected
void DisconnectFromServer();
// game state changes
void OnGameStateChanged( EClientGameState eGameStateNew );
// Draw the HUD text (should do this after drawing all the objects)
void DrawHUDText();
// Draw instructions for how to play the game
void DrawInstructions();
// Draw text telling the players who won (or that their was a draw)
void DrawWinnerDrawOrWaitingText();
// Draw text telling the user that the connection attempt has failed
void DrawConnectionFailureText();
// Draw connect to server text
void DrawConnectToServerText();
// Draw text telling the user a connection attempt is in progress
void DrawConnectionAttemptText();
// Updates what we show to friends about what we're doing and how to connect
void UpdateRichPresenceConnectionInfo();
// Draw description for all subscribed workshop items
void DrawWorkshopItems();
// load subscribed workshop items
void LoadWorkshopItems();
void QueryWorkshopItems();
// Set appropriate rich presence keys for a player who is currently in-game and
// return the value that should go in steam_display
const char *SetInGameRichPresence() const;
// Sets the player scores in the game phase
void UpdateScoreInGamePhase( bool bFinal );
// load a workshop item from file
bool LoadWorkshopItem( PublishedFileId_t workshopItemID );
CWorkshopItem *LoadWorkshopItemFromFile( const char *pszFileName );
// draw the in-game store
void DrawInGameStore();
// Server we are connected to
CSpaceWarServer *m_pServer;
// SteamID for the local user on this client
CSteamID m_SteamIDLocalUser;
// Our ship position in the array below
uint32 m_uPlayerShipIndex;
// List of steamIDs for each player
CSteamID m_rgSteamIDPlayers[MAX_PLAYERS_PER_SERVER];
// Ships for players, doubles as a way to check for open slots (pointer is NULL meaning open)
CShip *m_rgpShips[MAX_PLAYERS_PER_SERVER];
// Player scores
uint32 m_rguPlayerScores[MAX_PLAYERS_PER_SERVER];
// Who just won the game? Should be set if we go into the k_EGameWinner state
uint32 m_uPlayerWhoWonGame;
// Current game state
EClientGameState m_eGameState;
// true if we only just transitioned state
bool m_bTransitionedGameState;
// Font handle for drawing the HUD text
HGAMEFONT m_hHUDFont;
// Font handle for drawing the instructions text
HGAMEFONT m_hInstructionsFont;
// Font handle for drawing the in-game store
HGAMEFONT m_hInGameStoreFont;
// Time the last state transition occurred (so we can count-down round restarts)
uint64 m_ulStateTransitionTime;
// Time we started our last connection attempt
uint64 m_ulLastConnectionAttemptRetryTime;
// Time we last got data from the server
uint64 m_ulLastNetworkDataReceivedTime;
// Time when we sent our ping
uint64 m_ulPingSentTime;
// Text to display if we are in an error state
char m_rgchErrorText[256];
// Server address data
CSteamID m_steamIDGameServer;
CSteamID m_steamIDGameServerFromBrowser;
uint32 m_unServerIP;
uint16 m_usServerPort;
HAuthTicket m_hAuthTicket;
HSteamNetConnection m_hConnServer;
// keep track of if we opened the overlay for a gamewebcallback
bool m_bSentWebOpen;
// true if we want to show an on-screen timer in our main menu
bool m_bShowTimer;
uint32 m_unTicksAtLaunch;
HGAMEFONT m_hTimerFont;
// simple class to marshal callbacks from pinging a game server
class CGameServerPing : public ISteamMatchmakingPingResponse
{
public:
CGameServerPing()
{
m_hGameServerQuery = HSERVERQUERY_INVALID;
m_pSpaceWarsClient = NULL;
}
void RetrieveSteamIDFromGameServer( CSpaceWarClient *pSpaceWarClient, uint32 unIP, uint16 unPort )
{
m_pSpaceWarsClient = pSpaceWarClient;
m_hGameServerQuery = SteamMatchmakingServers()->PingServer( unIP, unPort, this );
}
void CancelPing()
{
m_hGameServerQuery = HSERVERQUERY_INVALID;
}
// Server has responded successfully and has updated data
virtual void ServerResponded( gameserveritem_t &server )
{
if ( m_hGameServerQuery != HSERVERQUERY_INVALID && server.m_steamID.IsValid() )
{
m_pSpaceWarsClient->InitiateServerConnection( server.m_steamID );
}
m_hGameServerQuery = HSERVERQUERY_INVALID;
}
// Server failed to respond to the ping request
virtual void ServerFailedToRespond()
{
m_hGameServerQuery = HSERVERQUERY_INVALID;
}
private:
HServerQuery m_hGameServerQuery; // we're ping a game server, so we can convert IP:Port to a steamID
CSpaceWarClient *m_pSpaceWarsClient;
};
CGameServerPing m_GameServerPing;
// Track whether we are connected to a server (and what specific state that connection is in)
EClientConnectionState m_eConnectedStatus;
// Star field instance
CStarField *m_pStarField;
// Sun instance
CSun *m_pSun;
// Steam Workshop items
CWorkshopItem *m_rgpWorkshopItems[ MAX_WORKSHOP_ITEMS ];
int m_nNumWorkshopItems; // items in m_rgpWorkshopItem
// Main menu instance
CMainMenu *m_pMainMenu;
// Connecting menu instance
CConnectingMenu *m_pConnectingMenu;
// Pause menu instance
CQuitMenu *m_pQuitMenu;
// pointer to game engine instance we are running under
IGameEngine *m_pGameEngine;
// track which steam image indexes we have textures for, and what handle that texture has
std::map<int, HGAMETEXTURE> m_MapSteamImagesToTextures;
CStatsAndAchievements *m_pStatsAndAchievements;
CTimeline *m_pTimeline;
uint32 m_unGamePhaseID = 0;
uint32 m_unLastGamePhaseID = 0;
uint64 m_ulLastCrashIntoSunEvent = 0;
CLeaderboards *m_pLeaderboards;
CFriendsList *m_pFriendsList;
CMusicPlayer *m_pMusicPlayer;
CClanChatRoom *m_pClanChatRoom;
CServerBrowser *m_pServerBrowser;
CRemotePlayList *m_pRemotePlayList;
CRemoteStorage *m_pRemoteStorage;
CItemStore *m_pItemStore;
COverlayExamples *m_pOverlayExamples;
// lobby handling
// the name of the lobby we're connected to
CSteamID m_steamIDLobby;
// callback for when we're creating a new lobby
void OnLobbyCreated( LobbyCreated_t *pCallback, bool bIOFailure );
CCallResult<CSpaceWarClient, LobbyCreated_t> m_SteamCallResultLobbyCreated;
// callback for when we've joined a lobby
void OnLobbyEntered( LobbyEnter_t *pCallback, bool bIOFailure );
CCallResult<CSpaceWarClient, LobbyEnter_t> m_SteamCallResultLobbyEntered;
// callback for when the lobby game server has started
STEAM_CALLBACK( CSpaceWarClient, OnLobbyGameCreated, LobbyGameCreated_t );
STEAM_CALLBACK( CSpaceWarClient, OnGameJoinRequested, GameRichPresenceJoinRequested_t );
STEAM_CALLBACK( CSpaceWarClient, OnAvatarImageLoaded, AvatarImageLoaded_t );
STEAM_CALLBACK( CSpaceWarClient, OnNewUrlLaunchParameters, NewUrlLaunchParameters_t );
STEAM_CALLBACK( CSpaceWarClient, OnGameOverlayActivated, GameOverlayActivated_t );
// callback when getting the results of a web call
STEAM_CALLBACK( CSpaceWarClient, OnGameWebCallback, GameWebCallback_t );
// callback when new Workshop item was installed
STEAM_CALLBACK(CSpaceWarClient, OnWorkshopItemInstalled, ItemInstalled_t);
void OnUGCQueryCompleted( SteamUGCQueryCompleted_t *pParam, bool bIOFailure );
CCallResult<CSpaceWarClient, SteamUGCQueryCompleted_t> m_SteamCallResultUGCQueryCompleted;
// callback when a Remote Play Together guest invite has been created
STEAM_CALLBACK( CSpaceWarClient, OnSteamRemotePlayTogetherGuestInvite, SteamRemotePlayTogetherGuestInvite_t );
// Steam China support. duration control callback can be posted asynchronously, but we also
// call it directly.
STEAM_CALLBACK( CSpaceWarClient, OnDurationControl, DurationControl_t );
// callresult callback, handles io failure
void OnDurationControlCallResult( DurationControl_t *pParam, bool bIOFailure )
{
if ( !bIOFailure )
{
OnDurationControl( pParam );
}
}
CCallResult< CSpaceWarClient, DurationControl_t > m_SteamCallResultDurationControl;
// lobby browser menu
CLobbyBrowser *m_pLobbyBrowser;
// local lobby display
CLobby *m_pLobby;
// p2p game auth manager
CP2PAuthedGame *m_pP2PAuthedGame;
// p2p voice chat
CVoiceChat *m_pVoiceChat;
// html page viewer
CHTMLSurface *m_pHTMLSurface;
// Called when we get new connections, or the state of a connection changes
STEAM_CALLBACK(CSpaceWarClient, OnNetConnectionStatusChanged, SteamNetConnectionStatusChangedCallback_t);
// ipc failure handler
STEAM_CALLBACK( CSpaceWarClient, OnIPCFailure, IPCFailure_t );
// Steam wants to shut down, Game for Windows applications should shutdown too
STEAM_CALLBACK( CSpaceWarClient, OnSteamShutdown, SteamShutdown_t );
// Called when SteamUser()->RequestEncryptedAppTicket() returns asynchronously
void OnRequestEncryptedAppTicket( EncryptedAppTicketResponse_t *pEncryptedAppTicketResponse, bool bIOFailure );
CCallResult< CSpaceWarClient, EncryptedAppTicketResponse_t > m_SteamCallResultEncryptedAppTicket;
};
// Must define this stuff before BaseMenu.h as it depends on calling back into us through these accessors
extern CSpaceWarClient *g_pSpaceWarClient;
CSpaceWarClient *SpaceWarClient();
#endif // SPACEWARCLIENT_H
@@ -0,0 +1,53 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: A SpaceWarEntity is just like a VectorEntity, except it knows how
// to apply gravity from the SpaceWar Sun
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "SpaceWarEntity.h"
#include "stdlib.h"
#include <math.h>
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CSpaceWarEntity::CSpaceWarEntity( IGameEngine *pGameEngine, uint32 uCollisionRadius, bool bAffectedByGravity )
: CVectorEntity( pGameEngine, uCollisionRadius )
{
m_bAffectedByGravity = bAffectedByGravity;
}
//-----------------------------------------------------------------------------
// Purpose: RunFrame
//-----------------------------------------------------------------------------
void CSpaceWarEntity::RunFrame()
{
if ( m_bAffectedByGravity )
{
float xAccel = GetXAcceleration();
float yAccel = GetYAcceleration();
// Ships are also affected by the suns gravity, compute that here, sun is always at the center of the screen
float xPosSun = (float)m_pGameEngine->GetViewportWidth()/2;
float yPosSun = (float)m_pGameEngine->GetViewportHeight()/2;
float distanceToSun = (float)sqrt( pow( xPosSun - GetXPos(), 2 ) + pow( yPosSun - GetYPos(), 2 ) );
float distancePower = (float)pow( distanceToSun, 2.0f ); // gravity power falls off exponentially
float factor = MIN( 5200000.0f / distancePower, 150.0f ); // arbitrary value for power of gravity
float xDirection = (GetXPos() - xPosSun)/distanceToSun;
float yDirection = (GetYPos() - yPosSun)/distanceToSun;
xAccel -= factor * xDirection;
yAccel -= factor * yDirection;
// Set updated acceleration
SetAcceleration( xAccel, yAccel );
}
CVectorEntity::RunFrame();
}
+31
View File
@@ -0,0 +1,31 @@
//========= Copyright Š 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: A SpaceWarEntity is just like a VectorEntity, except it knows how
// to apply gravity from the SpaceWar Sun
//
// $NoKeywords: $
//=============================================================================
#ifndef SPACEWARENTITY_H
#define SPACEWARENTITY_H
#include "GameEngine.h"
#include "VectorEntity.h"
class CSpaceWarEntity : public CVectorEntity
{
public:
// Constructor
CSpaceWarEntity( IGameEngine *pGameEngine, uint32 uCollisionRadius, bool bAffectedByGravity );
// Destructor
virtual ~CSpaceWarEntity() { return; }
// Run Frame
void RunFrame();
private:
bool m_bAffectedByGravity;
};
#endif // SPACEWARENTITY_H
+5
View File
@@ -0,0 +1,5 @@
/////////////////////////////////////////////////////////////////////////////
// Header File for : SpaceWar
#define ID_ICON 101
/////////////////////////////////////////////////////////////////////////////
+39
View File
@@ -0,0 +1,39 @@
/////////////////////////////////////////////////////////////////////////////
// Resource File for : SpaceWar
#include "SpaceWarRes.h"
// The following line is a workaround for a redefinition warning in sal.h
// when using Visual Studio 2005 compilers and includes. Comment out the
// line if you would like to see the warning.
#define _INC_CRTDEFS
/////////////////////////////////////////////////////////////////////////////
// This resource files requires the Platform SDK to be compiled.
// #include <gameux.h>
// These are the only two definitions needed from gameux.h
#define ID_GDF_XML __GDF_XML
#define ID_GDF_THUMBNAIL __GDF_THUMBNAIL
#define APSTUDIO_READONLY_SYMBOLS
#include <windows.h>
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// Neutral Resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU)
#ifdef _WIN32
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
#pragma code_page(DEFAULT)
#endif //_WIN32
ID_GDF_XML DATA "NEU\\SpaceWar.gdf.xml"
ID_GDF_THUMBNAIL DATA "NEU\\boxart_NEU.png"
ID_ICON ICON "NEU\\gameicon_NEU.ico"
#endif // Neutral resources
/////////////////////////////////////////////////////////////////////////////
File diff suppressed because it is too large Load Diff
+179
View File
@@ -0,0 +1,179 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Main class for the space war game server
//
// $NoKeywords: $
//=============================================================================
#ifndef SPACEWARSERVER_H
#define SPACEWARSERVER_H
#include <string>
#include "GameEngine.h"
#include "SpaceWar.h"
#include "Ship.h"
#include "Sun.h"
#include "steam/isteamnetworkingsockets.h"
#include "steam/steamclientpublic.h"
#include "Messages.h"
// Forward declaration
class CSpaceWarClient;
struct ClientConnectionData_t
{
bool m_bActive; // Is this slot in use? Or is it available for new connections?
CSteamID m_SteamIDUser; // What is the steamid of the player?
uint64 m_ulTickCountLastData; // What was the last time we got data from the player?
HSteamNetConnection m_hConn; // The handle for the connection to the player
ClientConnectionData_t() {
m_bActive = false;
m_ulTickCountLastData = 0;
m_hConn = 0;
}
};
class CSpaceWarServer
{
public:
//Constructor
CSpaceWarServer( IGameEngine *pEngine );
// Destructor
~CSpaceWarServer();
// Run a game frame
void RunFrame();
// Set game state
void SetGameState( EServerGameState eState );
// Checks for any incoming network data, then dispatches it
void ReceiveNetworkData();
// Reset player scores (occurs when starting a new game)
void ResetScores();
// Reset player positions (occurs in between rounds as well as at the start of a new game)
void ResetPlayerShips();
// Checks various game objects for collisions and updates state appropriately if they have occurred
void CheckForCollisions();
// Kicks a given player off the server
void KickPlayerOffServer( CSteamID steamID );
// data accessors
bool IsConnectedToSteam() { return m_bConnectedToSteam; }
CSteamID GetSteamID();
private:
//
// Various callback functions that Steam will call to let us know about events related to our
// connection to the Steam servers for authentication purposes.
//
// Tells us when we have successfully connected to Steam
STEAM_GAMESERVER_CALLBACK( CSpaceWarServer, OnSteamServersConnected, SteamServersConnected_t );
// Tells us when there was a failure to connect to Steam
STEAM_GAMESERVER_CALLBACK( CSpaceWarServer, OnSteamServersConnectFailure, SteamServerConnectFailure_t );
// Tells us when we have been logged out of Steam
STEAM_GAMESERVER_CALLBACK( CSpaceWarServer, OnSteamServersDisconnected, SteamServersDisconnected_t );
// Tells us that Steam has set our security policy (VAC on or off)
STEAM_GAMESERVER_CALLBACK( CSpaceWarServer, OnPolicyResponse, GSPolicyResponse_t );
//
// Various callback functions that Steam will call to let us know about whether we should
// allow clients to play or we should kick/deny them.
//
// Tells us a client has been authenticated and approved to play by Steam (passes auth, license check, VAC status, etc...)
STEAM_GAMESERVER_CALLBACK( CSpaceWarServer, OnValidateAuthTicketResponse, ValidateAuthTicketResponse_t );
// client connection state
// All connection changes are handled through this callback
STEAM_GAMESERVER_CALLBACK(CSpaceWarServer, OnNetConnectionStatusChanged, SteamNetConnectionStatusChangedCallback_t);
// Function to tell Steam about our servers details
void SendUpdatedServerDetailsToSteam();
// Receive updates from client
void OnReceiveClientUpdateData( uint32 uShipIndex, ClientSpaceWarUpdateData_t *pUpdateData );
// Send data to a client at the given ship index
bool BSendDataToClient( uint32 uShipIndex, char *pData, uint32 nSizeOfData );
// Send data to a client at the given pending index
bool BSendDataToPendingClient( uint32 uShipIndex, char *pData, uint32 nSizeOfData );
void OnClientBeginAuthentication(CSteamID steamIDClient, HSteamNetConnection connectionID, void* pToken, uint32 uTokenLen);
// Handles authentication completing for a client
void OnAuthCompleted( bool bAuthSuccess, uint32 iPendingAuthIndex );
// Adds/initializes a new player ship at the given position
void AddPlayerShip( uint32 uShipPosition );
// Removes a player from the server
void RemovePlayerFromServer( uint32 uShipPosition, EDisconnectReason reason);
// Send world update to all clients
void SendUpdateDataToAllClients();
// Send the same message to all clients, except the ignored connection if any
void SendMessageToAll( HSteamNetConnection hConnIgnore, const void* pubData, uint32 cubData );
// Track whether our server is connected to Steam ok (meaning we can restrict who plays based on
// ownership and VAC bans, etc...)
bool m_bConnectedToSteam;
// Ships for players, doubles as a way to check for open slots (pointer is NULL meaning open)
CShip *m_rgpShips[MAX_PLAYERS_PER_SERVER];
// Player scores
uint32 m_rguPlayerScores[MAX_PLAYERS_PER_SERVER];
// server name
std::string m_sServerName;
// Who just won the game? Should be set if we go into the k_EGameWinner state
uint32 m_uPlayerWhoWonGame;
// Last time state changed
uint64 m_ulStateTransitionTime;
// Last time we sent clients an update
uint64 m_ulLastServerUpdateTick;
// Number of players currently connected, updated each frame
uint32 m_uPlayerCount;
// Current game state
EServerGameState m_eGameState;
// Sun instance
CSun *m_pSun;
// pointer to game engine instance we are running under
IGameEngine *m_pGameEngine;
// Vector to keep track of client connections
ClientConnectionData_t m_rgClientData[MAX_PLAYERS_PER_SERVER];
// Vector to keep track of client connections which are pending auth
ClientConnectionData_t m_rgPendingClientData[MAX_PLAYERS_PER_SERVER];
// Socket to listen for new connections on
HSteamListenSocket m_hListenSocket;
// Poll group used to receive messages from all clients at once
HSteamNetPollGroup m_hNetPollGroup;
};
#endif // SPACEWARSERVER_H
+70
View File
@@ -0,0 +1,70 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for rendering the starfield
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "StarField.h"
#include "stdlib.h"
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CStarField::CStarField( IGameEngine *pGameEngine )
{
m_pGameEngine = pGameEngine;
Init();
}
void CStarField::Init()
{
StarVertex_t StarVertex;
m_nWidth = m_pGameEngine->GetViewportWidth();
m_nHeight = m_pGameEngine->GetViewportHeight();
m_VecStars.clear();
// Generate star field data
for( int i=0; i < STARFIELD_STAR_COUNT; ++i )
{
int32 nRand = (rand()%(255-50))+50; //value between 50 and 255 for shades of gray
StarVertex.color = D3DCOLOR_ARGB( 255, nRand, nRand, nRand );
StarVertex.x = (float)(rand()%m_nWidth);
StarVertex.y = (float)(rand()%m_nHeight);
m_VecStars.push_back( StarVertex );
// bugbug jmccaskey - sometimes make "big stars" which are 4 points right next to each other?
}
}
//-----------------------------------------------------------------------------
// Purpose: Render the star field
//-----------------------------------------------------------------------------
void CStarField::Render()
{
if ( ( m_pGameEngine->GetViewportWidth() != m_nWidth ) || ( m_pGameEngine->GetViewportHeight() != m_nHeight ) )
{
Init();
}
static int counter; // per starfield draw..
counter++;
for( size_t i = 0; i < m_VecStars.size(); ++i )
{
float x = m_VecStars[i].x;
float y = m_VecStars[i].y;
float scoot = (float)counter * (float)(m_VecStars[i].color & 0xFF) / (4.0f * 255.0f);
float newy = y - scoot; // make things float up
while( newy < 0.0f ) newy += m_nHeight; // keep it on screen
m_pGameEngine->BDrawPoint( x, newy, m_VecStars[i].color );
}
m_pGameEngine->BFlushPointBuffer();
}
+46
View File
@@ -0,0 +1,46 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for rendering the starfield
//
// $NoKeywords: $
//=============================================================================
#ifndef STARFIELD_H
#define STARFIELD_H
#include <vector>
#include "GameEngine.h"
#define STARFIELD_STAR_COUNT 600
struct StarVertex_t
{
float x, y;
DWORD color;
};
class CStarField
{
public:
// Constructor
CStarField( IGameEngine *pGameEngine );
// Render the star field
void Render();
private:
void Init();
private:
int m_nWidth;
int m_nHeight;
// Game engine instance we are running under
IGameEngine *m_pGameEngine;
// Vector for starfield data
std::vector<StarVertex_t> m_VecStars;
};
#endif // STARFIELD_H
@@ -0,0 +1,530 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking stats and achievements
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "StatsAndAchievements.h"
#include "Inventory.h"
#include <math.h>
#include "SpaceWarClient.h"
#define ACHDISP_FONT_HEIGHT 20
#define ACHDISP_COLUMN_WIDTH 340
#define ACHDISP_CENTER_SPACING 40
#define ACHDISP_VERT_SPACING 10
#define ACHDISP_IMG_SIZE 64
#define ACHDISP_IMG_PAD 10
#define _ACH_ID( id, name ) { id, #id, name, "", 0, 0 }
Achievement_t g_rgAchievements[] =
{
_ACH_ID( ACH_WIN_ONE_GAME, "Winner" ),
_ACH_ID( ACH_WIN_100_GAMES, "Champion" ),
_ACH_ID( ACH_TRAVEL_FAR_ACCUM, "Interstellar" ),
_ACH_ID( ACH_TRAVEL_FAR_SINGLE, "Orbiter" ),
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
#pragma warning( push )
// warning C4355: 'this' : used in base member initializer list
// This is OK because it's warning on setting up the Steam callbacks, they won't use this until after construction is done
#pragma warning( disable : 4355 )
CStatsAndAchievements::CStatsAndAchievements( IGameEngine *pGameEngine )
:
m_pGameEngine( pGameEngine ),
m_pSteamUser( NULL ),
m_pSteamUserStats( NULL ),
m_GameID( SteamUtils()->GetAppID() ),
m_CallbackUserStatsStored( this, &CStatsAndAchievements::OnUserStatsStored ),
m_CallbackAchievementStored( this, &CStatsAndAchievements::OnAchievementStored )
{
m_pSteamUser = SteamUser();
m_pSteamUserStats = SteamUserStats();
m_bStatsValid = false;
m_bStoreStats = false;
m_flGameFeetTraveled = 0;
m_nTotalGamesPlayed = 0;
m_nTotalNumWins = 0;
m_nTotalNumLosses = 0;
m_flTotalFeetTraveled = 0;
m_flMaxFeetTraveled = 0;
m_flAverageSpeed = 0;
m_hDisplayFont = pGameEngine->HCreateFont( ACHDISP_FONT_HEIGHT, FW_MEDIUM, false, "Arial" );
if ( !m_hDisplayFont )
OutputDebugString( "Stats font was not created properly, text won't draw\n" );
}
#pragma warning( pop )
//-----------------------------------------------------------------------------
// Purpose: Run a frame for the CStatsAndAchievements. does not need to run at
// full frame rate.
//-----------------------------------------------------------------------------
void CStatsAndAchievements::RunFrame()
{
if ( !m_bStatsValid )
LoadUserStats();
// Evaluate achievements
for ( int iAch = 0; iAch < ARRAYSIZE( g_rgAchievements ); ++iAch )
{
EvaluateAchievement( g_rgAchievements[iAch] );
}
// Store stats
StoreStatsIfNecessary();
}
//-----------------------------------------------------------------------------
// Purpose: Accumulate distance traveled
//-----------------------------------------------------------------------------
void CStatsAndAchievements::AddDistanceTraveled( float flDistance )
{
m_flGameFeetTraveled += SpaceWarClient()->PixelsToFeet( flDistance );
}
//-----------------------------------------------------------------------------
// Purpose: Game state has changed
//-----------------------------------------------------------------------------
void CStatsAndAchievements::OnGameStateChange( EClientGameState eNewState )
{
if ( !m_bStatsValid )
return;
switch ( eNewState )
{
case k_EClientStatsAchievements:
case k_EClientGameStartServer:
case k_EClientGameMenu:
case k_EClientGameQuitMenu:
case k_EClientGameExiting:
case k_EClientGameInstructions:
case k_EClientGameConnecting:
case k_EClientGameConnectionFailure:
default:
break;
case k_EClientGameActive:
// Reset per-game stats
m_flGameFeetTraveled = 0;
m_ulTickCountGameStart = m_pGameEngine->GetGameTickCount();
break;
case k_EClientFindInternetServers:
break;
case k_EClientGameWinner:
if ( SpaceWarClient()->BLocalPlayerWonLastGame() )
m_nTotalNumWins++;
else
m_nTotalNumLosses++;
// fall through
case k_EClientGameDraw:
// Tally games
m_nTotalGamesPlayed++;
// Accumulate distances
m_flTotalFeetTraveled += m_flGameFeetTraveled;
// New max?
if ( m_flGameFeetTraveled > m_flMaxFeetTraveled )
m_flMaxFeetTraveled = m_flGameFeetTraveled;
// Calc game duration
m_flGameDurationSeconds = ( m_pGameEngine->GetGameTickCount() - m_ulTickCountGameStart ) / 1000.0;
// We want to update stats the next frame.
m_bStoreStats = true;
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: see if we should unlock this achievement
//-----------------------------------------------------------------------------
void CStatsAndAchievements::EvaluateAchievement( Achievement_t &achievement )
{
// Already have it?
if ( achievement.m_bAchieved )
return;
switch ( achievement.m_eAchievementID )
{
case ACH_WIN_ONE_GAME:
if ( m_nTotalNumWins )
{
UnlockAchievement( achievement );
}
break;
case ACH_WIN_100_GAMES:
if ( m_nTotalNumWins >= 100 )
{
UnlockAchievement( achievement );
}
break;
case ACH_TRAVEL_FAR_ACCUM:
if ( m_flTotalFeetTraveled >= 5280 )
{
UnlockAchievement( achievement );
}
break;
case ACH_TRAVEL_FAR_SINGLE:
if ( m_flGameFeetTraveled > 500 )
{
UnlockAchievement( achievement );
}
break;
default:
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Unlock this achievement
//-----------------------------------------------------------------------------
void CStatsAndAchievements::UnlockAchievement( Achievement_t &achievement )
{
achievement.m_bAchieved = true;
// the icon may change once it's unlocked
achievement.m_iIconImage = 0;
// mark it down
m_pSteamUserStats->SetAchievement( achievement.m_pchAchievementID );
// Store stats end of frame
m_bStoreStats = true;
}
//-----------------------------------------------------------------------------
// Purpose: Store stats in the Steam database
//-----------------------------------------------------------------------------
void CStatsAndAchievements::StoreStatsIfNecessary()
{
if ( m_bStoreStats )
{
// already set any achievements in UnlockAchievement
// set stats
m_pSteamUserStats->SetStat( "NumGames", m_nTotalGamesPlayed );
m_pSteamUserStats->SetStat( "NumWins", m_nTotalNumWins );
m_pSteamUserStats->SetStat( "NumLosses", m_nTotalNumLosses );
m_pSteamUserStats->SetStat( "FeetTraveled", m_flTotalFeetTraveled );
m_pSteamUserStats->SetStat( "MaxFeetTraveled", m_flMaxFeetTraveled );
// Update average feet / second stat
m_pSteamUserStats->UpdateAvgRateStat( "AverageSpeed", m_flGameFeetTraveled, m_flGameDurationSeconds );
// The averaged result is calculated for us
m_pSteamUserStats->GetStat( "AverageSpeed", &m_flAverageSpeed );
bool bSuccess = m_pSteamUserStats->StoreStats();
// If this failed, we never sent anything to the server, try
// again later.
m_bStoreStats = !bSuccess;
}
}
//-----------------------------------------------------------------------------
// Purpose: We have stats data from Steam. It is authoritative, so update
// our data with those results now.
//-----------------------------------------------------------------------------
void CStatsAndAchievements::LoadUserStats()
{
if ( !m_pSteamUserStats )
return;
// load achievements
for ( int iAch = 0; iAch < ARRAYSIZE( g_rgAchievements ); ++iAch )
{
Achievement_t &ach = g_rgAchievements[iAch];
m_pSteamUserStats->GetAchievement( ach.m_pchAchievementID, &ach.m_bAchieved );
sprintf_safe( ach.m_rgchName, "%s", m_pSteamUserStats->GetAchievementDisplayAttribute( ach.m_pchAchievementID, "name" ) );
sprintf_safe( ach.m_rgchDescription, "%s", m_pSteamUserStats->GetAchievementDisplayAttribute( ach.m_pchAchievementID, "desc" ) );
}
// load stats
m_pSteamUserStats->GetStat( "NumGames", &m_nTotalGamesPlayed );
m_pSteamUserStats->GetStat( "NumWins", &m_nTotalNumWins );
m_pSteamUserStats->GetStat( "NumLosses", &m_nTotalNumLosses );
m_pSteamUserStats->GetStat( "FeetTraveled", &m_flTotalFeetTraveled );
m_pSteamUserStats->GetStat( "MaxFeetTraveled", &m_flMaxFeetTraveled );
m_pSteamUserStats->GetStat( "AverageSpeed", &m_flAverageSpeed );
m_bStatsValid = true;
}
//-----------------------------------------------------------------------------
// Purpose: Our stats data was stored!
//-----------------------------------------------------------------------------
void CStatsAndAchievements::OnUserStatsStored( UserStatsStored_t *pCallback )
{
// we may get callbacks for other games' stats arriving, ignore them
if ( m_GameID.ToUint64() == pCallback->m_nGameID )
{
if ( k_EResultOK == pCallback->m_eResult )
{
OutputDebugString( "StoreStats - success\n" );
}
else if ( k_EResultInvalidParam == pCallback->m_eResult )
{
// One or more stats we set broke a constraint. They've been reverted,
// and we should re-iterate the values now to keep in sync.
OutputDebugString( "StoreStats - some failed to validate\n" );
LoadUserStats();
}
else
{
char buffer[128];
sprintf_safe( buffer, "StoreStats - failed, %d\n", pCallback->m_eResult );
buffer[ sizeof(buffer) - 1 ] = 0;
OutputDebugString( buffer );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: An achievement was stored
//-----------------------------------------------------------------------------
void CStatsAndAchievements::OnAchievementStored( UserAchievementStored_t *pCallback )
{
// we may get callbacks for other games' stats arriving, ignore them
if ( m_GameID.ToUint64() == pCallback->m_nGameID )
{
if ( 0 == pCallback->m_nMaxProgress )
{
char buffer[128];
sprintf_safe( buffer, "Achievement '%s' unlocked!", pCallback->m_rgchAchievementName );
buffer[ sizeof(buffer) - 1 ] = 0;
OutputDebugString( buffer );
}
else
{
char buffer[128];
sprintf_safe( buffer, "Achievement '%s' progress callback, (%d,%d)\n",
pCallback->m_rgchAchievementName, pCallback->m_nCurProgress, pCallback->m_nMaxProgress );
buffer[ sizeof(buffer) - 1 ] = 0;
OutputDebugString( buffer );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Display the user's stats and achievements
//-----------------------------------------------------------------------------
void CStatsAndAchievements::Render()
{
const int32 width = m_pGameEngine->GetViewportWidth();
const int32 height = m_pGameEngine->GetViewportHeight();
const int32 pxColumn1Left = width / 2 - ACHDISP_COLUMN_WIDTH - ACHDISP_CENTER_SPACING / 2;
const int32 pxColumn2Left = width / 2 + ACHDISP_CENTER_SPACING / 2;
RECT rect;
char rgchBuffer[256];
if ( m_pGameEngine->BIsSteamInputDeviceActive() )
{
const char *rgchActionOrigin = m_pGameEngine->GetTextStringForControllerOriginDigital( eControllerActionSet_MenuControls, eControllerDigitalAction_MenuCancel );
if ( strcmp( rgchActionOrigin, "None" ) == 0 )
{
sprintf_safe( rgchBuffer, "Press ESC to return to the Main Menu. No controller button bound" );
}
else
{
sprintf_safe( rgchBuffer, "Press ESC or '%s' to return the Main Menu", rgchActionOrigin );
}
}
else
{
sprintf_safe( rgchBuffer, "Press ESC to return to the Main Menu" );
}
if ( !m_bStatsValid )
{
rect.top = 0;
rect.bottom = m_pGameEngine->GetViewportHeight();
rect.left = 0;
rect.right = width;
sprintf_safe( rgchBuffer, "Unable to retrieve data from Steam\n" );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_VCENTER, rgchBuffer );
rect.left = 0;
rect.right = width;
rect.top = LONG(m_pGameEngine->GetViewportHeight() * 0.7);
rect.bottom = m_pGameEngine->GetViewportHeight();
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_TOP, rgchBuffer );
}
else
{
// COLUMN 1
// Achievements above the midline
int32 pxVertOffset = height / 2 - 3 * ( ACHDISP_IMG_SIZE + ACHDISP_VERT_SPACING );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_IMG_SIZE;
rect.left = pxColumn1Left;
rect.right = rect.left + ACHDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawAchievementInfo( rect, g_rgAchievements[0] );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_IMG_SIZE;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawAchievementInfo( rect, g_rgAchievements[1] );
// Stats below the midline
pxVertOffset = height / 2 + ACHDISP_VERT_SPACING - 1 * ( ACHDISP_IMG_SIZE + ACHDISP_VERT_SPACING );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_FONT_HEIGHT;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawStatInfo( rect, "Games Played", static_cast<float>( m_nTotalGamesPlayed ) );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_FONT_HEIGHT;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawStatInfo( rect, "Games Won", static_cast<float>( m_nTotalNumWins ) );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_FONT_HEIGHT;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawStatInfo( rect, "Games Lost", static_cast<float>( m_nTotalNumLosses ) );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_FONT_HEIGHT;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_LEFT|TEXTPOS_VCENTER, "Inventory" );
std::list<CSpaceWarItem *>::const_iterator iter;
for ( iter = SpaceWarLocalInventory()->GetItemList().begin(); iter != SpaceWarLocalInventory()->GetItemList().end(); ++iter )
{
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_FONT_HEIGHT;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawInventory( rect, ( *iter )->GetItemId() );
}
// COLUMN 2
// Achievements above the midline
pxVertOffset = height / 2 - 3 * ( ACHDISP_IMG_SIZE + ACHDISP_VERT_SPACING );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_IMG_SIZE;
rect.left = pxColumn2Left;
rect.right = rect.left + ACHDISP_COLUMN_WIDTH;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawAchievementInfo( rect, g_rgAchievements[2] );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_IMG_SIZE;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawAchievementInfo( rect, g_rgAchievements[3] );
// Stats below the midline
pxVertOffset = height / 2 + ACHDISP_VERT_SPACING - 1 * ( ACHDISP_IMG_SIZE + ACHDISP_VERT_SPACING );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_FONT_HEIGHT;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawStatInfo( rect, "Feet Traveled", m_flTotalFeetTraveled );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_FONT_HEIGHT;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawStatInfo( rect, "Max Feet Traveled", m_flMaxFeetTraveled );
rect.top = pxVertOffset;
rect.bottom = rect.top + ACHDISP_FONT_HEIGHT;
pxVertOffset = rect.bottom + ACHDISP_VERT_SPACING;
DrawStatInfo( rect, "Average Inches / Second", m_flAverageSpeed * 12.0f );
// Footer
rect.left = 0;
rect.right = width;
rect.top = LONG(m_pGameEngine->GetViewportHeight() * 0.8);
rect.bottom = m_pGameEngine->GetViewportHeight();
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER|TEXTPOS_TOP, rgchBuffer );
}
}
void CStatsAndAchievements::DrawAchievementInfo( RECT &rect, Achievement_t &ach )
{
if ( ach.m_iIconImage == 0 )
{
ach.m_iIconImage = m_pSteamUserStats->GetAchievementIcon( ach.m_pchAchievementID );
}
HGAMETEXTURE hTexture = SpaceWarClient()->GetSteamImageAsTexture( ach.m_iIconImage );
// don't modify the caller's rect, they may use it later to locate something else
RECT rect2 = rect;
// could still be zero if the image isn't downloaded yet
if (hTexture )
{
m_pGameEngine->BDrawTexturedRect( (float)rect2.left, (float)rect2.top, (float)rect2.left+ACHDISP_IMG_SIZE, (float)rect2.bottom,
0.0f, 0.0f, 1.0, 1.0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), hTexture );
rect2.left += ACHDISP_IMG_SIZE + ACHDISP_IMG_PAD;
}
// todo: divide up so can draw image
char rgchBuffer[256];
sprintf_safe( rgchBuffer, "%s: %s\n%s",
ach.m_rgchName,
ach.m_bAchieved ? "Unlocked" : "Locked",
ach.m_rgchDescription );
m_pGameEngine->BDrawString( m_hDisplayFont, rect2, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_LEFT|TEXTPOS_VCENTER, rgchBuffer );
}
void CStatsAndAchievements::DrawStatInfo( RECT &rect, const char *pchName, float flValue )
{
// todo: divide up so can draw image
char rgchBuffer[256];
sprintf_safe( rgchBuffer, "%s: %.1f", pchName, flValue );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_LEFT|TEXTPOS_VCENTER, rgchBuffer );
}
void CStatsAndAchievements::DrawInventory( RECT &rect, SteamItemInstanceID_t itemid )
{
const CSpaceWarItem *pItem = SpaceWarLocalInventory()->GetItem( itemid );
if ( !pItem )
return;
// todo: divide up so can draw image
char rgchBuffer[256];
sprintf_safe( rgchBuffer, "%s", pItem->GetLocalizedName().c_str() );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_LEFT|TEXTPOS_VCENTER, rgchBuffer );
}
@@ -0,0 +1,113 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking stats and achievements
//
// $NoKeywords: $
//=============================================================================
#ifndef STATS_AND_ACHIEVEMENTS_H
#define STATS_AND_ACHIEVEMENTS_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "Inventory.h"
enum EAchievements
{
ACH_WIN_ONE_GAME = 0,
ACH_WIN_100_GAMES = 1,
ACH_HEAVY_FIRE = 2,
ACH_TRAVEL_FAR_ACCUM = 3,
ACH_TRAVEL_FAR_SINGLE = 4,
};
struct Achievement_t
{
EAchievements m_eAchievementID;
const char *m_pchAchievementID;
char m_rgchName[128];
char m_rgchDescription[256];
bool m_bAchieved;
int m_iIconImage;
};
class ISteamUser;
class CSpaceWarClient;
class CStatsAndAchievements
{
public:
// Constructor
CStatsAndAchievements( IGameEngine *pGameEngine );
// Run a frame. Does not need to run at full frame rate.
void RunFrame();
// Display the stats and achievements
void Render();
// Game state changed
void OnGameStateChange( EClientGameState eNewState );
// Accumulators
void AddDistanceTraveled( float flDistance );
// accessors
float GetGameFeetTraveled() { return m_flGameFeetTraveled; }
double GetGameDurationSeconds() { return m_flGameDurationSeconds; }
STEAM_CALLBACK( CStatsAndAchievements, OnUserStatsStored, UserStatsStored_t, m_CallbackUserStatsStored );
STEAM_CALLBACK( CStatsAndAchievements, OnAchievementStored, UserAchievementStored_t, m_CallbackAchievementStored );
private:
void LoadUserStats();
// Determine if we get this achievement now
void EvaluateAchievement( Achievement_t &achievement );
void UnlockAchievement( Achievement_t &achievement );
// Store stats
void StoreStatsIfNecessary();
// Render helpers
void DrawAchievementInfo( RECT &rect, Achievement_t &ach );
void DrawStatInfo( RECT &rect, const char *pchName, float flValue );
void DrawInventory( RECT &rect, SteamItemInstanceID_t itemid );
// our GameID
CGameID m_GameID;
// Engine
IGameEngine *m_pGameEngine;
// Steam User interface
ISteamUser *m_pSteamUser;
// Steam UserStats interface
ISteamUserStats *m_pSteamUserStats;
// Display font
HGAMEFONT m_hDisplayFont;
// Did we get the stats from Steam?
bool m_bStatsValid;
// Should we store stats this frame?
bool m_bStoreStats;
// Current Stat details
float m_flGameFeetTraveled;
uint64 m_ulTickCountGameStart;
double m_flGameDurationSeconds;
// Persisted Stat details
int m_nTotalGamesPlayed;
int m_nTotalNumWins;
int m_nTotalNumLosses;
float m_flTotalFeetTraveled;
float m_flMaxFeetTraveled;
float m_flAverageSpeed;
};
#endif // STATS_AND_ACHIEVEMENTS_H
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
@@ -0,0 +1,33 @@
#!/bin/bash
#
# This is a script which runs the SteamworksExample in the Steam runtime
# The program location
TOP=$(cd "${0%/*}" && echo ${PWD})
PROGRAM="${TOP}/SteamworksExampleLinux"
log () {
( echo "[$$]: $*" >&2 ) || :
}
# Require LDLP scout runtime environment
if [ -n "${STEAM_RUNTIME-}" ]; then
log "Detected scout LDLP runtime."
# continue
else
log "Relaunch under scout LDLP runtime."
log exec "$HOME/.steam/bin/steam-runtime/run.sh" "$0" "$@"
exec "$HOME/.steam/bin/steam-runtime/run.sh" "$0" "$@"
# unreachable
fi
# The public SDK binary links with -Wl,--rpath=$ORIGIN and doesn't need this,
# But the binary produced in-tree at Valve does
export LD_LIBRARY_PATH=${TOP}:${LD_LIBRARY_PATH-}
cd "${TOP}"
exec "${PROGRAM}" "$@"
# vi: ts=4 sw=4 expandtab
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.34931.43
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "steamworksexample", "SteamworksExample.vcxproj", "{FC177B29-2631-C58B-D723-530DA88155B4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FC177B29-2631-C58B-D723-530DA88155B4}.Debug|x64.ActiveCfg = Debug|x64
{FC177B29-2631-C58B-D723-530DA88155B4}.Debug|x64.Build.0 = Debug|x64
{FC177B29-2631-C58B-D723-530DA88155B4}.Debug|x86.ActiveCfg = Debug|Win32
{FC177B29-2631-C58B-D723-530DA88155B4}.Debug|x86.Build.0 = Debug|Win32
{FC177B29-2631-C58B-D723-530DA88155B4}.Release|x64.ActiveCfg = Release|x64
{FC177B29-2631-C58B-D723-530DA88155B4}.Release|x64.Build.0 = Release|x64
{FC177B29-2631-C58B-D723-530DA88155B4}.Release|x86.ActiveCfg = Release|Win32
{FC177B29-2631-C58B-D723-530DA88155B4}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D30502FB-58C1-4ADF-A153-A9F564A0910A}
EndGlobalSection
EndGlobal
@@ -0,0 +1,661 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectName>steamworksexample</ProjectName>
<ProjectGuid>{FC177B29-2631-C58B-D723-530DA88155B4}</ProjectGuid>
<DefaultLanguage>en-US</DefaultLanguage>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>steamworksexample</TargetName>
<PlatformToolset>v142</PlatformToolset>
<ProtobufVersion>3.15.3</ProtobufVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>steamworksexample</TargetName>
<PlatformToolset>v142</PlatformToolset>
<ProtobufVersion>3.15.3</ProtobufVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>steamworksexample</TargetName>
<PlatformToolset>v142</PlatformToolset>
<ProtobufVersion>3.15.3</ProtobufVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>steamworksexample</TargetName>
<PlatformToolset>v142</PlatformToolset>
<ProtobufVersion>3.15.3</ProtobufVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<SRCROOT>..</SRCROOT>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</PreLinkEventUseInBuild>
<IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</IgnoreImportLibrary>
<IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</IgnoreImportLibrary>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</PreLinkEventUseInBuild>
<IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</IgnoreImportLibrary>
<IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</IgnoreImportLibrary>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutDir>$(SolutionDir)win64\$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutDir>$(SolutionDir)win64\$(Configuration)\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
</PreBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
<ClCompile>
<AdditionalOptions> /std:c++17 /bigobj /Zc:__cplusplus</AdditionalOptions>
<Optimization>Disabled</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<AdditionalIncludeDirectories>$(DXSDK_DIR)Include;..\public;</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions);_DEBUG;_EXTERNAL_DLL_EXT=.dll;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\Steam\main\src\SteamWorksExample;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<MinimalRebuild>false</MinimalRebuild>
<ExceptionHandling>Async</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Precise</FloatingPointModel>
<TreatWChar_tAsBuiltInType>false</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<AssemblerListingLocation>$(IntDir)\</AssemblerListingLocation>
<ObjectFileName>$(IntDir)\</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)\</ProgramDataBaseFileName>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level3</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>OldStyle</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<DisableSpecificWarnings>;4577;4091</DisableSpecificWarnings>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<BrowseInformationFile>$(IntDir)\</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /ignore:4221</AdditionalOptions>
<AdditionalDependencies>;legacy_stdio_definitions.lib;%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\steamworksexample.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>;$(DXSDK_DIR)Lib\x86;</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>DebugFastLink</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)\$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(OutDir)\$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<BaseAddress>
</BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
<ImageHasSafeExceptionHandlers>true</ImageHasSafeExceptionHandlers>
</Link>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)\steamworksexample.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
</PostBuildEvent>
<Proto>
<ProtoBatch>Default</ProtoBatch>
<Service>.</Service>
</Proto>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions);_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalManifestFiles>SteamWorksExample.exe.manifest</AdditionalManifestFiles>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<PreBuildEvent />
<CustomBuildStep />
<ClCompile>
<AdditionalOptions> /std:c++17 /bigobj /Zc:__cplusplus</AdditionalOptions>
<Optimization>Disabled</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<AdditionalIncludeDirectories>$(DXSDK_DIR)Include;..\public;</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions);_DEBUG;_EXTERNAL_DLL_EXT=.dll;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\Steam\main\src\SteamWorksExample;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<MinimalRebuild>false</MinimalRebuild>
<ExceptionHandling>Async</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>
</EnableEnhancedInstructionSet>
<FloatingPointModel>Precise</FloatingPointModel>
<TreatWChar_tAsBuiltInType>false</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<AssemblerListingLocation>$(IntDir)\</AssemblerListingLocation>
<ObjectFileName>$(IntDir)\</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)\</ProgramDataBaseFileName>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level3</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>OldStyle</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<DisableSpecificWarnings>;4577;4091</DisableSpecificWarnings>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<BrowseInformationFile>$(IntDir)\</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<PreLinkEvent />
<Link>
<AdditionalOptions> /ignore:4221</AdditionalOptions>
<AdditionalDependencies>;legacy_stdio_definitions.lib;%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\steamworksexample.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>;$(DXSDK_DIR)Lib\x64;</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>DebugFastLink</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)\$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(OutDir)\$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<BaseAddress>
</BaseAddress>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
<ImageHasSafeExceptionHandlers>
</ImageHasSafeExceptionHandlers>
</Link>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)\steamworksexample.bsc</OutputFile>
</Bscmake>
<PostBuildEvent />
<Proto>
<ProtoBatch>Default</ProtoBatch>
<Service>.</Service>
</Proto>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions);_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalManifestFiles>SteamWorksExample.exe.manifest</AdditionalManifestFiles>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
</PreBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
<ClCompile>
<AdditionalOptions> /std:c++17 /bigobj /d2Zi+ /Zc:__cplusplus</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>$(DXSDK_DIR)Include;..\public;</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions);NDEBUG;_EXTERNAL_DLL_EXT=.dll;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\Steam\main\src\SteamWorksExample;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>Async</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Precise</FloatingPointModel>
<TreatWChar_tAsBuiltInType>false</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<AssemblerListingLocation>$(IntDir)\</AssemblerListingLocation>
<ObjectFileName>$(IntDir)\</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)\</ProgramDataBaseFileName>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level3</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>OldStyle</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<DisableSpecificWarnings>;4577;4091</DisableSpecificWarnings>
<OmitFramePointers>false</OmitFramePointers>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<BrowseInformationFile>$(IntDir)\</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /ignore:4221</AdditionalOptions>
<AdditionalDependencies>;legacy_stdio_definitions.lib;%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\steamworksexample.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>;$(DXSDK_DIR)Lib\x86;</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)\$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(OutDir)\$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress>
</BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
<ImageHasSafeExceptionHandlers>true</ImageHasSafeExceptionHandlers>
</Link>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)\steamworksexample.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
</PostBuildEvent>
<Proto>
<ProtoBatch>Default</ProtoBatch>
<Service>.</Service>
</Proto>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions);_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalManifestFiles>SteamWorksExample.exe.manifest</AdditionalManifestFiles>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<PreBuildEvent />
<CustomBuildStep />
<ClCompile>
<AdditionalOptions> /std:c++17 /bigobj /d2Zi+ /Zc:__cplusplus</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>$(DXSDK_DIR)Include;..\public;</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions);NDEBUG;_EXTERNAL_DLL_EXT=.dll;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\Steam\main\src\SteamWorksExample;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>Async</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>
</EnableEnhancedInstructionSet>
<FloatingPointModel>Precise</FloatingPointModel>
<TreatWChar_tAsBuiltInType>false</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<AssemblerListingLocation>$(IntDir)\</AssemblerListingLocation>
<ObjectFileName>$(IntDir)\</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)\</ProgramDataBaseFileName>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level3</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>OldStyle</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<DisableSpecificWarnings>;4577;4091</DisableSpecificWarnings>
<OmitFramePointers>false</OmitFramePointers>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<BrowseInformationFile>$(IntDir)\</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<PreLinkEvent />
<Link>
<AdditionalOptions> /ignore:4221</AdditionalOptions>
<AdditionalDependencies>;legacy_stdio_definitions.lib;%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\steamworksexample.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>;$(DXSDK_DIR)Lib\x64;</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)\$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(OutDir)\$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress>
</BaseAddress>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
<ImageHasSafeExceptionHandlers>
</ImageHasSafeExceptionHandlers>
</Link>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)\steamworksexample.bsc</OutputFile>
</Bscmake>
<PostBuildEvent />
<Proto>
<ProtoBatch>Default</ProtoBatch>
<Service>.</Service>
</Proto>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions);_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalManifestFiles>SteamWorksExample.exe.manifest</AdditionalManifestFiles>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="stdafx.h" />
<ClInclude Include="GameEngine.h" />
<ClInclude Include="gameengineosx.h">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClInclude>
<ClInclude Include="gameenginesdl.h">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClInclude>
<ClInclude Include="gameenginewin32.h" />
<ClInclude Include="glstringosx.h">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClInclude>
<ClInclude Include="VectorEntity.h" />
<ClInclude Include="BaseMenu.h" />
<ClInclude Include="clanchatroom.h" />
<ClInclude Include="connectingmenu.h" />
<ClInclude Include="Friends.h" />
<ClInclude Include="htmlsurface.h" />
<ClInclude Include="Inventory.h" />
<ClInclude Include="ItemStore.h" />
<ClInclude Include="Leaderboards.h" />
<ClInclude Include="Lobby.h" />
<ClInclude Include="MainMenu.h" />
<ClInclude Include="..\glmgr\mathlite.h">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClInclude>
<ClInclude Include="Messages.h" />
<ClInclude Include="musicplayer.h" />
<ClInclude Include="OverlayExamples.h" />
<ClInclude Include="p2pauth.h" />
<ClInclude Include="PhotonBeam.h" />
<ClInclude Include="QuitMenu.h" />
<ClInclude Include="RemotePlay.h" />
<ClInclude Include="RemoteStorage.h" />
<ClInclude Include="remotestoragesync.h" />
<ClInclude Include="ServerBrowser.h" />
<ClInclude Include="ServerBrowserMenu.h" />
<ClInclude Include="Ship.h" />
<ClInclude Include="SimpleProtobuf.h" />
<ClInclude Include="SpaceWar.h" />
<ClInclude Include="SpaceWarClient.h" />
<ClInclude Include="SpaceWarEntity.h" />
<ClInclude Include="SpaceWarServer.h" />
<ClInclude Include="StarField.h" />
<ClInclude Include="StatsAndAchievements.h" />
<ClInclude Include="Sun.h" />
<ClInclude Include="timeline.h" />
<ClInclude Include="voicechat.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Main.cpp" />
<ClCompile Include="stdafx.cpp" />
<ClCompile Include="gameenginesdl.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="gameenginewin32.cpp" />
<ClCompile Include="..\tier1\pathmatch.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="VectorEntity.cpp" />
<ClCompile Include="BaseMenu.cpp" />
<ClCompile Include="..\glmgr\cglmbuffer.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="..\glmgr\cglmfbo.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="..\glmgr\cglmprogram.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="..\glmgr\cglmquery.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="..\glmgr\cglmtex.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="clanchatroom.cpp" />
<ClCompile Include="..\glmgr\dx9asmtogl2.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="..\glmgr\dxabstract.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="Friends.cpp" />
<ClCompile Include="..\glmgr\glmgr.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="..\glmgr\glmgrbasics.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="..\glmgr\glmgrext.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="htmlsurface.cpp" />
<ClCompile Include="Inventory.cpp" />
<ClCompile Include="ItemStore.cpp" />
<ClCompile Include="Leaderboards.cpp" />
<ClCompile Include="Lobby.cpp" />
<ClCompile Include="MainMenu.cpp" />
<ClCompile Include="..\glmgr\mathlite.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="musicplayer.cpp" />
<ClCompile Include="OverlayExamples.cpp" />
<ClCompile Include="p2pauth.cpp" />
<ClCompile Include="PhotonBeam.cpp" />
<ClCompile Include="QuitMenu.cpp" />
<ClCompile Include="RemotePlay.cpp" />
<ClCompile Include="RemoteStorage.cpp" />
<ClCompile Include="ServerBrowser.cpp" />
<ClCompile Include="Ship.cpp" />
<ClCompile Include="SimpleProtobuf.cpp" />
<ClCompile Include="SpaceWarClient.cpp" />
<ClCompile Include="SpaceWarEntity.cpp" />
<ClCompile Include="SpaceWarServer.cpp" />
<ClCompile Include="StarField.cpp" />
<ClCompile Include="StatsAndAchievements.cpp" />
<ClCompile Include="Sun.cpp" />
<ClCompile Include="timeline.cpp" />
<ClCompile Include="voicechat.cpp" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="SpaceWarRes.rc" />
</ItemGroup>
<ItemGroup>
<Library Include="..\public\steam\lib\win32\sdkencryptedappticket.lib">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</Library>
<Library Include="..\public\steam\lib\win64\sdkencryptedappticket64.lib">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</Library>
<Library Include="..\redistributable_bin\steam_api.lib">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</Library>
<Library Include="..\redistributable_bin\win64\steam_api64.lib">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</Library>
</ItemGroup>
<ItemGroup>
<None Include="gameengineosx.mm">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</None>
<None Include="glstringosx.mm">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</None>
<None Include="..\glmgr\glmgrcocoa.mm">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</None>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,323 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="16.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{1680C80B-FF1E-EA4D-9817-CC12254F2E40}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Engine">
<UniqueIdentifier>{A9977944-E96C-5354-00E9-10543AF3AD45}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Game">
<UniqueIdentifier>{D228CF81-3F1C-A342-56D3-9CFD97D8D5F0}</UniqueIdentifier>
</Filter>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{FA3635CE-6C7C-7DE5-DDEB-60602507503F}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Engine">
<UniqueIdentifier>{3BC5273C-D80A-3936-3D84-35FC7E6269AE}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Game">
<UniqueIdentifier>{84F38993-4EB4-8F80-2E2C-37AA0D9C662A}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\public\steam\lib\win32\sdkencryptedappticket.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\redistributable_bin\steam_api.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\redistributable_bin\steam_api.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\public\steam\lib\win32\sdkencryptedappticket.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\public\steam\lib\win64\sdkencryptedappticket64.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\redistributable_bin\win64\steam_api64.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GameEngine.h">
<Filter>Header Files\Engine</Filter>
</ClInclude>
<ClInclude Include="gameengineosx.h">
<Filter>Header Files\Engine</Filter>
</ClInclude>
<ClInclude Include="gameenginesdl.h">
<Filter>Header Files\Engine</Filter>
</ClInclude>
<ClInclude Include="gameenginewin32.h">
<Filter>Header Files\Engine</Filter>
</ClInclude>
<ClInclude Include="glstringosx.h">
<Filter>Header Files\Engine</Filter>
</ClInclude>
<ClInclude Include="VectorEntity.h">
<Filter>Header Files\Engine</Filter>
</ClInclude>
<ClInclude Include="BaseMenu.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="clanchatroom.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="connectingmenu.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="Friends.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="htmlsurface.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="Inventory.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="ItemStore.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="Leaderboards.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="Lobby.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="MainMenu.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="..\glmgr\mathlite.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="Messages.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="musicplayer.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="OverlayExamples.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="p2pauth.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="PhotonBeam.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="QuitMenu.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="RemotePlay.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="RemoteStorage.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="remotestoragesync.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="ServerBrowser.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="ServerBrowserMenu.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="Ship.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="SimpleProtobuf.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="SpaceWar.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="SpaceWarClient.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="SpaceWarEntity.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="SpaceWarServer.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="StarField.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="StatsAndAchievements.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="Sun.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="timeline.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
<ClInclude Include="voicechat.h">
<Filter>Header Files\Game</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="gameenginesdl.cpp">
<Filter>Source Files\Engine</Filter>
</ClCompile>
<ClCompile Include="gameenginewin32.cpp">
<Filter>Source Files\Engine</Filter>
</ClCompile>
<ClCompile Include="..\tier1\pathmatch.cpp">
<Filter>Source Files\Engine</Filter>
</ClCompile>
<ClCompile Include="VectorEntity.cpp">
<Filter>Source Files\Engine</Filter>
</ClCompile>
<ClCompile Include="BaseMenu.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\cglmbuffer.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\cglmfbo.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\cglmprogram.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\cglmquery.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\cglmtex.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="clanchatroom.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\dx9asmtogl2.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\dxabstract.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="Friends.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\glmgr.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\glmgrbasics.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\glmgrext.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="htmlsurface.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="Inventory.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="ItemStore.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="Leaderboards.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="Lobby.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="MainMenu.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="..\glmgr\mathlite.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="musicplayer.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="OverlayExamples.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="p2pauth.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="PhotonBeam.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="QuitMenu.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="RemotePlay.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="RemoteStorage.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="ServerBrowser.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="Ship.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="SimpleProtobuf.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="SpaceWarClient.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="SpaceWarEntity.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="SpaceWarServer.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="StarField.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="StatsAndAchievements.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="Sun.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="timeline.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
<ClCompile Include="voicechat.cpp">
<Filter>Source Files\Game</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="SpaceWarRes.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<None Include="gameengineosx.mm">
<Filter>Source Files\Engine</Filter>
</None>
<None Include="glstringosx.mm">
<Filter>Source Files\Engine</Filter>
</None>
<None Include="..\glmgr\glmgrcocoa.mm">
<Filter>Source Files\Game</Filter>
</None>
</ItemGroup>
</Project>
+42
View File
@@ -0,0 +1,42 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for rendering the sun
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "Sun.h"
#include <math.h>
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CSun::CSun( IGameEngine *pGameEngine ) : CSpaceWarEntity( pGameEngine, 2*SUN_VECTOR_SCALE_FACTOR, false )
{
float xcenter = (float)pGameEngine->GetViewportWidth()/2;
float ycenter = (float)pGameEngine->GetViewportHeight()/2;
float sqrtof2 = (float)sqrt( 2.0 );
DWORD dwColor = D3DCOLOR_ARGB( 255, 255, 255, 102 );
// Initialize our geometry
AddLine( (2.0f*SUN_VECTOR_SCALE_FACTOR), 0.0f, (-2.0f*SUN_VECTOR_SCALE_FACTOR), 0.0f, dwColor );
AddLine( 0.0f, (2.0f*SUN_VECTOR_SCALE_FACTOR), 0.0f, (-2.0f*SUN_VECTOR_SCALE_FACTOR), dwColor );
AddLine( -1.0f*sqrtof2*SUN_VECTOR_SCALE_FACTOR, sqrtof2*SUN_VECTOR_SCALE_FACTOR, sqrtof2*SUN_VECTOR_SCALE_FACTOR, -1.0f*sqrtof2*SUN_VECTOR_SCALE_FACTOR, dwColor );
AddLine( sqrtof2*SUN_VECTOR_SCALE_FACTOR, sqrtof2*SUN_VECTOR_SCALE_FACTOR, -1.0f*sqrtof2*SUN_VECTOR_SCALE_FACTOR, -1.0f*sqrtof2*SUN_VECTOR_SCALE_FACTOR, dwColor );
// Has to be after unlock since the base class will lock in this call
SetPosition( xcenter, ycenter );
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame for the sun
//-----------------------------------------------------------------------------
void CSun::RunFrame()
{
// We want to rotate 90 degrees every 800ms (1.57 is 1/2pi, or 90 degrees in radians)
SetRotationDeltaNextFrame( (PI_VALUE/2.0f) * (float)m_pGameEngine->GetGameTicksFrameDelta()/800.0f );
CVectorEntity::RunFrame();
}
+27
View File
@@ -0,0 +1,27 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for rendering the sun
//
// $NoKeywords: $
//=============================================================================
#ifndef SUN_H
#define SUN_H
#include "GameEngine.h"
#include "SpaceWarEntity.h"
#define SUN_VECTOR_SCALE_FACTOR 14
class CSun : public CSpaceWarEntity
{
public:
// Constructor
CSun( IGameEngine *pGameEngine );
// Run a frame
void RunFrame();
};
#endif // SUN_H
+304
View File
@@ -0,0 +1,304 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Base class for representation objects in the game which are drawn as
// vector art (ie, a series of lines)
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "VectorEntity.h"
#include "stdlib.h"
#include <math.h>
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CVectorEntity::CVectorEntity( IGameEngine *pGameEngine, uint32 uCollisionRadius )
{
m_uCollisionRadius = uCollisionRadius;
m_pGameEngine = pGameEngine;
m_flRotationDeltaNextFrame = 0.0;
m_flAccumulatedRotation = 0.0;
m_flXAccel = 0.0;
m_flYAccel = 0.0;
m_flXAccelLastFrame = 0.0;
m_flYAccelLastFrame = 0.0;
m_flXPos = 0.0;
m_flYPos = 0.0;
m_flXVelocity = 0.0;
m_flYVelocity = 0.0;
m_bDisableCollisions = false;
m_flRotationDeltaLastFrame = 0.0;
// we should have at least one frame Run before
// anyone asks for a delta, so this shouldn't cause
// a large initial delta to our starting position, in theory
m_flXPosLastFrame = 0;
m_flYPosLastFrame = 0;
m_flMaximumVelocity = DEFAULT_MAXIMUM_VELOCITY;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CVectorEntity::~CVectorEntity()
{
}
//-----------------------------------------------------------------------------
// Purpose: Add a line to our geometry
//-----------------------------------------------------------------------------
void CVectorEntity::AddLine( float xPos0, float yPos0, float xPos1, float yPos1, DWORD dwColor )
{
VectorEntityVertex_t vert;
vert.x = xPos0;
vert.y = yPos0;
vert.color = dwColor;
m_VecVertexes.push_back( vert );
vert.x = xPos1;
vert.y = yPos1;
vert.color = dwColor;
m_VecVertexes.push_back( vert );
}
void CVectorEntity::ClearVertexes()
{
m_VecVertexes.clear();
}
//-----------------------------------------------------------------------------
// Purpose: Set the current position for the object
//-----------------------------------------------------------------------------
void CVectorEntity::SetPosition( float xPos, float yPos )
{
m_flXPos = xPos;
m_flYPos = yPos;
}
//-----------------------------------------------------------------------------
// Purpose: Set the rotation to be applied next frame (in radians)
//-----------------------------------------------------------------------------
void CVectorEntity::SetRotationDeltaNextFrame( float flRotationInRadians )
{
m_flRotationDeltaNextFrame = flRotationInRadians;
}
//-----------------------------------------------------------------------------
// Purpose: Set the acceleration to be applied next frame
//-----------------------------------------------------------------------------
void CVectorEntity::SetAcceleration( float flXAccel, float flYAccel )
{
m_flXAccel = flXAccel;
m_flYAccel = flYAccel;
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame for the vector entity (ie, compute rotation, position, etc...)
//-----------------------------------------------------------------------------
void CVectorEntity::RunFrame()
{
// Accumulate the rotation so we know our current rotation total at all times
m_flAccumulatedRotation += m_flRotationDeltaNextFrame;
m_flRotationDeltaLastFrame = m_flRotationDeltaNextFrame;
m_flRotationDeltaNextFrame = 0.0f;
m_flXPosLastFrame = m_flXPos;
m_flYPosLastFrame = m_flYPos;
// If the accumulated rotation is > 2pi (360) then wrap it (same for negative direction)
// This prevents the value getting really large and losing precision
int nInfiniteLoopProtector = 0;
while ( m_flAccumulatedRotation >= 2.0f*PI_VALUE && ++nInfiniteLoopProtector < 100 )
m_flAccumulatedRotation -= 2.0f*PI_VALUE;
nInfiniteLoopProtector = 0;
while ( m_flAccumulatedRotation <= -2.0f*PI_VALUE && ++nInfiniteLoopProtector < 100 )
m_flAccumulatedRotation += 2.0f*PI_VALUE;
// Update our acceleration, velocity, and finally position
// Note: The min here is so we don't get massive acceleration if frames for some reason don't run for a bit
float ulElapsedSeconds = MIN( (float)m_pGameEngine->GetGameTicksFrameDelta() / 1000.0f, 0.1f );
m_flXVelocity += m_flXAccel * ulElapsedSeconds;
m_flYVelocity += m_flYAccel * ulElapsedSeconds;
// Make sure velocity does not exceed maximum allowed
float flVelocity = (float)sqrt( m_flXVelocity*m_flXVelocity + m_flYVelocity*m_flYVelocity );
if ( flVelocity > m_flMaximumVelocity )
{
float flRatio = m_flMaximumVelocity / flVelocity;
m_flXVelocity = m_flXVelocity * flRatio;
m_flYVelocity = m_flYVelocity * flRatio;
}
m_flXPos += m_flXVelocity * ulElapsedSeconds;
m_flYPos += m_flYVelocity * ulElapsedSeconds;
// Clear acceleration values, child classes should keep reseting it as appropriate each frame
m_flXAccelLastFrame = m_flXAccel;
m_flYAccelLastFrame = m_flYAccel;
m_flXAccel = 0;
m_flYAccel = 0;
// Check for wrapping around the screen
float width = (float)m_pGameEngine->GetViewportWidth();
float height = (float)m_pGameEngine->GetViewportHeight();
if ( m_flXPos > width )
m_flXPos -= width;
if ( m_flXPos < 0 )
m_flXPos += width;
if ( m_flYPos > height )
m_flYPos -= height;
if ( m_flYPos < 0 )
m_flYPos += height;
}
//-----------------------------------------------------------------------------
// Purpose: Render the entity
//-----------------------------------------------------------------------------
void CVectorEntity::Render()
{
// Compute values which will be used for rotation below
float flSinRotation = (float)sin(m_flAccumulatedRotation);
float flCosRotation = (float)cos(m_flAccumulatedRotation);
if ( m_VecVertexes.size() < 2 )
return;
// Iterate our vector of vertexes 2 at a time drawing lines
for( size_t i=0; i < m_VecVertexes.size() - 1; ++i )
{
DWORD dwColor0, dwColor1;
float xPos0, yPos0, xPos1, yPos1;
float xPrime0, yPrime0, xPrime1, yPrime1;
// Grab the first point and apply rotation and translation
xPos0 = m_VecVertexes[i].x;
yPos0 = m_VecVertexes[i].y;
dwColor0 = m_VecVertexes[i].color;
// Apply any needed rotation
xPrime0 = flCosRotation*xPos0 - flSinRotation*yPos0;
yPrime0 = flSinRotation*xPos0 + flCosRotation*yPos0;
// Apply translation to current position
xPrime0 += m_flXPos;
yPrime0 += m_flYPos;
// Next vertex, we use 2 per iteration
++i;
// Grab the second point and apply rotation and translation
xPos1 = m_VecVertexes[i].x;
yPos1 = m_VecVertexes[i].y;
dwColor1 = m_VecVertexes[i].color;
// Apply any needed rotation
xPrime1 = flCosRotation*xPos1 - flSinRotation*yPos1;
yPrime1 = flSinRotation*xPos1 + flCosRotation*yPos1;
// Apply translation to current position
xPrime1 += m_flXPos;
yPrime1 += m_flYPos;
// Have the game engine draw the actual line (it batches these operations)
m_pGameEngine->BDrawLine( xPrime0, yPrime0, dwColor0, xPrime1, yPrime1, dwColor1 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Render the entity with an override color instead of the vertex color
//-----------------------------------------------------------------------------
void CVectorEntity::Render(DWORD overrideColor)
{
// Compute values which will be used for rotation below
float flSinRotation = (float)sin(m_flAccumulatedRotation);
float flCosRotation = (float)cos(m_flAccumulatedRotation);
// Iterate our vector of vertexes 2 at a time drawing lines
for( size_t i=0; i < m_VecVertexes.size() - 1; ++i )
{
DWORD dwColor0, dwColor1;
float xPos0, yPos0, xPos1, yPos1;
float xPrime0, yPrime0, xPrime1, yPrime1;
// Grab the first point and apply rotation and translation
xPos0 = m_VecVertexes[i].x;
yPos0 = m_VecVertexes[i].y;
dwColor0 = overrideColor;
// Apply any needed rotation
xPrime0 = flCosRotation*xPos0 - flSinRotation*yPos0;
yPrime0 = flSinRotation*xPos0 + flCosRotation*yPos0;
// Apply translation to current position
xPrime0 += m_flXPos;
yPrime0 += m_flYPos;
// Next vertex, we use 2 per iteration
++i;
// Grab the second point and apply rotation and translation
xPos1 = m_VecVertexes[i].x;
yPos1 = m_VecVertexes[i].y;
dwColor1 = overrideColor;
// Apply any needed rotation
xPrime1 = flCosRotation*xPos1 - flSinRotation*yPos1;
yPrime1 = flSinRotation*xPos1 + flCosRotation*yPos1;
// Apply translation to current position
xPrime1 += m_flXPos;
yPrime1 += m_flYPos;
// Have the game engine draw the actual line (it batches these operations)
m_pGameEngine->BDrawLine( xPrime0, yPrime0, dwColor0, xPrime1, yPrime1, dwColor1 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Check if the entity is colliding with the other given entity
//-----------------------------------------------------------------------------
bool CVectorEntity::BCollidesWith ( CVectorEntity * pTarget )
{
// Note: Yes, this is a lame way to do collision detection just using a set radius.
// I don't care for the moment, just want it running!
if ( m_bDisableCollisions )
return false;
else if ( pTarget->BCollisionDetectionDisabled() )
return false;
// Compute distance between the center of the two objects
float distance = (float)sqrt( pow( m_flXPos - pTarget->GetXPos(), 2 ) + pow( m_flYPos - pTarget->GetYPos(), 2 ) );
if ( distance < m_uCollisionRadius + pTarget->GetCollisionRadius() )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Check if the entity is colliding with the other given entity
//-----------------------------------------------------------------------------
float CVectorEntity::GetDistanceTraveledLastFrame()
{
return (float)sqrt( pow( m_flXPos - m_flXPosLastFrame, 2 ) + pow( m_flYPos - m_flYPosLastFrame, 2 ) );
}
+158
View File
@@ -0,0 +1,158 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Base class for representation objects in the game which are drawn as
// vector art (ie, a series of lines)
//
// $NoKeywords: $
//=============================================================================
#ifndef VECTORENTITY_H
#define VECTORENTITY_H
#include "GameEngine.h"
#include <vector>
struct VectorEntityVertex_t
{
float x, y;
DWORD color;
};
#define DEFAULT_MAXIMUM_VELOCITY 450.0f
#define PI_VALUE 3.14159265f
class CVectorEntity
{
public:
// Constructor
CVectorEntity( IGameEngine *pGameEngine, uint32 uCollisionRadius );
// Destructor
virtual ~CVectorEntity();
// Run a frame
virtual void RunFrame();
// Render the sun field
virtual void Render();
// Render with an explicit color
virtual void Render(DWORD overrideColor);
// Check if the entity is colliding with another given entity
bool BCollidesWith( CVectorEntity * pTarget );
// Get the rotation value that is to be applied next frame
float GetRotationDeltaNextFrame() { return m_flRotationDeltaNextFrame; }
// Get the rotation value that was applied last frame
float GetRotationDeltaLastFrame() { return m_flRotationDeltaLastFrame; }
// Get the cumulative rotation for this entity
float GetAccumulatedRotation() { return m_flAccumulatedRotation; }
// Get the acceleration to be applied next frame
float GetXAcceleration() { return m_flXAccel; }
float GetYAcceleration() { return m_flYAccel; }
// Get the acceleration applied last frame
float GetXAccelerationLastFrame() { return m_flXAccelLastFrame; }
float GetYAccelerationLastFrame() { return m_flYAccelLastFrame; }
// Get the current velocity
float GetXVelocity() { return m_flXVelocity; }
float GetYVelocity() { return m_flYVelocity; }
// Get the current position of the object
float GetXPos() { return m_flXPos; }
float GetYPos() { return m_flYPos; }
// Get the distance traveled each frame
float GetDistanceTraveledLastFrame();
// Add a line to the entity
void AddLine(float xPos0, float yPos0, float xPos1, float yPos1, DWORD dwColor);
// Clear all lines in the entity
void ClearVertexes();
// Set the objects current position
void SetPosition(float xPos, float yPos);
// Set the velocity of the entity (normally you should just set acceleration and this will be computed)
void SetVelocity(float xVelocity, float yVelocity) { m_flXVelocity = xVelocity; m_flYVelocity = yVelocity; }
protected:
// Set the rotation to be applied next frame
void SetRotationDeltaNextFrame( float flRotationInRadians );
// Set the acceleration to be applied next frame
void SetAcceleration( float xAccel, float yAccel );
// Set the cumulative rotation for this entity (overriding any existing value)
void SetAccumulatedRotation( float flRotation ) { m_flAccumulatedRotation = flRotation; }
// Reset velocity of the entity
void ResetVelocity() { m_flXVelocity = 0; m_flYVelocity = 0; }
// Get the collision radius for the entity
uint32 GetCollisionRadius() { return m_uCollisionRadius; }
// Enable/Disable collision detection for this entity
void SetCollisionDetectionDisabled( bool bDisabled ) { m_bDisableCollisions = bDisabled; }
// Check whether collision detection has been disabled for the entity
bool BCollisionDetectionDisabled() { return m_bDisableCollisions; }
// Set a maximum velocity other than the default
void SetMaximumVelocity( float flMaximumVelocity ) { m_flMaximumVelocity = flMaximumVelocity; }
protected:
// Game engine instance we are running under
IGameEngine *m_pGameEngine;
private:
// Vector of points (always built 2 at a time so it's actually lines)
std::vector< VectorEntityVertex_t > m_VecVertexes;
// Previous position
float m_flXPosLastFrame;
float m_flYPosLastFrame;
// current position (position is at the center of the object)
float m_flXPos;
float m_flYPos;
// maximum velocity the object can have in either x/y
float m_flMaximumVelocity;
// acceleration to be applied next frame
float m_flXAccel;
float m_flYAccel;
// acceleration applied last frame
float m_flXAccelLastFrame;
float m_flYAccelLastFrame;
// current velocity (affected by acceleration changes)
float m_flXVelocity;
float m_flYVelocity;
// rotation to apply this frame (in radians)
float m_flRotationDeltaNextFrame;
// rotation which was applied last frame
float m_flRotationDeltaLastFrame;
// total cumulative rotation that has been applied to this entity
float m_flAccumulatedRotation;
// radius to use for collisions, this is applied from the center of the object out
uint32 m_uCollisionRadius;
// bool to disable collision detection for this object
bool m_bDisableCollisions;
};
#endif // VECTORENTITY_H
+77
View File
@@ -0,0 +1,77 @@
//========= Copyright Valve LLC, All rights reserved. ============
//
// Purpose: Class for joining and showing clan chats
//
//================================================================
#include "stdafx.h"
#include "clanchatroom.h"
#include "BaseMenu.h"
#include <math.h>
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CClanChatRoom::CClanChatRoom( IGameEngine *pGameEngine ) : m_pGameEngine( pGameEngine )
{
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame for the CClanChatRoom
//-----------------------------------------------------------------------------
void CClanChatRoom::RunFrame()
{
}
//-----------------------------------------------------------------------------
// Purpose: Shows / Refreshes the chat room
//-----------------------------------------------------------------------------
void CClanChatRoom::Show()
{
// start joining a chat, if we aren't in one already
if ( !m_steamIDChat.IsValid() || !m_SteamCallResultJoinChatRoom.IsActive() )
{
// pick a clan to join from the users current data
CSteamID steamIDBestClan;
for ( int i = 0; i < SteamFriends()->GetClanCount(); i++ )
{
CSteamID steamIDClan = SteamFriends()->GetClanByIndex( i );
int online, ingame, chatting;
if ( SteamFriends()->GetClanActivityCounts( steamIDClan, &online, &ingame, &chatting ) )
{
if ( chatting > 0 )
{
steamIDBestClan = steamIDClan;
break;
}
else if ( online )
{
steamIDBestClan = steamIDClan;
}
}
}
if ( steamIDBestClan.IsValid() )
{
SteamAPICall_t hCall = SteamFriends()->JoinClanChatRoom( steamIDBestClan );
m_SteamCallResultJoinChatRoom.Set( hCall, this, &CClanChatRoom::OnJoinChatRoom );
OutputDebugString( "joining clan chat...\n" );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Called when SteamFriends()->JoinClanChatRoom() returns asynchronously
//-----------------------------------------------------------------------------
void CClanChatRoom::OnJoinChatRoom( JoinClanChatRoomCompletionResult_t *pResult, bool bIOFailure )
{
if ( pResult->m_eChatRoomEnterResponse == k_EChatRoomEnterResponseSuccess )
{
// we've entered
OutputDebugString( "succesfully joined clan chat\n" );
}
}
+42
View File
@@ -0,0 +1,42 @@
//========= Copyright © 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for joining and showing clan chat rooms
//
//=============================================================================
#ifndef CLANCHATROOM_H
#define CLANCHATROOM_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "StatsAndAchievements.h"
#include "SpaceWarClient.h"
class ISteamUser;
class CClanChatRoom
{
public:
// Constructor
CClanChatRoom( IGameEngine *pGameEngine );
// Run a frame
void RunFrame();
// shows / refreshes chat
void Show();
private:
// Engine
IGameEngine *m_pGameEngine;
// Called when SteamFriends()->JoinClanChatRoom() returns asynchronously
void OnJoinChatRoom( JoinClanChatRoomCompletionResult_t *pResult, bool bIOFailure );
CCallResult<CClanChatRoom, JoinClanChatRoomCompletionResult_t> m_SteamCallResultJoinChatRoom;
CSteamID m_steamIDChat;
};
#endif // CLANCHATROOM_H
@@ -0,0 +1 @@
480
+87
View File
@@ -0,0 +1,87 @@
ifeq "$(DOCKER_IMAGE_ALIAS)" ""
# This is setup when using Valve's docker scripts, but not when using podman/toolbox, so try to guess
$(shell grep -q -F VARIANT_ID=\"com.valvesoftware.steamruntime.sdk-amd64_i386-scout\" /etc/os-release)
ifeq ($(.SHELLSTATUS),0)
DOCKER_IMAGE_ALIAS := steamrt-scout-amd64
endif
endif
ifeq "$(DOCKER_IMAGE_ALIAS)" ""
$(info WARNING: No Steam for Linux runtime SDK detected - unsupported configuration.)
$(info See tools/linux/README.md)
$(info)
else
DOCKER_IMAGE_BASE:=$(DOCKER_IMAGE_ALIAS:-fastlink=)
DOCKER_IMAGE_BASE:=$(DOCKER_IMAGE_BASE:-i386=)
DOCKER_IMAGE_BASE:=$(DOCKER_IMAGE_BASE:-amd64=)
ifeq ($(DOCKER_IMAGE_BASE), steamrt-scout)
$(info Configuring for Steam for Linux runtime 1.0 (scout))
CC := gcc-9
CXX := g++-9
CXXFLAGS += -std=gnu++17
# unlike gcc 4.8, gcc 9 is not native to the scout runtime, it is recommended to statically link
LDFLAGS += -static-libgcc -static-libstdc++
endif
endif
ifeq ($(ARCH), 32)
ARCH_DIR := linux32
else
ARCH_DIR := linux64
endif
INCLUDE_DIRS := $(PWD)/../public
LIBRARY_DIRS := $(PWD)/../../client/$(ARCH_DIR)
LIBRARY_NAMES := steam_api
STEAM_API := libsteam_api.so
ifeq (,$(wildcard $(LIBRARY_DIRS)/$(STEAM_API)))
# Does not exist, substitue with a path valid for the public, zip version of the SDK
LIBRARY_DIRS := $(PWD)/../redistributable_bin/$(ARCH_DIR)
endif
CC ?= gcc
CXX ?= g++
LD := $(CXX)
AR := ar
OBJCOPY := objcopy
CP := cp
SDL_CONFIG := sdl2-config
# Since this is an example, we'll build Debug by default
CONFIG ?= DEBUG
COMMON_MACROS :=
DEBUG_MACROS := DEBUG
RELEASE_MACROS := NDEBUG RELEASE
MCUFLAGS :=
CFLAGS += -g -DPOSIX -DSDL $(shell $(SDL_CONFIG) --cflags) -DGNUC
CXXFLAGS += -g -DPOSIX -DSDL $(shell $(SDL_CONFIG) --cflags) -DGNUC
# Valve uses SDL3 internally (the default if USE_SDL2 is not specified)
# The zip version of the SDK uses the SDL2 package from the runtime SDK
CXXFLAGS += -DUSE_SDL2
DEBUG_CFLAGS := -O0
RELEASE_CFLAGS := -O3
DEBUG_CXXFLAGS := $(DEBUG_CFLAGS)
RELEASE_CXXFLAGS := $(RELEASE_CFLAGS)
MACOS_FRAMEWORKS :=
LDFLAGS := $(shell $(SDL_CONFIG) --libs) -lSDL2_ttf -lfreetype -lz -lGL -lopenal
DEBUG_LDFLAGS :=
RELEASE_LDGLAGS :=
START_GROUP := -Wl,--start-group
END_GROUP := -Wl,--end-group
USE_DEL_TO_CLEAN := 0
GENERATE_BIN_FILE := 0
ADDITIONAL_MAKE_FILES :=
IS_LINUX_PROJECT := 1
include $(ADDITIONAL_MAKE_FILES)
+523
View File
@@ -0,0 +1,523 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Main class for the game engine -- osx implementation
//
// $NoKeywords: $
//=============================================================================
#ifndef GAMEENGINEOSX_H
#define GAMEENGINEOSX_H
#ifdef __OBJC__
#define OBJC_ENABLED 1
#else
#define OBJC_ENABLED 0
#endif
typedef unsigned char byte;
#include "steam/steam_api.h"
#include "GameEngine.h"
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#include <OpenGL/OpenGL.h>
#include <string>
#include <set>
#include <map>
// How big is the vertex buffer for batching lines in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define LINE_BUFFER_TOTAL_SIZE 1000
// How many lines do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define LINE_BUFFER_BATCH_SIZE 250
// How big is the vertex buffer for batching points in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define POINT_BUFFER_TOTAL_SIZE 1800
// How many points do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define POINT_BUFFER_BATCH_SIZE 600
// How big is the vertex buffer for batching quads in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define QUAD_BUFFER_TOTAL_SIZE 1000
// How many quads do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define QUAD_BUFFER_BATCH_SIZE 250
#ifndef DX9MODE
#define DX9MODE 0 // change to 1 to turn on the DX9 mode
#endif
#if DX9MODE
#include "../glmgr/dxabstract.h"
class CShowPixelsParams
{
public:
GLuint m_srcTexName;
int m_width,m_height;
};
// Vertex struct for line batches
struct LineVertex_t
{
float x, y, z, rhw;
DWORD color;
};
// Vertex struct for point batches
struct PointVertex_t
{
float x, y, z, rhw;
DWORD color;
};
// Vertex struct for textured quads
struct TexturedQuadVertex_t
{
float x, y, z, rhw;
DWORD color;
float u, v; // texture coordinates
};
#endif
class CVoiceContext;
class CGameEngineGL : public IGameEngine
{
public:
// Constructor
CGameEngineGL();
// Destructor
~CGameEngineGL() { Shutdown(); }
// Check if the game engine is initialized ok and ready for use
bool BReadyForUse() { return m_bEngineReadyForUse; }
// Check if the engine is shutting down
bool BShuttingDown() { return m_bShuttingDown; }
// Set the background color
void SetBackgroundColor( short a, short r, short g, short b );
// Start a frame, clear(), beginscene(), etc
bool StartFrame();
// Finish a frame, endscene(), present(), etc.
void EndFrame();
// Shutdown the game engine
void Shutdown();
// Pump messages from the OS
void MessagePump();
// Accessors for game screen size
int32 GetViewportWidth() { return m_nWindowWidth; }
int32 GetViewportHeight() { return m_nWindowHeight; }
// Function for drawing text to the screen, dwFormat is a combination of flags like DT_LEFT, TEXTPOS_VCENTER etc...
// on OSX client with DX9MODE=1, the HGAMEFONT is a texture with the glyphs in a 16x16 grid (see "g_glmDebugFontMap" in glmgrbasics.cpp)
bool BDrawString( HGAMEFONT hFont, RECT rect, DWORD dwColor, DWORD dwFormat, const char *pchText );
// Create a new font returning our internal handle value for it (0 means failure)
HGAMEFONT HCreateFont( int nHeight, int nFontWeight, bool bItalic, const char * pchFont );
// Create a new texture returning our internal handle value for it (0 means failure)
HGAMETEXTURE HCreateTexture( byte *pRGBAData, uint32 uWidth, uint32 uHeight, ETEXTUREFORMAT eTextureFormat = eTextureFormat_RGBA );
// update an existing texture
bool UpdateTexture( HGAMETEXTURE texture, byte *pRGBAData, uint32 uWidth, uint32 uHeight, ETEXTUREFORMAT eTextureFormat );
// Draw a line, the engine itself will manage batching these (although you can explicitly flush if you need to)
bool BDrawLine( float xPos0, float yPos0, DWORD dwColor0, float xPos1, float yPos1, DWORD dwColor1 );
// Flush the line buffer
bool BFlushLineBuffer();
// Draw a point, the engine itself will manage batching these (although you can explicitly flush if you need to)
bool BDrawPoint( float xPos, float yPos, DWORD dwColor );
// Flush the point buffer
bool BFlushPointBuffer();
// Draw a filled quad
bool BDrawFilledRect( float xPos0, float yPos0, float xPos1, float yPos1, DWORD dwColor );
// Draw a textured rectangle
bool BDrawTexturedRect( float xPos0, float yPos0, float xPos1, float yPos1,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture );
// Draw a textured arbitrary quad
bool BDrawTexturedQuad( float xPos0, float yPos0, float xPos1, float yPos1, float xPos2, float yPos2, float xPos3, float yPos3,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture );
// Flush any still cached quad buffers
bool BFlushQuadBuffer();
// Get the current state of a key
bool BIsKeyDown( DWORD dwVK );
// Get the first (in some arbitrary order) key down, if any
bool BGetFirstKeyDown( DWORD *pdwVK );
// Return true if there is an active Steam Input device
bool BIsSteamInputDeviceActive( );
// Find the active device
void FindActiveSteamInputDevice( );
// Get the current state of a controller action
bool BIsControllerActionActive( ECONTROLLERDIGITALACTION dwAction );
// Get the current state of a controller action
void GetControllerAnalogAction( ECONTROLLERANALOGACTION dwAction, float *x, float *y );
// Set the current Steam Controller Action set
void SetSteamControllerActionSet( ECONTROLLERACTIONSET dwActionSet );
// Set an Action Set Layer for Steam Input
virtual void ActivateSteamControllerActionSetLayer( ECONTROLLERACTIONSET dwActionSet );
virtual void DeactivateSteamControllerActionSetLayer( ECONTROLLERACTIONSET dwActionSet );
// Returns whether a given action set layer is active
virtual bool BIsActionSetLayerActive( ECONTROLLERACTIONSET dwActionSetLayer );
// These calls return a string describing which controller button the action is currently bound to
const char *GetTextStringForControllerOriginDigital( ECONTROLLERACTIONSET dwActionSet, ECONTROLLERDIGITALACTION dwDigitalAction );
const char *GetTextStringForControllerOriginAnalog( ECONTROLLERACTIONSET dwActionSet, ECONTROLLERANALOGACTION dwDigitalAction );
// Set the controller LED Color, if available
void SetControllerColor( uint8 nColorR, uint8 nColorG, uint8 nColorB, unsigned int nFlags );
// Set the trigger effect on DualSense controllers
void SetTriggerEffect( bool bEnabled );
// Trigger a vibration on the controller, if available
void TriggerControllerVibration( unsigned short nLeftSpeed, unsigned short nRightSpeed );
// Trigger haptics on the specified pad of the controller, if available
void TriggerControllerHaptics( ESteamControllerPad ePad, unsigned short usOnMicroSec, unsigned short usOffMicroSec, unsigned short usRepeat );
// Initialize the Steam Input interface
void InitSteamInput( );
// Called each frame to update the Steam Input interface
void PollSteamInput();
// Get current tick count for the game engine
uint64 GetGameTickCount() { return m_ulGameTickCount; }
// Get the tick count elapsed since the previous frame
// bugbug - We use this time to compute things like thrust and acceleration in the game,
// so it's important in doesn't jump ahead by large increments... Need a better
// way to handle that.
uint64 GetGameTicksFrameDelta() { return m_ulGameTickCount - m_ulPreviousGameTickCount; }
// Tell the game engine to update current tick count
void UpdateGameTickCount();
// Tell the game engine to sleep for a bit if needed to limit frame rate
bool BSleepForFrameRateLimit( uint32 ulMaxFrameRate );
// Check if the game engine hwnd currently has focus (and a working d3d device)
bool BGameEngineHasFocus() { return true; }
// Voice chat functions
virtual HGAMEVOICECHANNEL HCreateVoiceChannel();
virtual void DestroyVoiceChannel( HGAMEVOICECHANNEL hChannel );
virtual bool AddVoiceData( HGAMEVOICECHANNEL hChannel, const uint8 *pVoiceData, uint32 uLength );
#if DX9MODE
#else
void AdjustViewport();
#endif
// Initialize graphics in either GL or DX9 form
bool BInitializeGraphics();
// Initialize the debug font library
bool BInitializeCellDbgFont();
bool BInitializeAudio();
void RunAudio();
void UpdateKey( uint32_t vkKey, int nDown );
// Tracks whether the engine is ready for use
bool m_bEngineReadyForUse;
// Tracks if we are shutting down
bool m_bShuttingDown;
// Size of the window to display the game in
int32 m_nWindowWidth;
int32 m_nWindowHeight;
// Current game time in milliseconds
uint64 m_ulGameTickCount;
// Game time at the start of the previous frame
uint64 m_ulPreviousGameTickCount;
#if DX9MODE
// Windows code transplants--------------------------------------------------------
// Resets all the render, texture, and sampler states to our defaults
void ResetRenderStates();
// Create a new vertex buffer returning our internal handle for it (0 means failure)
HGAMEVERTBUF HCreateVertexBuffer( uint32 nSizeInBytes, DWORD dwUsage, DWORD dwFVF );
// Lock an entire vertex buffer with the specified flags
bool BLockEntireVertexBuffer( HGAMEVERTBUF hVertBuf, void **ppVoid, DWORD dwFlags );
// Unlock a vertex buffer
bool BUnlockVertexBuffer( HGAMEVERTBUF hVertBuf );
// Release a vertex buffer and free its resources
bool BReleaseVertexBuffer( HGAMEVERTBUF hVertBuf );
// set vertex decl
bool BSetVertexDeclaration( IDirect3DVertexDeclaration9 *decl );
// Set stream source
bool BSetStreamSource( uint streamNumber, HGAMEVERTBUF hVertBuf, uint32 uOffset, uint32 uStride );
// Set shaders
bool BSetShaders( IDirect3DVertexShader9 *vsh, IDirect3DPixelShader9 *psh );
// Render primitives out of the current stream source
bool BRenderPrimitive( D3DPRIMITIVETYPE primType, uint32 uStartVertex, uint32 uCount );
bool BUberRenderPrimitive( IDirect3DVertexShader9 *vsh,
IDirect3DPixelShader9 *psh,
IDirect3DVertexDeclaration9 *decl,
uint streamNumber,
HGAMEVERTBUF hVertBuf,
uint32 uOffset,
uint32 uStride,
D3DPRIMITIVETYPE primType,
uint32 uStartVertex,
uint32 uCount );
// fake hwnd is a WindowRef ( = [m_window windowRef] )
void *m_hwnd;
// IDirect3D9 interface
IDirect3D9 *m_pD3D9Interface;
// IDirect3DDevice9 interface
IDirect3DDevice9 *m_pD3D9Device;
// Presentation parameters - device resets don't happen on OS X, but just for commonality with windows code
D3DPRESENT_PARAMETERS m_d3dpp;
// vertex declarations - one per vertex layout used
IDirect3DVertexDeclaration9 *m_decl_P4C1; // aka D3DFVF_XYZRHW | D3DFVF_DIFFUSE
// (4 floats pos, one ubyte4 color) - 20 bytes / vert
IDirect3DVertexDeclaration9 *m_decl_P4C1T2; // aka D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1
// (4 floats pos, one ubyte4 color, 2 floats texc) - 28 bytes / vert
// vertex and pixel shaders - one per vertex layout
IDirect3DVertexShader9 *m_vsh_P4C1;
IDirect3DVertexShader9 *m_vsh_P4C1T2;
IDirect3DPixelShader9 *m_psh_P4C1;
IDirect3DPixelShader9 *m_psh_P4C1T2;
// Color we clear the background of the window to each frame
DWORD m_dwBackgroundColor;
// Next vertex buffer handle value to give out
HGAMEVERTBUF m_nNextVertBufferHandle;
// Map of handles to vertex buffer objects
struct VertBufData_t
{
bool m_bIsLocked;
IDirect3DVertexBuffer9 * m_pBuffer;
};
std::map<HGAMEVERTBUF, VertBufData_t> m_MapVertexBuffers;
HGAMETEXTURE m_nNextTextureHandle;
// Map of handles to texture objects
struct TextureData_t
{
byte *m_pRGBAData; // We keep a copy of the raw data so we can rebuild textures after a device is lost
uint32 m_uWidth;
uint32 m_uHeight;
LPDIRECT3DTEXTURE9 m_pTexture;
};
std::map<HGAMETEXTURE, TextureData_t> m_MapTextures;
// Internal vertex buffer for batching line drawing
HGAMEVERTBUF m_hLineBuffer;
// Pointer to actual line buffer memory (valid only while locked)
LineVertex_t *m_pLineVertexes;
// Track how many lines are awaiting flushing in our line buffer
DWORD m_dwLinesToFlush;
// Track where the current batch starts in the vert buffer
DWORD m_dwLineBufferBatchPos;
// Internal vertex buffer for batching point drawing
HGAMEVERTBUF m_hPointBuffer;
// Pointer to actual point buffer memory (valid only while locked)
PointVertex_t *m_pPointVertexes;
// Track how many points are awaiting flushing in our line buffer
DWORD m_dwPointsToFlush;
// Track where the current batch starts in the vert buffer
DWORD m_dwPointBufferBatchPos;
// Vertex buffer for textured quads
HGAMEVERTBUF m_hQuadBuffer;
// Last texture used in drawing a batched quad
HGAMETEXTURE m_hLastTexture;
// Pointer to quad vertex data
TexturedQuadVertex_t *m_pQuadVertexes;
// How many quads are awaiting flushing
DWORD m_dwQuadsToFlush;
// Where does the current batch begin
DWORD m_dwQuadBufferBatchPos;
// White texture used when drawing filled quads
HGAMETEXTURE m_hTextureWhite;
// font stuff
HGAMEFONT m_nNextFontHandle;
std::map< HGAMEFONT, HGAMETEXTURE > m_MapGameFonts;
//CocoaMgr transplants-------------------------------------------------------------
GLMDisplayDB *GetDisplayDB ( void );
void GetRendererInfo ( GLMRendererInfoFields *rendInfoOut );
PseudoNSGLContextPtr GetNSGLContextForWindow( void* windowref );
void RenderedSize ( uint &width, uint &height, bool set ); // either set or retrieve rendered size value (from dxabstract)
void DisplayedSize ( uint &width, uint &height ); // query backbuffer size (window size whether FS or windowed)
void ShowPixels ( CShowPixelsParams *params ); // present
GLMDisplayDB *m_displayDB;
#else
// White texture used when drawing filled quads
HGAMETEXTURE m_hTextureWhite;
// Pointer to actual data for points
GLfloat *m_rgflPointsData;
GLubyte *m_rgflPointsColorData;
// How many points are outstanding needing flush
DWORD m_dwPointsToFlush;
// Pointer to actual data for lines
GLfloat *m_rgflLinesData;
GLubyte *m_rgflLinesColorData;
// How many lines are outstanding needing flush
DWORD m_dwLinesToFlush;
// Pointer to actual data for quads
GLfloat *m_rgflQuadsData;
GLubyte *m_rgflQuadsColorData;
GLfloat *m_rgflQuadsTextureData;
// How many lines are outstanding needing flush
DWORD m_dwQuadsToFlush;
// Map of font handles we have given out
HGAMEFONT m_nNextFontHandle;
std::map< HGAMEFONT, void* > m_MapGameFonts;
// Map of handles to texture objects
struct TextureData_t
{
uint32 m_uWidth;
uint32 m_uHeight;
GLuint m_uTextureID;
};
std::map<HGAMETEXTURE, TextureData_t> m_MapTextures;
HGAMETEXTURE m_nNextTextureHandle;
// Last bound texture, used to know when we must flush
HGAMETEXTURE m_hLastTexture;
#endif
// Map of button state, translated to VK for win32.
std::set< DWORD > m_SetKeysDown;
ALCcontext* m_palContext;
ALCdevice* m_palDevice;
// Map of voice handles
std::map<HGAMEVOICECHANNEL, CVoiceContext* > m_MapVoiceChannel;
uint32 m_unVoiceChannelCount;
#if OBJC_ENABLED
// any objective-c members go at the end of the class in a block
// they are invisible to callers in pure C++ files
// that also means callers in pure C++ files must not try to instantiate or destroy this type of object
#if DX9MODE
#else
std::map< std::string, GLString * > m_MapStrings;
#endif
NSOpenGLView *m_view;
NSWindow *m_window;
#endif
// An array of handles to Steam Controller events that player can bind to controls
InputDigitalActionHandle_t m_ControllerDigitalActionHandles[eControllerDigitalAction_NumActions];
// An array of handles to Steam Controller events that player can bind to controls
InputAnalogActionHandle_t m_ControllerAnalogActionHandles[eControllerAnalogAction_NumActions];
// An array of handles to different Steam Controller action set configurations
InputActionSetHandle_t m_ControllerActionSetHandles[eControllerActionSet_NumSets];
// A handle to the currently active Steam Controller.
InputHandle_t m_ActiveControllerHandle;
// Origins for all the Steam Input actions. The 'origin' is where the action is currently bound to,
// ie 'jump' is currently bound to the Steam Controller 'A' button.
EInputActionOrigin m_ControllerDigitalActionOrigins[eControllerDigitalAction_NumActions];
EInputActionOrigin m_ControllerAnalogActionOrigins[eControllerDigitalAction_NumActions];
};
#endif // GAMEENGINEOSX_H
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+235
View File
@@ -0,0 +1,235 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Main class for the game engine -- ps3 implementation
//
// $NoKeywords: $
//=============================================================================
#ifndef GAMEENGINEPS3_H
#define GAMEENGINEPS3_H
#include "GameEngine.h"
#include <set>
#include <map>
// Font info for PS3 dbg font output
struct PS3DbgFont_t
{
float m_nScale;
};
class CVoiceContext;
class CGameEnginePS3 : public IGameEngine, public ISteamPS3OverlayRenderHost
{
public:
// Static methods for tracing mapping of game engine class instances to hwnds
static CGameEnginePS3 * FindEngineInstanceForPtr( void *ptr );
static void AddInstanceToPtrMap( CGameEnginePS3* pInstance );
static void RemoveInstanceFromPtrMap( void *ptr );
// Constructor
CGameEnginePS3();
// Destructor
~CGameEnginePS3() { Shutdown(); }
// Check if the game engine is initialized ok and ready for use
bool BReadyForUse() { return m_bEngineReadyForUse; }
// Check if the engine is shutting down
bool BShuttingDown() { return m_bShuttingDown; }
// Set the background color
void SetBackgroundColor( short a, short r, short g, short b );
// Start a frame, clear(), beginscene(), etc
bool StartFrame();
// Finish a frame, endscene(), present(), etc.
void EndFrame();
// Shutdown the game engine
void Shutdown();
// Pump messages from the OS
void MessagePump();
// Accessors for game screen size
int32 GetViewportWidth() { return m_nWindowWidth; }
int32 GetViewportHeight() { return m_nWindowHeight; }
// Function for drawing text to the screen, dwFormat is a combination of flags like DT_LEFT, TEXTPOS_VCENTER etc...
bool BDrawString( HGAMEFONT hFont, RECT rect, DWORD dwColor, DWORD dwFormat, const char *pchText );
// Create a new font returning our internal handle value for it (0 means failure)
HGAMEFONT HCreateFont( int nHeight, int nFontWeight, bool bItalic, const char * pchFont );
// Create a new texture returning our internal handle value for it (0 means failure)
HGAMETEXTURE HCreateTexture( byte *pRGBAData, uint32 uWidth, uint32 uHeight );
// Draw a line, the engine itself will manage batching these (although you can explicitly flush if you need to)
bool BDrawLine( float xPos0, float yPos0, DWORD dwColor0, float xPos1, float yPos1, DWORD dwColor1 );
// Flush the line buffer
bool BFlushLineBuffer();
// Draw a point, the engine itself will manage batching these (although you can explicitly flush if you need to)
bool BDrawPoint( float xPos, float yPos, DWORD dwColor );
// Flush the point buffer
bool BFlushPointBuffer();
// Draw a filled quad
bool BDrawFilledQuad( float xPos0, float yPos0, float xPos1, float yPos1, DWORD dwColor );
// Draw a textured rectangle
bool BDrawTexturedQuad( float xPos0, float yPos0, float xPos1, float yPos1,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture );
// Flush any still cached quad buffers
bool BFlushQuadBuffer();
// Get the current state of a key
bool BIsKeyDown( DWORD dwVK );
// Get the first (in some arbitrary order) key down, if any
bool BGetFirstKeyDown( DWORD *pdwVK );
// Get current tick count for the game engine
uint64 GetGameTickCount() { return m_ulGameTickCount; }
// Get the tick count elapsed since the previous frame
// bugbug - We use this time to compute things like thrust and acceleration in the game,
// so it's important in doesn't jump ahead by large increments... Need a better
// way to handle that.
uint64 GetGameTicksFrameDelta() { return m_ulGameTickCount - m_ulPreviousGameTickCount; }
// Tell the game engine to update current tick count
void UpdateGameTickCount();
// Tell the game engine to sleep for a bit if needed to limit frame rate
bool BSleepForFrameRateLimit( uint32 ulMaxFrameRate );
// Check if the game engine hwnd currently has focus (and a working d3d device)
bool BGameEngineHasFocus() { return true; }
// Voice chat functions
virtual HGAMEVOICECHANNEL HCreateVoiceChannel();
virtual void DestroyVoiceChannel( HGAMEVOICECHANNEL hChannel );
virtual bool AddVoiceData( HGAMEVOICECHANNEL hChannel, const uint8 *pVoiceData, uint32 uLength );
// ISteamPS3OverlayRenderHost implementation
virtual void DrawTexturedRect( int x0, int y0, int x1, int y1, float u0, float v0, float u1, float v1, int32 iTextureID, DWORD colorStart, DWORD colorEnd, EOverlayGradientDirection eDirection );
virtual void LoadOrUpdateTexture( int32 iTextureID, bool bIsFullTexture, int x0, int y0, uint32 uWidth, uint32 uHeight, int32 iBytes, char *pData );
virtual void DeleteTexture( int32 iTextureID );
virtual void DeleteAllTextures();
private:
// Draw a textured rectangle
bool BDrawTexturedGradientQuad( float xPos0, float yPos0, float xPos1, float yPos1,
float u0, float v0, float u1, float v1,
DWORD dwColorTopLeft, DWORD dwColorTopRight, DWORD dwColorBottomLeft, DWORD dwColorBottomRight, HGAMETEXTURE hTexture );
// Initialize the PSGL rendering interfaces and default state
bool BInitializePSGL();
// Initialize the debug font library
bool BInitializeCellDbgFont();
// Initialize libpad for controller input
bool BInitializeLibPad();
bool BInitializeAudio();
void RunAudio();
private:
// Tracks whether the engine is ready for use
bool m_bEngineReadyForUse;
// Tracks if we are shutting down
bool m_bShuttingDown;
// Size of the window to display the game in
int32 m_nWindowWidth;
int32 m_nWindowHeight;
// Current game time in milliseconds
uint64 m_ulGameTickCount;
// Game time at the start of the previous frame
uint64 m_ulPreviousGameTickCount;
// White texture used when drawing filled quads
HGAMETEXTURE m_hTextureWhite;
// PSGL and CellDbgFont objects
PSGLcontext * m_pPSGLContext;
PSGLdevice * m_pPSGLDevice;
CellDbgFontConsoleId m_DbgFontConsoleID;
// Pointer to actual data for points
GLfloat *m_rgflPointsData;
GLubyte *m_rgflPointsColorData;
// How many points are outstanding needing flush
DWORD m_dwPointsToFlush;
// Pointer to actual data for lines
GLfloat *m_rgflLinesData;
GLubyte *m_rgflLinesColorData;
// How many lines are outstanding needing flush
DWORD m_dwLinesToFlush;
// Pointer to actual data for quads
GLfloat *m_rgflQuadsData;
GLubyte *m_rgflQuadsColorData;
GLfloat *m_rgflQuadsTextureData;
// How many lines are outstanding needing flush
DWORD m_dwQuadsToFlush;
// Currently active PS3 pad index to use for input
int m_iCurrentPadIndex;
// Map of engine instances by ptr, used in ps3 sys callbacks to find engine instance to handle callback
static std::map<void *, CGameEnginePS3 *> m_MapEngineInstances;
// Map of font handles we have given out
HGAMEFONT m_nNextFontHandle;
std::map< HGAMEFONT, PS3DbgFont_t > m_MapGameFonts;
// Map of handles to texture objects
struct TextureData_t
{
uint32 m_uWidth;
uint32 m_uHeight;
GLuint m_uTextureID;
};
std::map<HGAMETEXTURE, TextureData_t> m_MapTextures;
HGAMETEXTURE m_nNextTextureHandle;
// Last bound texture, used to know when we must flush
HGAMETEXTURE m_hLastTexture;
// Map of button state, translated to VK for win32.
std::set< DWORD > m_SetKeysDown;
// Map of voice handles
std::map<HGAMEVOICECHANNEL, CVoiceContext* > m_MapVoiceChannel;
uint32 m_unVoiceChannelCount;
// Map of Steam texture ids to our engine texture handles
std::map< int, HGAMETEXTURE> m_MapSteamTextures;
};
#endif // GAMEENGINEPS3_H
File diff suppressed because it is too large Load Diff
+324
View File
@@ -0,0 +1,324 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Main class for the game engine -- SDL implementation
//
// $NoKeywords: $
//=============================================================================
#ifndef GAMEENGINESDL_H
#define GAMEENGINESDL_H
typedef unsigned char byte;
#include "GameEngine.h"
#include <AL/al.h>
#include <AL/alc.h>
#if defined(USE_SDL2)
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <SDL2/SDL_ttf.h>
#else
#include <SDL3/SDL.h>
#include <SDL3/SDL_opengl.h>
#include <SDL3_ttf/SDL_ttf.h>
#endif
#include <string>
#include <set>
#include <map>
// How big is the vertex buffer for batching lines in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define LINE_BUFFER_TOTAL_SIZE 1000
// How many lines do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define LINE_BUFFER_BATCH_SIZE 250
// How big is the vertex buffer for batching points in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define POINT_BUFFER_TOTAL_SIZE 1800
// How many points do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define POINT_BUFFER_BATCH_SIZE 600
// How big is the vertex buffer for batching quads in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define QUAD_BUFFER_TOTAL_SIZE 1000
// How many quads do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define QUAD_BUFFER_BATCH_SIZE 250
class CVoiceContext;
class GLString;
class CGameEngineGL : public IGameEngine
{
public:
// Constructor
CGameEngineGL( );
// Destructor
~CGameEngineGL() { Shutdown(); }
// Check if the game engine is initialized ok and ready for use
bool BReadyForUse() { return m_bEngineReadyForUse; }
// Check if the engine is shutting down
bool BShuttingDown() { return m_bShuttingDown; }
// Set the background color
void SetBackgroundColor( short a, short r, short g, short b );
// Start a frame, clear(), beginscene(), etc
bool StartFrame();
// Finish a frame, endscene(), present(), etc.
void EndFrame();
// Shutdown the game engine
void Shutdown();
// Pump messages from the OS
void MessagePump();
// Accessors for game screen size
int32 GetViewportWidth() { return m_nWindowWidth; }
int32 GetViewportHeight() { return m_nWindowHeight; }
// Function for drawing text to the screen, dwFormat is a combination of flags like DT_LEFT, TEXTPOS_VCENTER etc...
bool BDrawString( HGAMEFONT hFont, RECT rect, DWORD dwColor, DWORD dwFormat, const char *pchText );
// Create a new font returning our internal handle value for it (0 means failure)
HGAMEFONT HCreateFont( int nHeight, int nFontWeight, bool bItalic, const char * pchFont );
// Create a new texture returning our internal handle value for it (0 means failure)
HGAMETEXTURE HCreateTexture( byte *pRGBAData, uint32 uWidth, uint32 uHeight, ETEXTUREFORMAT eTextureFormat = eTextureFormat_RGBA );
// update an existing texture
bool UpdateTexture( HGAMETEXTURE texture, byte *pRGBAData, uint32 uWidth, uint32 uHeight, ETEXTUREFORMAT eTextureFormat );
// Draw a line, the engine itself will manage batching these (although you can explicitly flush if you need to)
bool BDrawLine( float xPos0, float yPos0, DWORD dwColor0, float xPos1, float yPos1, DWORD dwColor1 );
// Flush the line buffer
bool BFlushLineBuffer();
// Draw a point, the engine itself will manage batching these (although you can explicitly flush if you need to)
bool BDrawPoint( float xPos, float yPos, DWORD dwColor );
// Flush the point buffer
bool BFlushPointBuffer();
// Draw a filled quad
bool BDrawFilledRect( float xPos0, float yPos0, float xPos1, float yPos1, DWORD dwColor );
// Draw a textured rectangle
bool BDrawTexturedRect( float xPos0, float yPos0, float xPos1, float yPos1,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture );
// Draw a textured arbitrary quad
bool BDrawTexturedQuad( float xPos0, float yPos0, float xPos1, float yPos1, float xPos2, float yPos2, float xPos3, float yPos3,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture );
// Flush any still cached quad buffers
bool BFlushQuadBuffer();
// Get the current state of a key
bool BIsKeyDown( DWORD dwVK );
// Get the first (in some arbitrary order) key down, if any
bool BGetFirstKeyDown( DWORD *pdwVK );
// Return true if there is an active Steam Controller
bool BIsSteamInputDeviceActive( );
// Find an active Steam controller
void FindActiveSteamInputDevice( );
// Get the current state of a controller action
bool BIsControllerActionActive( ECONTROLLERDIGITALACTION dwAction );
// Get the current state of a controller action
void GetControllerAnalogAction( ECONTROLLERANALOGACTION dwAction, float *x, float *y );
// Set the current Steam Controller Action set
void SetSteamControllerActionSet( ECONTROLLERACTIONSET dwActionSet );
// Set an Action Set Layer for Steam Input
virtual void ActivateSteamControllerActionSetLayer( ECONTROLLERACTIONSET dwActionSet );
virtual void DeactivateSteamControllerActionSetLayer( ECONTROLLERACTIONSET dwActionSet );
// Returns whether a given action set layer is active
virtual bool BIsActionSetLayerActive( ECONTROLLERACTIONSET dwActionSetLayer );
// These calls return a string describing which controller button the action is currently bound to
const char *GetTextStringForControllerOriginDigital( ECONTROLLERACTIONSET dwActionSet, ECONTROLLERDIGITALACTION dwDigitalAction );
const char *GetTextStringForControllerOriginAnalog( ECONTROLLERACTIONSET dwActionSet, ECONTROLLERANALOGACTION dwDigitalAction );
// Set the controller LED Color, if available
void SetControllerColor( uint8 nColorR, uint8 nColorG, uint8 nColorB, unsigned int nFlags );
// Set the trigger effect on DualSense controllers
void SetTriggerEffect( bool bEnabled );
// Trigger a vibration on the controller, if available
void TriggerControllerVibration( unsigned short nLeftSpeed, unsigned short nRightSpeed );
// Trigger haptics on the specified pad of the controller, if available
void TriggerControllerHaptics( ESteamControllerPad ePad, unsigned short usOnMicroSec, unsigned short usOffMicroSec, unsigned short usRepeat );
// Initialize the Steam Controller interfaces
void InitSteamInput( );
// Called each frame to update the Steam Input interface
void PollSteamInput();
// Get current tick count for the game engine
uint64 GetGameTickCount() { return m_ulGameTickCount; }
// Get the tick count elapsed since the previous frame
// bugbug - We use this time to compute things like thrust and acceleration in the game,
// so it's important in doesn't jump ahead by large increments... Need a better
// way to handle that.
uint64 GetGameTicksFrameDelta() { return m_ulGameTickCount - m_ulPreviousGameTickCount; }
// Tell the game engine to update current tick count
void UpdateGameTickCount();
// Tell the game engine to sleep for a bit if needed to limit frame rate
bool BSleepForFrameRateLimit( uint32 ulMaxFrameRate );
// Check if the game engine hwnd currently has focus (and a working d3d device)
bool BGameEngineHasFocus() { return true; }
// Voice chat functions
virtual HGAMEVOICECHANNEL HCreateVoiceChannel();
virtual void DestroyVoiceChannel( HGAMEVOICECHANNEL hChannel );
virtual bool AddVoiceData( HGAMEVOICECHANNEL hChannel, const uint8 *pVoiceData, uint32 uLength );
void AdjustViewport();
// Initialize graphics
bool BInitializeGraphics();
// Initialize the debug font library
bool BInitializeCellDbgFont();
bool BInitializeAudio();
void RunAudio();
void UpdateKey( uint32_t vkKey, int nDown );
// Tracks whether the engine is ready for use
bool m_bEngineReadyForUse;
// Tracks if we are shutting down
bool m_bShuttingDown;
// The SDL window
SDL_Window *m_window;
SDL_GLContext m_context;
// Size of the window to display the game in
int32 m_nWindowWidth;
int32 m_nWindowHeight;
// Current game time in milliseconds
uint64 m_ulGameTickCount;
// Game time at the start of the previous frame
uint64 m_ulPreviousGameTickCount;
// White texture used when drawing filled quads
HGAMETEXTURE m_hTextureWhite;
// Pointer to actual data for points
GLfloat *m_rgflPointsData;
GLubyte *m_rgflPointsColorData;
// How many points are outstanding needing flush
DWORD m_dwPointsToFlush;
// Pointer to actual data for lines
GLfloat *m_rgflLinesData;
GLubyte *m_rgflLinesColorData;
// How many lines are outstanding needing flush
DWORD m_dwLinesToFlush;
// Pointer to actual data for quads
GLfloat *m_rgflQuadsData;
GLubyte *m_rgflQuadsColorData;
GLfloat *m_rgflQuadsTextureData;
// How many lines are outstanding needing flush
DWORD m_dwQuadsToFlush;
// Map of font handles we have given out
HGAMEFONT m_nNextFontHandle;
std::map< HGAMEFONT, TTF_Font * > m_MapGameFonts;
std::map< std::string, HGAMETEXTURE > m_MapStrings;
// Map of handles to texture objects
struct TextureData_t
{
uint32 m_uWidth;
uint32 m_uHeight;
GLuint m_uTextureID;
};
std::map<HGAMETEXTURE, TextureData_t> m_MapTextures;
HGAMETEXTURE m_nNextTextureHandle;
// Last bound texture, used to know when we must flush
HGAMETEXTURE m_hLastTexture;
// Map of button state, translated to VK for win32.
std::set< DWORD > m_SetKeysDown;
ALCcontext* m_palContext;
ALCdevice* m_palDevice;
// Map of voice handles
std::map<HGAMEVOICECHANNEL, CVoiceContext* > m_MapVoiceChannel;
uint32 m_unVoiceChannelCount;
// An array of handles to Steam Controller events that player can bind to controls
InputDigitalActionHandle_t m_ControllerDigitalActionHandles[eControllerDigitalAction_NumActions];
// An array of handles to Steam Controller events that player can bind to controls
InputAnalogActionHandle_t m_ControllerAnalogActionHandles[eControllerAnalogAction_NumActions];
// An array of handles to different Steam Controller action set configurations
InputActionSetHandle_t m_ControllerActionSetHandles[eControllerActionSet_NumSets];
// A handle to the currently active Steam Controller.
InputHandle_t m_ActiveControllerHandle;
// Origins for all the Steam Input actions. The 'origin' is where the action is currently bound to,
// ie 'jump' is currently bound to the Steam Controller 'A' button.
EInputActionOrigin m_ControllerDigitalActionOrigins[eControllerDigitalAction_NumActions];
EInputActionOrigin m_ControllerAnalogActionOrigins[eControllerDigitalAction_NumActions];
static const char *pOriginStrings[k_EControllerActionOrigin_Count];
};
#endif // GAMEENGINESDL_H
File diff suppressed because it is too large Load Diff
+468
View File
@@ -0,0 +1,468 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Main class for the game engine -- win32 implementation
//
// $NoKeywords: $
//=============================================================================
#ifndef GAMEENGINEWIN32_H
#define GAMEENGINEWIN32_H
#include "GameEngine.h"
#include <set>
#include <map>
// How big is the vertex buffer for batching lines in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define LINE_BUFFER_TOTAL_SIZE 1000
// How many lines do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define LINE_BUFFER_BATCH_SIZE 250
// How big is the vertex buffer for batching points in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define POINT_BUFFER_TOTAL_SIZE 1800
// How many points do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define POINT_BUFFER_BATCH_SIZE 600
// How big is the vertex buffer for batching quads in total?
// NOTE: This must be a multiple of the batch size below!!! (crashes will occur if it isn't)
#define QUAD_BUFFER_TOTAL_SIZE 1000
// How many quads do we put in the buffer in between flushes?
//
// This should be enough smaller than the total size so that draw calls
// can finish using the data before we wrap around and discard it.
#define QUAD_BUFFER_BATCH_SIZE 250
// Vertex struct for line batches
struct LineVertex_t
{
float x, y, z, rhw;
DWORD color;
};
// Vertex struct for point batches
struct PointVertex_t
{
float x, y, z, rhw;
DWORD color;
};
// Vertex struct for textured quads in pixel space
struct TexturedQuadVertex_t
{
float x, y, z, rhw;
DWORD color;
float u, v; // texture coordinates
};
// Vertex struct for textured quads in 3D space
struct Textured3DQuadVertex_t
{
float x, y, z;
DWORD color;
float u, v; // texture coordinates
};
class CVoiceContext;
// WndProc declaration
LRESULT CALLBACK GameWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );
class CGameEngineWin32 : public IGameEngine
{
public:
// Static methods for tracing mapping of game engine class instances to hwnds
static CGameEngineWin32 * FindEngineInstanceForHWND( HWND hWnd );
static void AddInstanceToHWNDMap( CGameEngineWin32* pInstance, HWND hWnd );
static void RemoveInstanceFromHWNDMap( HWND hWnd );
// Constructor
CGameEngineWin32( HINSTANCE hInstance, int nShowCommand, int32 nWindowWidth, int32 nWindowHeight );
// Destructor
~CGameEngineWin32() { Shutdown(); }
// Check if the game engine is initialized ok and ready for use
bool BReadyForUse() { return m_bEngineReadyForUse; }
// Check if the engine is shutting down
bool BShuttingDown() { return m_bShuttingDown; }
// Set the background color
void SetBackgroundColor( short a, short r, short g, short b );
// Start a frame, clear(), beginscene(), etc
bool StartFrame();
// Finish a frame, endscene(), present(), etc.
void EndFrame();
// Shutdown the game engine
void Shutdown();
// Pump messages from the OS
void MessagePump();
// Accessors for game screen size
int32 GetViewportWidth() { return m_nViewportWidth; }
int32 GetViewportHeight() { return m_nViewportHeight; }
// Function for drawing text to the screen, dwFormat is a combination of flags like DT_LEFT, DT_VCENTER etc...
bool BDrawString( HGAMEFONT hFont, RECT rect, DWORD dwColor, DWORD dwFormat, const char *pchText );
// Create a new font returning our internal handle value for it (0 means failure)
HGAMEFONT HCreateFont( int nHeight, int nFontWeight, bool bItalic, const char * pchFont );
// Create a new texture returning our internal handle value for it (0 means failure)
HGAMETEXTURE HCreateTexture( byte *pRGBAData, uint32 uWidth, uint32 uHeight, ETEXTUREFORMAT eTextureFormat = eTextureFormat_RGBA );
// update an existing texture
bool UpdateTexture( HGAMETEXTURE texture, byte *pRGBAData, uint32 uWidth, uint32 uHeight, ETEXTUREFORMAT eTextureFormat );
// Draw a line, the engine itself will manage batching these (although you can explicitly flush if you need to)
bool BDrawLine( float xPos0, float yPos0, DWORD dwColor0, float xPos1, float yPos1, DWORD dwColor1 );
// Flush the line buffer
bool BFlushLineBuffer();
// Draw a point, the engine itself will manage batching these (although you can explicitly flush if you need to)
bool BDrawPoint( float xPos, float yPos, DWORD dwColor );
// Flush the point buffer
bool BFlushPointBuffer();
// Draw a filled quad
bool BDrawFilledRect( float xPos0, float yPos0, float xPos1, float yPos1, DWORD dwColor );
// Draw a textured rectangle
bool BDrawTexturedRect( float xPos0, float yPos0, float xPos1, float yPos1,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture );
// Draw a textured arbitrary quad
bool BDrawTexturedQuad( float xPos0, float yPos0, float xPos1, float yPos1, float xPos2, float yPos2, float xPos3, float yPos3,
float u0, float v0, float u1, float v1, DWORD dwColor, HGAMETEXTURE hTexture );
// Flush any still cached quad buffers
bool BFlushQuadBuffer();
// Draw a textured rectangle with full 3D points
bool BDraw3DTexturedQuad( Textured3DQuadVertex_t vert[4], HGAMETEXTURE hTexture );
// Flush any still cached quad buffers
bool BFlush3DQuadBuffer();
// sets the texture as the 0th one to draw with
bool BSetTexture( HGAMETEXTURE hTexture );
// sets the texture as a render target.
bool BSetRenderTarget( HGAMETEXTURE hTexture );
// sets the render target back to the frame buffer
bool BUnsetRenderTarget();
// make sure the texture is created on the device and ready to use
bool BReadyTexture( HGAMETEXTURE hTexture );
// Get the current state of a key
bool BIsKeyDown( DWORD dwVK );
// Get the first (in some arbitrary order) key down, if any
bool BGetFirstKeyDown( DWORD *pdwVK );
// Return true if there is an active Steam Controller
bool BIsSteamInputDeviceActive( );
// Find an active Steam controller
void FindActiveSteamInputDevice( );
// Get the current state of a controller action
bool BIsControllerActionActive( ECONTROLLERDIGITALACTION dwAction );
// Get the current state of a controller action
void GetControllerAnalogAction( ECONTROLLERANALOGACTION dwAction, float *x, float *y );
// Set the current Steam Controller Action set
void SetSteamControllerActionSet( ECONTROLLERACTIONSET dwActionSet );
// Set an Action Set Layer for Steam Input
virtual void ActivateSteamControllerActionSetLayer( ECONTROLLERACTIONSET dwActionSet );
virtual void DeactivateSteamControllerActionSetLayer( ECONTROLLERACTIONSET dwActionSet );
// Returns whether a given action set layer is active
virtual bool BIsActionSetLayerActive( ECONTROLLERACTIONSET dwActionSetLayer );
// These calls return a string describing which controller button the action is currently bound to
const char *GetTextStringForControllerOriginDigital( ECONTROLLERACTIONSET dwActionSet, ECONTROLLERDIGITALACTION dwDigitalAction );
const char *GetTextStringForControllerOriginAnalog( ECONTROLLERACTIONSET dwActionSet, ECONTROLLERANALOGACTION dwDigitalAction );
// Set the controller LED Color, if available
void SetControllerColor( uint8 nColorR, uint8 nColorG, uint8 nColorB, unsigned int nFlags );
// Set the trigger effect on DualSense controllers
void SetTriggerEffect( bool bEnabled );
// Trigger a vibration on the controller, if available
void TriggerControllerVibration( unsigned short nLeftSpeed, unsigned short nRightSpeed );
// Trigger haptics on the specified pad of the controller, if available
void TriggerControllerHaptics( ESteamControllerPad ePad, unsigned short usOnMicroSec, unsigned short usOffMicroSec, unsigned short usRepeat );
// Initialize the Steam Controller interfaces
void InitSteamInput( );
// Called each frame to update the Steam Controller interface
void PollSteamInput();
// Get current tick count for the game engine
uint64 GetGameTickCount() { return m_ulGameTickCount; }
// Get the tick count elapsed since the previous frame
// bugbug - We use this time to compute things like thrust and acceleration in the game,
// so it's important in doesn't jump ahead by large increments... Need a better
// way to handle that.
uint64 GetGameTicksFrameDelta() { return m_ulGameTickCount - m_ulPreviousGameTickCount; }
// Tell the game engine to update current tick count
void UpdateGameTickCount();
// Tell the game engine to sleep for a bit if needed to limit frame rate
bool BSleepForFrameRateLimit( uint32 ulMaxFrameRate );
// Check if the game engine hwnd currently has focus (and a working d3d device)
bool BGameEngineHasFocus() { return ::GetForegroundWindow() == m_hWnd && !m_bDeviceLost; }
// voice chat sound engine
virtual HGAMEVOICECHANNEL HCreateVoiceChannel();
virtual void DestroyVoiceChannel( HGAMEVOICECHANNEL hChannel );
virtual bool AddVoiceData( HGAMEVOICECHANNEL hChannel, const uint8 *pVoiceData, uint32 uLength );
// Track the state of keyboard input (these are public, but not part of the public interface)
void RecordKeyDown( DWORD dwVK );
void RecordKeyUp( DWORD dwVK );
private:
// Creates the hwnd for the game
bool BCreateGameWindow( int nShowCommand );
// Initializes D3D for the game
bool BInitializeD3D9();
// Resets all the render, texture, and sampler states to our defaults
void ResetRenderStates();
// Create a new vertex buffer returning our internal handle for it (0 means failure)
HGAMEVERTBUF HCreateVertexBuffer( uint32 nSizeInBytes, DWORD dwUsage, DWORD dwFVF );
// Lock an entire vertex buffer with the specified flags
bool BLockEntireVertexBuffer( HGAMEVERTBUF hVertBuf, void **ppVoid, DWORD dwFlags );
// Unlock a vertex buffer
bool BUnlockVertexBuffer( HGAMEVERTBUF hVertBuf );
// Release a vertex buffer and free its resources
bool BReleaseVertexBuffer( HGAMEVERTBUF hVertBuf );
// Set steam source
bool BSetStreamSource( HGAMEVERTBUF hVertBuf, uint32 uOffset, uint32 uStride );
// Render primitives out of the current stream source
bool BRenderPrimitive( D3DPRIMITIVETYPE primType, uint32 uStartVertex, uint32 uCount );
// Set vertex format
bool BSetFVF( DWORD dwFormat );
// Handle losing the d3d device (ie, release resources)
bool BHandleLostDevice();
// Handle reseting the d3d device (ie, acquire resources again)
bool BHandleResetDevice();
private:
// Tracks whether the engine is ready for use
bool m_bEngineReadyForUse;
// Tracks if we are shutting down
bool m_bShuttingDown;
// Color we clear the background of the window to each frame
DWORD m_dwBackgroundColor;
// HInstance for the application running the engine
HINSTANCE m_hInstance;
// HWND for the engine instance
HWND m_hWnd;
// IDirect3D9 interface
IDirect3D9 *m_pD3D9Interface;
// IDirect3DDevice9 interface
IDirect3DDevice9 *m_pD3D9Device;
// Depth/stencil surface associated with the back buffer
IDirect3DSurface9 *m_pBackbufferDepth;
// Size of the window to display the game in
int32 m_nWindowWidth;
int32 m_nWindowHeight;
// Size of actual d3d viewport (window size minus borders, title, etc)
int32 m_nViewportWidth;
int32 m_nViewportHeight;
// Next font handle value to give out
HGAMEFONT m_nNextFontHandle;
// Map of font handles to font objects
std::map<HGAMEFONT, ID3DXFont *> m_MapFontInstances;
// Next vertex buffer handle value to give out
HGAMEVERTBUF m_nNextVertBufferHandle;
// Map of handles to vertex buffer objects
struct VertBufData_t
{
bool m_bIsLocked;
IDirect3DVertexBuffer9 * m_pBuffer;
};
std::map<HGAMEVERTBUF, VertBufData_t> m_MapVertexBuffers;
HGAMETEXTURE m_nNextTextureHandle;
// Map of handles to texture objects
struct TextureData_t
{
byte *m_pRGBAData; // We keep a copy of the raw data so we can rebuild textures after a device is lost
uint32 m_uWidth;
uint32 m_uHeight;
LPDIRECT3DTEXTURE9 m_pTexture;
LPDIRECT3DSURFACE9 m_pDepthSurface; // render targets only
D3DFORMAT m_eFormat; // format for the texture on the card itself
ETEXTUREFORMAT m_eTextureFormat; // format of the data you provide
};
std::map<HGAMETEXTURE, TextureData_t> m_MapTextures;
// Vertex buffer for textured quads
HGAMEVERTBUF m_hQuadBuffer;
// Last texture used in drawing a batched quad
HGAMETEXTURE m_hLastTexture;
// Pointer to quad vertex data
TexturedQuadVertex_t *m_pQuadVertexes;
// How many quads are awaiting flushing
DWORD m_dwQuadsToFlush;
// Where does the current batch begin
DWORD m_dwQuadBufferBatchPos;
// Vertex buffer for textured quads
HGAMEVERTBUF m_h3DQuadBuffer;
// Last texture used in drawing a batched quad
HGAMETEXTURE m_h3DLastTexture;
// Pointer to quad 3D vertex data
Textured3DQuadVertex_t *m_p3DQuadVertexes;
// How many 3D quads are awaiting flushing
DWORD m_dw3DQuadsToFlush;
// Where does the current 3D batch begin
DWORD m_dw3DQuadBufferBatchPos;
// White texture used when drawing filled quads
HGAMETEXTURE m_hTextureWhite;
// Currently set FVF format
DWORD m_dwCurrentFVF;
// Map of key state
std::set<DWORD> m_SetKeysDown;
// Current game time in milliseconds
uint64 m_ulGameTickCount;
// Game time at the start of the previous frame
uint64 m_ulPreviousGameTickCount;
// Divisor for turning QPC values to milliseconds
uint64 m_ulPerfCounterToMillisecondsDivisor;
// First value for QPC when we started the process
uint64 m_ulFirstQueryPerformanceCounterValue;
// Map of engine instances by HWND, used in wndproc to find engine instance for messages
static std::map<HWND, CGameEngineWin32 *> m_MapEngineInstances;
// Internal vertex buffer for batching line drawing
HGAMEVERTBUF m_hLineBuffer;
// Pointer to actual line buffer memory (valid only while locked)
LineVertex_t *m_pLineVertexes;
// Track how many lines are awaiting flushing in our line buffer
DWORD m_dwLinesToFlush;
// Track where the current batch starts in the vert buffer
DWORD m_dwLineBufferBatchPos;
// Internal vertex buffer for batching point drawing
HGAMEVERTBUF m_hPointBuffer;
// Pointer to actual point buffer memory (valid only while locked)
PointVertex_t *m_pPointVertexes;
// Track how many points are awaiting flushing in our line buffer
DWORD m_dwPointsToFlush;
// Track where the current batch starts in the vert buffer
DWORD m_dwPointBufferBatchPos;
// Track if we have lost the d3d device
bool m_bDeviceLost;
// Presentation parameters, saved in case of lost device needing reset
D3DPRESENT_PARAMETERS m_d3dpp;
IXAudio2* m_pXAudio2;
IXAudio2MasteringVoice* m_pMasteringVoice;
// Map of font handles to font objects
std::map<HGAMEVOICECHANNEL, CVoiceContext* > m_MapVoiceChannel;
uint32 m_unVoiceChannelCount;
// An array of handles to Steam Controller events that player can bind to controls
InputDigitalActionHandle_t m_ControllerDigitalActionHandles[eControllerDigitalAction_NumActions];
// An array of handles to Steam Controller events that player can bind to controls
InputAnalogActionHandle_t m_ControllerAnalogActionHandles[eControllerAnalogAction_NumActions];
// An array of handles to different Steam Controller action set configurations
InputActionSetHandle_t m_ControllerActionSetHandles[eControllerActionSet_NumSets];
// A handle to the currently active Steam Controller.
InputHandle_t m_ActiveControllerHandle;
// Origins for all the Steam Input actions. The 'origin' is where the action is currently bound to,
// ie 'jump' is currently bound to the Steam Controller 'A' button.
EInputActionOrigin m_ControllerDigitalActionOrigins[eControllerDigitalAction_NumActions];
EInputActionOrigin m_ControllerAnalogActionOrigins[eControllerDigitalAction_NumActions];
};
#endif // GAMEENGINEWIN32_H
File diff suppressed because it is too large Load Diff
+46
View File
@@ -0,0 +1,46 @@
#ifdef __OBJC__ // this declaration only appears for files compiling with objc enabled
#import <Cocoa/Cocoa.h>
#import <OpenGL/gl.h>
#import <OpenGL/glext.h>
#import <OpenGL/OpenGL.h>
#import <OpenGL/CGLContext.h>
@interface GLString : NSObject {
CGLContextObj cgl_ctx; // current context at time of texture creation
GLuint texName;
NSSize texSize;
NSAttributedString * string;
NSFont * font;
NSColor * textColor; // default is opaque white
NSRect border;
uint32_t flags;
BOOL requiresUpdate;
}
- (id) initWithString:(NSString *)aString withFont:(NSFont *)inFont withTextColor:(NSColor *)color inBox:(NSRect *)box withFlags:(uint32_t) inFlags;
- (void) dealloc;
- (GLuint) texName; // 0 if no texture allocated
- (NSSize) texSize; // actually size of texture generated in texels, (0, 0) if no texture allocated
- (NSColor *) textColor; // get the pre-multiplied default text color (includes alpha) string attributes could override this
- (NSRect) border; // bounds for rect
- (NSFont *)font;
- (uint32_t) flags; // get the pre-multiplied default text color (includes alpha) string attributes could override this
- (void) setFont:(NSFont *)inFont;
- (void) setColor:(NSColor *)color;
- (void) setBox:(NSRect *)box;
- (void) setFlags:(uint32_t) inFlags;
- (void) genTexture; // generates the texture without drawing texture to current context
- (void) drawWithBounds:(NSRect)bounds; // will update the texture if required due to change in settings (note context should be setup to be orthographic scaled to per pixel scale)
- (void) drawAtPoint:(NSPoint)point;
@end
#endif
+255
View File
@@ -0,0 +1,255 @@
#include "stdafx.h"
#include "GameEngine.h"
#import "glstringosx.h"
// GLString follows
@implementation GLString
- (void) deleteTexture
{
if (texName && cgl_ctx) {
(*cgl_ctx->disp.delete_textures)(cgl_ctx->rend, 1, &texName);
texName = 0; // ensure it is zeroed for failure cases
cgl_ctx = 0;
}
}
- (void) dealloc
{
[self deleteTexture];
[textColor release];
[string release];
[super dealloc];
}
// designated initializer
- (id) initWithString:(NSString *)aString withFont:(NSFont *) inFont withTextColor:(NSColor *)color inBox:(NSRect *)box withFlags:(uint32_t) inFlags
{
[super init];
cgl_ctx = NULL;
texName = 0;
texSize.width = 0.0f;
texSize.height = 0.0f;
[color retain];
textColor = color;
[inFont retain];
font = inFont;
flags = inFlags;
NSMutableDictionary *attribs = [NSMutableDictionary dictionary];
[attribs setObject: font forKey: NSFontAttributeName];
[attribs setObject: textColor forKey: NSForegroundColorAttributeName];
string = [[NSAttributedString alloc] initWithString:aString attributes:attribs];
border = *box;
requiresUpdate = YES;
return self;
}
- (void) setFont:(NSFont *)inFont
{
if ( [font isEqual: inFont] )
return;
[string release];
[font release];
[inFont retain];
font = inFont;
NSMutableDictionary *attribs = [NSMutableDictionary dictionary];
[attribs setObject: font forKey: NSFontAttributeName];
[attribs setObject: textColor forKey: NSForegroundColorAttributeName];
string = [[NSAttributedString alloc] initWithString:[string string] attributes:attribs];
requiresUpdate = YES;
}
- (void) setColor:(NSColor *)color
{
if ( [textColor isEqual:color] )
return;
[string release];
[textColor release];
[color retain];
textColor = color;
NSMutableDictionary *attribs = [NSMutableDictionary dictionary];
[attribs setObject: font forKey: NSFontAttributeName];
[attribs setObject: textColor forKey: NSForegroundColorAttributeName];
string = [[NSAttributedString alloc] initWithString:[string string] attributes:attribs];
requiresUpdate = YES;
}
- (void) setBox:(NSRect *)box
{
if ( NSEqualRects(border, *box ) )
return;
border = *box;
requiresUpdate = YES;
}
- (void) setFlags:(uint32_t) inFlags
{
if ( inFlags == flags )
return;
flags = inFlags;
requiresUpdate = YES;
}
// generates the texture without drawing texture to current context
- (void) genTexture
{
NSSize previousSize = texSize;
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
pixelsWide:border.size.width
pixelsHigh:border.size.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bytesPerRow:border.size.width * 4
bitsPerPixel:0];
[textColor set];
float x = 0.0f;
float y = (border.size.height - [string size].height)/2;
if ( flags & TEXTPOS_CENTER )
x = (border.size.width - [string size].width)/2;
else if ( flags & TEXTPOS_RIGHT )
x = border.size.width - [string size].width;
[NSGraphicsContext saveGraphicsState];
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
[context setShouldAntialias:YES];
[NSGraphicsContext setCurrentContext:context];
[string drawAtPoint:NSMakePoint(x, y)]; // draw at offset position
[NSGraphicsContext restoreGraphicsState];
texSize.width = [bitmap pixelsWide];
texSize.height = [bitmap pixelsHigh];
if ( (cgl_ctx = CGLGetCurrentContext () ) )
{ // if we successfully retrieve a current context (required)
glPushAttrib(GL_TEXTURE_BIT);
if (0 == texName) glGenTextures (1, &texName);
glBindTexture (GL_TEXTURE_RECTANGLE_EXT, texName);
if (NSEqualSizes(previousSize, texSize)) {
glTexSubImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, 0, 0, texSize.width, texSize.height, [bitmap hasAlpha] ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, [bitmap bitmapData]);
} else {
glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, GL_RGBA, texSize.width, texSize.height, 0, [bitmap hasAlpha] ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, [bitmap bitmapData]);
}
glPopAttrib();
}
else
{
NSLog (@"-genTexture: Failure to get current OpenGL context\n");
}
[bitmap release];
requiresUpdate = NO;
}
- (GLuint) texName
{
return texName;
}
- (NSSize) texSize
{
return texSize;
}
- (void) setTextColor:(NSColor *)color // set default text color
{
[color retain];
[textColor release];
textColor = color;
requiresUpdate = YES;
}
- (NSColor *) textColor
{
return textColor;
}
- (NSRect) border
{
return border;
}
- (NSFont *)font
{
return font;
}
- (uint32_t) flags
{
return flags;
}
- (void) drawWithBounds:(NSRect)bounds
{
if (requiresUpdate)
[self genTexture];
if (texName)
{
glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_COLOR_BUFFER_BIT); // GL_COLOR_BUFFER_BIT for glBlendFunc, GL_ENABLE_BIT for glEnable / glDisable
glDisable (GL_DEPTH_TEST); // ensure text is not remove by depth buffer test.
glEnable (GL_BLEND); // for text fading
glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // ditto
glEnable (GL_TEXTURE_RECTANGLE_EXT);
glBindTexture (GL_TEXTURE_RECTANGLE_EXT, texName);
glBegin (GL_QUADS);
glTexCoord2f (0.0f, 0.0f); // draw upper left in world coordinates
glVertex2f (bounds.origin.x, bounds.origin.y);
glTexCoord2f (0.0f, texSize.height); // draw lower left in world coordinates
glVertex2f (bounds.origin.x, bounds.origin.y + bounds.size.height);
glTexCoord2f (texSize.width, texSize.height); // draw upper right in world coordinates
glVertex2f (bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height);
glTexCoord2f (texSize.width, 0.0f); // draw lower right in world coordinates
glVertex2f (bounds.origin.x + bounds.size.width, bounds.origin.y);
glEnd ();
glPopAttrib();
}
}
- (void) drawAtPoint:(NSPoint)point
{
if (requiresUpdate)
[self genTexture]; // ensure size is calculated for bounds
if (texName) // if successful
[self drawWithBounds:NSMakeRect (point.x, point.y, texSize.width, texSize.height)];
}
@end
+224
View File
@@ -0,0 +1,224 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class to render a HTML page on the screen
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "htmlsurface.h"
#include "SpaceWarClient.h"
#define HTML_TEXT_HEIGHT 20
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CHTMLSurface::CHTMLSurface( IGameEngine *pGameEngine )
{
m_pGameEngine = pGameEngine;
m_unBrowserHandle = INVALID_HTMLBROWSER;
m_hHTMLTexture = -1;
m_unHTMLWide = m_pGameEngine->GetViewportWidth() - 100;
m_unHTMLTall = m_pGameEngine->GetViewportHeight() - 100;
SteamHTMLSurface()->Init();
SteamHTMLSurface()->SetSize( m_unBrowserHandle, m_unHTMLWide, m_unHTMLTall );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CHTMLSurface::~CHTMLSurface()
{
if ( m_unBrowserHandle )
SteamHTMLSurface()->RemoveBrowser( m_unBrowserHandle );
m_unBrowserHandle = INVALID_HTMLBROWSER;
}
//-----------------------------------------------------------------------------
// Purpose: RunFrame
//-----------------------------------------------------------------------------
void CHTMLSurface::RunFrame()
{
if ( m_pGameEngine->BIsKeyDown( VK_ESCAPE ) ||
m_pGameEngine->BIsControllerActionActive( eControllerDigitalAction_MenuCancel ) )
{
SpaceWarClient()->SetGameState( k_EClientGameMenu );
}
}
//-----------------------------------------------------------------------------
// Purpose: draw the page
//-----------------------------------------------------------------------------
void CHTMLSurface::Render()
{
if (m_hHTMLTexture >= 0)
{
RECT rect;
rect.left = 50;
rect.top = 50;
rect.right = m_unHTMLWide + rect.left;
rect.bottom = m_unHTMLTall + rect.top;
m_pGameEngine->BDrawTexturedRect( (float)rect.left, (float)rect.top, (float)rect.right, (float)rect.bottom,
0.0f, 0.0f, 1.0, 1.0, D3DCOLOR_ARGB( 255, 255, 255, 255 ), m_hHTMLTexture );
}
RECT rect;
rect.top = m_unHTMLTall + 70;
rect.bottom = rect.top + HTML_TEXT_HEIGHT;
rect.left = m_unHTMLWide/2 - 200;
rect.right = rect.left + 400;
char rgchBuffer[256];
sprintf_safe( rgchBuffer, "Hit ESC to return to main menu" );
m_pGameEngine->BDrawString( m_hDisplayFont, rect, D3DCOLOR_ARGB( 255, 25, 200, 25 ), TEXTPOS_CENTER | TEXTPOS_VCENTER, rgchBuffer );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHTMLSurface::Show()
{
m_hDisplayFont = m_pGameEngine->HCreateFont(HTML_TEXT_HEIGHT, FW_MEDIUM, false, "Arial");
if (!m_hDisplayFont)
OutputDebugString("RemoteStorage font was not created properly, text won't draw\n");
SteamAPICall_t hSteamAPICall = SteamHTMLSurface()->CreateBrowser( "SpaceWars Test", NULL );
m_SteamCallResultBrowserReady.Set( hSteamAPICall, this, &CHTMLSurface::OnBrowserReady );
}
//-----------------------------------------------------------------------------
// Purpose: the page asked to be closed
//-----------------------------------------------------------------------------
void CHTMLSurface::OnCloseBrowser( HTML_CloseBrowser_t *pParam )
{
m_unBrowserHandle = INVALID_HTMLBROWSER;
}
//-----------------------------------------------------------------------------
// Purpose: the browser is ready to load pages and start sending us textures to render
//-----------------------------------------------------------------------------
void CHTMLSurface::OnBrowserReady( HTML_BrowserReady_t *pBrowserReady, bool bIOFailure )
{
if (bIOFailure)
return;
m_unBrowserHandle = pBrowserReady->unBrowserHandle;
SteamHTMLSurface()->SetSize( m_unBrowserHandle, m_unHTMLWide, m_unHTMLTall );
SteamHTMLSurface()->SetDPIScalingFactor( m_unBrowserHandle, 2.0f );
SteamHTMLSurface()->LoadURL( m_unBrowserHandle, "http://steamcommunity.com/", NULL );
}
//-----------------------------------------------------------------------------
// Purpose: we have a new texture to present
//-----------------------------------------------------------------------------
void CHTMLSurface::OnNeedsPaint( HTML_NeedsPaint_t *pParam )
{
if ( m_hHTMLTexture < 0 )
m_hHTMLTexture = m_pGameEngine->HCreateTexture( (byte *)pParam->pBGRA, pParam->unWide, pParam->unTall, eTextureFormat_BGRA );
else
m_pGameEngine->UpdateTexture( m_hHTMLTexture, (byte *)pParam->pBGRA, pParam->unWide, pParam->unTall, eTextureFormat_BGRA );
if (pParam->unWide != m_unHTMLWide)
OutputDebugString( "bad texture width for html\n" );
if (pParam->unTall != m_unHTMLTall)
OutputDebugString( "bad texture height for html\n" );
}
//-----------------------------------------------------------------------------
// Purpose: the underlying browser object restarted, update our handle if needed
//-----------------------------------------------------------------------------
void CHTMLSurface::OnBrowserRestarted( HTML_BrowserRestarted_t *pParam )
{
if ( pParam->unOldBrowserHandle == m_unBrowserHandle )
{
HTML_BrowserReady_t ready;
ready.unBrowserHandle = pParam->unBrowserHandle;;
OnBrowserReady( &ready, false );
}
}
//-----------------------------------------------------------------------------
// Purpose: the page requested that a URL be loaded, should we allow it?
//-----------------------------------------------------------------------------
void CHTMLSurface::OnStartRequest( HTML_StartRequest_t *pParam )
{
// MUST call AllowStartRequest once for every OnStartRequest callback!
SteamHTMLSurface()->AllowStartRequest( m_unBrowserHandle, true );
}
//-----------------------------------------------------------------------------
// Purpose: the page has requested a modal javascript message box
//-----------------------------------------------------------------------------
void CHTMLSurface::OnJSAlert( HTML_JSAlert_t *pParam )
{
// MUST call JSDialogResponse once for every OnJSAlert callback!
// ShowModalMessageBox( pParam->pchMessage );
SteamHTMLSurface()->JSDialogResponse( m_unBrowserHandle, true );
}
//-----------------------------------------------------------------------------
// Purpose: the page has requested a modal javascript yes/no dialog box
//-----------------------------------------------------------------------------
void CHTMLSurface::OnJSConfirm( HTML_JSConfirm_t *pParam )
{
// MUST call JSDialogResponse once for every OnJSConfirm callback!
// if ( ShowModalYesNoDialogBox( pParam->pchMessage ) == BUTTON_NO );
// SteamHTMLSurface()->JSDialogResponse( m_unBrowserHandle, false );
// else
SteamHTMLSurface()->JSDialogResponse( m_unBrowserHandle, true );
}
//-----------------------------------------------------------------------------
// Purpose: the page has requested a local file upload dialog box.
//-----------------------------------------------------------------------------
void CHTMLSurface::OnUploadLocalFile( HTML_FileOpenDialog_t *pParam )
{
// MUST call FileLoadDialogResponse once for every OnLocalFileBrowse callback!
// Most applications do NOT want to allow the web browser to upload local file
// content from the customer's hard drive to the remote web server! That would
// be a pretty big security hole, unless you carefully vetted every file path.
SteamHTMLSurface()->FileLoadDialogResponse( m_unBrowserHandle, NULL );
// But if you did want to allow it, you would do something like this:
// ... show modal file selection dialog box ...
// ... verify that the selected files are safe to upload ...
// std::vector< const char * > vecUTF8FilenamesArray;
// ... populate vecUTF8FilenamesArray ...
// vecUTF8FilenamesArray.push_back( NULL );
// SteamHTMLSurface()->FileLoadDialogResponse( m_unBrowserHandle, &vecUTF8FilenamesArray[0] );
}
//-----------------------------------------------------------------------------
// Purpose: the page is now fully loaded
//-----------------------------------------------------------------------------
void CHTMLSurface::OnFinishedRequest( HTML_FinishedRequest_t *pParam )
{
// Uncomment this if you want to scale a pages contents when you display it
//SteamHTMLSurface()->SetPageScaleFactor( m_unBrowserHandle, 2.0, 0, 0 );
}
+60
View File
@@ -0,0 +1,60 @@
//========= Copyright © 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose: Class for handling finding servers, getting their details, and displaying
// them inside the game
//
// $NoKeywords: $
//=============================================================================
#ifndef HTMLSURFACE_H
#define HTMLSURFACE_H
#include "SpaceWar.h"
#include "GameEngine.h"
#include "steam/steam_api.h"
#include "steam/isteamhtmlsurface.h"
class CHTMLSurface
{
public:
CHTMLSurface( IGameEngine *pGameEngine );
~CHTMLSurface();
// Run a frame (to handle kb input and such as well as render)
void RunFrame();
void Render();
void Show();
private:
STEAM_CALLBACK( CHTMLSurface, OnStartRequest, HTML_StartRequest_t ); // REQUIRED
STEAM_CALLBACK( CHTMLSurface, OnJSAlert, HTML_JSAlert_t ); // REQUIRED
STEAM_CALLBACK( CHTMLSurface, OnJSConfirm, HTML_JSConfirm_t ); // REQUIRED
STEAM_CALLBACK( CHTMLSurface, OnUploadLocalFile, HTML_FileOpenDialog_t ); // REQUIRED
STEAM_CALLBACK( CHTMLSurface, OnNeedsPaint, HTML_NeedsPaint_t );
STEAM_CALLBACK( CHTMLSurface, OnCloseBrowser, HTML_CloseBrowser_t );
STEAM_CALLBACK( CHTMLSurface, OnFinishedRequest, HTML_FinishedRequest_t );
STEAM_CALLBACK( CHTMLSurface, OnBrowserRestarted, HTML_BrowserRestarted_t );
void OnBrowserReady( HTML_BrowserReady_t *pBrowserReady, bool bIOFailure );
CCallResult< CHTMLSurface, HTML_BrowserReady_t > m_SteamCallResultBrowserReady;
// Pointer to engine instance (so we can draw stuff)
IGameEngine *m_pGameEngine;
HGAMEFONT m_hDisplayFont;
HHTMLBrowser m_unBrowserHandle; // handle to the html surface object
HGAMETEXTURE m_hHTMLTexture; // the texture data for the page
uint32 m_unHTMLWide; // the size of the html page we want to show
uint32 m_unHTMLTall;
};
#endif //HTMLSURFACE_H
+206
View File
@@ -0,0 +1,206 @@
//========= Copyright 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for tracking leaderboards
//
//=============================================================================
#include "stdafx.h"
#include "musicplayer.h"
#include "BaseMenu.h"
#include <math.h>
//-----------------------------------------------------------------------------
// Purpose: Menu that shows a music player
//-----------------------------------------------------------------------------
class CMusicPlayerMenu : public CBaseMenu< MusicPlayerMenuItem_t >
{
public:
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMusicPlayerMenu( IGameEngine *pGameEngine )
: CBaseMenu< MusicPlayerMenuItem_t >( pGameEngine )
, m_menuItemPause( "Pause" )
, m_menuItemPlay( "Play" )
, m_menuItemPlayPrevious( "Play Previous" )
, m_menuItemPlayNext( "Play Next" )
, m_menuItemIncreaseVolume( "Increase Volume" )
, m_menuItemDecreaseVolume( "Decrease Volume" )
, m_menuItemBack( "Back" )
{
}
//-----------------------------------------------------------------------------
// Purpose: Creates menu
//-----------------------------------------------------------------------------
void Rebuild()
{
PushSelectedItem();
ClearMenuItems();
AddMenuItem( CMusicPlayerMenu::MenuItem_t( "Pause", m_menuItemPause ) );
AddMenuItem( CMusicPlayerMenu::MenuItem_t( "Play", m_menuItemPlay ) );
AddMenuItem( CMusicPlayerMenu::MenuItem_t( "Play Previous", m_menuItemPlayPrevious ) );
AddMenuItem( CMusicPlayerMenu::MenuItem_t( "Play Next", m_menuItemPlayNext ) );
AddMenuItem( CMusicPlayerMenu::MenuItem_t( "Increase Volume", m_menuItemIncreaseVolume ) );
AddMenuItem( CMusicPlayerMenu::MenuItem_t( "Decrease Volume", m_menuItemDecreaseVolume ) );
AddMenuItem( CMusicPlayerMenu::MenuItem_t( "Return to main menu", m_menuItemBack ) );
UpdateHeading();
PopSelectedItem();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void UpdateHeading()
{
const char *pchEnabled = "Disabled";
if ( SteamMusic()->BIsEnabled() )
{
pchEnabled = "Enabled";
}
const char *pchPlaybackStatus = "";
AudioPlayback_Status nStatus = SteamMusic()->GetPlaybackStatus();
switch( nStatus )
{
case AudioPlayback_Undefined:
pchPlaybackStatus = "Undefined";
break;
case AudioPlayback_Playing:
pchPlaybackStatus = "Playing";
break;
case AudioPlayback_Paused:
pchPlaybackStatus = "Paused";
break;
case AudioPlayback_Idle:
pchPlaybackStatus = "Done";
break;
};
// Music Volume is between 0.0 and 1.0: multiply by ten, so its equivalent to Big Picture display.
float flVolume = SteamMusic()->GetVolume();
int nVolume = int( flVolume * 10 );
sprintf_safe( m_szHeadingString, "Music: %s Status: %s Volume: %d", pchEnabled, pchPlaybackStatus, nVolume );
SetHeading( m_szHeadingString );
}
//-----------------------------------------------------------------------------
// Purpose: variables
//-----------------------------------------------------------------------------
char m_szHeadingString[255]; // String to show in server browser
MusicPlayerMenuItem_t m_menuItemPause;
MusicPlayerMenuItem_t m_menuItemPlay;
MusicPlayerMenuItem_t m_menuItemPlayPrevious;
MusicPlayerMenuItem_t m_menuItemPlayNext;
MusicPlayerMenuItem_t m_menuItemIncreaseVolume;
MusicPlayerMenuItem_t m_menuItemDecreaseVolume;
MusicPlayerMenuItem_t m_menuItemBack;
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMusicPlayer::CMusicPlayer( IGameEngine *pGameEngine )
: m_pGameEngine( pGameEngine )
, m_CallbackVolumeChanged( this, &CMusicPlayer::OnVolumeChanged )
, m_CallbackPlaybackStatusHasChanged( this, &CMusicPlayer::OnPlaybackStatusHasChanged )
{
m_pMusicPlayerMenu = new CMusicPlayerMenu( pGameEngine );
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame
//-----------------------------------------------------------------------------
void CMusicPlayer::RunFrame()
{
m_pMusicPlayerMenu->RunFrame();
}
//-----------------------------------------------------------------------------
// Purpose: Handles menu actions
//-----------------------------------------------------------------------------
void CMusicPlayer::OnMenuSelection( MusicPlayerMenuItem_t selection )
{
if (selection == m_pMusicPlayerMenu->m_menuItemPlay)
{
SteamMusic()->Play();
}
else if (selection == m_pMusicPlayerMenu->m_menuItemPause)
{
SteamMusic()->Pause();
}
else if (selection == m_pMusicPlayerMenu->m_menuItemPlayPrevious)
{
SteamMusic()->PlayPrevious();
}
else if (selection == m_pMusicPlayerMenu->m_menuItemPlayNext)
{
SteamMusic()->PlayNext();
}
else if (selection == m_pMusicPlayerMenu->m_menuItemIncreaseVolume)
{
// conversion necessary, because the UI in big picture shows 10 bars,
// but volume is a value between 0.0 and 1.0
float flVolume = SteamMusic()->GetVolume();
int nVolume = int( flVolume * 10 );
nVolume = MIN( nVolume + 1, 10 );
SteamMusic()->SetVolume( (float)nVolume * 0.1f );
}
else if (selection == m_pMusicPlayerMenu->m_menuItemDecreaseVolume)
{
// conversion necessary, because the UI in big picture shows 10 bars,
// but volume is a value between 0.0 and 1.0
float flVolume = SteamMusic()->GetVolume();
int nVolume = int( flVolume * 10 );
nVolume = MAX( nVolume - 1, 0 );
SteamMusic()->SetVolume( (float)nVolume * 0.1f );
}
else if (selection == m_pMusicPlayerMenu->m_menuItemBack)
{
SpaceWarClient()->SetGameState(k_EClientGameMenu);
}
}
//-----------------------------------------------------------------------------
// Purpose: Shows / Refreshes
//-----------------------------------------------------------------------------
void CMusicPlayer::Show()
{
m_pMusicPlayerMenu->Rebuild();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMusicPlayer::OnPlaybackStatusHasChanged( PlaybackStatusHasChanged_t *pPlaybackStatusHasChanged )
{
m_pMusicPlayerMenu->UpdateHeading();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMusicPlayer::OnVolumeChanged( VolumeHasChanged_t *pVolumeChanged )
{
m_pMusicPlayerMenu->UpdateHeading();
}
+54
View File
@@ -0,0 +1,54 @@
//========= Copyright © 1996-2009, Valve LLC, All rights reserved. ============
//
// Purpose: Class for controlling the Music Player
//
//=============================================================================
#ifndef MUSICPLAYER_H
#define MUSICPLAYER_H
#include "GameEngine.h"
class CMusicPlayerMenu;
struct MusicPlayerMenuItem_t
{
const char *m_pchCommand;
MusicPlayerMenuItem_t() : m_pchCommand( "" ) {}
MusicPlayerMenuItem_t( const char *pchCommand ) : m_pchCommand( pchCommand ) {}
bool operator==( const MusicPlayerMenuItem_t& rhs ) const
{
return strncmp( m_pchCommand, rhs.m_pchCommand, strlen( m_pchCommand ) ) == 0;
}
};
class CMusicPlayer
{
public:
// Constructor
CMusicPlayer( IGameEngine *pGameEngine );
// Run a frame
void RunFrame();
// shows / refreshes music player
void Show();
// handles input from menu
void OnMenuSelection( MusicPlayerMenuItem_t selection );
private:
IGameEngine *m_pGameEngine;
CMusicPlayerMenu *m_pMusicPlayerMenu;
STEAM_CALLBACK( CMusicPlayer, OnPlaybackStatusHasChanged, PlaybackStatusHasChanged_t, m_CallbackPlaybackStatusHasChanged );
STEAM_CALLBACK( CMusicPlayer, OnVolumeChanged, VolumeHasChanged_t, m_CallbackVolumeChanged );
};
#endif // MUSICPLAYER_H
@@ -0,0 +1 @@
480
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDocumentTypes</key>
<array/>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>com.valvesoftware.steam.steamworksexample</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleURLTypes</key>
<array/>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>${MACOSX_DEPLOYMENT_TARGET}</string>
<key>NSPrincipalClass</key>
<string></string>
<key>NSServices</key>
<array/>
<key>UTExportedTypeDeclarations</key>
<array/>
<key>UTImportedTypeDeclarations</key>
<array/>
</dict>
</plist>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
<true/>
</dict>
</plist>
+282
View File
@@ -0,0 +1,282 @@
//========= Copyright © 1996-2004, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#include "stdafx.h"
#include "SpaceWarClient.h"
#include "p2pauth.h"
//-----------------------------------------------------------------------------
// Purpose: constructor
//-----------------------------------------------------------------------------
CP2PAuthPlayer::CP2PAuthPlayer( IGameEngine *pGameEngine, CSteamID steamID, HSteamNetConnection hServerConn )
: m_CallbackBeginAuthResponse( this, &CP2PAuthPlayer::OnBeginAuthResponse )
, m_steamID( steamID )
, m_hServerConnection( hServerConn )
{
m_pGameEngine = pGameEngine;
m_bSentTicket = false;
m_bSubmittedHisTicket = false;
m_bHaveAnswer = false;
m_ulConnectTime = GetGameTimeInSeconds();
m_cubTicketIGaveThisUser = 0;
m_cubTicketHeGaveMe = 0;
}
//-----------------------------------------------------------------------------
// Purpose: destructor
//-----------------------------------------------------------------------------
CP2PAuthPlayer::~CP2PAuthPlayer()
{
EndGame();
}
//-----------------------------------------------------------------------------
// Purpose: the steam backend has responded
//-----------------------------------------------------------------------------
void CP2PAuthPlayer::OnBeginAuthResponse( ValidateAuthTicketResponse_t *pCallback )
{
if ( m_steamID == pCallback->m_SteamID )
{
char rgch[128];
sprintf( rgch, "P2P:: Received steam response for account=%d\n", m_steamID.GetAccountID() );
OutputDebugString( rgch );
m_ulAnswerTime = GetGameTimeInSeconds();
m_bHaveAnswer = true;
m_eAuthSessionResponse = pCallback->m_eAuthSessionResponse;
}
}
void CP2PAuthPlayer::StartAuthPlayer()
{
// Create a ticket if we haven't yet
if ( m_cubTicketIGaveThisUser == 0 )
{
SteamNetworkingIdentity snid;
snid.SetSteamID( m_steamID );
m_hAuthTicketIGaveThisUser = SteamUser()->GetAuthSessionTicket( m_rgubTicketIGaveThisUser, sizeof( m_rgubTicketIGaveThisUser ), &m_cubTicketIGaveThisUser, &snid );
}
// Send the ticket to the server. It will relay to the client
MsgP2PSendingTicket_t msg;
msg.SetToken( m_rgubTicketIGaveThisUser, m_cubTicketIGaveThisUser );
msg.SetSteamID( m_steamID.ConvertToUint64() );
int64 nIgnoreMessageID;
if ( SteamNetworkingSockets()->SendMessageToConnection( m_hServerConnection, &msg, sizeof(msg), k_nSteamNetworkingSend_Reliable, &nIgnoreMessageID ) == k_EResultOK )
{
m_bSentTicket = true;
}
// start a timer on this, if we dont get a ticket back within reasonable time, mark him timed out
m_ulTicketTime = GetGameTimeInSeconds();
}
//-----------------------------------------------------------------------------
// Purpose: is this auth ok?
//-----------------------------------------------------------------------------
bool CP2PAuthPlayer::BIsAuthOk()
{
if ( m_steamID.IsValid() )
{
// Timeout if we fail to establish communication with this player
if ( !m_bSentTicket && !m_bSubmittedHisTicket )
{
if ( GetGameTimeInSeconds() - m_ulConnectTime > 30 )
{
char rgch[128];
sprintf( rgch, "P2P:: Nothing received for account=%d\n", m_steamID.GetAccountID() );
OutputDebugString( rgch );
return false;
}
}
// first ticket check: if i submitted his ticket - was it good?
if ( m_bSubmittedHisTicket && m_eBeginAuthSessionResult != k_EBeginAuthSessionResultOK )
{
char rgch[128];
sprintf( rgch, "P2P:: Ticket from account=%d was bad\n", m_steamID.GetAccountID() );
OutputDebugString( rgch );
return false;
}
// second ticket check: if the steam backend replied, was that good?
if ( m_bHaveAnswer && m_eAuthSessionResponse != k_EAuthSessionResponseOK )
{
char rgch[128];
sprintf( rgch, "P2P:: Steam response for account=%d was bad\n", m_steamID.GetAccountID() );
OutputDebugString( rgch );
return false;
}
// last: if i sent him a ticket and he has not reciprocated, time out after 30 sec
if ( m_bSentTicket && !m_bSubmittedHisTicket )
{
if ( GetGameTimeInSeconds() - m_ulTicketTime > 30 )
{
char rgch[128];
sprintf( rgch, "P2P:: No ticket received for account=%d\n", m_steamID.GetAccountID() );
OutputDebugString( rgch );
return false;
}
}
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: the game engine is telling us about someone who left the game
//-----------------------------------------------------------------------------
void CP2PAuthPlayer::EndGame()
{
if ( m_bSentTicket )
{
SteamUser()->CancelAuthTicket( m_hAuthTicketIGaveThisUser );
m_bSentTicket = false;
}
if ( m_bSubmittedHisTicket )
{
SteamUser()->EndAuthSession( m_steamID );
m_bSubmittedHisTicket = false;
}
}
//-----------------------------------------------------------------------------
// Purpose: message from another player providing his ticket
//-----------------------------------------------------------------------------
void CP2PAuthPlayer::HandleP2PSendingTicket( const MsgP2PSendingTicket_t *pMsg )
{
m_cubTicketHeGaveMe = pMsg->GetTokenLen();
memcpy( m_rgubTicketHeGaveMe, pMsg->GetTokenPtr(), m_cubTicketHeGaveMe );
m_eBeginAuthSessionResult = SteamUser()->BeginAuthSession( m_rgubTicketHeGaveMe, m_cubTicketHeGaveMe, m_steamID );
m_bSubmittedHisTicket = true;
char rgch[128];
sprintf( rgch, "P2P:: ReceivedTicket from account=%d \n", m_steamID.GetAccountID() );
OutputDebugString( rgch );
if ( !m_bSentTicket )
StartAuthPlayer();
}
//-----------------------------------------------------------------------------
// Purpose: utility wrapper
//-----------------------------------------------------------------------------
CSteamID CP2PAuthPlayer::GetSteamID()
{
return SteamUser()->GetSteamID();
}
//-----------------------------------------------------------------------------
// Purpose: constructor
//-----------------------------------------------------------------------------
CP2PAuthedGame::CP2PAuthedGame( IGameEngine *pGameEngine )
{
m_pGameEngine = pGameEngine;
m_hConnServer = k_HSteamNetConnection_Invalid;
// no players yet
for ( int i = 0; i < MAX_PLAYERS_PER_SERVER; i++ )
{
m_rgpP2PAuthPlayer[i] = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: game with this player is over
//-----------------------------------------------------------------------------
void CP2PAuthedGame::PlayerDisconnect( int iSlot )
{
if ( m_rgpP2PAuthPlayer[iSlot] )
{
m_rgpP2PAuthPlayer[iSlot]->EndGame();
delete m_rgpP2PAuthPlayer[iSlot];
m_rgpP2PAuthPlayer[iSlot] = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: game is over, disconnect everyone
//-----------------------------------------------------------------------------
void CP2PAuthedGame::EndGame()
{
for ( int i = 0; i < MAX_PLAYERS_PER_SERVER; i++ )
{
if ( m_rgpP2PAuthPlayer[i] )
{
m_rgpP2PAuthPlayer[i]->EndGame();
delete m_rgpP2PAuthPlayer[i];
m_rgpP2PAuthPlayer[i] = NULL;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: initialize player
//-----------------------------------------------------------------------------
void CP2PAuthedGame::InternalInitPlayer( int iSlot, CSteamID steamID, bool bStartAuthProcess )
{
char rgch[128];
sprintf( rgch, "P2P:: StartAuthPlayer slot=%d account=%d \n", iSlot, steamID.GetAccountID() );
OutputDebugString( rgch );
m_rgpP2PAuthPlayer[iSlot] = new CP2PAuthPlayer( m_pGameEngine, steamID, m_hConnServer );
if ( bStartAuthProcess )
m_rgpP2PAuthPlayer[iSlot]->StartAuthPlayer();
}
//-----------------------------------------------------------------------------
// Purpose: game host register this player, we wait for this player
// to start the auth process by sending us his ticket, then we will
// reciprocate
//-----------------------------------------------------------------------------
void CP2PAuthedGame::RegisterPlayer( int iSlot, CSteamID steamID )
{
if (iSlot < MAX_PLAYERS_PER_SERVER)
InternalInitPlayer( iSlot, steamID, false );
}
//-----------------------------------------------------------------------------
// Purpose: start the auth process by sending ticket to this player
// he will reciprocate
//-----------------------------------------------------------------------------
void CP2PAuthedGame::StartAuthPlayer( int iSlot, CSteamID steamID )
{
if (iSlot < MAX_PLAYERS_PER_SERVER)
InternalInitPlayer( iSlot, steamID, true );
}
//-----------------------------------------------------------------------------
// Purpose: message handler
//-----------------------------------------------------------------------------
void CP2PAuthedGame::HandleP2PSendingTicket( const void *pMessage )
{
const MsgP2PSendingTicket_t *pMsg = (const MsgP2PSendingTicket_t*)pMessage;
for ( int i = 0; i < MAX_PLAYERS_PER_SERVER; i++ )
{
if ( m_rgpP2PAuthPlayer[i] && m_rgpP2PAuthPlayer[i]->GetSteamID() == pMsg->GetSteamID() )
{
m_rgpP2PAuthPlayer[i]->HandleP2PSendingTicket( pMsg );
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: utility wrapper
//-----------------------------------------------------------------------------
CSteamID CP2PAuthedGame::GetSteamID()
{
return SteamUser()->GetSteamID();
}
+74
View File
@@ -0,0 +1,74 @@
//========= Copyright © 1996-2004, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
const int k_cMaxSockets = 16;
class CP2PAuthPlayer;
bool SendAuthTicketToConnection( CSteamID steamIDFrom, HSteamNetConnection hConnectionTo, uint32 cubTicket, uint8 *pubTicket );
//-----------------------------------------------------------------------------
// Purpose: one player p2p auth process state machine
//-----------------------------------------------------------------------------
class CP2PAuthPlayer
{
public:
CP2PAuthPlayer( IGameEngine *pGameEngine, CSteamID steamID, HSteamNetConnection hServerConn );
~CP2PAuthPlayer();
void EndGame();
void StartAuthPlayer();
bool BIsAuthOk();
void HandleP2PSendingTicket( const MsgP2PSendingTicket_t *pMsg );
CSteamID GetSteamID();
STEAM_CALLBACK( CP2PAuthPlayer, OnBeginAuthResponse, ValidateAuthTicketResponse_t, m_CallbackBeginAuthResponse );
const CSteamID m_steamID;
const HSteamNetConnection m_hServerConnection;
private:
uint64 GetGameTimeInSeconds()
{
return m_pGameEngine->GetGameTickCount()/1000;
}
bool m_bSentTicket;
bool m_bSubmittedHisTicket;
bool m_bHaveAnswer;
uint64 m_ulConnectTime;
uint64 m_ulTicketTime;
uint64 m_ulAnswerTime;
uint32 m_cubTicketIGaveThisUser;
uint8 m_rgubTicketIGaveThisUser[1024];
uint32 m_cubTicketHeGaveMe;
uint8 m_rgubTicketHeGaveMe[1024];
HAuthTicket m_hAuthTicketIGaveThisUser;
EBeginAuthSessionResult m_eBeginAuthSessionResult;
EAuthSessionResponse m_eAuthSessionResponse;
IGameEngine *m_pGameEngine;
};
//-----------------------------------------------------------------------------
// Purpose: simple wrapper for multiple players
//-----------------------------------------------------------------------------
class CP2PAuthedGame
{
public:
CP2PAuthedGame( IGameEngine *pGameEngine );
void PlayerDisconnect( int iSlot );
void EndGame();
void StartAuthPlayer( int iSlot, CSteamID steamID );
void RegisterPlayer( int iSlot, CSteamID steamID );
void HandleP2PSendingTicket( const void *pMessage );
CSteamID GetSteamID();
void InternalInitPlayer( int iSlot, CSteamID steamID, bool bStartAuthProcess );
CP2PAuthPlayer *m_rgpP2PAuthPlayer[MAX_PLAYERS_PER_SERVER];
IGameEngine *m_pGameEngine;
HSteamNetConnection m_hConnServer;
};
@@ -0,0 +1 @@
480
@@ -0,0 +1,27 @@
"lang"
{
"english"
{
"tokens"
{
"#StatusWithoutScore" "{#Status_%gamestatus%}"
"#StatusWithScore" "{#Status_%gamestatus%}: %score%"
"#Status_AtMainMenu" "At the main menu"
"#Status_WaitingForMatch" "Waiting for match"
"#Status_Winning" "Winning"
"#Status_Losing" "Losing"
"#Status_Tied" "Tied"
}
}
"french"
{
"tokens"
{
"#Status_AtMainMenu" "Au menu principal"
"#Status_WaitingForMatch" "En attente de match"
"#Status_Winning" "Gagnant"
"#Status_Losing" "Perdant"
"#Status_Tied" "Egalité"
}
}
}
+20
View File
@@ -0,0 +1,20 @@
//========= Copyright © 1996-2008 Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
// stdafx.cpp : source file that includes just the standard includes
// SteamworksExample.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
#include <stdio.h>
#ifdef WIN32
#include <varargs.h>
#include <tchar.h>
#endif
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
+244
View File
@@ -0,0 +1,244 @@
//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include <stdio.h>
#include <stdarg.h>
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#ifdef WIN32
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
// Allow use of features specific to Windows 8.1 or later.
// Change this to the appropriate value to target other versions of Windows.
#ifndef WINVER
#define WINVER 0x0602
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0602
#endif
#ifndef _WIN32_WINDOWS
#define _WIN32_WINDOWS 0x0602
#endif
#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later.
#define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE.
#endif
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#pragma comment( lib, "d3d9.lib" )
#pragma comment( lib, "d3dx9.lib" )
#pragma comment( lib, "dxguid.lib" )
// Windows Header Files:
#include <windows.h>
#include <tchar.h>
// Winsock
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib" )
// d3d header files
#include "d3d9.h"
#include "d3dx9.h"
// XAudio2 header files
#include <xaudio2.h>
typedef __int16 int16;
typedef unsigned __int16 uint16;
typedef __int32 int32;
typedef unsigned __int32 uint32;
typedef __int64 int64;
typedef unsigned __int64 uint64;
#include "steam/isteamuserstats.h"
#include "steam/isteamremotestorage.h"
#include "steam/isteammatchmaking.h"
#include "steam/steam_gameserver.h"
#elif defined(POSIX)
#include <limits.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#if defined(OSX)
#include <OpenGL/OpenGL.h>
#endif
#define ARRAYSIZE(A) ( sizeof(A)/sizeof(A[0]) )
// Need to define some types on POSIX
typedef short int16;
typedef unsigned short uint16;
typedef int int32;
typedef unsigned int uint32;
typedef long long int64;
typedef unsigned long long uint64;
typedef uint32 DWORD;
typedef DWORD HWND;
typedef DWORD HINSTANCE;
typedef short SHORT;
typedef long LONG;
typedef unsigned char byte;
typedef unsigned char uint8;
/* Font Weights */
#define FW_DONTCARE 0
#define FW_THIN 100
#define FW_EXTRALIGHT 200
#define FW_LIGHT 300
#define FW_NORMAL 400
#define FW_MEDIUM 500
#define FW_SEMIBOLD 600
#define FW_BOLD 700
#define FW_EXTRABOLD 800
#define FW_HEAVY 900
/* Some VK_ defines from windows, we'll map these for posix */
#define VK_BACK 0x08
#define VK_TAB 0x09
#define VK_RETURN 0x0D
#define VK_SHIFT 0x10
#define VK_CONTROL 0x11
#define VK_ESCAPE 0x1B
#define VK_SPACE 0x20
#define VK_LEFT 0x25
#define VK_UP 0x26
#define VK_RIGHT 0x27
#define VK_DOWN 0x28
#define VK_SELECT 0x29
#define VK_F5 0x74
#ifndef VALVE_RECT_DEFINED
#define VALVE_RECT_DEFINED
typedef struct tagRECT
{
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT;
#define _RECT tagRECT
#endif
#define D3DCOLOR_ARGB(a,r,g,b) \
((DWORD)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))
// Macros for converting ARGB DWORD color representation into opengl formats...
#define COLOR_RED( color ) \
(GLubyte)(((color)>>16)&0xff)
#define COLOR_GREEN( color ) \
(GLubyte)(((color)>>8)&0xff)
#define COLOR_BLUE( color ) \
(GLubyte)((color)&0xff)
#define COLOR_ALPHA( color ) \
(GLubyte)(((color)>>24)&0xff)
#define DWARGB_TO_DWRGBA(color) \
((DWORD)(( (((((color)>>16)&0xff))<<24)|(((((color)>>8)&0xff))<<16)|((color&0xff)<<8)|((color)>>24)&0xff)))
#define DWARGB_TO_DWABGR(color) \
((DWORD)(( (((((color)>>24)&0xff))<<24)|(((((color))&0xff))<<16)|(((color>>8)&0xff)<<8)|((color)>>16)&0xff)))
#define DWRGBA_TO_DWARGB(color) \
((DWORD)(( (((((color))&0xff))<<24)|(((((color>>24))&0xff))<<16)|(((color>>16)&0xff)<<8)|((color)>>8)&0xff)))
// steam api header file
#include "steam/steam_api.h"
#include "steam/isteamuserstats.h"
#include "steam/isteamremotestorage.h"
#include "steam/isteammatchmaking.h"
#include "steam/steam_gameserver.h"
extern void OutputDebugString( const char *pchMsg );
extern int Alert( const char *lpCaption, const char *lpText );
extern const char *GetUserSaveDataPath();
#ifdef OSX
extern uint64_t GetTickCount();
#endif // OSX
#define V_ARRAYSIZE(a) sizeof(a)/sizeof(a[0])
#endif // POSIX
// OUT_Z_ARRAY indicates an output array that will be null-terminated.
#if _MSC_VER >= 1600
// Include the annotation header file.
#include <sal.h>
#if _MSC_VER >= 1700
// VS 2012+
#define OUT_Z_ARRAY _Post_z_
#else
// VS 2010
#define OUT_Z_ARRAY _Deref_post_z_
#endif
#else
// gcc, clang, old versions of VS
#define OUT_Z_ARRAY
#endif
template <size_t maxLenInChars> void sprintf_safe(OUT_Z_ARRAY char (&pDest)[maxLenInChars], const char *pFormat, ... )
{
va_list params;
va_start( params, pFormat );
#ifdef POSIX
vsnprintf( pDest, maxLenInChars, pFormat, params );
#else
_vsnprintf( pDest, maxLenInChars, pFormat, params );
#endif
pDest[maxLenInChars - 1] = '\0';
va_end( params );
}
inline void strncpy_safe( char *pDest, char const *pSrc, size_t maxLen )
{
size_t nCount = maxLen;
char *pstrDest = pDest;
const char *pstrSource = pSrc;
while ( 0 < nCount && 0 != ( *pstrDest++ = *pstrSource++ ) )
nCount--;
if ( maxLen > 0 )
pstrDest[-1] = 0;
}
#ifdef STEAM_CEG
// Steam DRM header file
#include "cegclient.h"
#else
#define Steamworks_InitCEGLibrary() (true)
#define Steamworks_TermCEGLibrary()
#define Steamworks_TestSecret()
#define Steamworks_SelfCheck()
#endif
+38
View File
@@ -0,0 +1,38 @@
//========= Copyright Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
// stdafx_ps3.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently on the PS3 platform
//
#include <cell/error.h>
#include <sys/process.h>
#include <sys/paths.h>
#include <sys/prx.h>
#include <sys/spu_initialize.h>
#include <sys/memory.h>
#include <PSGL/psgl.h>
#include <PSGL/psglu.h>
#include <sys/types.h>
#include <cell/fios/fios_common.h>
#include <cell/fios/fios_memory.h>
#include <cell/fios/fios_configuration.h>
#include <cell/fios/fios_time.h>
#include <cell/dbgfont.h>
#include <cell/pad/libpad.h>
#include <sysutil/sysutil_syscache.h>
#include <sys/tty.h>
//#define PS3_MTT_DEBUG
#ifdef PS3_MTT_DEBUG
#include "../external/libmtt/libmtt/libmtt_log.h"
#endif
extern CellDbgFontConsoleId g_DbgFontConsoleID;
@@ -0,0 +1,646 @@
"controller_mappings"
{
"version" "3"
"title" "#title"
"description" "#description"
"controller_type" "controller_steamcontroller_gordon"
"Timestamp" "1529529957"
"actions"
{
"ship_controls"
{
"title" "Ship Controls"
"legacy_set" "0"
"StickPadGyro"
{
"analog_controls"
{
"title" "#AnalogControls"
"input_mode" "joystick_move"
}
}
"Button"
{
"turn_left" "#TurnLeft"
"turn_right" "#TurnRight"
"fire_lasers" "#FireLasers"
"pause_menu" "#PauseMenu"
"forward_thrust" "#ForwardThrust"
"backward_thrust" "#BackwardThrust"
}
"Layers"
{
"thrust_action_layer" "#ThrustLayer"
}
}
"menu_controls"
{
"title" "#MenuControls"
"legacy_set" "0"
"Button"
{
"menu_up" "#MenuUp"
"menu_down" "#MenuDown"
"menu_left" "#MenuLeft"
"menu_right" "#MenuRight"
"menu_select" "#MenuSelect"
"menu_cancel" "#MenuCancel"
}
}
}
"action_layers"
{
"thrust_action_layer"
{
"title" "#ThrustLayer"
"legacy_set" "1"
"set_layer" "1"
"parent_set_name" "ship_controls"
}
}
"localization"
{
"english"
{
"title" "Space War Action Set Config Sample"
"description" "This is an example configuration for using Steamworks Action Sets."
"AnalogControls" "Analog Controls"
"TurnLeft" "Turn Left"
"TurnRight" "Turn Right"
"FireLasers" "Fire Lasers"
"PauseMenu" "Pause Menu"
"BackwardThrust" "Backward Thrust"
"MenuControls" "Menu Controls"
"MenuUp" "Menu Up"
"MenuDown" "Menu Down"
"MenuLeft" "Menu Left"
"MenuRight" "Menu Right"
"MenuSelect" "Menu Select"
"ThrustLayer" "Thrust Layer"
}
}
"group"
{
"id" "0"
"mode" "four_buttons"
"inputs"
{
}
"settings"
{
"button_size" "17988"
"button_dist" "19988"
}
}
"group"
{
"id" "1"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "2"
"mode" "trigger"
"inputs"
{
"edge"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action ship_controls fire_lasers"
}
"settings"
{
"haptic_intensity" "2"
}
}
}
}
}
}
"group"
{
"id" "3"
"mode" "four_buttons"
"inputs"
{
"button_a"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action menu_controls menu_select"
}
}
}
}
"button_b"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action menu_controls menu_cancel"
}
}
}
}
}
"settings"
{
"button_size" "17992"
"button_dist" "19992"
}
}
"group"
{
"id" "4"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "5"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "6"
"mode" "dpad"
"inputs"
{
"dpad_north"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action menu_controls menu_up"
}
}
}
}
"dpad_south"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action menu_controls menu_down"
}
}
}
}
"dpad_east"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action menu_controls menu_right"
}
}
}
}
"dpad_west"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action menu_controls menu_left"
}
}
}
}
}
"settings"
{
"edge_binding_radius" "24995"
"analog_emulation_period" "29"
}
}
"group"
{
"id" "7"
"mode" "dpad"
"inputs"
{
}
"settings"
{
"edge_binding_radius" "24995"
"analog_emulation_period" "29"
}
}
"group"
{
"id" "8"
"mode" "joystick_move"
"inputs"
{
}
"settings"
{
"virtual_mode" "1"
"edge_binding_radius" "24997"
"sensitivity" "98"
}
}
"group"
{
"id" "9"
"mode" "joystick_move"
"inputs"
{
}
"settings"
{
"virtual_mode" "1"
"edge_binding_radius" "24997"
"sensitivity" "98"
}
}
"group"
{
"id" "10"
"mode" "joystick_move"
"inputs"
{
}
"settings"
{
"virtual_mode" "1"
"edge_binding_radius" "24996"
"sensitivity" "98"
}
}
"group"
{
"id" "11"
"mode" "four_buttons"
"inputs"
{
}
}
"group"
{
"id" "12"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "13"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "14"
"mode" "four_buttons"
"inputs"
{
}
}
"group"
{
"id" "15"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "16"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "17"
"mode" "four_buttons"
"inputs"
{
}
}
"group"
{
"id" "18"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "19"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "20"
"mode" "four_buttons"
"inputs"
{
}
}
"group"
{
"id" "21"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "22"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "23"
"mode" "four_buttons"
"inputs"
{
}
}
"group"
{
"id" "24"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "25"
"mode" "trigger"
"inputs"
{
}
}
"group"
{
"id" "26"
"mode" "joystick_move"
"inputs"
{
}
"settings"
{
"virtual_mode" "1"
"edge_binding_radius" "24999"
"sensitivity" "99"
}
"gameactions"
{
"ship_controls" "analog_controls"
}
}
"group"
{
"id" "35"
"mode" "four_buttons"
"inputs"
{
"button_a"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action ship_controls fire_lasers, Fire Lasers"
}
}
}
}
}
"settings"
{
"layer" "1"
}
}
"group"
{
"id" "36"
"mode" "trigger"
"inputs"
{
}
"settings"
{
"layer" "1"
}
}
"group"
{
"id" "37"
"mode" "trigger"
"inputs"
{
}
"settings"
{
"layer" "1"
}
}
"group"
{
"id" "38"
"mode" "joystick_move"
"inputs"
{
}
"settings"
{
"layer" "1"
}
"gameactions"
{
"ship_controls" "analog_controls"
}
}
"group"
{
"id" "39"
"mode" "joystick_move"
"inputs"
{
}
"settings"
{
"layer" "1"
}
}
"group"
{
"id" "27"
"mode" "switches"
"inputs"
{
"button_escape"
{
"activators"
{
"Full_Press"
{
"bindings"
{
"binding" "game_action ship_controls pause_menu"
}
}
}
}
}
}
"group"
{
"id" "28"
"mode" "switches"
"inputs"
{
}
}
"group"
{
"id" "29"
"mode" "switches"
"inputs"
{
}
}
"group"
{
"id" "30"
"mode" "switches"
"inputs"
{
}
}
"group"
{
"id" "31"
"mode" "switches"
"inputs"
{
}
}
"group"
{
"id" "32"
"mode" "switches"
"inputs"
{
}
}
"group"
{
"id" "33"
"mode" "switches"
"inputs"
{
}
}
"group"
{
"id" "34"
"mode" "switches"
"inputs"
{
}
"settings"
{
"layer" "1"
}
}
"preset"
{
"id" "0"
"name" "ship_controls"
"group_source_bindings"
{
"27" "switch active"
"0" "button_diamond active"
"1" "left_trigger active"
"2" "right_trigger active"
"7" "joystick inactive"
"10" "joystick inactive"
"26" "joystick active"
"8" "left_trackpad inactive"
"9" "right_trackpad active"
}
}
"preset"
{
"id" "1"
"name" "menu_controls"
"group_source_bindings"
{
"28" "switch active"
"3" "button_diamond active"
"4" "left_trigger active"
"5" "right_trigger active"
"6" "joystick active"
}
}
"preset"
{
"id" "2"
"name" "thrust_action_layer"
"group_source_bindings"
{
"34" "switch active"
"35" "button_diamond active"
"36" "left_trigger active"
"37" "right_trigger active"
"38" "joystick active"
"39" "right_trackpad active"
}
}
"settings"
{
}
}
@@ -0,0 +1,95 @@
"Action Manifest"
{
"configurations"
{
"controller_xboxone"
{
"0"
{
"path" "xbox_controller.vdf"
}
}
"controller_steamcontroller_gordon"
{
"0"
{
"path" "steam_controller.vdf"
}
}
}
"actions"
{
"ship_controls"
{
"title" "Ship Controls"
"legacy_set" "0"
"StickPadGyro"
{
"analog_controls"
{
"title" "#AnalogControls"
"input_mode" "joystick_move"
}
}
"Button"
{
"turn_left" "#TurnLeft"
"turn_right" "#TurnRight"
"fire_lasers" "#FireLasers"
"pause_menu" "#PauseMenu"
"forward_thrust" "#ForwardThrust"
"backward_thrust" "#BackwardThrust"
}
"Layers"
{
"thrust_action_layer" "#ThrustLayer"
}
}
"menu_controls"
{
"title" "#MenuControls"
"legacy_set" "0"
"Button"
{
"menu_up" "#MenuUp"
"menu_down" "#MenuDown"
"menu_left" "#MenuLeft"
"menu_right" "#MenuRight"
"menu_select" "#MenuSelect"
"menu_cancel" "#MenuCancel"
}
}
}
"action_layers"
{
"thrust_action_layer"
{
"title" "#ThrustLayer"
"legacy_set" "1"
"set_layer" "1"
"parent_set_name" "ship_controls"
}
}
"localization"
{
"english"
{
"title" "Space War Action Set Config Sample"
"description" "This is an example configuration for using Steamworks Action Sets."
"AnalogControls" "Analog Controls"
"TurnLeft" "Turn Left"
"TurnRight" "Turn Right"
"FireLasers" "Fire Lasers"
"PauseMenu" "Pause Menu"
"ForwardThrust" "Forward Thrust"
"BackwardThrust" "Backward Thrust"
"MenuControls" "Menu Controls"
"MenuUp" "Menu Up"
"MenuDown" "Menu Down"
"MenuLeft" "Menu Left"
"MenuRight" "Menu Right"
"MenuSelect" "Menu Select"
"ThrustLayer" "Thrust Layer"
}
}
}
@@ -0,0 +1,591 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
503C6CB61268F34200B66E3B /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 503C6CB51268F34200B66E3B /* Cocoa.framework */; };
503C6D0F1268F49F00B66E3B /* BaseMenu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CD91268F49F00B66E3B /* BaseMenu.cpp */; };
503C6D121268F49F00B66E3B /* gameengineosx.mm in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CE01268F49F00B66E3B /* gameengineosx.mm */; };
503C6D131268F49F00B66E3B /* glstringosx.mm in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CE21268F49F00B66E3B /* glstringosx.mm */; };
503C6D141268F49F00B66E3B /* Leaderboards.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CE31268F49F00B66E3B /* Leaderboards.cpp */; };
503C6D151268F49F00B66E3B /* Lobby.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CE51268F49F00B66E3B /* Lobby.cpp */; };
503C6D161268F49F00B66E3B /* Main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CE71268F49F00B66E3B /* Main.cpp */; };
503C6D171268F49F00B66E3B /* MainMenu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CE81268F49F00B66E3B /* MainMenu.cpp */; };
503C6D191268F49F00B66E3B /* p2pauth.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CED1268F49F00B66E3B /* p2pauth.cpp */; };
503C6D1A1268F49F00B66E3B /* PhotonBeam.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CEF1268F49F00B66E3B /* PhotonBeam.cpp */; };
503C6D1B1268F49F00B66E3B /* QuitMenu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CF11268F49F00B66E3B /* QuitMenu.cpp */; };
503C6D1C1268F49F00B66E3B /* RemoteStorage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CF31268F49F00B66E3B /* RemoteStorage.cpp */; };
503C6D1D1268F49F00B66E3B /* ServerBrowser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CF51268F49F00B66E3B /* ServerBrowser.cpp */; };
503C6D1E1268F49F00B66E3B /* Ship.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CF81268F49F00B66E3B /* Ship.cpp */; };
503C6D1F1268F49F00B66E3B /* SpaceWarClient.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CFB1268F49F00B66E3B /* SpaceWarClient.cpp */; };
503C6D201268F49F00B66E3B /* SpaceWarEntity.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6CFD1268F49F00B66E3B /* SpaceWarEntity.cpp */; };
503C6D221268F49F00B66E3B /* SpaceWarServer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6D011268F49F00B66E3B /* SpaceWarServer.cpp */; };
503C6D231268F49F00B66E3B /* StarField.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6D031268F49F00B66E3B /* StarField.cpp */; };
503C6D241268F49F00B66E3B /* StatsAndAchievements.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6D051268F49F00B66E3B /* StatsAndAchievements.cpp */; };
503C6D251268F49F00B66E3B /* stdafx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6D071268F49F00B66E3B /* stdafx.cpp */; };
503C6D261268F49F00B66E3B /* Sun.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6D091268F49F00B66E3B /* Sun.cpp */; };
503C6D271268F49F00B66E3B /* VectorEntity.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6D0B1268F49F00B66E3B /* VectorEntity.cpp */; };
503C6D281268F49F00B66E3B /* voicechat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 503C6D0D1268F49F00B66E3B /* voicechat.cpp */; };
503C6DAC1268FE1000B66E3B /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 503C6DAA1268FE1000B66E3B /* OpenAL.framework */; };
503C6DAD1268FE1000B66E3B /* OpenGL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 503C6DAB1268FE1000B66E3B /* OpenGL.framework */; };
503C6DB41269002800B66E3B /* libsteam_api.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 503C6DB31269002800B66E3B /* libsteam_api.dylib */; };
504EDCBC126901EC00F96D63 /* libsteam_api.dylib in CopyFiles */ = {isa = PBXBuildFile; fileRef = 503C6DB31269002800B66E3B /* libsteam_api.dylib */; };
504EDCC21269026C00F96D63 /* steam_appid.txt in CopyFiles */ = {isa = PBXBuildFile; fileRef = 504EDCC01269025A00F96D63 /* steam_appid.txt */; };
50D642871461EF3200A5739B /* clanchatroom.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50D642851461EF3200A5739B /* clanchatroom.cpp */; };
50E77DEB1362190C000FC072 /* cglmbuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DD11362190C000FC072 /* cglmbuffer.cpp */; };
50E77DEC1362190C000FC072 /* cglmfbo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DD31362190C000FC072 /* cglmfbo.cpp */; };
50E77DED1362190C000FC072 /* cglmprogram.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DD51362190C000FC072 /* cglmprogram.cpp */; };
50E77DEE1362190C000FC072 /* cglmquery.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DD71362190C000FC072 /* cglmquery.cpp */; };
50E77DEF1362190C000FC072 /* cglmtex.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DD91362190C000FC072 /* cglmtex.cpp */; };
50E77DF01362190C000FC072 /* dx9asmtogl2.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DDB1362190C000FC072 /* dx9asmtogl2.cpp */; };
50E77DF11362190C000FC072 /* dxabstract.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DDD1362190C000FC072 /* dxabstract.cpp */; };
50E77DF21362190C000FC072 /* glmgr.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DE11362190C000FC072 /* glmgr.cpp */; };
50E77DF31362190C000FC072 /* glmgrbasics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DE31362190C000FC072 /* glmgrbasics.cpp */; };
50E77DF41362190C000FC072 /* glmgrcocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DE51362190C000FC072 /* glmgrcocoa.mm */; };
50E77DF51362190C000FC072 /* glmgrext.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DE61362190C000FC072 /* glmgrext.cpp */; };
50E77DF61362190C000FC072 /* mathlite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50E77DE91362190C000FC072 /* mathlite.cpp */; };
50E77DF813621991000FC072 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 50E77DF713621991000FC072 /* IOKit.framework */; };
840B387019BB91C50084B9F1 /* htmlsurface.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 840B386E19BB91C50084B9F1 /* htmlsurface.cpp */; };
975820DB2765BE3900093F91 /* ItemStore.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 975820DA2765BE3900093F91 /* ItemStore.cpp */; };
97919DA62C22281400272343 /* timeline.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 97919DA52C22281400272343 /* timeline.cpp */; };
A4B5A0FD24906974000E9151 /* RemotePlay.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4B5A0FC24906974000E9151 /* RemotePlay.cpp */; };
A4B5A10424906A0E000E9151 /* SimpleProtobuf.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4B5A10324906A0E000E9151 /* SimpleProtobuf.cpp */; };
BA60B6B81A82EDD200F4AC4F /* Friends.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA60B6B41A82EDD200F4AC4F /* Friends.cpp */; };
BA60B6B91A82EDD200F4AC4F /* Inventory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA60B6B61A82EDD200F4AC4F /* Inventory.cpp */; };
F323060928947C1800E66D30 /* OverlayExamples.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F323060828947C1800E66D30 /* OverlayExamples.cpp */; };
F803305119087F9200344590 /* musicplayer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F803305019087F9200344590 /* musicplayer.cpp */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
504EDCBB126901D200F96D63 /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 6;
files = (
504EDCC21269026C00F96D63 /* steam_appid.txt in CopyFiles */,
504EDCBC126901EC00F96D63 /* libsteam_api.dylib in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
503C6CB21268F34200B66E3B /* steamworksexample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = steamworksexample.app; sourceTree = BUILT_PRODUCTS_DIR; };
503C6CB51268F34200B66E3B /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; };
503C6CD91268F49F00B66E3B /* BaseMenu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BaseMenu.cpp; sourceTree = "<group>"; };
503C6CDA1268F49F00B66E3B /* BaseMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BaseMenu.h; sourceTree = "<group>"; };
503C6CDD1268F49F00B66E3B /* GameEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GameEngine.h; sourceTree = "<group>"; };
503C6CDF1268F49F00B66E3B /* gameengineosx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = gameengineosx.h; sourceTree = "<group>"; };
503C6CE01268F49F00B66E3B /* gameengineosx.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = gameengineosx.mm; sourceTree = "<group>"; };
503C6CE11268F49F00B66E3B /* glstringosx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = glstringosx.h; sourceTree = "<group>"; };
503C6CE21268F49F00B66E3B /* glstringosx.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = glstringosx.mm; sourceTree = "<group>"; };
503C6CE31268F49F00B66E3B /* Leaderboards.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Leaderboards.cpp; sourceTree = "<group>"; };
503C6CE41268F49F00B66E3B /* Leaderboards.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Leaderboards.h; sourceTree = "<group>"; };
503C6CE51268F49F00B66E3B /* Lobby.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Lobby.cpp; sourceTree = "<group>"; };
503C6CE61268F49F00B66E3B /* Lobby.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Lobby.h; sourceTree = "<group>"; };
503C6CE71268F49F00B66E3B /* Main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Main.cpp; sourceTree = "<group>"; };
503C6CE81268F49F00B66E3B /* MainMenu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MainMenu.cpp; sourceTree = "<group>"; };
503C6CE91268F49F00B66E3B /* MainMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MainMenu.h; sourceTree = "<group>"; };
503C6CEA1268F49F00B66E3B /* Messages.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Messages.h; sourceTree = "<group>"; };
503C6CED1268F49F00B66E3B /* p2pauth.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = p2pauth.cpp; sourceTree = "<group>"; };
503C6CEE1268F49F00B66E3B /* p2pauth.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = p2pauth.h; sourceTree = "<group>"; };
503C6CEF1268F49F00B66E3B /* PhotonBeam.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PhotonBeam.cpp; sourceTree = "<group>"; };
503C6CF01268F49F00B66E3B /* PhotonBeam.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PhotonBeam.h; sourceTree = "<group>"; };
503C6CF11268F49F00B66E3B /* QuitMenu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = QuitMenu.cpp; sourceTree = "<group>"; };
503C6CF21268F49F00B66E3B /* QuitMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = QuitMenu.h; sourceTree = "<group>"; };
503C6CF31268F49F00B66E3B /* RemoteStorage.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RemoteStorage.cpp; sourceTree = "<group>"; };
503C6CF41268F49F00B66E3B /* RemoteStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RemoteStorage.h; sourceTree = "<group>"; };
503C6CF51268F49F00B66E3B /* ServerBrowser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ServerBrowser.cpp; sourceTree = "<group>"; };
503C6CF61268F49F00B66E3B /* ServerBrowser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ServerBrowser.h; sourceTree = "<group>"; };
503C6CF71268F49F00B66E3B /* ServerBrowserMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ServerBrowserMenu.h; sourceTree = "<group>"; };
503C6CF81268F49F00B66E3B /* Ship.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Ship.cpp; sourceTree = "<group>"; };
503C6CF91268F49F00B66E3B /* Ship.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Ship.h; sourceTree = "<group>"; };
503C6CFA1268F49F00B66E3B /* SpaceWar.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpaceWar.h; sourceTree = "<group>"; };
503C6CFB1268F49F00B66E3B /* SpaceWarClient.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SpaceWarClient.cpp; sourceTree = "<group>"; };
503C6CFC1268F49F00B66E3B /* SpaceWarClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpaceWarClient.h; sourceTree = "<group>"; };
503C6CFD1268F49F00B66E3B /* SpaceWarEntity.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SpaceWarEntity.cpp; sourceTree = "<group>"; };
503C6CFE1268F49F00B66E3B /* SpaceWarEntity.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpaceWarEntity.h; sourceTree = "<group>"; };
503C6CFF1268F49F00B66E3B /* SpaceWarRes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpaceWarRes.h; sourceTree = "<group>"; };
503C6D011268F49F00B66E3B /* SpaceWarServer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SpaceWarServer.cpp; sourceTree = "<group>"; };
503C6D021268F49F00B66E3B /* SpaceWarServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpaceWarServer.h; sourceTree = "<group>"; };
503C6D031268F49F00B66E3B /* StarField.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StarField.cpp; sourceTree = "<group>"; };
503C6D041268F49F00B66E3B /* StarField.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StarField.h; sourceTree = "<group>"; };
503C6D051268F49F00B66E3B /* StatsAndAchievements.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StatsAndAchievements.cpp; sourceTree = "<group>"; };
503C6D061268F49F00B66E3B /* StatsAndAchievements.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = StatsAndAchievements.h; sourceTree = "<group>"; };
503C6D071268F49F00B66E3B /* stdafx.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = stdafx.cpp; sourceTree = "<group>"; };
503C6D081268F49F00B66E3B /* stdafx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = stdafx.h; sourceTree = "<group>"; };
503C6D091268F49F00B66E3B /* Sun.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Sun.cpp; sourceTree = "<group>"; };
503C6D0A1268F49F00B66E3B /* Sun.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Sun.h; sourceTree = "<group>"; };
503C6D0B1268F49F00B66E3B /* VectorEntity.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = VectorEntity.cpp; sourceTree = "<group>"; };
503C6D0C1268F49F00B66E3B /* VectorEntity.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = VectorEntity.h; sourceTree = "<group>"; };
503C6D0D1268F49F00B66E3B /* voicechat.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = voicechat.cpp; sourceTree = "<group>"; };
503C6D0E1268F49F00B66E3B /* voicechat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = voicechat.h; sourceTree = "<group>"; };
503C6DAA1268FE1000B66E3B /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; };
503C6DAB1268FE1000B66E3B /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = System/Library/Frameworks/OpenGL.framework; sourceTree = SDKROOT; };
503C6DB31269002800B66E3B /* libsteam_api.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsteam_api.dylib; path = ../redistributable_bin/osx/libsteam_api.dylib; sourceTree = "<absolute>"; };
504EDCB4126900D600F96D63 /* steamworksexample-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "steamworksexample-Info.plist"; path = "osx/steamworksexample-Info.plist"; sourceTree = "<group>"; };
504EDCC01269025A00F96D63 /* steam_appid.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = steam_appid.txt; path = osx/steam_appid.txt; sourceTree = "<group>"; };
50D642851461EF3200A5739B /* clanchatroom.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = clanchatroom.cpp; sourceTree = "<group>"; };
50D642861461EF3200A5739B /* clanchatroom.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = clanchatroom.h; sourceTree = "<group>"; };
50E77DD11362190C000FC072 /* cglmbuffer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cglmbuffer.cpp; path = ../glmgr/cglmbuffer.cpp; sourceTree = "<group>"; };
50E77DD21362190C000FC072 /* cglmbuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cglmbuffer.h; path = ../glmgr/cglmbuffer.h; sourceTree = "<group>"; };
50E77DD31362190C000FC072 /* cglmfbo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cglmfbo.cpp; path = ../glmgr/cglmfbo.cpp; sourceTree = "<group>"; };
50E77DD41362190C000FC072 /* cglmfbo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cglmfbo.h; path = ../glmgr/cglmfbo.h; sourceTree = "<group>"; };
50E77DD51362190C000FC072 /* cglmprogram.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cglmprogram.cpp; path = ../glmgr/cglmprogram.cpp; sourceTree = "<group>"; };
50E77DD61362190C000FC072 /* cglmprogram.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cglmprogram.h; path = ../glmgr/cglmprogram.h; sourceTree = "<group>"; };
50E77DD71362190C000FC072 /* cglmquery.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cglmquery.cpp; path = ../glmgr/cglmquery.cpp; sourceTree = "<group>"; };
50E77DD81362190C000FC072 /* cglmquery.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cglmquery.h; path = ../glmgr/cglmquery.h; sourceTree = "<group>"; };
50E77DD91362190C000FC072 /* cglmtex.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cglmtex.cpp; path = ../glmgr/cglmtex.cpp; sourceTree = "<group>"; };
50E77DDA1362190C000FC072 /* cglmtex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cglmtex.h; path = ../glmgr/cglmtex.h; sourceTree = "<group>"; };
50E77DDB1362190C000FC072 /* dx9asmtogl2.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = dx9asmtogl2.cpp; path = ../glmgr/dx9asmtogl2.cpp; sourceTree = "<group>"; };
50E77DDC1362190C000FC072 /* dx9asmtogl2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dx9asmtogl2.h; path = ../glmgr/dx9asmtogl2.h; sourceTree = "<group>"; };
50E77DDD1362190C000FC072 /* dxabstract.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = dxabstract.cpp; path = ../glmgr/dxabstract.cpp; sourceTree = "<group>"; };
50E77DDE1362190C000FC072 /* dxabstract.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = dxabstract.h; path = ../glmgr/dxabstract.h; sourceTree = "<group>"; };
50E77DDF1362190C000FC072 /* glmdebug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = glmdebug.h; path = ../glmgr/glmdebug.h; sourceTree = "<group>"; };
50E77DE01362190C000FC072 /* glmdisplay.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = glmdisplay.h; path = ../glmgr/glmdisplay.h; sourceTree = "<group>"; };
50E77DE11362190C000FC072 /* glmgr.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = glmgr.cpp; path = ../glmgr/glmgr.cpp; sourceTree = "<group>"; };
50E77DE21362190C000FC072 /* glmgr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = glmgr.h; path = ../glmgr/glmgr.h; sourceTree = "<group>"; };
50E77DE31362190C000FC072 /* glmgrbasics.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = glmgrbasics.cpp; path = ../glmgr/glmgrbasics.cpp; sourceTree = "<group>"; };
50E77DE41362190C000FC072 /* glmgrbasics.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = glmgrbasics.h; path = ../glmgr/glmgrbasics.h; sourceTree = "<group>"; };
50E77DE51362190C000FC072 /* glmgrcocoa.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = glmgrcocoa.mm; path = ../glmgr/glmgrcocoa.mm; sourceTree = "<group>"; };
50E77DE61362190C000FC072 /* glmgrext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = glmgrext.cpp; path = ../glmgr/glmgrext.cpp; sourceTree = "<group>"; };
50E77DE71362190C000FC072 /* glmgrext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = glmgrext.h; path = ../glmgr/glmgrext.h; sourceTree = "<group>"; };
50E77DE81362190C000FC072 /* imageformat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imageformat.h; path = ../glmgr/imageformat.h; sourceTree = "<group>"; };
50E77DE91362190C000FC072 /* mathlite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = mathlite.cpp; path = ../glmgr/mathlite.cpp; sourceTree = "<group>"; };
50E77DEA1362190C000FC072 /* mathlite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = mathlite.h; path = ../glmgr/mathlite.h; sourceTree = "<group>"; };
50E77DF713621991000FC072 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; };
840B386E19BB91C50084B9F1 /* htmlsurface.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = htmlsurface.cpp; sourceTree = "<group>"; };
840B386F19BB91C50084B9F1 /* htmlsurface.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = htmlsurface.h; sourceTree = "<group>"; };
975820DA2765BE3900093F91 /* ItemStore.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ItemStore.cpp; sourceTree = "<group>"; };
975820DD2765BE5000093F91 /* ItemStore.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ItemStore.h; sourceTree = "<group>"; };
97919DA42C22280B00272343 /* timeline.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = timeline.h; sourceTree = "<group>"; };
97919DA52C22281400272343 /* timeline.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = timeline.cpp; sourceTree = "<group>"; };
A46ECF6D26BE389800985AA7 /* steamworksexample.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; name = steamworksexample.entitlements; path = osx/steamworksexample.entitlements; sourceTree = "<group>"; };
A4B5A0FC24906974000E9151 /* RemotePlay.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RemotePlay.cpp; sourceTree = "<group>"; };
A4B5A0FE2490698A000E9151 /* RemotePlay.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RemotePlay.h; sourceTree = "<group>"; };
A4B5A10224906A0E000E9151 /* SimpleProtobuf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleProtobuf.h; sourceTree = "<group>"; };
A4B5A10324906A0E000E9151 /* SimpleProtobuf.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SimpleProtobuf.cpp; sourceTree = "<group>"; };
BA60B6B41A82EDD200F4AC4F /* Friends.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Friends.cpp; sourceTree = "<group>"; };
BA60B6B51A82EDD200F4AC4F /* Friends.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Friends.h; sourceTree = "<group>"; };
BA60B6B61A82EDD200F4AC4F /* Inventory.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Inventory.cpp; sourceTree = "<group>"; };
BA60B6B71A82EDD200F4AC4F /* Inventory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Inventory.h; sourceTree = "<group>"; };
F323060828947C1800E66D30 /* OverlayExamples.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = OverlayExamples.cpp; sourceTree = "<group>"; };
F323060A28947C2C00E66D30 /* OverlayExamples.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OverlayExamples.h; sourceTree = "<group>"; };
F803304F19087DA600344590 /* musicplayer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = musicplayer.h; sourceTree = "<group>"; };
F803305019087F9200344590 /* musicplayer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = musicplayer.cpp; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
503C6CAF1268F34200B66E3B /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
50E77DF813621991000FC072 /* IOKit.framework in Frameworks */,
503C6DB41269002800B66E3B /* libsteam_api.dylib in Frameworks */,
503C6DAC1268FE1000B66E3B /* OpenAL.framework in Frameworks */,
503C6DAD1268FE1000B66E3B /* OpenGL.framework in Frameworks */,
503C6CB61268F34200B66E3B /* Cocoa.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
503C6CA31268F34200B66E3B = {
isa = PBXGroup;
children = (
503C6D291268F4EE00B66E3B /* Headers */,
503C6CAB1268F34200B66E3B /* Source */,
503C6CAC1268F34200B66E3B /* Resources */,
503C6CAD1268F34200B66E3B /* Frameworks */,
503C6CB31268F34200B66E3B /* Products */,
);
sourceTree = "<group>";
};
503C6CAB1268F34200B66E3B /* Source */ = {
isa = PBXGroup;
children = (
50E77DCF136218F5000FC072 /* glmgr */,
503C6CD91268F49F00B66E3B /* BaseMenu.cpp */,
50D642851461EF3200A5739B /* clanchatroom.cpp */,
BA60B6B41A82EDD200F4AC4F /* Friends.cpp */,
503C6CE01268F49F00B66E3B /* gameengineosx.mm */,
503C6CE21268F49F00B66E3B /* glstringosx.mm */,
840B386E19BB91C50084B9F1 /* htmlsurface.cpp */,
BA60B6B61A82EDD200F4AC4F /* Inventory.cpp */,
975820DA2765BE3900093F91 /* ItemStore.cpp */,
503C6CE31268F49F00B66E3B /* Leaderboards.cpp */,
503C6CE51268F49F00B66E3B /* Lobby.cpp */,
503C6CE71268F49F00B66E3B /* Main.cpp */,
503C6CE81268F49F00B66E3B /* MainMenu.cpp */,
F803305019087F9200344590 /* musicplayer.cpp */,
F323060828947C1800E66D30 /* OverlayExamples.cpp */,
503C6CED1268F49F00B66E3B /* p2pauth.cpp */,
503C6CEF1268F49F00B66E3B /* PhotonBeam.cpp */,
503C6CF11268F49F00B66E3B /* QuitMenu.cpp */,
A4B5A0FC24906974000E9151 /* RemotePlay.cpp */,
503C6CF31268F49F00B66E3B /* RemoteStorage.cpp */,
503C6CF51268F49F00B66E3B /* ServerBrowser.cpp */,
503C6CF81268F49F00B66E3B /* Ship.cpp */,
A4B5A10324906A0E000E9151 /* SimpleProtobuf.cpp */,
503C6CFB1268F49F00B66E3B /* SpaceWarClient.cpp */,
503C6CFD1268F49F00B66E3B /* SpaceWarEntity.cpp */,
503C6D011268F49F00B66E3B /* SpaceWarServer.cpp */,
503C6D031268F49F00B66E3B /* StarField.cpp */,
503C6D051268F49F00B66E3B /* StatsAndAchievements.cpp */,
503C6D071268F49F00B66E3B /* stdafx.cpp */,
503C6D091268F49F00B66E3B /* Sun.cpp */,
97919DA52C22281400272343 /* timeline.cpp */,
503C6D0B1268F49F00B66E3B /* VectorEntity.cpp */,
503C6D0D1268F49F00B66E3B /* voicechat.cpp */,
);
name = Source;
sourceTree = "<group>";
};
503C6CAC1268F34200B66E3B /* Resources */ = {
isa = PBXGroup;
children = (
A46ECF6D26BE389800985AA7 /* steamworksexample.entitlements */,
504EDCC01269025A00F96D63 /* steam_appid.txt */,
504EDCB4126900D600F96D63 /* steamworksexample-Info.plist */,
);
name = Resources;
sourceTree = "<group>";
};
503C6CAD1268F34200B66E3B /* Frameworks */ = {
isa = PBXGroup;
children = (
50E77DF713621991000FC072 /* IOKit.framework */,
503C6DAA1268FE1000B66E3B /* OpenAL.framework */,
503C6DAB1268FE1000B66E3B /* OpenGL.framework */,
503C6DB31269002800B66E3B /* libsteam_api.dylib */,
503C6CB51268F34200B66E3B /* Cocoa.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
503C6CB31268F34200B66E3B /* Products */ = {
isa = PBXGroup;
children = (
503C6CB21268F34200B66E3B /* steamworksexample.app */,
);
name = Products;
sourceTree = "<group>";
};
503C6D291268F4EE00B66E3B /* Headers */ = {
isa = PBXGroup;
children = (
503C6CDA1268F49F00B66E3B /* BaseMenu.h */,
50D642861461EF3200A5739B /* clanchatroom.h */,
BA60B6B51A82EDD200F4AC4F /* Friends.h */,
503C6CDD1268F49F00B66E3B /* GameEngine.h */,
503C6CDF1268F49F00B66E3B /* gameengineosx.h */,
503C6CE11268F49F00B66E3B /* glstringosx.h */,
840B386F19BB91C50084B9F1 /* htmlsurface.h */,
BA60B6B71A82EDD200F4AC4F /* Inventory.h */,
975820DD2765BE5000093F91 /* ItemStore.h */,
503C6CE41268F49F00B66E3B /* Leaderboards.h */,
503C6CE61268F49F00B66E3B /* Lobby.h */,
503C6CE91268F49F00B66E3B /* MainMenu.h */,
503C6CEA1268F49F00B66E3B /* Messages.h */,
F803304F19087DA600344590 /* musicplayer.h */,
F323060A28947C2C00E66D30 /* OverlayExamples.h */,
503C6CEE1268F49F00B66E3B /* p2pauth.h */,
503C6CF01268F49F00B66E3B /* PhotonBeam.h */,
503C6CF21268F49F00B66E3B /* QuitMenu.h */,
A4B5A0FE2490698A000E9151 /* RemotePlay.h */,
503C6CF41268F49F00B66E3B /* RemoteStorage.h */,
503C6CF61268F49F00B66E3B /* ServerBrowser.h */,
503C6CF71268F49F00B66E3B /* ServerBrowserMenu.h */,
503C6CF91268F49F00B66E3B /* Ship.h */,
A4B5A10224906A0E000E9151 /* SimpleProtobuf.h */,
503C6CFA1268F49F00B66E3B /* SpaceWar.h */,
503C6CFC1268F49F00B66E3B /* SpaceWarClient.h */,
503C6CFE1268F49F00B66E3B /* SpaceWarEntity.h */,
503C6CFF1268F49F00B66E3B /* SpaceWarRes.h */,
503C6D021268F49F00B66E3B /* SpaceWarServer.h */,
503C6D041268F49F00B66E3B /* StarField.h */,
503C6D061268F49F00B66E3B /* StatsAndAchievements.h */,
503C6D081268F49F00B66E3B /* stdafx.h */,
503C6D0A1268F49F00B66E3B /* Sun.h */,
97919DA42C22280B00272343 /* timeline.h */,
503C6D0C1268F49F00B66E3B /* VectorEntity.h */,
503C6D0E1268F49F00B66E3B /* voicechat.h */,
);
name = Headers;
sourceTree = "<group>";
};
50E77DCF136218F5000FC072 /* glmgr */ = {
isa = PBXGroup;
children = (
50E77DD11362190C000FC072 /* cglmbuffer.cpp */,
50E77DD21362190C000FC072 /* cglmbuffer.h */,
50E77DD31362190C000FC072 /* cglmfbo.cpp */,
50E77DD41362190C000FC072 /* cglmfbo.h */,
50E77DD51362190C000FC072 /* cglmprogram.cpp */,
50E77DD61362190C000FC072 /* cglmprogram.h */,
50E77DD71362190C000FC072 /* cglmquery.cpp */,
50E77DD81362190C000FC072 /* cglmquery.h */,
50E77DD91362190C000FC072 /* cglmtex.cpp */,
50E77DDA1362190C000FC072 /* cglmtex.h */,
50E77DDB1362190C000FC072 /* dx9asmtogl2.cpp */,
50E77DDC1362190C000FC072 /* dx9asmtogl2.h */,
50E77DDD1362190C000FC072 /* dxabstract.cpp */,
50E77DDE1362190C000FC072 /* dxabstract.h */,
50E77DDF1362190C000FC072 /* glmdebug.h */,
50E77DE01362190C000FC072 /* glmdisplay.h */,
50E77DE11362190C000FC072 /* glmgr.cpp */,
50E77DE21362190C000FC072 /* glmgr.h */,
50E77DE31362190C000FC072 /* glmgrbasics.cpp */,
50E77DE41362190C000FC072 /* glmgrbasics.h */,
50E77DE51362190C000FC072 /* glmgrcocoa.mm */,
50E77DE61362190C000FC072 /* glmgrext.cpp */,
50E77DE71362190C000FC072 /* glmgrext.h */,
50E77DE81362190C000FC072 /* imageformat.h */,
50E77DE91362190C000FC072 /* mathlite.cpp */,
50E77DEA1362190C000FC072 /* mathlite.h */,
);
name = glmgr;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
503C6CB11268F34200B66E3B /* steamworksexample */ = {
isa = PBXNativeTarget;
buildConfigurationList = 503C6CC91268F34200B66E3B /* Build configuration list for PBXNativeTarget "steamworksexample" */;
buildPhases = (
503C6CAE1268F34200B66E3B /* Sources */,
503C6CAF1268F34200B66E3B /* Frameworks */,
503C6CB01268F34200B66E3B /* Resources */,
504EDCBB126901D200F96D63 /* CopyFiles */,
);
buildRules = (
);
dependencies = (
);
name = steamworksexample;
productName = steamworksexample;
productReference = 503C6CB21268F34200B66E3B /* steamworksexample.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
503C6CA51268F34200B66E3B /* Project object */ = {
isa = PBXProject;
attributes = {
};
buildConfigurationList = 503C6CA81268F34200B66E3B /* Build configuration list for PBXProject "steamworksexample" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
English,
en,
);
mainGroup = 503C6CA31268F34200B66E3B;
productRefGroup = 503C6CB31268F34200B66E3B /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
503C6CB11268F34200B66E3B /* steamworksexample */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
503C6CB01268F34200B66E3B /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
503C6CAE1268F34200B66E3B /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
840B387019BB91C50084B9F1 /* htmlsurface.cpp in Sources */,
503C6D0F1268F49F00B66E3B /* BaseMenu.cpp in Sources */,
F803305119087F9200344590 /* musicplayer.cpp in Sources */,
503C6D121268F49F00B66E3B /* gameengineosx.mm in Sources */,
503C6D131268F49F00B66E3B /* glstringosx.mm in Sources */,
503C6D141268F49F00B66E3B /* Leaderboards.cpp in Sources */,
503C6D151268F49F00B66E3B /* Lobby.cpp in Sources */,
A4B5A0FD24906974000E9151 /* RemotePlay.cpp in Sources */,
503C6D161268F49F00B66E3B /* Main.cpp in Sources */,
503C6D171268F49F00B66E3B /* MainMenu.cpp in Sources */,
503C6D191268F49F00B66E3B /* p2pauth.cpp in Sources */,
503C6D1A1268F49F00B66E3B /* PhotonBeam.cpp in Sources */,
503C6D1B1268F49F00B66E3B /* QuitMenu.cpp in Sources */,
503C6D1C1268F49F00B66E3B /* RemoteStorage.cpp in Sources */,
503C6D1D1268F49F00B66E3B /* ServerBrowser.cpp in Sources */,
503C6D1E1268F49F00B66E3B /* Ship.cpp in Sources */,
503C6D1F1268F49F00B66E3B /* SpaceWarClient.cpp in Sources */,
503C6D201268F49F00B66E3B /* SpaceWarEntity.cpp in Sources */,
503C6D221268F49F00B66E3B /* SpaceWarServer.cpp in Sources */,
503C6D231268F49F00B66E3B /* StarField.cpp in Sources */,
503C6D241268F49F00B66E3B /* StatsAndAchievements.cpp in Sources */,
503C6D251268F49F00B66E3B /* stdafx.cpp in Sources */,
503C6D261268F49F00B66E3B /* Sun.cpp in Sources */,
503C6D271268F49F00B66E3B /* VectorEntity.cpp in Sources */,
503C6D281268F49F00B66E3B /* voicechat.cpp in Sources */,
50E77DEB1362190C000FC072 /* cglmbuffer.cpp in Sources */,
50E77DEC1362190C000FC072 /* cglmfbo.cpp in Sources */,
F323060928947C1800E66D30 /* OverlayExamples.cpp in Sources */,
50E77DED1362190C000FC072 /* cglmprogram.cpp in Sources */,
BA60B6B91A82EDD200F4AC4F /* Inventory.cpp in Sources */,
975820DB2765BE3900093F91 /* ItemStore.cpp in Sources */,
50E77DEE1362190C000FC072 /* cglmquery.cpp in Sources */,
50E77DEF1362190C000FC072 /* cglmtex.cpp in Sources */,
A4B5A10424906A0E000E9151 /* SimpleProtobuf.cpp in Sources */,
50E77DF01362190C000FC072 /* dx9asmtogl2.cpp in Sources */,
50E77DF11362190C000FC072 /* dxabstract.cpp in Sources */,
50E77DF21362190C000FC072 /* glmgr.cpp in Sources */,
50E77DF31362190C000FC072 /* glmgrbasics.cpp in Sources */,
50E77DF41362190C000FC072 /* glmgrcocoa.mm in Sources */,
50E77DF51362190C000FC072 /* glmgrext.cpp in Sources */,
97919DA62C22281400272343 /* timeline.cpp in Sources */,
BA60B6B81A82EDD200F4AC4F /* Friends.cpp in Sources */,
50E77DF61362190C000FC072 /* mathlite.cpp in Sources */,
50D642871461EF3200A5739B /* clanchatroom.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
503C6CC71268F34200B66E3B /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = osx/steamworksexample.entitlements;
ENABLE_HARDENED_RUNTIME = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
DEBUG,
GL_SILENCE_DEPRECATION,
);
"GCC_PREPROCESSOR_DEFINITIONS[arch=*]" = (
POSIX,
OSX,
GL_SILENCE_DEPRECATION,
);
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO;
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = NO;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = NO;
MACOSX_DEPLOYMENT_TARGET = 10.11;
OTHER_CODE_SIGN_FLAGS = "--deep";
SDKROOT = macosx;
USER_HEADER_SEARCH_PATHS = ../public;
};
name = Debug;
};
503C6CC81268F34200B66E3B /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = osx/steamworksexample.entitlements;
ENABLE_HARDENED_RUNTIME = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
"GCC_PREPROCESSOR_DEFINITIONS[arch=*]" = (
POSIX,
OSX,
);
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO;
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = NO;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = NO;
MACOSX_DEPLOYMENT_TARGET = 10.11;
OTHER_CODE_SIGN_FLAGS = "--deep";
SDKROOT = macosx;
USER_HEADER_SEARCH_PATHS = ../public;
};
name = Release;
};
503C6CCA1268F34200B66E3B /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
CLANG_LINK_OBJC_RUNTIME = NO;
COPY_PHASE_STRIP = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
INFOPLIST_FILE = "osx/steamworksexample-Info.plist";
INSTALL_PATH = "$(HOME)/Applications";
LIBRARY_SEARCH_PATHS = (
../lib/osx32/release,
"\"$(SRCROOT)/../lib/osx32/release\"",
../lib/osx/release,
"\"$(SRCROOT)/../lib/osx/release\"",
../redistributable_bin/osx/,
);
PRODUCT_BUNDLE_IDENTIFIER = com.valvesoftware.steam.steamworksexample;
PRODUCT_NAME = steamworksexample;
WRAPPER_EXTENSION = app;
};
name = Debug;
};
503C6CCB1268F34200B66E3B /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
CLANG_LINK_OBJC_RUNTIME = NO;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
INFOPLIST_FILE = "osx/steamworksexample-Info.plist";
INSTALL_PATH = "$(HOME)/Applications";
LIBRARY_SEARCH_PATHS = (
../lib/osx32/debug,
"\"$(SRCROOT)/../lib/osx32/release\"",
../lib/osx/debug,
"\"$(SRCROOT)/../lib/osx/release\"",
../redistributable_bin/osx/,
);
PRODUCT_BUNDLE_IDENTIFIER = com.valvesoftware.steam.steamworksexample;
PRODUCT_NAME = steamworksexample;
WRAPPER_EXTENSION = app;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
503C6CA81268F34200B66E3B /* Build configuration list for PBXProject "steamworksexample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
503C6CC71268F34200B66E3B /* Debug */,
503C6CC81268F34200B66E3B /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
503C6CC91268F34200B66E3B /* Build configuration list for PBXNativeTarget "steamworksexample" */ = {
isa = XCConfigurationList;
buildConfigurations = (
503C6CCA1268F34200B66E3B /* Debug */,
503C6CCB1268F34200B66E3B /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 503C6CA51268F34200B66E3B /* Project object */;
}
+121
View File
@@ -0,0 +1,121 @@
//====== Copyright © 1996-2023 Valve Corporation, All rights reserved. =======
//
// Purpose: Class for adding to the Game Recording Timeline for different game states
//
//=============================================================================
#include "stdafx.h"
#include "timeline.h"
#include "SpaceWarClient.h"
extern uint32 Plat_GetTicks();
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CTimeline::CTimeline( IGameEngine *pGameEngine ) :
m_pGameEngine( pGameEngine ),
m_GameID( SteamUtils()->GetAppID() ),
m_bInGame( false )
{
SteamTimeline()->SetTimelineGameMode( k_ETimelineGameMode_Menus );
m_ulSessionCounter = 0;
m_ulInGameStartTime = 0;
m_unLastTimestampIndexDisplayed = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Game state has changed
//-----------------------------------------------------------------------------
void CTimeline::OnGameStateChange( EClientGameState eNewState )
{
bool bInGameNow = false;
switch ( eNewState )
{
case k_EClientGameWaitingForPlayers:
case k_EClientGameActive:
case k_EClientGameQuitMenu:
case k_EClientGameDraw:
case k_EClientGameWinner:
bInGameNow = true;
break;
case k_EClientStatsAchievements:
case k_EClientGameStartServer:
case k_EClientGameMenu:
case k_EClientGameExiting:
case k_EClientGameInstructions:
case k_EClientGameConnecting:
case k_EClientGameConnectionFailure:
case k_EClientFindInternetServers:
default:
break;
}
// change the timeline bar from gray to blue and add a timeline range covering the game session
if ( m_bInGame != bInGameNow )
{
if ( bInGameNow )
{
SteamTimeline()->SetTimelineGameMode( k_ETimelineGameMode_Playing );
m_unSessionStart = Plat_GetTicks();
// start timers for adding timeline timestamps
m_ulInGameStartTime = m_pGameEngine->GetGameTickCount();
m_unLastTimestampIndexDisplayed = 0;
}
else
{
SteamTimeline()->SetTimelineGameMode( k_ETimelineGameMode_Menus );
uint32 unSessionEnd = Plat_GetTicks();
uint32 unSessionDuration = unSessionEnd - m_unSessionStart;
float flDurationSeconds = (float)unSessionDuration / 1000.f;
float flStartOffsetSeconds = -flDurationSeconds;
SteamTimeline()->AddRangeTimelineEvent( "In Match", nullptr, "steam_starburst", 100, flStartOffsetSeconds, flDurationSeconds, k_ETimelineEventClipPriority_None );
}
m_bInGame = bInGameNow;
}
// add a highlight marker every time the player wins
if ( eNewState == k_EClientGameWinner && SpaceWarClient()->BLocalPlayerWonLastGame() )
{
SteamTimeline()->AddInstantaneousTimelineEvent( "Winner!", "You won a round!", "steam_attack", 10, 0, k_ETimelineEventClipPriority_Standard );
}
else if ( eNewState == k_EClientGameDraw )
{
SteamTimeline()->AddInstantaneousTimelineEvent( "Draw", "This round was a draw.", "steam_defend", 5, 0, k_ETimelineEventClipPriority_None );
}
}
//-----------------------------------------------------------------------------
// Purpose: Run a frame. Does not need to run at full frame rate.
//-----------------------------------------------------------------------------
void CTimeline::RunFrame()
{
if ( m_bInGame )
{
// every 5 minutes, add a new timeline timestamp in the form of "05:00", "10:00", etc.
// Note: we use 5 minutes here for demo purposes, but if appropriate for your game, you
// might want to choose a larger interval to keep the Timeline less cluttered for users
const uint32 k_unMinutesBetweenTimestamps = 5;
const uint64 k_unMaxTimeToDisplayIndex = 95 / k_unMinutesBetweenTimestamps;
uint64 ulSinceStartMS = m_pGameEngine->GetGameTickCount() - m_ulInGameStartTime;
uint32 unTimestampIndex = (int)( ulSinceStartMS / (k_unMinutesBetweenTimestamps * 60 * 1000) );
if ( unTimestampIndex > 0 && unTimestampIndex > m_unLastTimestampIndexDisplayed && unTimestampIndex <= k_unMaxTimeToDisplayIndex )
{
// max string length is "95:00"
char rgchBuffer[ 6 ];
sprintf_safe( rgchBuffer, "%02d:00", unTimestampIndex * k_unMinutesBetweenTimestamps );
SteamTimeline()->SetTimelineTooltip( rgchBuffer, 0 );
m_unLastTimestampIndexDisplayed = unTimestampIndex;
}
}
}
+33
View File
@@ -0,0 +1,33 @@
//====== Copyright © 1996-2023 Valve Corporation, All rights reserved. =======
//
// Purpose: Class for adding to the Game Recording Timeline for different game states
//
//=============================================================================
#ifndef TIMELINE_H
#define TIMELINE_H
#include "SpaceWar.h"
#include "GameEngine.h"
class CTimeline
{
public:
CTimeline( IGameEngine *pGameEngine );
void RunFrame();
void OnGameStateChange( EClientGameState eNewState );
private:
CGameID m_GameID;
IGameEngine *m_pGameEngine;
bool m_bInGame;
uint64 m_ulInGameStartTime;
uint32 m_unLastTimestampIndexDisplayed;
uint64 m_ulSessionCounter;
uint32 m_unSessionStart;
};
#endif // TIMELINE_H

Some files were not shown because too many files have changed in this diff Show More