This commit is contained in:
FluorescentCIAAfricanAmerican
2020-04-22 12:56:21 -04:00
commit 3bf9df6b27
15370 changed files with 5489726 additions and 0 deletions

View File

@ -0,0 +1,72 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "BackgroundMenuButton.h"
#include <KeyValues.h>
#include <vgui/IImage.h>
#include <vgui/IScheme.h>
#include <vgui_controls/Menu.h>
#include <vgui_controls/MenuItem.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CBackgroundMenuButton::CBackgroundMenuButton(vgui::Panel *parent, const char *name) : BaseClass(parent, name, "")
{
m_pImage = NULL;
m_pMouseOverImage = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CBackgroundMenuButton::~CBackgroundMenuButton()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBackgroundMenuButton::OnCommand(const char *command)
{
BaseClass::OnCommand(command);
}
//-----------------------------------------------------------------------------
// Purpose: Makes the button transparent
//-----------------------------------------------------------------------------
void CBackgroundMenuButton::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
// hack some colors in
SetFgColor(Color(255, 255, 255, 255));
SetBgColor(Color(0, 0, 0, 0));
SetDefaultColor(Color(255, 255, 255, 255), Color(0, 0, 0, 0));
SetArmedColor(Color(255, 255, 0, 255), Color(0, 0, 0, 0));
SetDepressedColor(Color(255, 255, 0, 255), Color(0, 0, 0, 0));
SetContentAlignment(Label::a_west);
SetBorder(NULL);
SetDefaultBorder(NULL);
SetDepressedBorder(NULL);
SetKeyFocusBorder(NULL);
SetTextInset(0, 0);
SetAlpha(0);
/*
// sounds disabled for this button (since it's so big now)
SetArmedSound("UI/buttonrollover.wav");
SetDepressedSound("UI/buttonclick.wav");
SetReleasedSound("UI/buttonclickrelease.wav");
*/
}

View File

@ -0,0 +1,39 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef BACKGROUNDMENUBUTTON_H
#define BACKGROUNDMENUBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Button.h>
//-----------------------------------------------------------------------------
// Purpose: Baseclass for the left and right ingame menus that lay on the background
//-----------------------------------------------------------------------------
class CBackgroundMenuButton : public vgui::Button
{
public:
CBackgroundMenuButton(vgui::Panel *parent, const char *name);
~CBackgroundMenuButton();
virtual void OnCommand(const char *command);
protected:
vgui::Menu *RecursiveLoadGameMenu(KeyValues *datafile);
vgui::Menu *m_pMenu;
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
private:
vgui::IImage *m_pImage, *m_pMouseOverImage;
typedef vgui::Button BaseClass;
};
#endif // BACKGROUNDMENUBUTTON_H

4832
gameui/BasePanel.cpp Normal file

File diff suppressed because it is too large Load Diff

462
gameui/BasePanel.h Normal file
View File

@ -0,0 +1,462 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef BASEPANEL_H
#define BASEPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Panel.h"
#include "vgui_controls/PHandle.h"
#include "vgui_controls/MenuItem.h"
#include "vgui_controls/MessageDialog.h"
#include "KeyValues.h"
#include "utlvector.h"
#include "tier1/CommandBuffer.h"
#include "ixboxsystem.h"
#if !defined( _X360 )
#include "xbox/xboxstubs.h"
#endif
enum
{
DIALOG_STACK_IDX_STANDARD,
DIALOG_STACK_IDX_WARNING,
DIALOG_STACK_IDX_ERROR,
};
class CMatchmakingBasePanel;
class CBackgroundMenuButton;
class CGameMenu;
class CAsyncCtxOnDeviceAttached;
// X360TBD: Move into a separate module when finished
class CMessageDialogHandler
{
public:
CMessageDialogHandler();
void ShowMessageDialog( int nType, vgui::Panel *pOwner );
void CloseMessageDialog( const uint nType = 0 );
void CloseAllMessageDialogs();
void CreateMessageDialog( const uint nType, const char *pTitle, const char *pMsg, const char *pCmdA, const char *pCmdB, vgui::Panel *pCreator, bool bShowActivity = false );
void ActivateMessageDialog( int nStackIdx );
void PositionDialogs( int wide, int tall );
void PositionDialog( vgui::PHandle dlg, int wide, int tall );
private:
static const int MAX_MESSAGE_DIALOGS = 3;
vgui::DHANDLE< CMessageDialog > m_hMessageDialogs[MAX_MESSAGE_DIALOGS];
int m_iDialogStackTop;
};
//-----------------------------------------------------------------------------
// Purpose: Panel that acts as background for button icons and help text in the UI
//-----------------------------------------------------------------------------
class CFooterPanel : public vgui::EditablePanel
{
DECLARE_CLASS_SIMPLE( CFooterPanel, vgui::EditablePanel );
public:
CFooterPanel( Panel *parent, const char *panelName );
virtual ~CFooterPanel();
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void ApplySettings( KeyValues *pResourceData );
virtual void Paint( void );
virtual void PaintBackground( void );
// caller tags the current hint, used to assist in ownership
void SetHelpNameAndReset( const char *pName );
const char *GetHelpName();
void AddButtonsFromMap( vgui::Frame *pMenu );
void SetStandardDialogButtons();
void AddNewButtonLabel( const char *text, const char *icon );
void ShowButtonLabel( const char *name, bool show = true );
void SetButtonText( const char *buttonName, const char *text );
void ClearButtons();
void SetButtonGap( int nButtonGap ){ m_nButtonGap = nButtonGap; }
void UseDefaultButtonGap(){ m_nButtonGap = m_nButtonGapDefault; }
private:
struct ButtonLabel_t
{
bool bVisible;
char name[MAX_PATH];
wchar_t text[MAX_PATH];
wchar_t icon[2]; // icon is a single character
};
CUtlVector< ButtonLabel_t* > m_ButtonLabels;
vgui::Label *m_pSizingLabel; // used to measure font sizes
bool m_bPaintBackground; // fill the background?
bool m_bCenterHorizontal; // center buttons horizontally?
int m_ButtonPinRight; // if not centered, this is the distance from the right margin that we use to start drawing buttons (right to left)
int m_nButtonGap; // space between buttons when drawing
int m_nButtonGapDefault; // space between buttons (initial value)
int m_FooterTall; // height of the footer
int m_ButtonOffsetFromTop; // how far below the top the buttons should be drawn
int m_ButtonSeparator; // space between the button icon and text
int m_TextAdjust; // extra adjustment for the text (vertically)...text is centered on the button icon and then this value is applied
char m_szTextFont[64]; // font for the button text
char m_szButtonFont[64]; // font for the button icon
char m_szFGColor[64]; // foreground color (text)
char m_szBGColor[64]; // background color (fill color)
vgui::HFont m_hButtonFont;
vgui::HFont m_hTextFont;
char *m_pHelpName;
};
//-----------------------------------------------------------------------------
// Purpose: EditablePanel that can replace the GameMenuButtons in CBasePanel
//-----------------------------------------------------------------------------
class CMainMenuGameLogo : public vgui::EditablePanel
{
DECLARE_CLASS_SIMPLE( CMainMenuGameLogo, vgui::EditablePanel );
public:
CMainMenuGameLogo( vgui::Panel *parent, const char *name );
virtual void ApplySettings( KeyValues *inResourceData );
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
int GetOffsetX(){ return m_nOffsetX; }
int GetOffsetY(){ return m_nOffsetY; }
private:
int m_nOffsetX;
int m_nOffsetY;
};
//-----------------------------------------------------------------------------
// Purpose: Transparent menu item designed to sit on the background ingame
//-----------------------------------------------------------------------------
class CGameMenuItem : public vgui::MenuItem
{
DECLARE_CLASS_SIMPLE( CGameMenuItem, vgui::MenuItem );
public:
CGameMenuItem(vgui::Menu *parent, const char *name);
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void PaintBackground( void );
void SetRightAlignedText( bool state );
private:
bool m_bRightAligned;
};
//-----------------------------------------------------------------------------
// Purpose: This is the panel at the top of the panel hierarchy for GameUI
// It handles all the menus, background images, and loading dialogs
//-----------------------------------------------------------------------------
class CBasePanel : public vgui::Panel
{
DECLARE_CLASS_SIMPLE( CBasePanel, vgui::Panel );
public:
CBasePanel();
virtual ~CBasePanel();
public:
//
// Implementation of async jobs
// An async job is enqueued by calling "ExecuteAsync" with the proper job context.
// Job's function "ExecuteAsync" is called on a separate thread.
// After the job finishes the "Completed" function is called on the
// main thread.
//
class CAsyncJobContext
{
public:
CAsyncJobContext( float flLeastExecuteTime = 0.0f ) : m_flLeastExecuteTime( flLeastExecuteTime ), m_hThreadHandle( NULL ) {}
virtual ~CAsyncJobContext() {}
virtual void ExecuteAsync() = 0; // Executed on the secondary thread
virtual void Completed() = 0; // Executed on the main thread
public:
void * volatile m_hThreadHandle; // Handle to an async job thread waiting for
float m_flLeastExecuteTime; // Least amount of time this job should keep executing
};
CAsyncJobContext *m_pAsyncJob;
void ExecuteAsync( CAsyncJobContext *pAsync );
public:
// notifications
void OnLevelLoadingStarted();
void OnLevelLoadingFinished();
// update the taskbar a frame
void RunFrame();
// fades to black then runs an engine command (usually to start a level)
void FadeToBlackAndRunEngineCommand( const char *engineCommand );
// sets the blinking state of a menu item
void SetMenuItemBlinkingState( const char *itemName, bool state );
// handles gameUI being shown
void OnGameUIActivated();
// game dialogs
void OnOpenNewGameDialog( const char *chapter = NULL );
void OnOpenBonusMapsDialog();
void OnOpenLoadGameDialog();
void OnOpenLoadGameDialog_Xbox();
void OnOpenSaveGameDialog();
void OnOpenSaveGameDialog_Xbox();
void OnOpenServerBrowser();
void OnOpenFriendsDialog();
void OnOpenDemoDialog();
void OnOpenCreateMultiplayerGameDialog();
void OnOpenQuitConfirmationDialog();
void OnOpenDisconnectConfirmationDialog();
void OnOpenChangeGameDialog();
void OnOpenPlayerListDialog();
void OnOpenBenchmarkDialog();
void OnOpenOptionsDialog();
void OnOpenOptionsDialog_Xbox();
void OnOpenLoadCommentaryDialog();
void OpenLoadSingleplayerCommentaryDialog();
void OnOpenAchievementsDialog();
//=============================================================================
// HPE_BEGIN:
// [dwenger] Specific code for CS Achievements Display
//=============================================================================
// $TODO(HPE): Move this to a game-specific location
void OnOpenCSAchievementsDialog();
//=============================================================================
// HPE_END
//=============================================================================
void OnOpenAchievementsDialog_Xbox();
void OnOpenControllerDialog();
// Xbox 360
CMatchmakingBasePanel* GetMatchmakingBasePanel();
void OnOpenMatchmakingBasePanel();
void SessionNotification( const int notification, const int param = 0 );
void SystemNotification( const int notification );
void ShowMessageDialog( const uint nType, vgui::Panel *pParent = NULL );
void CloseMessageDialog( const uint nType );
void UpdatePlayerInfo( uint64 nPlayerId, const char *pName, int nTeam, byte cVoiceState, int nPlayersNeeded, bool bHost );
void SessionSearchResult( int searchIdx, void *pHostData, XSESSION_SEARCHRESULT *pResult, int ping );
void OnChangeStorageDevice();
bool ValidateStorageDevice();
bool ValidateStorageDevice( int *pStorageDeviceValidated );
void OnCreditsFinished();
KeyValues *GetConsoleControlSettings( void );
// forces any changed options dialog settings to be applied immediately, if it's open
void ApplyOptionsDialogSettings();
vgui::AnimationController *GetAnimationController( void ) { return m_pConsoleAnimationController; }
void RunCloseAnimation( const char *animName );
void RunAnimationWithCallback( vgui::Panel *parent, const char *animName, KeyValues *msgFunc );
void PositionDialog( vgui::PHandle dlg );
virtual void OnSizeChanged( int newWide, int newTall );
void ArmFirstMenuItem( void );
void OnGameUIHidden();
void CloseBaseDialogs( void );
bool IsWaitingForConsoleUI( void ) { return m_bWaitingForStorageDeviceHandle || m_bWaitingForUserSignIn || m_bXUIVisible; }
#if defined( _X360 )
CON_COMMAND_MEMBER_F( CBasePanel, "gameui_reload_resources", Reload_Resources, "Reload the Xbox 360 UI res files", 0 );
#endif
int GetMenuAlpha( void );
void SetMainMenuOverride( vgui::VPANEL panel );
protected:
virtual void PaintBackground();
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
public:
// FIXME: This should probably become a friend relationship between the classes
bool HandleSignInRequest( const char *command );
bool HandleStorageDeviceRequest( const char *command );
void ClearPostPromptCommand( const char *pCompletedCommand );
private:
enum EBackgroundState
{
BACKGROUND_INITIAL,
BACKGROUND_LOADING,
BACKGROUND_MAINMENU,
BACKGROUND_LEVEL,
BACKGROUND_DISCONNECTED,
BACKGROUND_EXITING, // Console has started an exiting state, cannot be stopped
};
void SetBackgroundRenderState(EBackgroundState state);
friend class CAsyncCtxOnDeviceAttached;
void OnDeviceAttached( void );
void OnCompletedAsyncDeviceAttached( CAsyncCtxOnDeviceAttached *job );
void IssuePostPromptCommand( void );
void UpdateBackgroundState();
// sets the menu alpha [0..255]
void SetMenuAlpha(int alpha);
// menu manipulation
void CreatePlatformMenu();
void CreateGameMenu();
void CreateGameLogo();
void CheckBonusBlinkState();
void UpdateGameMenus();
CGameMenu *RecursiveLoadGameMenu(KeyValues *datafile);
void StartExitingProcess();
bool IsPromptableCommand( const char *command );
bool CommandRequiresSignIn( const char *command );
bool CommandRequiresStorageDevice( const char *command );
bool CommandRespectsSignInDenied( const char *command );
void QueueCommand( const char *pCommand );
void RunQueuedCommands();
void ClearQueuedCommands();
virtual void OnCommand(const char *command);
virtual void PerformLayout();
MESSAGE_FUNC_INT( OnActivateModule, "ActivateModule", moduleIndex);
void UpdateRichPresenceInfo();
// menu logo
CMainMenuGameLogo *m_pGameLogo;
// menu buttons
CUtlVector< CBackgroundMenuButton * >m_pGameMenuButtons;
CGameMenu *m_pGameMenu;
bool m_bPlatformMenuInitialized;
int m_iGameMenuInset;
vgui::VPANEL m_hMainMenuOverridePanel;
struct coord {
int x;
int y;
};
CUtlVector< coord > m_iGameTitlePos;
coord m_iGameMenuPos;
// base dialogs
vgui::DHANDLE<vgui::Frame> m_hNewGameDialog;
vgui::DHANDLE<vgui::Frame> m_hBonusMapsDialog;
vgui::DHANDLE<vgui::Frame> m_hLoadGameDialog;
vgui::DHANDLE<vgui::Frame> m_hLoadGameDialog_Xbox;
vgui::DHANDLE<vgui::Frame> m_hSaveGameDialog;
vgui::DHANDLE<vgui::Frame> m_hSaveGameDialog_Xbox;
vgui::DHANDLE<vgui::PropertyDialog> m_hOptionsDialog;
vgui::DHANDLE<vgui::Frame> m_hOptionsDialog_Xbox;
vgui::DHANDLE<vgui::Frame> m_hCreateMultiplayerGameDialog;
//vgui::DHANDLE<vgui::Frame> m_hDemoPlayerDialog;
vgui::DHANDLE<vgui::Frame> m_hChangeGameDialog;
vgui::DHANDLE<vgui::Frame> m_hPlayerListDialog;
vgui::DHANDLE<vgui::Frame> m_hBenchmarkDialog;
vgui::DHANDLE<vgui::Frame> m_hLoadCommentaryDialog;
vgui::DHANDLE<vgui::Frame> m_hAchievementsDialog;
// Xbox 360
vgui::DHANDLE<vgui::Frame> m_hMatchmakingBasePanel;
vgui::DHANDLE<vgui::Frame> m_hControllerDialog;
EBackgroundState m_eBackgroundState;
CMessageDialogHandler m_MessageDialogHandler;
CUtlVector< CUtlString > m_CommandQueue;
vgui::AnimationController *m_pConsoleAnimationController;
KeyValues *m_pConsoleControlSettings;
void DrawBackgroundImage();
int m_iBackgroundImageID;
int m_iRenderTargetImageID;
int m_iLoadingImageID;
int m_iProductImageID;
bool m_bLevelLoading;
bool m_bEverActivated;
bool m_bCopyFrameBuffer;
bool m_bUseRenderTargetImage;
int m_ExitingFrameCount;
bool m_bXUIVisible;
bool m_bUseMatchmaking;
bool m_bRestartFromInvite;
bool m_bRestartSameGame;
// Used for internal state dealing with blades
bool m_bUserRefusedSignIn;
bool m_bUserRefusedStorageDevice;
bool m_bWaitingForUserSignIn;
bool m_bStorageBladeShown;
CUtlString m_strPostPromptCommand;
// Storage device changing vars
bool m_bWaitingForStorageDeviceHandle;
bool m_bNeedStorageDeviceHandle;
AsyncHandle_t m_hStorageDeviceChangeHandle;
uint m_iStorageID;
int *m_pStorageDeviceValidatedNotify;
// background transition
bool m_bFadingInMenus;
float m_flFadeMenuStartTime;
float m_flFadeMenuEndTime;
bool m_bRenderingBackgroundTransition;
float m_flTransitionStartTime;
float m_flTransitionEndTime;
// Used for rich presence updates on xbox360
bool m_bSinglePlayer;
uint m_iGameID; // matches context value in hl2orange.spa.h
// background fill transition
bool m_bHaveDarkenedBackground;
bool m_bHaveDarkenedTitleText;
bool m_bForceTitleTextUpdate;
float m_flFrameFadeInTime;
Color m_BackdropColor;
CPanelAnimationVar( float, m_flBackgroundFillAlpha, "m_flBackgroundFillAlpha", "0" );
// fading to game
MESSAGE_FUNC_CHARPTR( RunEngineCommand, "RunEngineCommand", command );
MESSAGE_FUNC( FinishDialogClose, "FinishDialogClose" );
public:
MESSAGE_FUNC_CHARPTR( RunMenuCommand, "RunMenuCommand", command );
};
//-----------------------------------------------------------------------------
// Purpose: singleton accessor
//-----------------------------------------------------------------------------
extern CBasePanel *BasePanel();
#endif // BASEPANEL_H

View File

@ -0,0 +1,668 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "BaseSaveGameDialog.h"
#include "filesystem.h"
#include "savegame_version.h"
#include "vgui_controls/PanelListPanel.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/ImagePanel.h"
#include "vgui_controls/Button.h"
#include "tier1/utlbuffer.h"
#include <stdio.h>
#include <stdlib.h>
#include "filesystem.h"
#include "MouseMessageForwardingPanel.h"
#include "TGAImagePanel.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
#define TGA_IMAGE_PANEL_WIDTH 180
#define TGA_IMAGE_PANEL_HEIGHT 100
#define MAX_LISTED_SAVE_GAMES 128
//-----------------------------------------------------------------------------
// Purpose: Describes the layout of a same game pic
//-----------------------------------------------------------------------------
class CSaveGamePanel : public vgui::EditablePanel
{
DECLARE_CLASS_SIMPLE( CSaveGamePanel, vgui::EditablePanel );
public:
CSaveGamePanel( PanelListPanel *parent, const char *name, int saveGameListItemID ) : BaseClass( parent, name )
{
m_iSaveGameListItemID = saveGameListItemID;
m_pParent = parent;
m_pSaveGameImage = new CTGAImagePanel( this, "SaveGameImage" );
m_pAutoSaveImage = new ImagePanel( this, "AutoSaveImage" );
m_pSaveGameScreenshotBackground = new ImagePanel( this, "SaveGameScreenshotBackground" );
m_pChapterLabel = new Label( this, "ChapterLabel", "" );
m_pTypeLabel = new Label( this, "TypeLabel", "" );
m_pElapsedTimeLabel = new Label( this, "ElapsedTimeLabel", "" );
m_pFileTimeLabel = new Label( this, "FileTimeLabel", "" );
CMouseMessageForwardingPanel *panel = new CMouseMessageForwardingPanel(this, NULL);
panel->SetZPos(2);
SetSize( 200, 140 );
LoadControlSettings( "resource/SaveGamePanel.res" );
m_FillColor = m_pSaveGameScreenshotBackground->GetFillColor();
}
void SetSaveGameInfo( SaveGameDescription_t &save )
{
// set the bitmap to display
char tga[_MAX_PATH];
Q_strncpy( tga, save.szFileName, sizeof(tga) );
char *ext = strstr( tga, ".sav" );
if ( ext )
{
strcpy( ext, ".tga" );
}
// If a TGA file exists then it is a user created savegame
if ( g_pFullFileSystem->FileExists( tga ) )
{
m_pSaveGameImage->SetTGA( tga );
}
// If there is no TGA then it is either an autosave or the user TGA file has been deleted
else
{
m_pSaveGameImage->SetVisible( false );
m_pAutoSaveImage->SetVisible( true );
m_pAutoSaveImage->SetImage( "resource\\autosave" );
}
// set the title text
m_pChapterLabel->SetText( save.szComment );
// type
SetControlString( "TypeLabel", save.szType );
SetControlString( "ElapsedTimeLabel", save.szElapsedTime );
SetControlString( "FileTimeLabel", save.szFileTime );
}
MESSAGE_FUNC_INT( OnPanelSelected, "PanelSelected", state )
{
if ( state )
{
// set the text color to be orange, and the pic border to be orange
m_pSaveGameScreenshotBackground->SetFillColor( m_SelectedColor );
m_pChapterLabel->SetFgColor( m_SelectedColor );
m_pTypeLabel->SetFgColor( m_SelectedColor );
m_pElapsedTimeLabel->SetFgColor( m_SelectedColor );
m_pFileTimeLabel->SetFgColor( m_SelectedColor );
}
else
{
m_pSaveGameScreenshotBackground->SetFillColor( m_FillColor );
m_pChapterLabel->SetFgColor( m_TextColor );
m_pTypeLabel->SetFgColor( m_TextColor );
m_pElapsedTimeLabel->SetFgColor( m_TextColor );
m_pFileTimeLabel->SetFgColor( m_TextColor );
}
PostMessage( m_pParent->GetVParent(), new KeyValues("PanelSelected") );
}
virtual void OnMousePressed( vgui::MouseCode code )
{
m_pParent->SetSelectedPanel( this );
}
virtual void ApplySchemeSettings( IScheme *pScheme )
{
m_TextColor = pScheme->GetColor( "NewGame.TextColor", Color(255, 255, 255, 255) );
m_SelectedColor = pScheme->GetColor( "NewGame.SelectionColor", Color(255, 255, 255, 255) );
BaseClass::ApplySchemeSettings( pScheme );
}
virtual void OnMouseDoublePressed( vgui::MouseCode code )
{
// call the panel
OnMousePressed( code );
PostMessage( m_pParent->GetParent(), new KeyValues("Command", "command", "loadsave") );
}
int GetSaveGameListItemID()
{
return m_iSaveGameListItemID;
}
private:
vgui::PanelListPanel *m_pParent;
vgui::Label *m_pChapterLabel;
CTGAImagePanel *m_pSaveGameImage;
ImagePanel *m_pAutoSaveImage;
// things to change color when the selection changes
ImagePanel *m_pSaveGameScreenshotBackground;
Label *m_pTypeLabel;
Label *m_pElapsedTimeLabel;
Label *m_pFileTimeLabel;
Color m_TextColor, m_FillColor, m_SelectedColor;
int m_iSaveGameListItemID;
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CBaseSaveGameDialog::CBaseSaveGameDialog( vgui::Panel *parent, const char *name ) : BaseClass( parent, name )
{
CreateSavedGamesList();
ScanSavedGames();
m_pLoadButton = new vgui::Button( this, "loadsave", "" );
SetControlEnabled( "loadsave", false );
}
//-----------------------------------------------------------------------------
// Purpose: Creates the load game display list
//-----------------------------------------------------------------------------
void CBaseSaveGameDialog::CreateSavedGamesList()
{
m_pGameList = new vgui::PanelListPanel( this, "listpanel_loadgame" );
m_pGameList->SetFirstColumnWidth( 0 );
}
//-----------------------------------------------------------------------------
// Purpose: returns the save file name of the selected item
//-----------------------------------------------------------------------------
int CBaseSaveGameDialog::GetSelectedItemSaveIndex()
{
CSaveGamePanel *panel = dynamic_cast<CSaveGamePanel *>(m_pGameList->GetSelectedPanel());
if ( panel )
{
// find the panel in the list
for ( int i = 0; i < m_SaveGames.Count(); i++ )
{
if ( i == panel->GetSaveGameListItemID() )
{
return i;
}
}
}
return m_SaveGames.InvalidIndex();
}
//-----------------------------------------------------------------------------
// Purpose: builds save game list from directory
//-----------------------------------------------------------------------------
void CBaseSaveGameDialog::ScanSavedGames()
{
// populate list box with all saved games on record:
char szDirectory[_MAX_PATH];
Q_snprintf( szDirectory, sizeof( szDirectory ), "save/*.sav" );
// clear the current list
m_pGameList->DeleteAllItems();
m_SaveGames.RemoveAll();
// iterate the saved files
FileFindHandle_t handle;
const char *pFileName = g_pFullFileSystem->FindFirst( szDirectory, &handle );
while (pFileName)
{
if ( !Q_strnicmp(pFileName, "HLSave", strlen( "HLSave" ) ) )
{
pFileName = g_pFullFileSystem->FindNext( handle );
continue;
}
char szFileName[_MAX_PATH];
Q_snprintf(szFileName, sizeof( szFileName ), "save/%s", pFileName);
// Only load save games from the current mod's save dir
if( !g_pFullFileSystem->FileExists( szFileName, "MOD" ) )
{
pFileName = g_pFullFileSystem->FindNext( handle );
continue;
}
SaveGameDescription_t save;
if ( ParseSaveData( szFileName, pFileName, save ) )
{
m_SaveGames.AddToTail( save );
}
pFileName = g_pFullFileSystem->FindNext( handle );
}
g_pFullFileSystem->FindClose( handle );
// notify derived classes that save games are being scanned (so they can insert their own)
OnScanningSaveGames();
// sort the save list
qsort( m_SaveGames.Base(), m_SaveGames.Count(), sizeof(SaveGameDescription_t), &SaveGameSortFunc );
// add to the list
for ( int saveIndex = 0; saveIndex < m_SaveGames.Count() && saveIndex < MAX_LISTED_SAVE_GAMES; saveIndex++ )
{
// add the item to the panel
AddSaveGameItemToList( saveIndex );
}
// display a message if there are no save games
if ( !m_SaveGames.Count() )
{
vgui::Label *pNoSavesLabel = SETUP_PANEL(new Label(m_pGameList, "NoSavesLabel", "#GameUI_NoSaveGamesToDisplay"));
pNoSavesLabel->SetTextColorState(vgui::Label::CS_DULL);
m_pGameList->AddItem( NULL, pNoSavesLabel );
}
SetControlEnabled( "loadsave", false );
SetControlEnabled( "delete", false );
}
//-----------------------------------------------------------------------------
// Purpose: Adds an item to the list
//-----------------------------------------------------------------------------
void CBaseSaveGameDialog::AddSaveGameItemToList( int saveIndex )
{
// create the new panel and add to the list
CSaveGamePanel *saveGamePanel = new CSaveGamePanel( m_pGameList, "SaveGamePanel", saveIndex );
saveGamePanel->SetSaveGameInfo( m_SaveGames[saveIndex] );
m_pGameList->AddItem( NULL, saveGamePanel );
}
//-----------------------------------------------------------------------------
// Purpose: Parses the save game info out of the .sav file header
//-----------------------------------------------------------------------------
bool CBaseSaveGameDialog::ParseSaveData( char const *pszFileName, char const *pszShortName, SaveGameDescription_t &save )
{
char szMapName[SAVEGAME_MAPNAME_LEN];
char szComment[SAVEGAME_COMMENT_LEN];
char szElapsedTime[SAVEGAME_ELAPSED_LEN];
if ( !pszFileName || !pszShortName )
return false;
Q_strncpy( save.szShortName, pszShortName, sizeof(save.szShortName) );
Q_strncpy( save.szFileName, pszFileName, sizeof(save.szFileName) );
FileHandle_t fh = g_pFullFileSystem->Open( pszFileName, "rb", "MOD" );
if (fh == FILESYSTEM_INVALID_HANDLE)
return false;
int readok = SaveReadNameAndComment( fh, szMapName, ARRAYSIZE(szMapName), szComment, ARRAYSIZE(szComment) );
g_pFullFileSystem->Close(fh);
if ( !readok )
{
return false;
}
Q_strncpy( save.szMapName, szMapName, sizeof(save.szMapName) );
// Elapsed time is the last 6 characters in comment. (mmm:ss)
int i;
i = strlen( szComment );
Q_strncpy( szElapsedTime, "??", sizeof( szElapsedTime ) );
if (i >= 6)
{
Q_strncpy( szElapsedTime, (char *)&szComment[i - 6], 7 );
szElapsedTime[6] = '\0';
// parse out
int minutes = atoi( szElapsedTime );
int seconds = atoi( szElapsedTime + 4);
// reformat
if ( minutes )
{
Q_snprintf( szElapsedTime, sizeof(szElapsedTime), "%d %s %d seconds", minutes, minutes > 1 ? "minutes" : "minute", seconds );
}
else
{
Q_snprintf( szElapsedTime, sizeof(szElapsedTime), "%d seconds", seconds );
}
// Chop elapsed out of comment.
int n;
n = i - 6;
szComment[n] = '\0';
n--;
// Strip back the spaces at the end.
while ((n >= 1) &&
szComment[n] &&
szComment[n] == ' ')
{
szComment[n--] = '\0';
}
}
// calculate the file name to print
const char *pszType = "";
if (strstr(pszFileName, "quick"))
{
pszType = "#GameUI_QuickSave";
}
else if (strstr(pszFileName, "autosave"))
{
pszType = "#GameUI_AutoSave";
}
Q_strncpy( save.szType, pszType, sizeof(save.szType) );
Q_strncpy( save.szComment, szComment, sizeof(save.szComment) );
Q_strncpy( save.szElapsedTime, szElapsedTime, sizeof(save.szElapsedTime) );
// Now get file time stamp.
long fileTime = g_pFullFileSystem->GetFileTime(pszFileName);
char szFileTime[32];
g_pFullFileSystem->FileTimeToString(szFileTime, sizeof(szFileTime), fileTime);
char *newline = strstr(szFileTime, "\n");
if (newline)
{
*newline = 0;
}
Q_strncpy( save.szFileTime, szFileTime, sizeof(save.szFileTime) );
save.iTimestamp = fileTime;
return true;
}
void CBaseSaveGameDialog::OnKeyCodeTyped( vgui::KeyCode code )
{
if ( code == KEY_ESCAPE )
{
OnCommand( "Close" );
return;
}
BaseClass::OnKeyCodeTyped( code );
}
void CBaseSaveGameDialog::OnKeyCodePressed( vgui::KeyCode code )
{
if ( code == KEY_XBUTTON_B )
{
OnCommand( "Close" );
return;
}
else if ( code == KEY_XSTICK1_DOWN ||
code == KEY_XSTICK2_DOWN ||
code == KEY_XBUTTON_DOWN ||
code == KEY_DOWN )
{
if ( m_pGameList->GetItemCount() )
{
Panel *pSelectedPanel = m_pGameList->GetSelectedPanel();
if ( !pSelectedPanel )
{
m_pGameList->SetSelectedPanel( m_pGameList->GetItemPanel( m_pGameList->FirstItem() ) );
m_pGameList->ScrollToItem( m_pGameList->FirstItem() );
return;
}
else
{
int nNextPanelID = m_pGameList->FirstItem();
while ( nNextPanelID != m_pGameList->InvalidItemID() )
{
if ( m_pGameList->GetItemPanel( nNextPanelID ) == pSelectedPanel )
{
nNextPanelID = m_pGameList->NextItem( nNextPanelID );
if ( nNextPanelID != m_pGameList->InvalidItemID() )
{
m_pGameList->SetSelectedPanel( m_pGameList->GetItemPanel( nNextPanelID ) );
m_pGameList->ScrollToItem( nNextPanelID );
return;
}
break;
}
nNextPanelID = m_pGameList->NextItem( nNextPanelID );
}
}
}
}
else if ( code == KEY_XSTICK1_UP ||
code == KEY_XSTICK2_UP ||
code == KEY_XBUTTON_UP ||
code == KEY_UP )
{
if ( m_pGameList->GetItemCount() )
{
Panel *pSelectedPanel = m_pGameList->GetSelectedPanel();
if ( !pSelectedPanel )
{
m_pGameList->SetSelectedPanel( m_pGameList->GetItemPanel( m_pGameList->FirstItem() ) );
m_pGameList->ScrollToItem( m_pGameList->FirstItem() );
return;
}
else
{
int nNextPanelID = m_pGameList->FirstItem();
if ( m_pGameList->GetItemPanel( nNextPanelID ) != pSelectedPanel )
{
while ( nNextPanelID != m_pGameList->InvalidItemID() )
{
int nOldPanelID = nNextPanelID;
nNextPanelID = m_pGameList->NextItem( nNextPanelID );
if ( nNextPanelID != m_pGameList->InvalidItemID() )
{
if ( m_pGameList->GetItemPanel( nNextPanelID ) == pSelectedPanel )
{
m_pGameList->SetSelectedPanel( m_pGameList->GetItemPanel( nOldPanelID ) );
m_pGameList->ScrollToItem( nOldPanelID );
return;
}
}
}
}
}
}
}
else if ( code == KEY_ENTER || code == KEY_XBUTTON_A || code == STEAMCONTROLLER_A )
{
Panel *pSelectedPanel = m_pGameList->GetSelectedPanel();
if ( pSelectedPanel )
{
if ( code == KEY_XBUTTON_A || code == STEAMCONTROLLER_A )
{
ConVarRef var( "joystick" );
if ( var.IsValid() && !var.GetBool() )
{
var.SetValue( true );
}
ConVarRef var2( "hud_fastswitch" );
if ( var2.IsValid() && var2.GetInt() != 2 )
{
var2.SetValue( 2 );
}
}
m_pLoadButton->DoClick();
return;
}
}
BaseClass::OnKeyCodePressed( code );
}
//-----------------------------------------------------------------------------
// Purpose: timestamp sort function for savegames
//-----------------------------------------------------------------------------
int CBaseSaveGameDialog::SaveGameSortFunc( const void *lhs, const void *rhs )
{
const SaveGameDescription_t *s1 = (const SaveGameDescription_t *)lhs;
const SaveGameDescription_t *s2 = (const SaveGameDescription_t *)rhs;
if (s1->iTimestamp < s2->iTimestamp)
return 1;
else if (s1->iTimestamp > s2->iTimestamp)
return -1;
// timestamps are equal, so just sort by filename
return strcmp(s1->szFileName, s2->szFileName);
}
#define MAKEID(d,c,b,a) ( ((int)(a) << 24) | ((int)(b) << 16) | ((int)(c) << 8) | ((int)(d)) )
int SaveReadNameAndComment( FileHandle_t f, OUT_Z_CAP(nameSize) char *name, int nameSize, OUT_Z_CAP(commentSize) char *comment, int commentSize )
{
int i, tag, size, tokenSize, tokenCount;
char *pSaveData, *pFieldName, **pTokenList;
name[0] = '\0';
comment[0] = '\0';
g_pFullFileSystem->Read( &tag, sizeof(int), f );
if ( tag != MAKEID('J','S','A','V') )
{
return 0;
}
g_pFullFileSystem->Read( &tag, sizeof(int), f );
if ( tag != SAVEGAME_VERSION ) // Enforce version for now
{
return 0;
}
g_pFullFileSystem->Read( &size, sizeof(int), f );
g_pFullFileSystem->Read( &tokenCount, sizeof(int), f ); // These two ints are the token list
g_pFullFileSystem->Read( &tokenSize, sizeof(int), f );
size += tokenSize;
// Sanity Check.
if ( tokenCount < 0 || tokenCount > 1024*1024*32 )
{
return 0;
}
if ( tokenSize < 0 || tokenSize > 1024*1024*32 )
{
return 0;
}
pSaveData = (char *)new char[size];
g_pFullFileSystem->Read(pSaveData, size, f);
int nNumberOfFields;
char *pData;
int nFieldSize;
pData = pSaveData;
// Allocate a table for the strings, and parse the table
if ( tokenSize > 0 )
{
pTokenList = new char *[tokenCount];
// Make sure the token strings pointed to by the pToken hashtable.
for( i=0; i<tokenCount; i++ )
{
pTokenList[i] = *pData ? pData : NULL; // Point to each string in the pToken table
while( *pData++ ); // Find next token (after next null)
}
}
else
pTokenList = NULL;
// short, short (size, index of field name)
nFieldSize = *(short *)pData;
pData += sizeof(short);
pFieldName = pTokenList[ *(short *)pData ];
if (stricmp(pFieldName, "GameHeader"))
{
delete[] pSaveData;
return 0;
};
// int (fieldcount)
pData += sizeof(short);
nNumberOfFields = *(int*)pData;
pData += nFieldSize;
// Each field is a short (size), short (index of name), binary string of "size" bytes (data)
for (i = 0; i < nNumberOfFields; i++)
{
// Data order is:
// Size
// szName
// Actual Data
nFieldSize = *(short *)pData;
pData += sizeof(short);
pFieldName = pTokenList[ *(short *)pData ];
pData += sizeof(short);
if (!stricmp(pFieldName, "comment"))
{
int copySize = MAX(commentSize, nFieldSize);
Q_strncpy(comment, pData, copySize);
}
else if (!stricmp(pFieldName, "mapName"))
{
int copySize = MAX(nameSize, nFieldSize);
Q_strncpy(name, pData, copySize);
};
// Move to Start of next field.
pData += nFieldSize;
};
// Delete the string table we allocated
delete[] pTokenList;
delete[] pSaveData;
if (strlen(name) > 0 && strlen(comment) > 0)
return 1;
return 0;
}
//-----------------------------------------------------------------------------
// Purpose: deletes an existing save game
//-----------------------------------------------------------------------------
void CBaseSaveGameDialog::DeleteSaveGame( const char *fileName )
{
if ( !fileName || !fileName[0] )
return;
// delete the save game file
g_pFullFileSystem->RemoveFile( fileName, "MOD" );
// delete the associated tga
char tga[_MAX_PATH];
Q_strncpy( tga, fileName, sizeof(tga) );
char *ext = strstr( tga, ".sav" );
if ( ext )
{
strcpy( ext, ".tga" );
}
g_pFullFileSystem->RemoveFile( tga, "MOD" );
}
//-----------------------------------------------------------------------------
// Purpose: One item has been selected
//-----------------------------------------------------------------------------
void CBaseSaveGameDialog::OnPanelSelected()
{
SetControlEnabled( "loadsave", true );
SetControlEnabled( "delete", true );
}

View File

@ -0,0 +1,81 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef BASESAVEGAMEDIALOG_H
#define BASESAVEGAMEDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "vgui/MouseCode.h"
#include "KeyValues.h"
#include "utlvector.h"
#define SAVEGAME_MAPNAME_LEN 32
#define SAVEGAME_COMMENT_LEN 80
#define SAVEGAME_ELAPSED_LEN 32
namespace vgui
{
class Button;
};
struct SaveGameDescription_t
{
char szShortName[64];
char szFileName[128];
char szMapName[SAVEGAME_MAPNAME_LEN];
char szComment[SAVEGAME_COMMENT_LEN];
char szType[64];
char szElapsedTime[SAVEGAME_ELAPSED_LEN];
char szFileTime[32];
unsigned int iTimestamp;
unsigned int iSize;
};
int SaveReadNameAndComment( FileHandle_t f, OUT_Z_CAP(nameSize) char *name, int nameSize, OUT_Z_CAP(commentSize) char *comment, int commentSize );
//-----------------------------------------------------------------------------
// Purpose: Base class for save & load game dialogs
//-----------------------------------------------------------------------------
class CBaseSaveGameDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CBaseSaveGameDialog, vgui::Frame );
public:
CBaseSaveGameDialog( vgui::Panel *parent, const char *name );
static int __cdecl SaveGameSortFunc( const void *lhs, const void *rhs );
protected:
CUtlVector<SaveGameDescription_t> m_SaveGames;
vgui::PanelListPanel *m_pGameList;
virtual void OnScanningSaveGames() {}
void DeleteSaveGame( const char *fileName );
void ScanSavedGames();
void CreateSavedGamesList();
int GetSelectedItemSaveIndex();
void AddSaveGameItemToList( int saveIndex );
bool ParseSaveData( char const *pszFileName, char const *pszShortName, SaveGameDescription_t &save );
void OnKeyCodeTyped( vgui::KeyCode code );
void OnKeyCodePressed( vgui::KeyCode code );
private:
MESSAGE_FUNC( OnPanelSelected, "PanelSelected" );
vgui::Button *m_pLoadButton;
};
#endif // BASESAVEGAMEDIALOG_H

130
gameui/BenchmarkDialog.cpp Normal file
View File

@ -0,0 +1,130 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "BenchmarkDialog.h"
#include "EngineInterface.h"
#include "BasePanel.h"
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
#include "filesystem.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/CheckButton.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CBenchmarkDialog::CBenchmarkDialog(vgui::Panel *parent, const char *name) : BaseClass(parent, name)
{
Button *button = new Button(this, "RunButton", "RunButton");
button->SetCommand(new KeyValues("RunBenchmark"));
SetSizeable(false);
SetDeleteSelfOnClose(true);
LoadControlSettings("Resource/BenchmarkDialog.res");
}
//-----------------------------------------------------------------------------
// Purpose: Launches the benchmark
//-----------------------------------------------------------------------------
void CBenchmarkDialog::RunBenchmark()
{
// apply settings
BasePanel()->ApplyOptionsDialogSettings();
// launch the map
engine->ClientCmd_Unrestricted("disconnect\n");
engine->ClientCmd_Unrestricted("wait\n");
engine->ClientCmd_Unrestricted("wait\n");
engine->ClientCmd_Unrestricted("maxplayers 1\n");
engine->ClientCmd_Unrestricted("progress_enable\n");
engine->ClientCmd_Unrestricted("map test_hardware\n");
// close this dialog
Close();
}
//-----------------------------------------------------------------------------
// Purpose: Displays benchmark results
//-----------------------------------------------------------------------------
class CBenchmarkResultsDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CBenchmarkResultsDialog, vgui::Frame );
public:
CBenchmarkResultsDialog( vgui::Panel *parent, const char *name ) : BaseClass( parent, name )
{
SetTitle("#GameUI_BenchmarkResults_Title", true);
SetDeleteSelfOnClose(true);
SetSizeable(false);
m_pUploadCheck = new CheckButton( this, "UploadCheck", "#GameUI_BenchmarkResults_UploadNow" );
LoadControlSettings("Resource/BenchmarkResultsDialog.res");
m_pUploadCheck->SetSelected( true );
MoveToCenterOfScreen();
}
virtual void Activate()
{
BaseClass::Activate();
KeyValues *kv = new KeyValues( "Benchmark" );
if ( kv->LoadFromFile( g_pFullFileSystem, "results/results.txt", "MOD" ) )
{
// get the framerate
char szFrameRate[32];
Q_snprintf( szFrameRate, sizeof(szFrameRate), "%.2f", kv->GetFloat("framerate") );
SetDialogVariable( "framerate", szFrameRate );
}
else
{
Close();
}
kv->deleteThis();
}
void OnKeyCodePressed( KeyCode code )
{
if ( code == KEY_XBUTTON_B )
{
Close();
}
else
{
BaseClass::OnKeyCodePressed(code);
}
}
private:
virtual void OnClose()
{
if ( m_pUploadCheck->IsSelected() )
{
engine->ClientCmd_Unrestricted( "bench_upload\n" );
}
BaseClass::OnClose();
}
vgui::CheckButton *m_pUploadCheck;
};
//-----------------------------------------------------------------------------
// Purpose: Launches the stats dialog
//-----------------------------------------------------------------------------
CON_COMMAND_F( bench_showstatsdialog, "Shows a dialog displaying the most recent benchmark results.", FCVAR_CHEAT )
{
static vgui::DHANDLE<CBenchmarkResultsDialog> g_BenchmarkResultsDialog;
if (!g_BenchmarkResultsDialog.Get())
{
g_BenchmarkResultsDialog = new CBenchmarkResultsDialog( BasePanel(), "BenchmarkResultsDialog" );
}
g_BenchmarkResultsDialog->Activate();
}

45
gameui/BenchmarkDialog.h Normal file
View File

@ -0,0 +1,45 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef BENCHMARKDIALOG_H
#define BENCHMARKDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
//-----------------------------------------------------------------------------
// Purpose: Benchmark launch dialog
//-----------------------------------------------------------------------------
class CBenchmarkDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CBenchmarkDialog, vgui::Frame );
public:
CBenchmarkDialog(vgui::Panel *parent, const char *name);
void OnKeyCodePressed( vgui::KeyCode code )
{
if ( code == KEY_XBUTTON_B || code == STEAMCONTROLLER_B )
{
Close();
}
else if ( code == KEY_XBUTTON_A || code == STEAMCONTROLLER_A )
{
RunBenchmark();
}
else
{
BaseClass::OnKeyCodePressed(code);
}
}
private:
MESSAGE_FUNC( RunBenchmark, "RunBenchmark" );
};
#endif // BENCHMARKDIALOG_H

View File

@ -0,0 +1,78 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "BitmapImagePanel.h"
#include <vgui/ISurface.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
CBitmapImagePanel::CBitmapImagePanel( Panel *parent, char const *panelName,
char const *filename /*= NULL*/ ) : Panel( parent, panelName )
{
m_szTexture[ 0 ] = 0;
m_bUploaded = false;
m_nTextureId = -1;
SetBounds( 0, 0, 100, 100 );
if ( filename && filename[ 0 ] )
{
Q_strncpy( m_szTexture, filename, sizeof( m_szTexture ) );
}
}
void CBitmapImagePanel::PaintBackground()
{
if (!m_szTexture[0])
return;
if ( !m_bUploaded )
forceUpload();
int w, h;
GetSize( w, h );
surface()->DrawSetColor( Color( 255, 255, 255, 255 ) );
surface()->DrawSetTexture( m_nTextureId );
surface()->DrawTexturedRect( 0, 0, w, h );
}
void CBitmapImagePanel::setTexture( char const *filename )
{
Q_strncpy( m_szTexture, filename, sizeof( m_szTexture ) );
if ( m_bUploaded )
{
forceReload();
}
else
{
forceUpload();
}
}
void CBitmapImagePanel::forceUpload()
{
if ( !m_szTexture[ 0 ] )
return;
m_bUploaded = true;
m_nTextureId = surface()->CreateNewTextureID();
surface()->DrawSetTextureFile( m_nTextureId, m_szTexture, false, true);
}
void CBitmapImagePanel::forceReload( void )
{
if ( !m_bUploaded )
return;
// Force texture to re-upload to video card
surface()->DrawSetTextureFile( m_nTextureId, m_szTexture, false, true);
}

37
gameui/BitmapImagePanel.h Normal file
View File

@ -0,0 +1,37 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef BITMAPIMAGEPANEL_H
#define BITMAPIMAGEPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Panel.h>
class CBitmapImagePanel : public vgui::Panel
{
public:
CBitmapImagePanel( vgui::Panel *parent, char const *panelName, char const *filename = NULL );
virtual void PaintBackground();
virtual void setTexture( char const *filename );
virtual void forceReload( void );
private:
typedef vgui::Panel BaseClass;
void forceUpload();
bool m_bUploaded;
int m_nTextureId;
char m_szTexture[ 128 ];
};
#endif // BITMAPIMAGEPANEL_H

View File

@ -0,0 +1,916 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "BonusMapsDatabase.h"
#include "EngineInterface.h"
#include "tier1/convar.h"
#include "tier1/utlbuffer.h"
#include "filesystem.h"
#include "ModInfo.h"
#include "EngineInterface.h"
#include "ixboxsystem.h"
#include "KeyValues.h"
#include "BasePanel.h"
#include "GameUI_Interface.h"
#include "BonusMapsDialog.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define MOD_DIR ( IsXbox() ? "DEFAULT_WRITE_PATH" : "MOD" )
const char g_pszMedalNames[4][8] =
{
"none",
"bronze",
"silver",
"gold"
};
const char *COM_GetModDirectory();
bool WriteBonusMapSavedData( KeyValues *data )
{
if ( IsX360() && ( XBX_GetStorageDeviceId() == XBX_INVALID_STORAGE_ID || XBX_GetStorageDeviceId() == XBX_STORAGE_DECLINED ) )
return false;
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
data->RecursiveSaveToFile( buf, 0 );
char szFilename[_MAX_PATH];
if ( IsX360() )
Q_snprintf( szFilename, sizeof( szFilename ), "cfg:/bonus_maps_data.bmd" );
else
Q_snprintf( szFilename, sizeof( szFilename ), "save/bonus_maps_data.bmd" );
bool bWriteSuccess = g_pFullFileSystem->WriteFile( szFilename, MOD_DIR, buf );
xboxsystem->FinishContainerWrites();
return bWriteSuccess;
}
void GetBooleanStatus( KeyValues *pBonusFilesKey, BonusMapDescription_t &map )
{
KeyValues *pFileKey = NULL;
KeyValues *pBonusKey = NULL;
for ( pFileKey = pBonusFilesKey->GetFirstSubKey(); pFileKey; pFileKey = pFileKey->GetNextTrueSubKey() )
{
if ( Q_strcmp( pFileKey->GetName(), map.szFileName ) == 0 )
{
for ( pBonusKey = pFileKey->GetFirstSubKey(); pBonusKey; pBonusKey = pBonusKey->GetNextKey() )
{
if ( Q_strcmp( pBonusKey->GetName(), map.szMapName ) == 0 )
{
// Found the data
break;
}
}
break;
}
}
if ( pBonusKey )
{
map.bLocked = ( pBonusKey->GetInt( "lock" ) != 0 );
map.bComplete = ( pBonusKey->GetInt( "complete" ) != 0 );
}
}
bool SetBooleanStatus( KeyValues *pBonusFilesKey, const char *pchName, const char *pchFileName, const char *pchMapName, bool bValue )
{
// Don't create entries for files that don't exist
if ( !IsX360() && ! (g_pFullFileSystem->FileExists( pchFileName, "MOD" ) || g_pFullFileSystem->IsDirectory( pchFileName, "MOD" ) ) )
{
DevMsg( "Failed to set boolean status for file %s.", pchFileName );
return false;
}
bool bChanged = false;
KeyValues *pFileKey = NULL;
KeyValues *pBonusKey = NULL;
for ( pFileKey = pBonusFilesKey->GetFirstSubKey(); pFileKey; pFileKey = pFileKey->GetNextTrueSubKey() )
{
if ( Q_strcmp( pFileKey->GetName(), pchFileName ) == 0 )
{
for ( pBonusKey = pFileKey->GetFirstSubKey(); pBonusKey; pBonusKey = pBonusKey->GetNextKey() )
{
if ( Q_strcmp( pBonusKey->GetName(), pchMapName ) == 0 )
{
// Found the data
break;
}
}
break;
}
}
if ( !pFileKey )
{
// Didn't find it, so create a new spot for the data
pFileKey = new KeyValues( pchFileName );
pBonusFilesKey->AddSubKey( pFileKey );
}
if ( !pBonusKey )
{
pBonusKey = new KeyValues( pchMapName, pchName, "0" );
pFileKey->AddSubKey( pBonusKey );
bChanged = true;
}
if ( ( pBonusKey->GetInt( pchName ) != 0 ) != bValue )
{
bChanged = true;
pBonusKey->SetInt( pchName, bValue );
}
return bChanged;
}
float GetChallengeBests( KeyValues *pBonusFilesKey, BonusMapDescription_t &challenge )
{
// There's no challenges, so bail and assume 0% challenge completion
if ( challenge.m_pChallenges == NULL || challenge.m_pChallenges->Count() == 0 )
return 0.0f;
KeyValues *pFileKey = NULL;
KeyValues *pBonusKey = NULL;
for ( pFileKey = pBonusFilesKey->GetFirstSubKey(); pFileKey; pFileKey = pFileKey->GetNextTrueSubKey() )
{
if ( Q_strcmp( pFileKey->GetName(), challenge.szFileName ) == 0 )
{
for ( pBonusKey = pFileKey->GetFirstSubKey(); pBonusKey; pBonusKey = pBonusKey->GetNextKey() )
{
if ( Q_strcmp( pBonusKey->GetName(), challenge.szMapName ) == 0 )
{
// Found the data
break;
}
}
break;
}
}
float fChallengePoints = 0.0f;
for ( int iChallenge = 0; iChallenge < challenge.m_pChallenges->Count(); ++iChallenge )
{
ChallengeDescription_t *pChallengeDescription = &((*challenge.m_pChallenges)[ iChallenge ]);
pChallengeDescription->iBest = ( ( pBonusKey ) ? ( pBonusKey->GetInt( pChallengeDescription->szName, -1 ) ) : ( -1 ) );
if ( pChallengeDescription->iBest >= 0 )
{
if ( pChallengeDescription->iBest <= pChallengeDescription->iGold )
fChallengePoints += 3.0f;
else if ( pChallengeDescription->iBest <= pChallengeDescription->iSilver )
fChallengePoints += 2.0f;
else if ( pChallengeDescription->iBest <= pChallengeDescription->iBronze )
fChallengePoints += 1.0f;
}
}
return fChallengePoints / ( challenge.m_pChallenges->Count() * 3.0f );
}
bool UpdateChallengeBest( KeyValues *pBonusFilesKey, const BonusMapChallenge_t &challenge )
{
// Don't create entries for files that don't exist
if ( !IsX360() && !g_pFullFileSystem->FileExists( challenge.szFileName, "MOD" ) )
{
DevMsg( "Failed to set challenge best for file %s.", challenge.szFileName );
return false;
}
bool bChanged = false;
KeyValues *pFileKey = NULL;
KeyValues *pBonusKey = NULL;
for ( pFileKey = pBonusFilesKey->GetFirstSubKey(); pFileKey; pFileKey = pFileKey->GetNextTrueSubKey() )
{
if ( Q_strcmp( pFileKey->GetName(), challenge.szFileName ) == 0 )
{
for ( pBonusKey = pFileKey->GetFirstSubKey(); pBonusKey; pBonusKey = pBonusKey->GetNextKey() )
{
if ( Q_strcmp( pBonusKey->GetName(), challenge.szMapName ) == 0 )
{
// Found the challenge
break;
}
}
break;
}
}
if ( !pFileKey )
{
// Didn't find it, so create a new spot for data
pFileKey = new KeyValues( challenge.szFileName );
pBonusFilesKey->AddSubKey( pFileKey );
}
if ( !pBonusKey )
{
pBonusKey = new KeyValues( challenge.szMapName, challenge.szChallengeName, -1 );
pFileKey->AddSubKey( pBonusKey );
bChanged = true;
}
int iCurrentBest = pBonusKey->GetInt( challenge.szChallengeName, -1 );
if ( iCurrentBest == -1 || iCurrentBest > challenge.iBest )
{
bChanged = true;
pBonusKey->SetInt( challenge.szChallengeName, challenge.iBest );
}
return bChanged;
}
void GetChallengeMedals( ChallengeDescription_t *pChallengeDescription, int &iBest, int &iEarnedMedal, int &iNext, int &iNextMedal )
{
iBest = pChallengeDescription->iBest;
if ( iBest == -1 )
iEarnedMedal = 0;
else if ( iBest <= pChallengeDescription->iGold )
iEarnedMedal = 3;
else if ( iBest <= pChallengeDescription->iSilver )
iEarnedMedal = 2;
else if ( iBest <= pChallengeDescription->iBronze )
iEarnedMedal = 1;
else
iEarnedMedal = 0;
iNext = -1;
switch ( iEarnedMedal )
{
case 0:
iNext = pChallengeDescription->iBronze;
iNextMedal = 1;
break;
case 1:
iNext = pChallengeDescription->iSilver;
iNextMedal = 2;
break;
case 2:
iNext = pChallengeDescription->iGold;
iNextMedal = 3;
break;
case 3:
iNext = -1;
iNextMedal = -1;
break;
}
}
CBonusMapsDatabase *g_pBonusMapsDatabase = NULL;
CBonusMapsDatabase *BonusMapsDatabase( void )
{
if ( !g_pBonusMapsDatabase )
static CBonusMapsDatabase StaticBonusMapsDatabase;
return g_pBonusMapsDatabase;
}
//-----------------------------------------------------------------------------
// Purpose:Constructor
//-----------------------------------------------------------------------------
CBonusMapsDatabase::CBonusMapsDatabase( void )
{
Assert( g_pBonusMapsDatabase == NULL ); // There should only be 1 bonus maps database
g_pBonusMapsDatabase = this;
RootPath();
m_pBonusMapsManifest = new KeyValues( "bonus_maps_manifest" );
m_pBonusMapsManifest->LoadFromFile( g_pFullFileSystem, "scripts/bonus_maps_manifest.txt", NULL );
m_iX360BonusesUnlocked = -1; // Only used on X360
m_bHasLoadedSaveData = false;
ReadBonusMapSaveData();
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CBonusMapsDatabase::~CBonusMapsDatabase()
{
g_pBonusMapsDatabase = NULL;
}
extern bool g_bIsCreatingNewGameMenuForPreFetching;
bool CBonusMapsDatabase::ReadBonusMapSaveData( void )
{
if ( !m_pBonusMapSavedData )
m_pBonusMapSavedData = new KeyValues( "bonus_map_saved_data" );
if ( g_bIsCreatingNewGameMenuForPreFetching )
{
// Although we may have a storage device it's not going to be able to find our file at this point! BAIL!
return false;
}
#ifdef _X360
// Nothing to read
if ( XBX_GetStorageDeviceId() == XBX_INVALID_STORAGE_ID || XBX_GetStorageDeviceId() == XBX_STORAGE_DECLINED )
return false;
#endif
char szFilename[_MAX_PATH];
if ( IsX360() )
Q_snprintf( szFilename, sizeof( szFilename ), "cfg:/bonus_maps_data.bmd" );
else
Q_snprintf( szFilename, sizeof( szFilename ), "save/bonus_maps_data.bmd" );
m_pBonusMapSavedData->LoadFromFile( g_pFullFileSystem, szFilename, NULL );
m_bSavedDataChanged = false;
m_bHasLoadedSaveData = true;
return true;
}
bool CBonusMapsDatabase::WriteSaveData( void )
{
bool bSuccess = false;
if ( m_bSavedDataChanged )
bSuccess = WriteBonusMapSavedData( m_pBonusMapSavedData );
if ( bSuccess )
m_bSavedDataChanged = false;
return bSuccess;
}
void CBonusMapsDatabase::RootPath( void )
{
m_iDirDepth = 0;
V_strcpy_safe( m_szCurrentPath, "." );
}
void CBonusMapsDatabase::AppendPath( const char *pchAppend )
{
++m_iDirDepth;
char szCurPathTmp[MAX_PATH];
V_strcpy_safe( szCurPathTmp, m_szCurrentPath );
Q_snprintf( m_szCurrentPath, sizeof( m_szCurrentPath ), "%s/%s", szCurPathTmp, pchAppend );
}
void CBonusMapsDatabase::BackPath( void )
{
if ( m_iDirDepth == 0 )
return;
if ( m_iDirDepth == 1 )
{
RootPath(); // back to root
return;
}
--m_iDirDepth;
Q_strrchr( m_szCurrentPath, '/' )[ 0 ] = '\0'; // remove a dir from the end
}
void CBonusMapsDatabase::SetPath( const char *pchPath, int iDirDepth )
{
V_strcpy_safe( m_szCurrentPath, pchPath );
m_iDirDepth = iDirDepth;
}
void CBonusMapsDatabase::ClearBonusMapsList( void )
{
m_BonusMaps.RemoveAll();
}
//-----------------------------------------------------------------------------
// Purpose: builds bonus map list from directory
//-----------------------------------------------------------------------------
void CBonusMapsDatabase::ScanBonusMaps( void )
{
// Don't load in the bonus maps before we've properly read in the save data
if ( !m_bHasLoadedSaveData )
{
if ( ! ReadBonusMapSaveData() )
return;
}
char *pCurrentPath = &(m_szCurrentPath[2]);
// Reset completion percentage
m_iCompletableLevels = 0;
m_fCurrentCompletion = 0.0f;
// populate list box with all bonus maps in the current path
char szDirectory[_MAX_PATH];
if ( Q_strcmp( m_szCurrentPath, "." ) == 0 )
{
// We're at the root, so look at the directories in the manifest
KeyValues *pKey = NULL;
for ( pKey = m_pBonusMapsManifest->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey() )
{
const char *pchType = pKey->GetName();
if ( Q_strcmp( pchType, "search" ) == 0 )
{
// Search through the directory
Q_snprintf( szDirectory, sizeof( szDirectory ), "%s/", pKey->GetString() );
BuildSubdirectoryList( szDirectory, true );
BuildBonusMapsList( szDirectory, true );
}
else if ( Q_strcmp( pchType, "dir" ) == 0 )
{
AddBonus( "", pKey->GetString(), true );
}
else if ( Q_strcmp( pchType, "map" ) == 0 )
{
AddBonus( "", pKey->GetString(), false );
}
}
}
else
{
// Search through the current directory
Q_snprintf( szDirectory, sizeof( szDirectory ), "%s/", pCurrentPath );
BuildSubdirectoryList( szDirectory, false );
BuildBonusMapsList( szDirectory, false );
}
}
void CBonusMapsDatabase::RefreshMapData( void )
{
// Reset completion percentage
m_iCompletableLevels = 0;
m_fCurrentCompletion = 0.0f;
for ( int iMap = 0; iMap < m_BonusMaps.Count(); ++iMap )
{
BonusMapDescription_t *pMap = &m_BonusMaps[ iMap ];
float fCompletion = GetChallengeBests( m_pBonusMapSavedData->FindKey( "bonusfiles", true ), *pMap );
// If all the challenges are completed set it as complete
if ( fCompletion == 1.0f )
SetBooleanStatus( "complete", pMap->szFileName, pMap->szMapName, true );
GetBooleanStatus( m_pBonusMapSavedData->FindKey( "bonusfiles", true ), *pMap );
if ( pMap->bComplete )
fCompletion = 1.0f;
if ( !pMap->bIsFolder )
{
m_fCurrentCompletion += fCompletion;
++m_iCompletableLevels;
}
}
}
int CBonusMapsDatabase::BonusCount( void )
{
if ( m_BonusMaps.Count() == 0 )
ScanBonusMaps();
return m_BonusMaps.Count();
}
bool CBonusMapsDatabase::GetBlink( void )
{
KeyValues *pBlinkKey = m_pBonusMapSavedData->FindKey( "blink" );
if ( !pBlinkKey )
return false;
return ( pBlinkKey->GetInt() != 0 );
}
void CBonusMapsDatabase::SetBlink( bool bState )
{
KeyValues *pBlinkKey = m_pBonusMapSavedData->FindKey( "blink" );
if ( pBlinkKey )
{
bool bCurrentState = ( pBlinkKey->GetInt() != 0 );
if ( bState && !bCurrentState )
{
pBlinkKey->SetStringValue( "1" );
m_bSavedDataChanged = true;
}
else if ( !bState && bCurrentState )
{
pBlinkKey->SetStringValue( "0" );
m_bSavedDataChanged = true;
}
}
}
// Only used on X360
bool CBonusMapsDatabase::BonusesUnlocked( void )
{
if ( m_iX360BonusesUnlocked == -1 )
{
// Never checked, so set up the proper X360 scan
BonusMapsDatabase()->ClearBonusMapsList(); // clear the current list
BonusMapsDatabase()->RootPath();
BonusMapsDatabase()->ScanBonusMaps();
m_iX360BonusesUnlocked = 0;
}
if ( m_iX360BonusesUnlocked == 0 )
{
// Hasn't been recorded as unlocked yet
for ( int iBonusMap = 0; iBonusMap < BonusMapsDatabase()->BonusCount(); ++iBonusMap )
{
BonusMapDescription_t *pMap = BonusMapsDatabase()->GetBonusData( iBonusMap );
if ( Q_strcmp( pMap->szMapName, "#Bonus_Map_AdvancedChambers" ) == 0 && !pMap->bLocked )
{
// All bonuses unlocked, remember this and set up the proper X360 scan to get info.
m_iX360BonusesUnlocked = 1;
break;
}
}
}
return ( m_iX360BonusesUnlocked != 0 );
}
void CBonusMapsDatabase::SetCurrentChallengeNames( const char *pchFileName, const char *pchMapName, const char *pchChallengeName )
{
V_strcpy_safe( m_CurrentChallengeNames.szFileName, pchFileName );
V_strcpy_safe( m_CurrentChallengeNames.szMapName, pchMapName );
V_strcpy_safe( m_CurrentChallengeNames.szChallengeName, pchChallengeName );
}
void CBonusMapsDatabase::GetCurrentChallengeNames( char *pchFileName, char *pchMapName, char *pchChallengeName )
{
Q_strcpy( pchFileName, m_CurrentChallengeNames.szFileName );
Q_strcpy( pchMapName, m_CurrentChallengeNames.szMapName );
Q_strcpy( pchChallengeName, m_CurrentChallengeNames.szChallengeName );
}
void CBonusMapsDatabase::SetCurrentChallengeObjectives( int iBronze, int iSilver, int iGold )
{
m_CurrentChallengeObjectives.iBronze = iBronze;
m_CurrentChallengeObjectives.iSilver = iSilver;
m_CurrentChallengeObjectives.iGold = iGold;
}
void CBonusMapsDatabase::GetCurrentChallengeObjectives( int &iBronze, int &iSilver, int &iGold )
{
iBronze = m_CurrentChallengeObjectives.iBronze;
iSilver = m_CurrentChallengeObjectives.iSilver;
iGold = m_CurrentChallengeObjectives.iGold;
}
bool CBonusMapsDatabase::SetBooleanStatus( const char *pchName, const char *pchFileName, const char *pchMapName, bool bValue )
{
bool bChanged = ::SetBooleanStatus( m_pBonusMapSavedData->FindKey( "bonusfiles", true ), pchName, pchFileName, pchMapName, bValue );
if ( bChanged )
m_bSavedDataChanged = true;
return bChanged;
}
bool CBonusMapsDatabase::SetBooleanStatus( const char *pchName, int iIndex, bool bValue )
{
BonusMapDescription_t *pMap = &(m_BonusMaps[iIndex]);
bool bChanged = SetBooleanStatus( pchName, pMap->szFileName, pMap->szMapName, bValue );
GetBooleanStatus( m_pBonusMapSavedData->FindKey( "bonusfiles", true ), *pMap );
return bChanged;
}
bool CBonusMapsDatabase::UpdateChallengeBest( const char *pchFileName, const char *pchMapName, const char *pchChallengeName, int iBest )
{
BonusMapChallenge_t challenge;
V_strcpy_safe( challenge.szFileName, pchFileName );
V_strcpy_safe( challenge.szMapName, pchMapName );
V_strcpy_safe( challenge.szChallengeName, pchChallengeName );
challenge.iBest = iBest;
bool bChanged = ::UpdateChallengeBest( m_pBonusMapSavedData->FindKey( "bonusfiles", true ), challenge );
if ( bChanged )
m_bSavedDataChanged = true;
return bChanged;
}
float CBonusMapsDatabase::GetCompletionPercentage( void )
{
// Avoid divide by zero
if ( m_iCompletableLevels <= 0 )
return 0.0f;
return m_fCurrentCompletion / m_iCompletableLevels;
}
int CBonusMapsDatabase::NumAdvancedComplete( void )
{
char szCurrentPath[_MAX_PATH];
V_strcpy_safe( szCurrentPath, m_szCurrentPath );
int iDirDepth = m_iDirDepth;
BonusMapsDatabase()->ClearBonusMapsList();
SetPath( "./scripts/advanced_chambers", 1 );
ScanBonusMaps();
int iNumComplete = 0;
// Look through all the bonus maps
for ( int iBonusMap = 0; iBonusMap < BonusMapsDatabase()->BonusCount(); ++iBonusMap )
{
BonusMapDescription_t *pMap = BonusMapsDatabase()->GetBonusData( iBonusMap );
if ( pMap && Q_strstr( pMap->szMapName, "Advanced" ) != NULL )
{
// It's an advanced map, so check if it's complete
if ( pMap->bComplete )
++iNumComplete;
}
}
BonusMapsDatabase()->ClearBonusMapsList();
SetPath( szCurrentPath, iDirDepth );
ScanBonusMaps();
return iNumComplete;
}
void CBonusMapsDatabase::NumMedals( int piNumMedals[ 3 ] )
{
char szCurrentPath[_MAX_PATH];
V_strcpy_safe( szCurrentPath, m_szCurrentPath );
int iDirDepth = m_iDirDepth;
BonusMapsDatabase()->ClearBonusMapsList();
SetPath( "./scripts/challenges", 1 );
ScanBonusMaps();
for ( int i = 0; i < 3; ++i )
piNumMedals[ i ] = 0;
// Look through all the bonus maps
for ( int iBonusMap = 0; iBonusMap < BonusMapsDatabase()->BonusCount(); ++iBonusMap )
{
BonusMapDescription_t *pMap = BonusMapsDatabase()->GetBonusData( iBonusMap );
if ( pMap && pMap->m_pChallenges )
{
for ( int iChallenge = 0; iChallenge < pMap->m_pChallenges->Count(); ++iChallenge )
{
ChallengeDescription_t *pChallengeDescription = &((*pMap->m_pChallenges)[ iChallenge ]);
int iBest, iEarnedMedal, iNext, iNextMedal;
GetChallengeMedals( pChallengeDescription, iBest, iEarnedMedal, iNext, iNextMedal );
// Increase the count for this medal and every medal below it
while ( iEarnedMedal > 0 )
{
--iEarnedMedal; // Medals are 1,2&3 so subtract 1 first
piNumMedals[ iEarnedMedal ]++;
}
}
}
}
BonusMapsDatabase()->ClearBonusMapsList();
SetPath( szCurrentPath, iDirDepth );
ScanBonusMaps();
}
void CBonusMapsDatabase::AddBonus( const char *pCurrentPath, const char *pDirFileName, bool bIsFolder )
{
char szFileName[_MAX_PATH];
Q_snprintf( szFileName, sizeof( szFileName ), "%s%s", pCurrentPath, pDirFileName );
// Only load bonus maps from the current mod's maps dir
if( !IsX360() && !( g_pFullFileSystem->IsDirectory( szFileName, "MOD" ) || g_pFullFileSystem->FileExists( szFileName, "MOD" ) ))
return;
ParseBonusMapData( szFileName, pDirFileName, bIsFolder );
}
void CBonusMapsDatabase::BuildSubdirectoryList( const char *pCurrentPath, bool bOutOfRoot )
{
char szDirectory[_MAX_PATH];
Q_snprintf( szDirectory, sizeof( szDirectory ), "%s*", pCurrentPath );
FileFindHandle_t dirHandle;
const char *pDirFileName = g_pFullFileSystem->FindFirst( szDirectory, &dirHandle );
while (pDirFileName)
{
// Skip it if it's not a directory, is the root, is back, or is an invalid folder
if ( !g_pFullFileSystem->FindIsDirectory( dirHandle ) ||
Q_strcmp( pDirFileName, "." ) == 0 ||
Q_strcmp( pDirFileName, ".." ) == 0 ||
Q_stricmp( pDirFileName, "soundcache" ) == 0 ||
Q_stricmp( pDirFileName, "graphs" ) == 0 )
{
pDirFileName = g_pFullFileSystem->FindNext( dirHandle );
continue;
}
if ( !bOutOfRoot )
AddBonus( pCurrentPath, pDirFileName, true );
else
{
char szFileName[_MAX_PATH];
Q_snprintf( szFileName, sizeof( szFileName ), "%s%s", pCurrentPath, pDirFileName );
AddBonus( "", szFileName, true );
}
pDirFileName = g_pFullFileSystem->FindNext( dirHandle );
}
g_pFullFileSystem->FindClose( dirHandle );
}
void CBonusMapsDatabase::BuildBonusMapsList( const char *pCurrentPath, bool bOutOfRoot )
{
char szDirectory[_MAX_PATH];
Q_snprintf( szDirectory, sizeof( szDirectory ), "%s*.bns", pCurrentPath );
FileFindHandle_t mapHandle;
const char *pMapFileName = g_pFullFileSystem->FindFirst( szDirectory, &mapHandle );
while ( pMapFileName && Q_strlen(pMapFileName)>0 )
{
// Skip it if it's a directory or is the folder info
if ( g_pFullFileSystem->FindIsDirectory( mapHandle ) || Q_strstr( pMapFileName, "folderinfo.bns" ) )
{
pMapFileName = g_pFullFileSystem->FindNext( mapHandle );
continue;
}
if ( !bOutOfRoot )
AddBonus( pCurrentPath, pMapFileName, false );
else
{
char szFileName[_MAX_PATH];
Q_snprintf( szFileName, sizeof( szFileName ), "%s%s", pCurrentPath, pMapFileName );
AddBonus( "", szFileName, false );
}
pMapFileName = g_pFullFileSystem->FindNext( mapHandle );
}
g_pFullFileSystem->FindClose( mapHandle );
}
//-----------------------------------------------------------------------------
// Purpose: Parses the save game info out of the .sav file header
//-----------------------------------------------------------------------------
void CBonusMapsDatabase::ParseBonusMapData( char const *pszFileName, char const *pszShortName, bool bIsFolder )
{
if ( !pszFileName || !pszShortName )
return;
char szMapInfo[_MAX_PATH];
// if it's a directory, there's no optional info
if ( bIsFolder )
{
// get the folder info file name
Q_snprintf( szMapInfo, sizeof(szMapInfo), "%s/folderinfo.bns", pszFileName );
}
else
{
// get the map info file name
Q_strncpy( szMapInfo, pszFileName, sizeof(szMapInfo) );
}
KeyValues *kv = new KeyValues( pszShortName );
if ( !kv->LoadFromFile( g_pFullFileSystem, szMapInfo, NULL ) )
DevMsg( "Unable to load bonus map info file %s\n", szMapInfo );
while ( kv )
{
int iMap = m_BonusMaps.AddToTail();
BonusMapDescription_t *pMap = &m_BonusMaps[ iMap ];
// set required map data
Q_strncpy( pMap->szFileName, pszFileName, sizeof(pMap->szFileName) );
Q_strncpy( pMap->szShortName, pszShortName, sizeof(pMap->szShortName) );
pMap->bIsFolder = bIsFolder;
// set optional map data
V_strcpy_safe( pMap->szMapName, kv->GetName() );
V_strcpy_safe( pMap->szMapFileName, kv->GetString( "map" ) );
V_strcpy_safe( pMap->szChapterName, kv->GetString( "chapter" ) );
V_strcpy_safe( pMap->szImageName, kv->GetString( "image" ) );
V_strcpy_safe( pMap->szComment, kv->GetString( "comment" ) );
pMap->bLocked = ( kv->GetInt( "lock", 0 ) != 0 );
pMap->bComplete = ( kv->GetInt( "complete", 0 ) != 0 );
float fCompletion = 0.0f;
KeyValues *pChallenges = kv->FindKey( "challenges" );
if ( pChallenges )
{
for ( KeyValues *pChallengeKey = pChallenges->GetFirstSubKey(); pChallengeKey; pChallengeKey = pChallengeKey->GetNextKey() )
{
if ( !pMap->m_pChallenges )
pMap->m_pChallenges = new CUtlVector<ChallengeDescription_t>;
int iChallenge = pMap->m_pChallenges->AddToTail();
ChallengeDescription_t *pChallenge = &(*pMap->m_pChallenges)[ iChallenge ];
V_strcpy_safe( pChallenge->szName, pChallengeKey->GetName() );
V_strcpy_safe( pChallenge->szComment, pChallengeKey->GetString( "comment" ) );
pChallenge->iType = pChallengeKey->GetInt( "type", -1 );
pChallenge->iBronze = pChallengeKey->GetInt( "bronze" );
pChallenge->iSilver = pChallengeKey->GetInt( "silver" );
pChallenge->iGold = pChallengeKey->GetInt( "gold" );
}
fCompletion = GetChallengeBests( m_pBonusMapSavedData->FindKey( "bonusfiles", true ), *pMap );
// If all the challenges are completed set it as complete
if ( fCompletion == 1.0f )
SetBooleanStatus( "complete", pMap->szFileName, pMap->szMapName, true );
}
// Get boolean status last because it can be altered if all the challenges were completed
GetBooleanStatus( m_pBonusMapSavedData->FindKey( "bonusfiles", true ), *pMap );
if ( pMap->bComplete )
fCompletion = 1.0f;
if ( !pMap->bIsFolder )
{
m_fCurrentCompletion += fCompletion;
++m_iCompletableLevels;
kv = kv->GetNextTrueSubKey();
}
else
kv = NULL;
}
}
void CC_BonusMapUnlock( const CCommand &args )
{
if ( args.ArgC() < 3 )
{
GameUI().BonusMapUnlock();
return;
}
GameUI().BonusMapUnlock( args[ 1 ], args[ 2 ] );
}
static ConCommand sv_bonus_map_unlock("sv_bonus_map_unlock", CC_BonusMapUnlock, "Locks a bonus map.", FCVAR_CHEAT );
void CC_BonusMapComplete( const CCommand &args )
{
if ( args.ArgC() < 3 )
{
GameUI().BonusMapComplete();
return;
}
GameUI().BonusMapComplete( args[ 1 ], args[ 2 ] );
}
static ConCommand sv_bonus_map_complete("sv_bonus_map_complete", CC_BonusMapComplete, "Completes a bonus map.", FCVAR_CHEAT );
void CC_BonusMapChallengeUpdate( const CCommand &args )
{
if ( args.ArgC() < 5 )
{
return;
}
GameUI().BonusMapChallengeUpdate( args[ 1 ], args[ 2 ], args[ 3 ], atoi( args[ 4 ] ) );
}
static ConCommand sv_bonus_map_challenge_update("sv_bonus_map_challenge_update", CC_BonusMapChallengeUpdate, "Updates a bonus map challenge score.", FCVAR_CHEAT );

167
gameui/BonusMapsDatabase.h Normal file
View File

@ -0,0 +1,167 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef BONUSMAPSDATABASE_H
#define BONUSMAPSDATABASE_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
struct ChallengeDescription_t
{
char szName[32];
char szComment[256];
int iType;
int iBronze;
int iSilver;
int iGold;
int iBest;
};
struct BonusMapDescription_t
{
bool bIsFolder;
char szShortName[64];
char szFileName[128];
char szMapFileName[128];
char szChapterName[128];
char szImageName[128];
char szMapName[64];
char szComment[256];
bool bLocked;
bool bComplete;
CUtlVector<ChallengeDescription_t> *m_pChallenges;
BonusMapDescription_t( void )
{
bIsFolder = false;
szShortName[ 0 ] = '\0';
szFileName[ 0 ] = '\0';
szMapFileName[ 0 ] = '\0';
szChapterName[ 0 ] = '\0';
szImageName[ 0 ] = '\0';
szMapName[ 0 ] = '\0';
szComment[ 0 ] = '\0';
bLocked = false;
bComplete = false;
m_pChallenges = NULL;
}
};
struct BonusMapChallenge_t
{
char szFileName[128];
char szMapName[32];
char szChallengeName[32];
int iBest;
};
class KeyValues;
//-----------------------------------------------------------------------------
// Purpose: Keeps track of bonus maps on disk
//-----------------------------------------------------------------------------
class CBonusMapsDatabase
{
public:
CBonusMapsDatabase( void );
~CBonusMapsDatabase();
bool ReadBonusMapSaveData( void );
bool WriteSaveData( void );
const char * GetPath( void ) { return m_szCurrentPath; }
void RootPath( void );
void AppendPath( const char *pchAppend );
void BackPath( void );
void SetPath( const char *pchPath, int iDirDepth );
void ClearBonusMapsList( void );
void ScanBonusMaps( void );
void RefreshMapData( void );
int BonusCount( void );
BonusMapDescription_t * GetBonusData( int iIndex ) { return &(m_BonusMaps[ iIndex ]); }
int InvalidIndex( void ) { return m_BonusMaps.InvalidIndex(); }
bool IsValidIndex( int iIndex ) { return m_BonusMaps.IsValidIndex( iIndex ); }
bool GetBlink( void );
void SetBlink( bool bState );
bool BonusesUnlocked( void );
void SetCurrentChallengeNames( const char *pchFileName, const char *pchMapName, const char *pchChallengeName );
void GetCurrentChallengeNames( char *pchFileName, char *pchMapName, char *pchChallengeName );
void SetCurrentChallengeObjectives( int iBronze, int iSilver, int iGold );
void GetCurrentChallengeObjectives( int &iBronze, int &iSilver, int &iGold );
bool SetBooleanStatus( const char *pchName, const char *pchFileName, const char *pchMapName, bool bValue );
bool SetBooleanStatus( const char *pchName, int iIndex, bool bValue );
bool UpdateChallengeBest( const char *pchFileName, const char *pchMapName, const char *pchChallengeName, int iBest );
float GetCompletionPercentage( void );
int NumAdvancedComplete( void );
void NumMedals( int piNumMedals[ 3 ] );
private:
void AddBonus( const char *pCurrentPath, const char *pDirFileName, bool bIsFolder );
void BuildSubdirectoryList( const char *pCurrentPath, bool bOutOfRoot );
void BuildBonusMapsList( const char *pCurrentPath, bool bOutOfRoot );
void ParseBonusMapData( char const *pszFileName, char const *pszShortName, bool bIsFolder );
private:
KeyValues *m_pBonusMapsManifest;
CUtlVector<BonusMapDescription_t> m_BonusMaps;
KeyValues *m_pBonusMapSavedData;
bool m_bSavedDataChanged;
int m_iX360BonusesUnlocked; // Only used on 360
bool m_bHasLoadedSaveData;
int m_iDirDepth;
char m_szCurrentPath[_MAX_PATH];
float m_fCurrentCompletion;
int m_iCompletableLevels;
BonusMapChallenge_t m_CurrentChallengeNames;
ChallengeDescription_t m_CurrentChallengeObjectives;
};
void GetChallengeMedals( ChallengeDescription_t *pChallengeDescription, int &iBest, int &iEarnedMedal, int &iNext, int &iNextMedal );
CBonusMapsDatabase *BonusMapsDatabase( void );
extern const char g_pszMedalNames[4][8];
#endif // BONUSMAPSDATABASE_H

1006
gameui/BonusMapsDialog.cpp Normal file

File diff suppressed because it is too large Load Diff

75
gameui/BonusMapsDialog.h Normal file
View File

@ -0,0 +1,75 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef BONUSMAPSDIALOG_H
#define BONUSMAPSDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "BonusMapsDatabase.h"
//-----------------------------------------------------------------------------
// Purpose: Displays and loads available bonus maps
//-----------------------------------------------------------------------------
class CBonusMapsDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CBonusMapsDialog, vgui::Frame );
public:
CBonusMapsDialog(vgui::Panel *parent);
~CBonusMapsDialog();
void SetSelectedBooleanStatus( const char *pchName, bool bValue );
void RefreshData( void );
int GetSelectedChallenge( void );
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void OnCommand( const char *command );
void OnKeyCodeTyped( vgui::KeyCode code );
void OnKeyCodePressed( vgui::KeyCode code );
private:
bool ImportZippedBonusMaps( const char *pchZippedFileName );
void BuildMapsList( void );
void CreateBonusMapsList();
int GetSelectedItemBonusMapIndex();
void RefreshDialog( BonusMapDescription_t *pMap );
void RefreshMedalDisplay( BonusMapDescription_t *pMap );
void RefreshCompletionPercentage( void );
MESSAGE_FUNC( OnPanelSelected, "PanelSelected" );
MESSAGE_FUNC( OnControlModified, "ControlModified" );
MESSAGE_FUNC( OnTextChanged, "TextChanged" )
{
OnControlModified();
}
MESSAGE_FUNC_CHARPTR( OnFileSelected, "FileSelected", fullpath );
private:
Color m_PercentageBarBackgroundColor, m_PercentageBarColor;
vgui::FileOpenDialog *m_hImportBonusMapsDialog;
vgui::PanelListPanel *m_pGameList;
vgui::ComboBox *m_pChallengeSelection;
vgui::ImagePanel *m_pPercentageBarBackground;
vgui::ImagePanel *m_pPercentageBar;
};
extern CBonusMapsDialog *g_pBonusMapsDialog;
#endif // BONUSMAPSDIALOG_H

323
gameui/CDKeyEntryDialog.cpp Normal file
View File

@ -0,0 +1,323 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "CDKeyEntryDialog.h"
#include "EngineInterface.h"
#include "steamcommon.h" // VALVE_AUTH cd key checking code
#include "ValidateNewValveCDKeyClient.h"
#include "ValveCDKeyGameAndTerritoryCodes.h"
#include "vgui/IInput.h"
#include "vgui/IPanel.h"
#include "vgui/ISystem.h"
#include "vgui/ISurface.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/MessageBox.h"
#include "vgui_controls/TextEntry.h"
#include "vstdlib/random.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#include <ctype.h>
using namespace vgui;
#define FAKE_CDKEY_LEN 49
#define FAKE_CDKEY_REGKEY "HKEY_CURRENT_USER\\Software\\Valve\\Source\\Settings\\EncryptedCDKey"
//-----------------------------------------------------------------------------
// Purpose: hacky class to make all input uppercase
//-----------------------------------------------------------------------------
class CUpperCaseTextEntry : public vgui::TextEntry
{
DECLARE_CLASS_SIMPLE( CUpperCaseTextEntry, vgui::TextEntry );
public:
CUpperCaseTextEntry(vgui::Panel *parent, const char *name) : TextEntry(parent, name) {}
virtual void InsertChar(wchar_t unichar)
{
// only allow input of valid cdkey characters
if (unichar >= 'a' && unichar <= 'z')
{
// force to be uppercase
BaseClass::InsertChar(unichar - 'a' + 'A');
}
else if ((unichar >= 'A' && unichar <= 'Z')
|| (unichar >= '0' && unichar <= '9'))
{
BaseClass::InsertChar(unichar);
}
}
};
class CloseMessageBox : public vgui::MessageBox
{
public:
CloseMessageBox(const char *title, const char *text, Panel *parent = NULL): MessageBox( title, text, parent) {}
virtual void OnClose()
{
engine->ClientCmd_Unrestricted("quit\n");
}
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CCDKeyEntryDialog::CCDKeyEntryDialog(vgui::Panel *parent, bool inConnect) : BaseClass(parent, "CDKeyEntryDialog")
{
// see what type of cdkey we have
SetDeleteSelfOnClose(true);
m_bInConnect = inConnect;
m_iErrCount = 0;
m_bEnteredValidCDKey = false;
m_pOK = new Button(this, "OKButton", "#GameUI_OK");
m_pQuitGame = new Button(this, "CancelButton", "#GameUI_Quit");
m_pEntry1 = new CUpperCaseTextEntry(this, "Entry1");;
m_pEntry2 = new CUpperCaseTextEntry(this, "Entry2");
m_pEntry3 = new CUpperCaseTextEntry(this, "Entry3");
m_pEntry4 = new CUpperCaseTextEntry(this, "Entry4");
m_pEntry5 = new CUpperCaseTextEntry(this, "Entry5");
m_pEntry1->SetMaximumCharCount(5);
m_pEntry2->SetMaximumCharCount(5);
m_pEntry3->SetMaximumCharCount(5);
m_pEntry4->SetMaximumCharCount(5);
m_pEntry5->SetMaximumCharCount(5);
m_pEntry1->SetAutoProgressOnHittingCharLimit(true);
m_pEntry2->SetAutoProgressOnHittingCharLimit(true);
m_pEntry3->SetAutoProgressOnHittingCharLimit(true);
m_pEntry4->SetAutoProgressOnHittingCharLimit(true);
m_pEntry5->SetAutoProgressOnHittingCharLimit(false);
SetSizeable(false);
SetSize(360, 224);
SetTitle("#GameUI_CDKey", true);
LoadControlSettings("Resource/ValveCDKeyEntryDialog.res");
// MoveToCenterOfScreen();
SetMinimizeButtonVisible(false);
SetMaximizeButtonVisible(false);
m_pOK->SetEnabled(false);
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CCDKeyEntryDialog::~CCDKeyEntryDialog()
{
vgui::surface()->RestrictPaintToSinglePanel(NULL);
}
//-----------------------------------------------------------------------------
// Purpose: returns true if there is a valid weak check key in the registry
//-----------------------------------------------------------------------------
bool CCDKeyEntryDialog::IsValidWeakCDKeyInRegistry()
{
char fakekey[FAKE_CDKEY_LEN];
if (vgui::system()->GetRegistryString(FAKE_CDKEY_REGKEY, fakekey, sizeof(fakekey)))
{
if (strlen(fakekey) == (FAKE_CDKEY_LEN - 1)
&& fakekey[17] == 'E'
&& fakekey[31] == 'z'
&& fakekey[43] == 'n')
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCDKeyEntryDialog::OnCommand(const char *command)
{
if (!stricmp(command, "OK"))
{
if (IsEnteredKeyValid())
{
m_bEnteredValidCDKey = true;
// write out fake key and continue
char fakekey[FAKE_CDKEY_LEN];
for (int i = 0; i < sizeof(fakekey) - 1; i++)
{
// pick some random fields for us to check later
if (i == 17)
{
fakekey[i] = 'E';
}
else if (i == 31)
{
fakekey[i] = 'z';
}
else if (i == 43)
{
fakekey[i] = 'n';
}
else
{
fakekey[i] = RandomInt('0', 'z');
}
}
fakekey[sizeof(fakekey) - 1] = 0;
vgui::system()->SetRegistryString(FAKE_CDKEY_REGKEY, fakekey);
if ( m_bInConnect )
{
engine->ClientCmd_Unrestricted( "retry\n" ); // retry the server connection with this new key...
}
Close();
}
else
{
m_hErrorBox = new MessageBox("#GameUI_CDKey_Invalid_Title","#GameUI_CDKey_Invalid_Text", this);
m_hErrorBox->ShowWindow( this );
}
}
else if (!stricmp(command, "Cancel") || !stricmp(command, "Close"))
{
Close();
}
else
{
BaseClass::OnCommand(command);
}
if (!m_bEnteredValidCDKey) // moved away from the dialog box to make it a little harder to crack...
{
m_iErrCount++;
if( m_iErrCount >= MAX_CDKEY_ERRORS )
{
// too many bad entries, make em quit
CloseMessageBox *bx = new CloseMessageBox("#GameUI_CDKey_Invalid_Title","#GameUI_CDKey_TooManyTries", this);
bx->ShowWindow( this );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCDKeyEntryDialog::OnClose()
{
if (!m_bEnteredValidCDKey)
{
// if we don't have a valid key we can't continue
engine->ClientCmd_Unrestricted("quit\n");
}
BaseClass::OnClose();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCDKeyEntryDialog::OnThink()
{
if (!m_bEnteredValidCDKey)
{
// force us to be the only thing to draw
VPANEL vpanel = m_hErrorBox.Get() ? m_hErrorBox->GetVPanel() : GetVPanel();
vgui::surface()->RestrictPaintToSinglePanel(vpanel);
// make sure we're the focus
if (!(input()->GetFocus() && ipanel()->HasParent(input()->GetFocus(), GetVPanel())))
{
BaseClass::Activate();
}
}
BaseClass::OnThink();
}
//-----------------------------------------------------------------------------
// Purpose: returns whether or not the key entered by the user passes the simple check
//-----------------------------------------------------------------------------
bool CCDKeyEntryDialog::IsEnteredKeyValid()
{
// get the entered text
char cdkey[32];
m_pEntry1->GetText(cdkey, 6);
m_pEntry2->GetText(cdkey + 6, 6);
m_pEntry3->GetText(cdkey + 12, 6);
m_pEntry4->GetText(cdkey + 18, 6);
m_pEntry5->GetText(cdkey + 24, 6);
// add in the hyphens
cdkey[5] = '-';
cdkey[11] = '-';
cdkey[17] = '-';
cdkey[23] = '-';
// verify the entry
for (int i = 0; i < 29; i++)
{
if (cdkey[i] != '-' && !isalnum(cdkey[i]))
return false;
}
#if !defined( NO_STEAM )
uint gameCode, salesTerritoryCode, uniqueSerialNumber;
// test key - this key passes they weak check, but not the strong check
// "5J5Q3-QCME2-2SMMV-SBHN9-43S2S"
if ( SteamWeakVerifyNewValveCDKey(cdkey, &gameCode, &salesTerritoryCode, &uniqueSerialNumber) == eSteamErrorNone )
{
// require hl2 retail cdkey (ATI Bundle keys are also in this category)
if (gameCode == eHalfLife2)
return true;
}
#endif
return false;
}
//-----------------------------------------------------------------------------
// Purpose: handles user entering data in fields
//-----------------------------------------------------------------------------
void CCDKeyEntryDialog::OnTextChanged(Panel *entry)
{
char cdkey[32];
m_pEntry1->GetText(cdkey, 6);
m_pEntry2->GetText(cdkey + 6, 6);
m_pEntry3->GetText(cdkey + 12, 6);
m_pEntry4->GetText(cdkey + 18, 6);
m_pEntry5->GetText(cdkey + 24, 6);
// add in the hyphens
cdkey[5] = '-';
cdkey[11] = '-';
cdkey[17] = '-';
cdkey[23] = '-';
if (strlen(cdkey) == 29)
{
m_pOK->SetEnabled(true);
}
else
{
m_pOK->SetEnabled(false);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCDKeyEntryDialog::Activate()
{
BaseClass::Activate();
m_pEntry1->RequestFocus();
}

58
gameui/CDKeyEntryDialog.h Normal file
View File

@ -0,0 +1,58 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CDKEYENTRYDIALOG_H
#define CDKEYENTRYDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CCDKeyEntryDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CCDKeyEntryDialog, vgui::Frame );
public:
CCDKeyEntryDialog(vgui::Panel *parent, bool inConnect = false);
~CCDKeyEntryDialog();
virtual void Activate();
static bool IsValidWeakCDKeyInRegistry();
private:
enum { MAX_CDKEY_ERRORS = 5 };
virtual void OnCommand(const char *command);
virtual void OnClose();
virtual void OnThink();
MESSAGE_FUNC_PTR( OnTextChanged, "TextChanged", panel );
bool IsEnteredKeyValid();
vgui::Button *m_pOK;
vgui::Button *m_pQuitGame;
vgui::TextEntry *m_pEntry1;
vgui::TextEntry *m_pEntry2;
vgui::TextEntry *m_pEntry3;
vgui::TextEntry *m_pEntry4;
vgui::TextEntry *m_pEntry5;
vgui::DHANDLE<vgui::MessageBox> m_hErrorBox;
bool m_bEnteredValidCDKey;
bool m_bInConnect;
int m_iErrCount;
};
#endif // CDKEYENTRYDIALOG_H

161
gameui/ChangeGameDialog.cpp Normal file
View File

@ -0,0 +1,161 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifdef _XBOX
#include "xbox/xbox_platform.h"
#include "xbox/xbox_win32stubs.h"
#endif
#if !defined( _X360 )
#include <windows.h>
#endif
#include <stdio.h>
#include "ChangeGameDialog.h"
#include "ModInfo.h"
#include "EngineInterface.h"
#include <vgui_controls/ListPanel.h>
#include <KeyValues.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CChangeGameDialog::CChangeGameDialog(vgui::Panel *parent) : Frame(parent, "ChangeGameDialog")
{
SetSize(400, 340);
SetMinimumSize(400, 340);
SetTitle("#GameUI_ChangeGame", true);
m_pModList = new ListPanel(this, "ModList");
m_pModList->SetEmptyListText("#GameUI_NoOtherGamesAvailable");
m_pModList->AddColumnHeader(0, "ModName", "#GameUI_Game", 128);
LoadModList();
LoadControlSettings("Resource/ChangeGameDialog.res");
// if there's a mod in the list, select the first one
if (m_pModList->GetItemCount() > 0)
{
m_pModList->SetSingleSelectedItem(m_pModList->GetItemIDFromRow(0));
}
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CChangeGameDialog::~CChangeGameDialog()
{
}
//-----------------------------------------------------------------------------
// Purpose: Fills the mod list
//-----------------------------------------------------------------------------
void CChangeGameDialog::LoadModList()
{
// look for third party games
char szSearchPath[_MAX_PATH + 5];
Q_strncpy(szSearchPath, "*.*", sizeof( szSearchPath ) );
// use local filesystem since it has to look outside path system, and will never be used under steam
WIN32_FIND_DATA wfd;
HANDLE hResult;
memset(&wfd, 0, sizeof(WIN32_FIND_DATA));
hResult = FindFirstFile( szSearchPath, &wfd);
if (hResult != INVALID_HANDLE_VALUE)
{
BOOL bMoreFiles;
while (1)
{
if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (Q_strnicmp(wfd.cFileName, ".", 1)))
{
// Check for dlls\*.dll
char szDllDirectory[MAX_PATH + 16];
Q_snprintf(szDllDirectory, sizeof( szDllDirectory ), "%s\\gameinfo.txt", wfd.cFileName);
FILE *f = fopen(szDllDirectory, "rb");
if (f)
{
// find the description
fseek(f, 0, SEEK_END);
unsigned int size = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = (char *)malloc(size + 1);
if (fread(buf, 1, size, f) == size)
{
buf[size] = 0;
CModInfo modInfo;
modInfo.LoadGameInfoFromBuffer(buf);
if (strcmp(modInfo.GetGameName(), ModInfo().GetGameName()))
{
// Add the game directory.
strlwr(wfd.cFileName);
KeyValues *itemData = new KeyValues("Mod");
itemData->SetString("ModName", modInfo.GetGameName());
itemData->SetString("ModDir", wfd.cFileName);
m_pModList->AddItem(itemData, 0, false, false);
}
}
free(buf);
fclose(f);
}
}
bMoreFiles = FindNextFile(hResult, &wfd);
if (!bMoreFiles)
break;
}
FindClose(hResult);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CChangeGameDialog::OnCommand(const char *command)
{
if (!stricmp(command, "OK"))
{
if (m_pModList->GetSelectedItemsCount() > 0)
{
KeyValues *kv = m_pModList->GetItem(m_pModList->GetSelectedItem(0));
if (kv)
{
// change the game dir and restart the engine
char szCmd[256];
Q_snprintf(szCmd, sizeof( szCmd ), "_setgamedir %s\n", kv->GetString("ModDir"));
engine->ClientCmd_Unrestricted(szCmd);
// Force restart of entire engine
engine->ClientCmd_Unrestricted("_restart\n");
}
}
}
else if (!stricmp(command, "Cancel"))
{
Close();
}
else
{
BaseClass::OnCommand(command);
}
}

36
gameui/ChangeGameDialog.h Normal file
View File

@ -0,0 +1,36 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CHANGEGAMEDIALOG_H
#define CHANGEGAMEDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Frame.h>
//-----------------------------------------------------------------------------
// Purpose: Dialogs for use to change current loaded mod
//-----------------------------------------------------------------------------
class CChangeGameDialog : public vgui::Frame
{
public:
CChangeGameDialog(vgui::Panel *parent);
~CChangeGameDialog();
virtual void OnCommand( const char *command );
private:
void LoadModList();
vgui::ListPanel *m_pModList;
typedef vgui::Frame BaseClass;
};
#endif // CHANGEGAMEDIALOG_H

View File

@ -0,0 +1,47 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "CommandCheckButton.h"
#include "EngineInterface.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
CCommandCheckButton::CCommandCheckButton( Panel *parent, const char *panelName, const char *text, const char *downcmd, const char *upcmd )
: CheckButton( parent, panelName, text )
{
m_pszDown = downcmd ? strdup( downcmd ) : NULL;
m_pszUp = upcmd ? strdup( upcmd ) : NULL;
}
CCommandCheckButton::~CCommandCheckButton()
{
free( m_pszDown );
free( m_pszUp );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *panel -
//-----------------------------------------------------------------------------
void CCommandCheckButton::SetSelected( bool state )
{
BaseClass::SetSelected( state );
if ( IsSelected() && m_pszDown )
{
engine->ClientCmd_Unrestricted( m_pszDown );
engine->ClientCmd_Unrestricted( "\n" );
}
else if ( !IsSelected() && m_pszUp )
{
engine->ClientCmd_Unrestricted( m_pszUp );
engine->ClientCmd_Unrestricted( "\n" );
}
}

View File

@ -0,0 +1,30 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef COMMANDCHECKBUTTON_H
#define COMMANDCHECKBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/CheckButton.h>
class CCommandCheckButton : public vgui::CheckButton
{
public:
CCommandCheckButton( vgui::Panel *parent, const char *panelName, const char *text, const char *downcmd, const char *upcmd );
~CCommandCheckButton();
// virtual void OnCheckButtonChecked(vgui::Panel *panel);
virtual void SetSelected( bool state );
private:
typedef vgui::CheckButton BaseClass;
char *m_pszDown;
char *m_pszUp;
};
#endif // COMMANDCHECKBUTTON_H

255
gameui/CommentaryDialog.cpp Normal file
View File

@ -0,0 +1,255 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "CommentaryDialog.h"
#include "BasePanel.h"
#include "convar.h"
#include "EngineInterface.h"
#include "GameUI_Interface.h"
#include "vgui/ISurface.h"
#include "vgui/IInput.h"
#include <stdio.h>
using namespace vgui;
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CCommentaryDialog::CCommentaryDialog(vgui::Panel *parent) : BaseClass(parent, "CommentaryDialog")
{
SetDeleteSelfOnClose(true);
SetSizeable( false );
input()->SetAppModalSurface(GetVPanel());
vgui::surface()->RestrictPaintToSinglePanel(GetVPanel());
GameUI().PreventEngineHideGameUI();
SetTitle("#GameUI_CommentaryDialogTitle", true);
LoadControlSettings("Resource/CommentaryDialog.res");
MoveToCenterOfScreen();
bool bCommentaryOn = false;
ConVarRef commentary( "commentary" );
if ( commentary.IsValid() )
{
bCommentaryOn = commentary.GetBool();
}
// Setup the buttons & labels to reflect the current state of the commentary
if ( bCommentaryOn )
{
SetControlString( "ModeLabel", "#GAMEUI_Commentary_LabelOn" );
SetControlString( "TurnOnButton", "#GAMEUI_Commentary_LeaveOn" );
SetControlString( "TurnOffButton", "#GAMEUI_Commentary_TurnOff" );
}
else
{
SetControlString( "ModeLabel", "#GAMEUI_Commentary_LabelOff" );
SetControlString( "TurnOnButton", "#GAMEUI_Commentary_TurnOn" );
SetControlString( "TurnOffButton", "#GAMEUI_Commentary_LeaveOff" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CCommentaryDialog::~CCommentaryDialog()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCommentaryDialog::OnClose( void )
{
BaseClass::OnClose();
vgui::surface()->RestrictPaintToSinglePanel(NULL);
GameUI().AllowEngineHideGameUI();
// Bring up the post dialog
DHANDLE<CPostCommentaryDialog> hPostCommentaryDialog;
if ( !hPostCommentaryDialog.Get() )
{
hPostCommentaryDialog = new CPostCommentaryDialog( BasePanel() );
}
hPostCommentaryDialog->Activate();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *command -
//-----------------------------------------------------------------------------
void CCommentaryDialog::OnCommand( const char *command )
{
if ( !Q_stricmp( command, "TurnOn" ) )
{
ConVarRef commentary("commentary");
commentary.SetValue( 1 );
Close();
}
else if ( !Q_stricmp( command, "TurnOff" ) )
{
ConVarRef commentary("commentary");
commentary.SetValue( 0 );
Close();
}
else
{
BaseClass::OnCommand( command );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCommentaryDialog::OnKeyCodePressed(KeyCode code)
{
// Ignore escape key
if ( code == KEY_ESCAPE )
return;
if ( code == KEY_XBUTTON_A || code == STEAMCONTROLLER_A )
{
OnCommand( "TurnOn" );
return;
}
else if ( code == KEY_XBUTTON_B || code == STEAMCONTROLLER_B )
{
OnCommand( "TurnOff" );
return;
}
BaseClass::OnKeyCodePressed(code);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void OpenCommentaryDialog( void )
{
DHANDLE<CCommentaryDialog> hCommentaryDialog;
if ( !hCommentaryDialog.Get() )
{
hCommentaryDialog = new CCommentaryDialog( BasePanel() );
}
GameUI().ActivateGameUI();
hCommentaryDialog->Activate();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
ConVar commentary_firstrun("commentary_firstrun", "0", FCVAR_ARCHIVE );
void CC_CommentaryTestFirstRun( void )
{
// The enable/disable commentary box in the sound options got lost in time;
// always prompt the user for commentary mode instead on new game.
//if ( !commentary_firstrun.GetBool() )
{
commentary_firstrun.SetValue(1);
OpenCommentaryDialog();
}
}
static ConCommand commentary_testfirstrun("commentary_testfirstrun", CC_CommentaryTestFirstRun, 0 );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CPostCommentaryDialog::CPostCommentaryDialog(vgui::Panel *parent) : BaseClass(parent, "PostCommentaryDialog")
{
SetDeleteSelfOnClose(true);
SetSizeable( false );
input()->SetAppModalSurface(GetVPanel());
vgui::surface()->RestrictPaintToSinglePanel(GetVPanel());
m_bResetPaintRestrict = false;
SetTitle("#GameUI_CommentaryDialogTitle", true);
LoadControlSettings("Resource/PostCommentaryDialog.res");
MoveToCenterOfScreen();
bool bCommentaryOn = false;
ConVarRef commentary("commentary");
if ( commentary.IsValid() )
{
bCommentaryOn = commentary.GetBool();
}
// Setup the buttons & labels to reflect the current state of the commentary
if ( bCommentaryOn )
{
SetControlString( "PostModeLabel", "#GAMEUI_PostCommentary_ModeLabelOn" );
}
else
{
SetControlString( "PostModeLabel", "#GAMEUI_PostCommentary_ModeLabelOff" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CPostCommentaryDialog::~CPostCommentaryDialog()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPostCommentaryDialog::OnFinishedClose( void )
{
BaseClass::OnFinishedClose();
if ( !m_bResetPaintRestrict )
{
m_bResetPaintRestrict = true;
vgui::surface()->RestrictPaintToSinglePanel(NULL);
GameUI().HideGameUI();
}
}
void CPostCommentaryDialog::OnKeyCodeTyped(KeyCode code)
{
if ( code == KEY_ESCAPE )
{
Close();
vgui::surface()->RestrictPaintToSinglePanel(NULL);
m_bResetPaintRestrict = true;
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPostCommentaryDialog::OnKeyCodePressed(KeyCode code)
{
if ( code == KEY_XBUTTON_A || code == KEY_XBUTTON_B || code == STEAMCONTROLLER_B )
{
Close();
vgui::surface()->RestrictPaintToSinglePanel(NULL);
m_bResetPaintRestrict = true;
}
else
{
BaseClass::OnKeyCodePressed(code);
}
}

55
gameui/CommentaryDialog.h Normal file
View File

@ -0,0 +1,55 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef COMMENTARYDIALOG_H
#define COMMENTARYDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "utlvector.h"
#include <vgui/KeyCode.h>
class CGameChapterPanel;
class CSkillSelectionDialog;
//-----------------------------------------------------------------------------
// Purpose: Handles selection of commentary mode on/off
//-----------------------------------------------------------------------------
class CCommentaryDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CCommentaryDialog, vgui::Frame );
public:
CCommentaryDialog(vgui::Panel *parent);
~CCommentaryDialog();
virtual void OnClose( void );
virtual void OnCommand( const char *command );
virtual void OnKeyCodePressed(vgui::KeyCode code);
};
//-----------------------------------------------------------------------------
// Purpose: Small dialog to remind players on method of changing commentary mode
//-----------------------------------------------------------------------------
class CPostCommentaryDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CPostCommentaryDialog, vgui::Frame );
public:
CPostCommentaryDialog(vgui::Panel *parent);
~CPostCommentaryDialog();
virtual void OnFinishedClose( void );
virtual void OnKeyCodeTyped(vgui::KeyCode code);
virtual void OnKeyCodePressed(vgui::KeyCode code);
private:
bool m_bResetPaintRestrict;
};
#endif // COMMENTARYDIALOG_H

View File

@ -0,0 +1,107 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "CommentaryExplanationDialog.h"
#include "BasePanel.h"
#include "convar.h"
#include "EngineInterface.h"
#include "GameUI_Interface.h"
#include "vgui/ISurface.h"
#include "vgui/IInput.h"
#include <stdio.h>
using namespace vgui;
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CCommentaryExplanationDialog::CCommentaryExplanationDialog(vgui::Panel *parent, char *pszFinishCommand) : BaseClass(parent, "CommentaryExplanationDialog")
{
SetDeleteSelfOnClose(true);
SetSizeable( false );
input()->SetAppModalSurface(GetVPanel());
LoadControlSettings("Resource/CommentaryExplanationDialog.res");
MoveToCenterOfScreen();
GameUI().PreventEngineHideGameUI();
// Save off the finish command
Q_snprintf( m_pszFinishCommand, sizeof( m_pszFinishCommand ), "%s", pszFinishCommand );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CCommentaryExplanationDialog::~CCommentaryExplanationDialog()
{
}
void CCommentaryExplanationDialog::OnKeyCodeTyped(KeyCode code)
{
if ( code == KEY_ESCAPE )
{
OnCommand( "cancel" );
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCommentaryExplanationDialog::OnKeyCodePressed(KeyCode code)
{
if ( GetBaseButtonCode( code ) == KEY_XBUTTON_B || GetBaseButtonCode( code ) == STEAMCONTROLLER_B )
{
OnCommand( "cancel" );
}
else if ( GetBaseButtonCode( code ) == KEY_XBUTTON_A || GetBaseButtonCode( code ) == STEAMCONTROLLER_A )
{
OnCommand( "ok" );
}
else
{
BaseClass::OnKeyCodePressed(code);
}
}
//-----------------------------------------------------------------------------
// Purpose: handles button commands
//-----------------------------------------------------------------------------
void CCommentaryExplanationDialog::OnCommand( const char *command )
{
if ( !stricmp( command, "ok" ) )
{
Close();
BasePanel()->FadeToBlackAndRunEngineCommand( m_pszFinishCommand );
}
else if ( !stricmp( command, "cancel" ) || !stricmp( command, "close" ) )
{
Close();
}
else
{
BaseClass::OnCommand( command );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCommentaryExplanationDialog::OnClose( void )
{
BaseClass::OnClose();
GameUI().AllowEngineHideGameUI();
}

View File

@ -0,0 +1,37 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef COMMENTARYEXPLANATIONDIALOG_H
#define COMMENTARYEXPLANATIONDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "utlvector.h"
#include <vgui/KeyCode.h>
//-----------------------------------------------------------------------------
// Purpose: Dialog that explains the commentary mode
//-----------------------------------------------------------------------------
class CCommentaryExplanationDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CCommentaryExplanationDialog, vgui::Frame );
public:
CCommentaryExplanationDialog(vgui::Panel *parent, char *pszFinishCommand);
~CCommentaryExplanationDialog();
virtual void OnKeyCodeTyped(vgui::KeyCode code);
virtual void OnKeyCodePressed(vgui::KeyCode code);
virtual void OnCommand( const char *command );
virtual void OnClose( void );
private:
char m_pszFinishCommand[ 512 ];
};
#endif // COMMENTARYEXPLANATIONDIALOG_H

View File

@ -0,0 +1,406 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <stdio.h>
#include <memory.h>
#if defined( WIN32 ) && !defined( _X360 )
#include <windows.h>
#endif
#include "ContentControlDialog.h"
#include "checksum_md5.h"
#include "EngineInterface.h"
#include <vgui/IInput.h>
#include <vgui/ISystem.h>
#include <vgui/ISurface.h>
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
#include <vgui_controls/Button.h>
#include <vgui_controls/CheckButton.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/RadioButton.h>
#include <vgui_controls/TextEntry.h>
#include <tier0/vcrmode.h>
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Basic help dialog
//-----------------------------------------------------------------------------
CContentControlDialog::CContentControlDialog(vgui::Panel *parent) : vgui::Frame(parent, "ContentControlDialog")
{
SetBounds(0, 0, 372, 160);
SetSizeable( false );
SetTitle( "#GameUI_ContentLock", true );
m_pStatus = new vgui::Label( this, "ContentStatus", "" );
m_pPasswordLabel = new vgui::Label( this, "PasswordPrompt", "#GameUI_PasswordPrompt" );
m_pPassword2Label = new vgui::Label( this, "PasswordReentryPrompt", "#GameUI_PasswordReentryPrompt" );
m_pExplain = new vgui::Label( this, "ContentControlExplain", "" );
m_pPassword = new vgui::TextEntry( this, "Password" );
m_pPassword2 = new vgui::TextEntry( this, "Password2" );
m_pOK = new vgui::Button( this, "Ok", "#GameUI_OK" );
m_pOK->SetCommand( "Ok" );
vgui::Button *cancel = new vgui::Button( this, "Cancel", "#GameUI_Cancel" );
cancel->SetCommand( "Cancel" );
m_szGorePW[ 0 ] = 0;
ResetPassword();
LoadControlSettings("Resource\\ContentControlDialog.res");
// Explain("");
// UpdateContentControlStatus();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CContentControlDialog::~CContentControlDialog()
{
}
void CContentControlDialog::Activate()
{
BaseClass::Activate();
m_pPassword->SetText("");
m_pPassword->RequestFocus();
m_pPassword2->SetText("");
Explain("");
UpdateContentControlStatus();
input()->SetAppModalSurface(GetVPanel());
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CContentControlDialog::ResetPassword()
{
// Set initial value
#ifdef WIN32
#ifndef _XBOX
HKEY key;
if ( ERROR_SUCCESS == VCRHook_RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Valve\\Half-Life\\Settings", 0, KEY_READ, &key))
{
DWORD type;
DWORD bufSize = sizeof(m_szGorePW);
VCRHook_RegQueryValueEx(key, "User Token 2", NULL, &type, (unsigned char *)m_szGorePW, &bufSize );
VCRHook_RegCloseKey( key );
}
else
#endif
{
m_szGorePW[ 0 ] = 0;
}
#else
vgui::system()->SetRegistryString( "Software\\Valve\\Half-Life\\Settings\\User Token 2", m_szGorePW );
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CContentControlDialog::ApplyPassword()
{
WriteToken( m_szGorePW );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CContentControlDialog::Explain( char const *fmt, ... )
{
if ( !m_pExplain )
return;
va_list argptr;
char text[1024];
va_start (argptr,fmt);
Q_vsnprintf (text, sizeof(text), fmt, argptr);
va_end (argptr);
m_pExplain->SetText( text );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *command -
//-----------------------------------------------------------------------------
void CContentControlDialog::OnCommand( const char *command )
{
if ( !stricmp( command, "Ok" ) )
{
bool canclose = false;
char pw1[ 256 ];
char pw2[ 256 ];
m_pPassword->GetText( pw1, 256 );
m_pPassword2->GetText( pw2, 256 );
// Get text and check
// bool enabled = PasswordEnabled(); //( m_szGorePW[0]!=0 ) ? true : false;
// bool pwMatch = stricmp( pw1, pw2 ) == 0 ? true : false;
if (IsPasswordEnabledInDialog())
{
canclose = DisablePassword(pw1);
// canclose = CheckPassword( m_szGorePW, pw1, false );
}
else if (!strcmp(pw1, pw2))
{
canclose = EnablePassword(pw1);
// canclose = CheckPassword( NULL, pw1, true );
}
else
{
Explain( "#GameUI_PasswordsDontMatch" );
}
if ( canclose )
{
OnClose();
}
}
else if ( !stricmp( command, "Cancel" ) )
{
OnClose();
}
else
{
BaseClass::OnCommand( command );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CContentControlDialog::OnClose()
{
BaseClass::OnClose();
PostActionSignal(new KeyValues("ContentControlClose"));
// MarkForDeletion();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CContentControlDialog::WriteToken( const char *str )
{
// Set initial value
#ifdef WIN32
#ifndef _XBOX
HKEY key;
if ( ERROR_SUCCESS == VCRHook_RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Valve\\Half-Life\\Settings", 0, KEY_WRITE, &key))
{
DWORD type = REG_SZ;
DWORD bufSize = strlen( str ) + 1;
VCRHook_RegSetValueEx(key, "User Token 2", 0, type, (const unsigned char *)str, bufSize );
VCRHook_RegCloseKey( key );
}
#endif
#else
vgui::system()->SetRegistryString( "Software\\Valve\\Half-Life\\Settings\\User Token 2", m_szGorePW );
#endif
Q_strncpy( m_szGorePW, str, sizeof( m_szGorePW ) );
UpdateContentControlStatus();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CContentControlDialog::HashPassword(const char *newPW, char *hashBuffer, int maxlen )
{
// Compute the md5 hash and save it.
unsigned char md5_hash[16];
MD5Context_t ctx;
MD5Init( &ctx );
MD5Update( &ctx, (unsigned char const *)newPW, strlen( newPW ) );
MD5Final( md5_hash, &ctx );
char hex[ 128 ];
Q_binarytohex( md5_hash, sizeof( md5_hash ), hex, sizeof( hex ) );
// char digestedPW[ 128 ];
Q_strncpy( hashBuffer, hex, maxlen );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
/*
bool CContentControlDialog::CheckPassword( char const *oldPW, char const *newPW, bool enableContentControl )
{
char digestedPW[ 128 ];
HashPassword(newPW, digestedPW, sizeof( digestedPW ) );
// Compute the md5 hash and save it.
unsigned char md5_hash[16];
MD5Context_t ctx;
MD5Init( &ctx );
MD5Update( &ctx, (unsigned char const *)(LPCSTR)newPW, strlen( newPW ) );
MD5Final( md5_hash, &ctx );
char hex[ 128 ];
Q_binarytohex( md5_hash, sizeof( md5_hash ), hex, sizeof( hex ) );
Q_strncpy( digestedPW, hex, sizeof( digestedPW ) );
*/
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CContentControlDialog::EnablePassword(const char *newPW)
{
if ( !newPW[ 0 ] )
{
Explain( "#GameUI_MustEnterPassword" );
return false;
}
char digestedPW[ 128 ];
HashPassword(newPW, digestedPW, sizeof( digestedPW ) );
// disable violence
/* engine->Cvar_SetValue("violence_hblood", 0.0 );
engine->Cvar_SetValue("violence_hgibs" , 0.0 );
engine->Cvar_SetValue("violence_ablood", 0.0 );
engine->Cvar_SetValue("violence_agibs" , 0.0 );
*/
ConVarRef violence_hblood( "violence_hblood" );
violence_hblood.SetValue(false);
ConVarRef violence_hgibs( "violence_hgibs" );
violence_hgibs.SetValue(false);
ConVarRef violence_ablood( "violence_ablood" );
violence_ablood.SetValue(false);
ConVarRef violence_agibs( "violence_agibs" );
violence_agibs.SetValue(false);
// Store digest to registry
// WriteToken( digestedPW );
Q_strncpy(m_szGorePW, digestedPW, sizeof( m_szGorePW ) );
/*
}
else
{
if ( stricmp( oldPW, digestedPW ) )
{
// Warn that password is invalid
Explain( "#GameUI_IncorrectPassword" );
return false;
}
}
}*/
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CContentControlDialog::DisablePassword(const char *oldPW)
{
if ( !oldPW[ 0 ] )
{
Explain( "#GameUI_MustEnterPassword" );
return false;
}
char digestedPW[ 128 ];
HashPassword(oldPW, digestedPW, sizeof( digestedPW ) );
if( stricmp( m_szGorePW, digestedPW ) )
{
Explain( "#GameUI_IncorrectPassword" );
return false;
}
m_szGorePW[0] = 0;
// set the violence cvars
/* engine->Cvar_SetValue("violence_hblood", 1.0 );
engine->Cvar_SetValue("violence_hgibs" , 1.0 );
engine->Cvar_SetValue("violence_ablood", 1.0 );
engine->Cvar_SetValue("violence_agibs" , 1.0 );
*/
ConVarRef violence_hblood( "violence_hblood" );
violence_hblood.SetValue(true);
ConVarRef violence_hgibs( "violence_hgibs" );
violence_hgibs.SetValue(true);
ConVarRef violence_ablood( "violence_ablood" );
violence_ablood.SetValue(true);
ConVarRef violence_agibs( "violence_agibs" );
violence_agibs.SetValue(true);
// // Remove digest value
// WriteToken( "" );
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CContentControlDialog::IsPasswordEnabledInDialog()
{
return m_szGorePW[0] != 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CContentControlDialog::UpdateContentControlStatus( void )
{
bool enabled = IsPasswordEnabledInDialog(); //( m_szGorePW[0]!=0 ) ? true : false;
m_pStatus->SetText( enabled ? "#GameUI_ContentStatusEnabled" : "#GameUI_ContentStatusDisabled" );
if (enabled)
{
m_pPasswordLabel->SetText("#GameUI_PasswordDisablePrompt");
}
else
{
m_pPasswordLabel->SetText("#GameUI_PasswordPrompt");
}
// hide the re-entry
m_pPassword2Label->SetVisible(!enabled);
m_pPassword2->SetVisible(!enabled);
// m_pOK->SetText( enabled ? "#GameUI_Disable" : "#GameUI_Enable" );
}

View File

@ -0,0 +1,66 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CONTENTCONTROLDIALOG_H
#define CONTENTCONTROLDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CContentControlDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CContentControlDialog, vgui::Frame );
public:
CContentControlDialog(vgui::Panel *parent);
~CContentControlDialog();
virtual void OnCommand( const char *command );
virtual void OnClose();
virtual void Activate();
void ResetPassword();
void ApplyPassword();
bool IsPasswordEnabledInDialog();
bool IsPasswordEnabled() { return ( m_szGorePW[0] != 0 ); }
protected:
void WriteToken( const char *str );
bool CheckPassword( char const *oldPW, char const *newPW, bool enableContentControl );
void UpdateContentControlStatus( void );
void Explain( PRINTF_FORMAT_STRING char const *fmt, ... );
void HashPassword(const char *newPW, char *hashBuffer, int maxlen );
bool EnablePassword(const char *newPW);
bool DisablePassword(const char *oldPW);
enum
{
MAX_GORE_PW = 64,
};
char m_szGorePW[ MAX_GORE_PW ];
bool m_bDefaultPassword;
vgui::Label *m_pStatus;
vgui::Button *m_pOK;
vgui::TextEntry *m_pPassword;
vgui::Label *m_pPasswordLabel;
vgui::Label *m_pPassword2Label;
vgui::TextEntry *m_pPassword2;
vgui::Label *m_pExplain;
};
#endif // CONTENTCONTROLDIALOG_H

View File

@ -0,0 +1,25 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "BasePanel.h"
#include "ControllerDialog.h"
using namespace vgui;
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
CControllerDialog::CControllerDialog( vgui::Panel *parent ) : BaseClass( parent, true ) // TRUE second param says we want the controller options
{
}
void CControllerDialog::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
SetControlString( "TitleLabel", "#GameUI_Controller" );
}

27
gameui/ControllerDialog.h Normal file
View File

@ -0,0 +1,27 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef CONTROLLERDIALOG_H
#define CONTROLLERDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "OptionsDialog.h"
class CControllerDialog : public COptionsDialogXbox
{
DECLARE_CLASS_SIMPLE( CControllerDialog, COptionsDialogXbox );
public:
CControllerDialog(vgui::Panel *parent);
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
};
#endif // CONTROLLERDIALOG_H

View File

@ -0,0 +1,228 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "CreateMultiplayerGameBotPage.h"
using namespace vgui;
#include <KeyValues.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/CheckButton.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/TextEntry.h>
#include "filesystem.h"
#include "PanelListPanel.h"
#include "scriptobject.h"
#include <tier0/vcrmode.h>
#include "tier1/convar.h"
#include "EngineInterface.h"
#include "CvarToggleCheckButton.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
// for join team combo box
enum BotGUITeamType
{
BOT_GUI_TEAM_RANDOM = 0,
BOT_GUI_TEAM_CT = 1,
BOT_GUI_TEAM_T = 2
};
// these must correlate with above enum
static const char *joinTeamArg[] = { "any", "ct", "t", NULL };
// for bot chatter combo box
enum BotGUIChatterType
{
BOT_GUI_CHATTER_NORMAL = 0,
BOT_GUI_CHATTER_MINIMAL = 1,
BOT_GUI_CHATTER_RADIO = 2,
BOT_GUI_CHATTER_OFF = 3
};
// these must correlate with above enum
static const char *chatterArg[] = { "normal", "minimal", "radio", "off", NULL };
extern void UTIL_StripInvalidCharacters( char *pszInput );
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameBotPage::SetJoinTeamCombo( const char *team )
{
if (team)
{
for( int i=0; joinTeamArg[i]; ++i )
if (!stricmp( team, joinTeamArg[i] ))
{
m_joinTeamCombo->ActivateItemByRow( i );
return;
}
}
else
{
m_joinTeamCombo->ActivateItemByRow( BOT_GUI_TEAM_RANDOM );
}
}
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameBotPage::SetChatterCombo( const char *chatter )
{
if (chatter)
{
for( int i=0; chatterArg[i]; ++i )
if (!stricmp( chatter, chatterArg[i] ))
{
m_chatterCombo->ActivateItemByRow( i );
return;
}
}
else
{
m_joinTeamCombo->ActivateItemByRow( BOT_GUI_CHATTER_NORMAL );
}
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameBotPage::CCreateMultiplayerGameBotPage( vgui::Panel *parent, const char *name, KeyValues *botKeys ) : PropertyPage( parent, name )
{
m_pSavedData = botKeys;
m_allowRogues = new CCvarToggleCheckButton( this, "BotAllowRogueCheck", "", "bot_allow_rogues" );
m_allowPistols = new CCvarToggleCheckButton( this, "BotAllowPistolsCheck", "", "bot_allow_pistols" );
m_allowShotguns = new CCvarToggleCheckButton( this, "BotAllowShotgunsCheck", "", "bot_allow_shotguns" );
m_allowSubmachineGuns = new CCvarToggleCheckButton( this, "BotAllowSubmachineGunsCheck", "", "bot_allow_sub_machine_guns" );
m_allowRifles = new CCvarToggleCheckButton( this, "BotAllowRiflesCheck", "", "bot_allow_rifles" );
m_allowMachineGuns = new CCvarToggleCheckButton( this, "BotAllowMachineGunsCheck", "", "bot_allow_machine_guns" );
m_allowGrenades = new CCvarToggleCheckButton( this, "BotAllowGrenadesCheck", "", "bot_allow_grenades" );
m_allowSnipers = new CCvarToggleCheckButton( this, "BotAllowSnipersCheck", "", "bot_allow_snipers" );
#ifdef CS_SHIELD_ENABLED
m_allowShields = new CCvarToggleCheckButton( this, "BotAllowShieldCheck", "", "bot_allow_shield" );
#endif // CS_SHIELD_ENABLED
m_joinAfterPlayer = new CCvarToggleCheckButton( this, "BotJoinAfterPlayerCheck", "", "bot_join_after_player" );
m_deferToHuman = new CCvarToggleCheckButton( this, "BotDeferToHumanCheck", "", "bot_defer_to_human" );
// set up team join combo box
// NOTE: If order of AddItem is changed, update the associated enum
m_joinTeamCombo = new ComboBox( this, "BotJoinTeamCombo", 3, false );
m_joinTeamCombo->AddItem( "#Cstrike_Random", NULL );
m_joinTeamCombo->AddItem( "#Cstrike_Team_CT", NULL );
m_joinTeamCombo->AddItem( "#Cstrike_Team_T", NULL );
// set up chatter combo box
// NOTE: If order of AddItem is changed, update the associated enum
m_chatterCombo = new ComboBox( this, "BotChatterCombo", 4, false );
m_chatterCombo->AddItem( "#Cstrike_Bot_Chatter_Normal", NULL );
m_chatterCombo->AddItem( "#Cstrike_Bot_Chatter_Minimal", NULL );
m_chatterCombo->AddItem( "#Cstrike_Bot_Chatter_Radio", NULL );
m_chatterCombo->AddItem( "#Cstrike_Bot_Chatter_Off", NULL );
// create text entry fields for quota and prefix
m_prefixEntry = new TextEntry( this, "BotPrefixEntry" );
// set positions and sizes from resources file
LoadControlSettings( "Resource/CreateMultiplayerGameBotPage.res" );
// get initial values from bot keys
m_joinAfterPlayer->SetSelected( botKeys->GetInt( "bot_join_after_player", 1 ) );
m_allowRogues->SetSelected( botKeys->GetInt( "bot_allow_rogues", 1 ) );
m_allowPistols->SetSelected( botKeys->GetInt( "bot_allow_pistols", 1 ) );
m_allowShotguns->SetSelected( botKeys->GetInt( "bot_allow_shotguns", 1 ) );
m_allowSubmachineGuns->SetSelected( botKeys->GetInt( "bot_allow_sub_machine_guns", 1 ) );
m_allowMachineGuns->SetSelected( botKeys->GetInt( "bot_allow_machine_guns", 1 ) );
m_allowRifles->SetSelected( botKeys->GetInt( "bot_allow_rifles", 1 ) );
m_allowSnipers->SetSelected( botKeys->GetInt( "bot_allow_snipers", 1 ) );
m_allowGrenades->SetSelected( botKeys->GetInt( "bot_allow_grenades", 1 ) );
#ifdef CS_SHIELD_ENABLED
m_allowShields->SetSelected( botKeys->GetInt( "bot_allow_shield", 1 ) );
#endif // CS_SHIELD_ENABLED
m_deferToHuman->SetSelected( botKeys->GetInt( "bot_defer_to_human", 1 ) );
SetJoinTeamCombo( botKeys->GetString( "bot_join_team", "any" ) );
SetChatterCombo( botKeys->GetString( "bot_chatter", "normal" ) );
// set bot_prefix
const char *prefix = botKeys->GetString( "bot_prefix" );
if (prefix)
SetControlString( "BotPrefixEntry", prefix );
}
//-----------------------------------------------------------------------------
// Destructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameBotPage::~CCreateMultiplayerGameBotPage()
{
// vgui handles deletion of children automatically through the hierarchy
}
//-----------------------------------------------------------------------------
// Reset values
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameBotPage::OnResetChanges()
{
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void UpdateValue( KeyValues *data, const char *cvarName, int value )
{
data->SetInt( cvarName, value );
ConVarRef var( cvarName );
var.SetValue( value );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void UpdateValue( KeyValues *data, const char *cvarName, const char *value )
{
data->SetString( cvarName, value );
ConVarRef var( cvarName );
var.SetValue( value );
}
//-----------------------------------------------------------------------------
// Called to get data from the page
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameBotPage::OnApplyChanges()
{
UpdateValue( m_pSavedData, "bot_join_after_player", m_joinAfterPlayer->IsSelected() );
UpdateValue( m_pSavedData, "bot_allow_rogues", m_allowRogues->IsSelected() );
UpdateValue( m_pSavedData, "bot_allow_pistols", m_allowPistols->IsSelected() );
UpdateValue( m_pSavedData, "bot_allow_shotguns", m_allowShotguns->IsSelected() );
UpdateValue( m_pSavedData, "bot_allow_sub_machine_guns", m_allowSubmachineGuns->IsSelected() );
UpdateValue( m_pSavedData, "bot_allow_machine_guns", m_allowMachineGuns->IsSelected() );
UpdateValue( m_pSavedData, "bot_allow_rifles", m_allowRifles->IsSelected() );
UpdateValue( m_pSavedData, "bot_allow_snipers", m_allowSnipers->IsSelected() );
UpdateValue( m_pSavedData, "bot_allow_grenades", m_allowGrenades->IsSelected() );
#ifdef CS_SHIELD_ENABLED
UpdateValue( m_pSavedData, "bot_allow_shield", m_allowShields->IsSelected() );
#endif // CS_SHIELD_ENABLED
UpdateValue( m_pSavedData, "bot_defer_to_human", m_deferToHuman->IsSelected() );
// set bot_join_team
UpdateValue( m_pSavedData, "bot_join_team", joinTeamArg[ m_joinTeamCombo->GetActiveItem() ] );
// set bot_chatter
UpdateValue( m_pSavedData, "bot_chatter", chatterArg[ m_chatterCombo->GetActiveItem() ] );
// set bot_prefix
#define BUF_LENGTH 256
char entryBuffer[ BUF_LENGTH ];
m_prefixEntry->GetText( entryBuffer, BUF_LENGTH );
UpdateValue( m_pSavedData, "bot_prefix", entryBuffer );
}

View File

@ -0,0 +1,66 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CREATEMULTIPLAYERGAMEBOTPAGE_H
#define CREATEMULTIPLAYERGAMEBOTPAGE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/PropertyPage.h>
class CPanelListPanel;
class CDescription;
class mpcontrol_t;
class CCvarToggleCheckButton;
//-----------------------------------------------------------------------------
// Purpose: advanced bot properties page of the create game server dialog
//-----------------------------------------------------------------------------
class CCreateMultiplayerGameBotPage : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( CCreateMultiplayerGameBotPage, vgui::PropertyPage );
public:
CCreateMultiplayerGameBotPage( vgui::Panel *parent, const char *name, KeyValues *botKeys );
~CCreateMultiplayerGameBotPage();
protected:
virtual void OnResetChanges();
virtual void OnApplyChanges();
private:
CCvarToggleCheckButton *m_joinAfterPlayer;
CCvarToggleCheckButton *m_allowRogues;
CCvarToggleCheckButton *m_allowPistols;
CCvarToggleCheckButton *m_allowShotguns;
CCvarToggleCheckButton *m_allowSubmachineGuns;
CCvarToggleCheckButton *m_allowMachineGuns;
CCvarToggleCheckButton *m_allowRifles;
CCvarToggleCheckButton *m_allowGrenades;
#ifdef CS_SHIELD_ENABLED
CCvarToggleCheckButton *m_allowShields;
#endif // CS_SHIELD_ENABLED
CCvarToggleCheckButton *m_allowSnipers;
CCvarToggleCheckButton *m_deferToHuman;
vgui::ComboBox *m_joinTeamCombo;
void SetJoinTeamCombo( const char *team );
vgui::ComboBox *m_chatterCombo;
void SetChatterCombo( const char *team );
vgui::TextEntry *m_prefixEntry;
KeyValues *m_pSavedData;
};
#endif // CREATEMULTIPLAYERGAMEBOTPAGE_H

View File

@ -0,0 +1,190 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "CreateMultiplayerGameDialog.h"
#include "CreateMultiplayerGameServerPage.h"
#include "CreateMultiplayerGameGameplayPage.h"
#include "CreateMultiplayerGameBotPage.h"
#include "EngineInterface.h"
#include "ModInfo.h"
#include "GameUI_Interface.h"
#include <stdio.h>
using namespace vgui;
#include "vgui_controls/ComboBox.h"
#include <vgui/ILocalize.h>
#include "filesystem.h"
#include <KeyValues.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameDialog::CCreateMultiplayerGameDialog(vgui::Panel *parent) : PropertyDialog(parent, "CreateMultiplayerGameDialog")
{
m_bBotsEnabled = false;
SetDeleteSelfOnClose(true);
SetSize(348, 460);
SetTitle("#GameUI_CreateServer", true);
SetOKButtonText("#GameUI_Start");
if ( ModInfo().UseBots() )
{
m_bBotsEnabled = true;
}
m_pServerPage = new CCreateMultiplayerGameServerPage(this, "ServerPage");
m_pGameplayPage = new CCreateMultiplayerGameGameplayPage(this, "GameplayPage");
m_pBotPage = NULL;
AddPage(m_pServerPage, "#GameUI_Server");
AddPage(m_pGameplayPage, "#GameUI_Game");
// create KeyValues object to load/save config options
m_pSavedData = new KeyValues( "ServerConfig" );
// load the config data
if (m_pSavedData)
{
m_pSavedData->LoadFromFile( g_pFullFileSystem, "ServerConfig.vdf", "GAME" ); // this is game-specific data, so it should live in GAME, not CONFIG
const char *startMap = m_pSavedData->GetString("map", "");
if (startMap[0])
{
m_pServerPage->SetMap(startMap);
}
}
if ( m_bBotsEnabled )
{
// add a page of advanced bot controls
// NOTE: These controls will use the bot keys to initialize their values
m_pBotPage = new CCreateMultiplayerGameBotPage( this, "BotPage", m_pSavedData );
AddPage( m_pBotPage, "#GameUI_CPUPlayerOptions" );
m_pServerPage->EnableBots( m_pSavedData );
}
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameDialog::~CCreateMultiplayerGameDialog()
{
if (m_pSavedData)
{
m_pSavedData->deleteThis();
m_pSavedData = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: runs the server when the OK button is pressed
//-----------------------------------------------------------------------------
bool CCreateMultiplayerGameDialog::OnOK(bool applyOnly)
{
// reset server enforced cvars
g_pCVar->RevertFlaggedConVars( FCVAR_REPLICATED );
// Cheats were disabled; revert all cheat cvars to their default values.
// This must be done heading into multiplayer games because people can play
// demos etc and set cheat cvars with sv_cheats 0.
g_pCVar->RevertFlaggedConVars( FCVAR_CHEAT );
DevMsg( "FCVAR_CHEAT cvars reverted to defaults.\n" );
BaseClass::OnOK(applyOnly);
// get these values from m_pServerPage and store them temporarily
char szMapName[64], szHostName[64], szPassword[64];
strncpy(szMapName, m_pServerPage->GetMapName(), sizeof( szMapName ));
strncpy(szHostName, m_pGameplayPage->GetHostName(), sizeof( szHostName ));
strncpy(szPassword, m_pGameplayPage->GetPassword(), sizeof( szPassword ));
// save the config data
if (m_pSavedData)
{
if (m_pServerPage->IsRandomMapSelected())
{
// it's set to random map, just save an
m_pSavedData->SetString("map", "");
}
else
{
m_pSavedData->SetString("map", szMapName);
}
// save config to a file
m_pSavedData->SaveToFile( g_pFullFileSystem, "ServerConfig.vdf", "GAME" );
}
char szMapCommand[1024];
// create the command to execute
Q_snprintf(szMapCommand, sizeof( szMapCommand ), "disconnect\nwait\nwait\nsv_lan 1\nsetmaster enable\nmaxplayers %i\nsv_password \"%s\"\nhostname \"%s\"\nprogress_enable\nmap %s\n",
m_pGameplayPage->GetMaxPlayers(),
szPassword,
szHostName,
szMapName
);
// exec
engine->ClientCmd_Unrestricted(szMapCommand);
return true;
}
void CCreateMultiplayerGameDialog::OnKeyCodePressed( vgui::KeyCode code )
{
// Handle close here, CBasePanel parent doesn't support "DialogClosing" command
ButtonCode_t nButtonCode = GetBaseButtonCode( code );
if ( nButtonCode == KEY_XBUTTON_B || nButtonCode == STEAMCONTROLLER_B )
{
OnCommand( "Close" );
}
else if ( nButtonCode == KEY_XBUTTON_A || nButtonCode == STEAMCONTROLLER_A )
{
OnOK( false );
}
else if ( nButtonCode == KEY_XBUTTON_UP ||
nButtonCode == KEY_XSTICK1_UP ||
nButtonCode == KEY_XSTICK2_UP ||
nButtonCode == STEAMCONTROLLER_DPAD_UP ||
nButtonCode == KEY_UP )
{
int nItem = m_pServerPage->GetMapList()->GetActiveItem() - 1;
if ( nItem < 0 )
{
nItem = m_pServerPage->GetMapList()->GetItemCount() - 1;
}
m_pServerPage->GetMapList()->ActivateItem( nItem );
}
else if ( nButtonCode == KEY_XBUTTON_DOWN ||
nButtonCode == KEY_XSTICK1_DOWN ||
nButtonCode == KEY_XSTICK2_DOWN ||
nButtonCode == STEAMCONTROLLER_DPAD_DOWN ||
nButtonCode == KEY_DOWN )
{
int nItem = m_pServerPage->GetMapList()->GetActiveItem() + 1;
if ( nItem >= m_pServerPage->GetMapList()->GetItemCount() )
{
nItem = 0;
}
m_pServerPage->GetMapList()->ActivateItem( nItem );
}
else
{
BaseClass::OnKeyCodePressed( code );
}
}

View File

@ -0,0 +1,47 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CREATEMULTIPLAYERGAMEDIALOG_H
#define CREATEMULTIPLAYERGAMEDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/PropertyDialog.h>
class CCreateMultiplayerGameServerPage;
class CCreateMultiplayerGameGameplayPage;
class CCreateMultiplayerGameBotPage;
//-----------------------------------------------------------------------------
// Purpose: dialog for launching a listenserver
//-----------------------------------------------------------------------------
class CCreateMultiplayerGameDialog : public vgui::PropertyDialog
{
DECLARE_CLASS_SIMPLE( CCreateMultiplayerGameDialog, vgui::PropertyDialog );
public:
CCreateMultiplayerGameDialog(vgui::Panel *parent);
~CCreateMultiplayerGameDialog();
protected:
virtual bool OnOK(bool applyOnly);
virtual void OnKeyCodePressed( vgui::KeyCode code );
private:
CCreateMultiplayerGameServerPage *m_pServerPage;
CCreateMultiplayerGameGameplayPage *m_pGameplayPage;
CCreateMultiplayerGameBotPage *m_pBotPage;
bool m_bBotsEnabled;
// for loading/saving game config
KeyValues *m_pSavedData;
};
#endif // CREATEMULTIPLAYERGAMEDIALOG_H

View File

@ -0,0 +1,475 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <stdio.h>
#include <time.h>
#include "CreateMultiplayerGameGameplayPage.h"
using namespace vgui;
#include <KeyValues.h>
#include <vgui/ILocalize.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/CheckButton.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/TextEntry.h>
#include "filesystem.h"
#include "PanelListPanel.h"
#include "scriptobject.h"
#include <tier0/vcrmode.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
#define OPTIONS_DIR "cfg"
#define DEFAULT_OPTIONS_FILE OPTIONS_DIR "/settings_default.scr"
#define OPTIONS_FILE OPTIONS_DIR "/settings.scr"
//-----------------------------------------------------------------------------
// Purpose: class for loading/saving server config file
//-----------------------------------------------------------------------------
class CServerDescription : public CDescription
{
public:
CServerDescription( void );
void WriteScriptHeader( FileHandle_t fp );
void WriteFileHeader( FileHandle_t fp );
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameGameplayPage::CCreateMultiplayerGameGameplayPage(vgui::Panel *parent, const char *name) : PropertyPage(parent, name)
{
SetSize( 10, 10 ); // Quiet "parent not sized yet" spew
m_pOptionsList = new CPanelListPanel(this, "GameOptions");
m_pDescription = new CServerDescription();
m_pDescription->InitFromFile( DEFAULT_OPTIONS_FILE );
m_pDescription->InitFromFile( OPTIONS_FILE );
m_pList = NULL;
LoadControlSettings("Resource/CreateMultiplayerGameGameplayPage.res");
LoadGameOptionsList();
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameGameplayPage::~CCreateMultiplayerGameGameplayPage()
{
delete m_pDescription;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CCreateMultiplayerGameGameplayPage::GetMaxPlayers()
{
return atoi(GetValue("maxplayers", "32"));
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CCreateMultiplayerGameGameplayPage::GetPassword()
{
return GetValue("sv_password", "");
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CCreateMultiplayerGameGameplayPage::GetHostName()
{
return GetValue("hostname", "Half-Life");
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CCreateMultiplayerGameGameplayPage::GetValue(const char *cvarName, const char *defaultValue)
{
for (mpcontrol_t *mp = m_pList; mp != NULL; mp = mp->next)
{
Panel *control = mp->pControl;
if (control && !stricmp(mp->GetName(), cvarName))
{
KeyValues *data = new KeyValues("GetText");
static char buf[128];
if (control && control->RequestInfo(data))
{
strncpy(buf, data->GetString("text", defaultValue), sizeof(buf) - 1);
}
else
{
// no value found, copy in default text
strncpy(buf, defaultValue, sizeof(buf) - 1);
}
// ensure null termination of string
buf[sizeof(buf) - 1] = 0;
// free
data->deleteThis();
return buf;
}
}
return defaultValue;
}
//-----------------------------------------------------------------------------
// Purpose: called to get data from the page
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameGameplayPage::OnApplyChanges()
{
// Get the values from the controls
GatherCurrentValues();
// Create the game.cfg file
if ( m_pDescription )
{
FileHandle_t fp;
// Add settings to config.cfg
m_pDescription->WriteToConfig();
// save out in the settings file
g_pFullFileSystem->CreateDirHierarchy( OPTIONS_DIR, "GAME" );
fp = g_pFullFileSystem->Open( OPTIONS_FILE, "wb", "GAME" );
if ( fp )
{
m_pDescription->WriteToScriptFile( fp );
g_pFullFileSystem->Close( fp );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Creates all the controls in the game options list
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameGameplayPage::LoadGameOptionsList()
{
// destroy any existing controls
mpcontrol_t *p, *n;
p = m_pList;
while ( p )
{
n = p->next;
//
delete p->pControl;
delete p->pPrompt;
delete p;
p = n;
}
m_pList = NULL;
// Go through desciption creating controls
CScriptObject *pObj;
pObj = m_pDescription->pObjList;
mpcontrol_t *pCtrl;
CheckButton *pBox;
TextEntry *pEdit;
ComboBox *pCombo;
CScriptListItem *pListItem;
Panel *objParent = m_pOptionsList;
while ( pObj )
{
if ( pObj->type == O_OBSOLETE )
{
pObj = pObj->pNext;
continue;
}
pCtrl = new mpcontrol_t( objParent, pObj->cvarname );
pCtrl->type = pObj->type;
switch ( pCtrl->type )
{
case O_BOOL:
pBox = new CheckButton( pCtrl, "DescCheckButton", pObj->prompt );
pBox->SetSelected( pObj->fdefValue != 0.0f ? true : false );
pCtrl->pControl = (Panel *)pBox;
break;
case O_STRING:
case O_NUMBER:
pEdit = new TextEntry( pCtrl, "DescEdit");
pEdit->InsertString(pObj->defValue);
pCtrl->pControl = (Panel *)pEdit;
break;
case O_LIST:
pCombo = new ComboBox( pCtrl, "DescEdit", 5, false );
pListItem = pObj->pListItems;
while ( pListItem )
{
pCombo->AddItem(pListItem->szItemText, NULL);
pListItem = pListItem->pNext;
}
pCombo->ActivateItemByRow((int)pObj->fdefValue);
pCtrl->pControl = (Panel *)pCombo;
break;
default:
break;
}
if ( pCtrl->type != O_BOOL )
{
pCtrl->pPrompt = new vgui::Label( pCtrl, "DescLabel", "" );
pCtrl->pPrompt->SetContentAlignment( vgui::Label::a_west );
pCtrl->pPrompt->SetTextInset( 5, 0 );
pCtrl->pPrompt->SetText( pObj->prompt );
}
pCtrl->pScrObj = pObj;
pCtrl->SetSize( 100, 28 );
//pCtrl->SetBorder( scheme()->GetBorder(1, "DepressedButtonBorder") );
m_pOptionsList->AddItem( pCtrl );
// Link it in
if ( !m_pList )
{
m_pList = pCtrl;
pCtrl->next = NULL;
}
else
{
mpcontrol_t *p;
p = m_pList;
while ( p )
{
if ( !p->next )
{
p->next = pCtrl;
pCtrl->next = NULL;
break;
}
p = p->next;
}
}
pObj = pObj->pNext;
}
}
//-----------------------------------------------------------------------------
// Purpose: applies all the values in the page
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameGameplayPage::GatherCurrentValues()
{
if ( !m_pDescription )
return;
// OK
CheckButton *pBox;
TextEntry *pEdit;
ComboBox *pCombo;
mpcontrol_t *pList;
CScriptObject *pObj;
CScriptListItem *pItem;
char szValue[256];
char strValue[256];
wchar_t w_szStrValue[256];
pList = m_pList;
while ( pList )
{
pObj = pList->pScrObj;
if ( !pList->pControl )
{
pObj->SetCurValue( pObj->defValue );
pList = pList->next;
continue;
}
switch ( pObj->type )
{
case O_BOOL:
pBox = (CheckButton *)pList->pControl;
Q_snprintf( szValue, sizeof( szValue ), "%s", pBox->IsSelected() ? "1" : "0" );
break;
case O_NUMBER:
pEdit = ( TextEntry * )pList->pControl;
pEdit->GetText( strValue, sizeof( strValue ) );
Q_snprintf( szValue, sizeof( szValue ), "%s", strValue );
break;
case O_STRING:
pEdit = ( TextEntry * )pList->pControl;
pEdit->GetText( strValue, sizeof( strValue ) );
Q_snprintf( szValue, sizeof( szValue ), "%s", strValue );
break;
case O_LIST:
pCombo = ( ComboBox *)pList->pControl;
pCombo->GetText( w_szStrValue, sizeof( w_szStrValue ) / sizeof( wchar_t ) );
pItem = pObj->pListItems;
while ( pItem )
{
wchar_t *wLocalizedString = NULL;
wchar_t w_szStrTemp[256];
// Localized string?
if ( pItem->szItemText[0] == '#' )
{
wLocalizedString = g_pVGuiLocalize->Find( pItem->szItemText );
}
if ( wLocalizedString )
{
// Copy the string we found into our temp array
V_wcscpy_safe( w_szStrTemp, wLocalizedString );
}
else
{
// Just convert what we have to Unicode
g_pVGuiLocalize->ConvertANSIToUnicode( pItem->szItemText, w_szStrTemp, sizeof( w_szStrTemp ) );
}
if ( _wcsicmp( w_szStrTemp, w_szStrValue ) == 0 )
{
// Found a match!
break;
}
pItem = pItem->pNext;
}
if ( pItem )
{
Q_snprintf( szValue, sizeof( szValue ), "%s", pItem->szValue );
}
else //Couldn't find index
{
Q_snprintf( szValue, sizeof( szValue ), "%s", pObj->defValue );
}
break;
}
// Remove double quotes and % characters
UTIL_StripInvalidCharacters( szValue, sizeof( szValue ) );
Q_strncpy( strValue, szValue, sizeof( strValue ) );
pObj->SetCurValue( strValue );
pList = pList->next;
}
}
//-----------------------------------------------------------------------------
// Purpose: Constructor, load/save server settings object
//-----------------------------------------------------------------------------
CServerDescription::CServerDescription( void ) : CDescription()
{
setHint( "// NOTE: THIS FILE IS AUTOMATICALLY REGENERATED, \r\n"
"//DO NOT EDIT THIS HEADER, YOUR COMMENTS WILL BE LOST IF YOU DO\r\n"
"// Multiplayer options script\r\n"
"//\r\n"
"// Format:\r\n"
"// Version [float]\r\n"
"// Options description followed by \r\n"
"// Options defaults\r\n"
"//\r\n"
"// Option description syntax:\r\n"
"//\r\n"
"// \"cvar\" { \"Prompt\" { type [ type info ] } { default } }\r\n"
"//\r\n"
"// type = \r\n"
"// BOOL (a yes/no toggle)\r\n"
"// STRING\r\n"
"// NUMBER\r\n"
"// LIST\r\n"
"//\r\n"
"// type info:\r\n"
"// BOOL no type info\r\n"
"// NUMBER min max range, use -1 -1 for no limits\r\n"
"// STRING no type info\r\n"
"// LIST "" delimited list of options value pairs\r\n"
"//\r\n"
"//\r\n"
"// default depends on type\r\n"
"// BOOL is \"0\" or \"1\"\r\n"
"// NUMBER is \"value\"\r\n"
"// STRING is \"value\"\r\n"
"// LIST is \"index\", where index \"0\" is the first element of the list\r\n\r\n\r\n" );
setDescription ( "SERVER_OPTIONS" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CServerDescription::WriteScriptHeader( FileHandle_t fp )
{
char am_pm[] = "AM";
tm newtime;
VCRHook_LocalTime( &newtime );
if( newtime.tm_hour > 12 ) /* Set up extension. */
Q_strncpy( am_pm, "PM", sizeof( am_pm ) );
if( newtime.tm_hour > 12 ) /* Convert from 24-hour */
newtime.tm_hour -= 12; /* to 12-hour clock. */
if( newtime.tm_hour == 0 ) /*Set hour to 12 if midnight. */
newtime.tm_hour = 12;
g_pFullFileSystem->FPrintf( fp, (char *)getHint() );
// Write out the comment and Cvar Info:
g_pFullFileSystem->FPrintf( fp, "// Half-Life Server Configuration Layout Script (stores last settings chosen, too)\r\n" );
g_pFullFileSystem->FPrintf( fp, "// File generated: %.19s %s\r\n", asctime( &newtime ), am_pm );
g_pFullFileSystem->FPrintf( fp, "//\r\n//\r\n// Cvar\t-\tSetting\r\n\r\n" );
g_pFullFileSystem->FPrintf( fp, "VERSION %.1f\r\n\r\n", SCRIPT_VERSION );
g_pFullFileSystem->FPrintf( fp, "DESCRIPTION SERVER_OPTIONS\r\n{\r\n" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CServerDescription::WriteFileHeader( FileHandle_t fp )
{
char am_pm[] = "AM";
tm newtime;
VCRHook_LocalTime( &newtime );
if( newtime.tm_hour > 12 ) /* Set up extension. */
Q_strncpy( am_pm, "PM", sizeof( am_pm ) );
if( newtime.tm_hour > 12 ) /* Convert from 24-hour */
newtime.tm_hour -= 12; /* to 12-hour clock. */
if( newtime.tm_hour == 0 ) /*Set hour to 12 if midnight. */
newtime.tm_hour = 12;
g_pFullFileSystem->FPrintf( fp, "// Half-Life Server Configuration Settings\r\n" );
g_pFullFileSystem->FPrintf( fp, "// DO NOT EDIT, GENERATED BY HALF-LIFE\r\n" );
g_pFullFileSystem->FPrintf( fp, "// File generated: %.19s %s\r\n", asctime( &newtime ), am_pm );
g_pFullFileSystem->FPrintf( fp, "//\r\n//\r\n// Cvar\t-\tSetting\r\n\r\n" );
}

View File

@ -0,0 +1,48 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CREATEMULTIPLAYERGAMEGAMEPLAYPAGE_H
#define CREATEMULTIPLAYERGAMEGAMEPLAYPAGE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/PropertyPage.h>
class CPanelListPanel;
class CDescription;
class mpcontrol_t;
//-----------------------------------------------------------------------------
// Purpose: server options page of the create game server dialog
//-----------------------------------------------------------------------------
class CCreateMultiplayerGameGameplayPage : public vgui::PropertyPage
{
public:
CCreateMultiplayerGameGameplayPage(vgui::Panel *parent, const char *name);
~CCreateMultiplayerGameGameplayPage();
// returns currently entered information about the server
int GetMaxPlayers();
const char *GetPassword();
const char *GetHostName();
protected:
virtual void OnApplyChanges();
private:
const char *GetValue(const char *cvarName, const char *defaultValue);
void LoadGameOptionsList();
void GatherCurrentValues();
CDescription *m_pDescription;
mpcontrol_t *m_pList;
CPanelListPanel *m_pOptionsList;
};
#endif // CREATEMULTIPLAYERGAMEGAMEPLAYPAGE_H

View File

@ -0,0 +1,313 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "CreateMultiplayerGameServerPage.h"
using namespace vgui;
#include <KeyValues.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/RadioButton.h>
#include <vgui_controls/CheckButton.h>
#include "filesystem.h"
#include "tier1/convar.h"
#include "EngineInterface.h"
#include "CvarToggleCheckButton.h"
#include "ModInfo.h"
// for SRC
#include <vstdlib/random.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
#define RANDOM_MAP "#GameUI_RandomMap"
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameServerPage::CCreateMultiplayerGameServerPage(vgui::Panel *parent, const char *name) : PropertyPage(parent, name)
{
m_pSavedData = NULL;
// we can use this if we decide we want to put "listen server" at the end of the game name
m_pMapList = new ComboBox(this, "MapList", 12, false);
m_pEnableBotsCheck = new CheckButton( this, "EnableBotsCheck", "" );
m_pEnableBotsCheck->SetVisible( false );
m_pEnableBotsCheck->SetEnabled( false );
LoadControlSettings("Resource/CreateMultiplayerGameServerPage.res");
LoadMapList();
m_szMapName[0] = 0;
// initialize hostname
SetControlString("ServerNameEdit", ModInfo().GetGameName());//szHostName);
// initialize password
// SetControlString("PasswordEdit", engine->pfnGetCvarString("sv_password"));
ConVarRef var( "sv_password" );
if ( var.IsValid() )
{
SetControlString("PasswordEdit", var.GetString() );
}
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CCreateMultiplayerGameServerPage::~CCreateMultiplayerGameServerPage()
{
}
void CCreateMultiplayerGameServerPage::OnKeyCodePressed( vgui::KeyCode code )
{
if ( code == KEY_XBUTTON_LEFT || code == KEY_XSTICK1_LEFT || code == KEY_XSTICK2_LEFT )
{
int nItem = m_pMapList->GetActiveItem();
nItem -= 1;
if ( nItem < 0 )
{
nItem = m_pMapList->GetItemCount() - 1;
}
m_pMapList->SilentActivateItem( nItem );
}
else if ( code == KEY_XBUTTON_RIGHT || code == KEY_XSTICK1_RIGHT || code == KEY_XSTICK2_RIGHT )
{
int nItem = m_pMapList->GetActiveItem();
nItem += 1;
if ( nItem >= m_pMapList->GetItemCount() )
{
nItem = 0;
}
m_pMapList->SilentActivateItem( nItem );
}
else
{
BaseClass::OnKeyCodePressed(code);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameServerPage::EnableBots( KeyValues *data )
{
m_pSavedData = data;
int quota = data->GetInt( "bot_quota", 0 );
SetControlInt( "BotQuotaCombo", quota );
m_pEnableBotsCheck->SetSelected( (quota > 0) );
int difficulty = data->GetInt( "bot_difficulty", 0 );
difficulty = max( difficulty, 0 );
difficulty = min( 3, difficulty );
char buttonName[64];
Q_snprintf( buttonName, sizeof( buttonName ), "SkillLevel%d", difficulty );
vgui::RadioButton *button = dynamic_cast< vgui::RadioButton * >(FindChildByName( buttonName ));
if ( button )
{
button->SetSelected( true );
}
}
//-----------------------------------------------------------------------------
// Purpose: called to get the info from the dialog
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameServerPage::OnApplyChanges()
{
KeyValues *kv = m_pMapList->GetActiveItemUserData();
strncpy(m_szMapName, kv->GetString("mapname", ""), DATA_STR_LENGTH);
if ( m_pSavedData )
{
int quota = GetControlInt( "BotQuotaCombo", 0 );
if ( !m_pEnableBotsCheck->IsSelected() )
{
quota = 0;
}
m_pSavedData->SetInt( "bot_quota", quota );
ConVarRef bot_quota( "bot_quota" );
bot_quota.SetValue( quota );
int difficulty = 0;
for ( int i=0; i<4; ++i )
{
char buttonName[64];
Q_snprintf( buttonName, sizeof( buttonName ), "SkillLevel%d", i );
vgui::RadioButton *button = dynamic_cast< vgui::RadioButton * >(FindChildByName( buttonName ));
if ( button )
{
if ( button->IsSelected() )
{
difficulty = i;
break;
}
}
}
m_pSavedData->SetInt( "bot_difficulty", difficulty );
ConVarRef bot_difficulty( "bot_difficulty" );
bot_difficulty.SetValue( difficulty );
}
}
//-----------------------------------------------------------------------------
// Purpose: loads the list of available maps into the map list
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameServerPage::LoadMaps( const char *pszPathID )
{
FileFindHandle_t findHandle = NULL;
KeyValues *hiddenMaps = ModInfo().GetHiddenMaps();
const char *pszFilename = g_pFullFileSystem->FindFirstEx( "maps/*.bsp", pszPathID, &findHandle );
while ( pszFilename )
{
char mapname[256];
char *ext, *str;
// FindFirst ignores the pszPathID, so check it here
// TODO: this doesn't find maps in fallback dirs
_snprintf( mapname, sizeof(mapname), "maps/%s", pszFilename );
if ( !g_pFullFileSystem->FileExists( mapname, pszPathID ) )
{
goto nextFile;
}
// remove the text 'maps/' and '.bsp' from the file name to get the map name
str = Q_strstr( pszFilename, "maps" );
if ( str )
{
strncpy( mapname, str + 5, sizeof(mapname) - 1 ); // maps + \\ = 5
}
else
{
strncpy( mapname, pszFilename, sizeof(mapname) - 1 );
}
ext = Q_strstr( mapname, ".bsp" );
if ( ext )
{
*ext = 0;
}
//!! hack: strip out single player HL maps
// this needs to be specified in a seperate file
if ( !stricmp( ModInfo().GetGameName(), "Half-Life" ) && ( mapname[0] == 'c' || mapname[0] == 't') && mapname[2] == 'a' && mapname[1] >= '0' && mapname[1] <= '5' )
{
goto nextFile;
}
// strip out maps that shouldn't be displayed
if ( hiddenMaps )
{
if ( hiddenMaps->GetInt( mapname, 0 ) )
{
goto nextFile;
}
}
// add to the map list
m_pMapList->AddItem( mapname, new KeyValues( "data", "mapname", mapname ) );
// get the next file
nextFile:
pszFilename = g_pFullFileSystem->FindNext( findHandle );
}
g_pFullFileSystem->FindClose( findHandle );
}
//-----------------------------------------------------------------------------
// Purpose: loads the list of available maps into the map list
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameServerPage::LoadMapList()
{
// clear the current list (if any)
m_pMapList->DeleteAllItems();
// add special "name" to represent loading a randomly selected map
m_pMapList->AddItem( RANDOM_MAP, new KeyValues( "data", "mapname", RANDOM_MAP ) );
// Load the GameDir maps
LoadMaps( "GAME" );
// set the first item to be selected
m_pMapList->ActivateItem( 0 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CCreateMultiplayerGameServerPage::IsRandomMapSelected()
{
const char *mapname = m_pMapList->GetActiveItemUserData()->GetString("mapname");
if (!stricmp( mapname, RANDOM_MAP ))
{
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CCreateMultiplayerGameServerPage::GetMapName()
{
int count = m_pMapList->GetItemCount();
// if there is only one entry it's the special "select random map" entry
if( count <= 1 )
return NULL;
const char *mapname = m_pMapList->GetActiveItemUserData()->GetString("mapname");
if (!strcmp( mapname, RANDOM_MAP ))
{
int which = RandomInt( 1, count - 1 );
mapname = m_pMapList->GetItemUserData( which )->GetString("mapname");
}
return mapname;
}
//-----------------------------------------------------------------------------
// Purpose: Sets currently selected map in the map combobox
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameServerPage::SetMap(const char *mapName)
{
for (int i = 0; i < m_pMapList->GetItemCount(); i++)
{
if (!m_pMapList->IsItemIDValid(i))
continue;
if (!stricmp(m_pMapList->GetItemUserData(i)->GetString("mapname"), mapName))
{
m_pMapList->ActivateItem(i);
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCreateMultiplayerGameServerPage::OnCheckButtonChecked()
{
SetControlEnabled("SkillLevel0", m_pEnableBotsCheck->IsSelected());
SetControlEnabled("SkillLevel1", m_pEnableBotsCheck->IsSelected());
SetControlEnabled("SkillLevel2", m_pEnableBotsCheck->IsSelected());
SetControlEnabled("SkillLevel3", m_pEnableBotsCheck->IsSelected());
SetControlEnabled("BotQuotaCombo", m_pEnableBotsCheck->IsSelected());
SetControlEnabled("BotQuotaLabel", m_pEnableBotsCheck->IsSelected());
SetControlEnabled("BotDifficultyLabel", m_pEnableBotsCheck->IsSelected());
}

View File

@ -0,0 +1,60 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CREATEMULTIPLAYERGAMESERVERPAGE_H
#define CREATEMULTIPLAYERGAMESERVERPAGE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/PropertyPage.h>
#include "CvarToggleCheckButton.h"
//-----------------------------------------------------------------------------
// Purpose: server options page of the create game server dialog
//-----------------------------------------------------------------------------
class CCreateMultiplayerGameServerPage : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( CCreateMultiplayerGameServerPage, vgui::PropertyPage );
public:
CCreateMultiplayerGameServerPage(vgui::Panel *parent, const char *name);
~CCreateMultiplayerGameServerPage();
virtual void OnKeyCodePressed( vgui::KeyCode code );
// returns currently entered information about the server
void SetMap(const char *name);
bool IsRandomMapSelected();
const char *GetMapName();
vgui::ComboBox *GetMapList( void ) { return m_pMapList; }
// CS Bots
void EnableBots( KeyValues *data );
int GetBotQuota( void );
bool GetBotsEnabled( void );
protected:
virtual void OnApplyChanges();
MESSAGE_FUNC( OnCheckButtonChecked, "CheckButtonChecked" );
private:
void LoadMapList();
void LoadMaps( const char *pszPathID );
vgui::ComboBox *m_pMapList;
vgui::CheckButton *m_pEnableBotsCheck;
CCvarToggleCheckButton *m_pEnableTutorCheck;
KeyValues *m_pSavedData;
enum { DATA_STR_LENGTH = 64 };
char m_szMapName[DATA_STR_LENGTH];
};
#endif // CREATEMULTIPLAYERGAMESERVERPAGE_H

View File

@ -0,0 +1,93 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "CustomTabExplanationDialog.h"
#include "BasePanel.h"
#include "convar.h"
#include "EngineInterface.h"
#include "GameUI_Interface.h"
#include "vgui/ISurface.h"
#include "vgui/IInput.h"
#include "ModInfo.h"
#include <stdio.h>
using namespace vgui;
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CCustomTabExplanationDialog::CCustomTabExplanationDialog(vgui::Panel *parent) : BaseClass(parent, "CustomTabExplanationDialog")
{
SetDeleteSelfOnClose(true);
SetSizeable( false );
input()->SetAppModalSurface(GetVPanel());
LoadControlSettings("Resource/CustomTabExplanationDialog.res");
MoveToCenterOfScreen();
GameUI().PreventEngineHideGameUI();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CCustomTabExplanationDialog::~CCustomTabExplanationDialog()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCustomTabExplanationDialog::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
SetDialogVariable( "game", ModInfo().GetGameName() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCustomTabExplanationDialog::OnKeyCodePressed(KeyCode code)
{
if (code == KEY_ESCAPE)
{
Close();
}
else
{
BaseClass::OnKeyCodePressed(code);
}
}
//-----------------------------------------------------------------------------
// Purpose: handles button commands
//-----------------------------------------------------------------------------
void CCustomTabExplanationDialog::OnCommand( const char *command )
{
if ( !stricmp( command, "ok" ) || !stricmp( command, "cancel" ) || !stricmp( command, "close" ) )
{
Close();
}
else
{
BaseClass::OnCommand( command );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCustomTabExplanationDialog::OnClose( void )
{
BaseClass::OnClose();
GameUI().AllowEngineHideGameUI();
}

View File

@ -0,0 +1,35 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef CUSTOMTABEXPLANATIONDIALOG_H
#define CUSTOMTABEXPLANATIONDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "utlvector.h"
#include <vgui/KeyCode.h>
#include "vgui_controls/URLLabel.h"
//-----------------------------------------------------------------------------
// Purpose: Dialog that explains the custom tab
//-----------------------------------------------------------------------------
class CCustomTabExplanationDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CCustomTabExplanationDialog, vgui::Frame );
public:
CCustomTabExplanationDialog(vgui::Panel *parent);
~CCustomTabExplanationDialog();
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void OnKeyCodePressed(vgui::KeyCode code);
virtual void OnCommand( const char *command );
virtual void OnClose( void );
};
#endif // CUSTOMTABEXPLANATIONDIALOG_H

View File

@ -0,0 +1,136 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "CvarNegateCheckButton.h"
#include "EngineInterface.h"
#include <vgui/IVGui.h>
#include "IGameUIFuncs.h"
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
CCvarNegateCheckButton::CCvarNegateCheckButton( Panel *parent, const char *panelName, const char *text,
const char *cvarname )
: CheckButton( parent, panelName, text )
{
m_pszCvarName = cvarname ? strdup( cvarname ) : NULL;
Reset();
AddActionSignalTarget( this );
}
CCvarNegateCheckButton::~CCvarNegateCheckButton()
{
free( m_pszCvarName );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCvarNegateCheckButton::Paint()
{
if ( !m_pszCvarName )
{
BaseClass::Paint();
return;
}
// Look up current value
// float value = engine->pfnGetCvarFloat( m_pszCvarName );
ConVarRef var( m_pszCvarName );
if ( !var.IsValid() )
return;
float value = var.GetFloat();
if ( value < 0 )
{
if ( !m_bStartState )
{
SetSelected( true );
m_bStartState = true;
}
}
else
{
if ( m_bStartState )
{
SetSelected( false );
m_bStartState = false;
}
}
BaseClass::Paint();
}
void CCvarNegateCheckButton::Reset()
{
// Look up current value
// float value = engine->pfnGetCvarFloat( m_pszCvarName );
ConVarRef var( m_pszCvarName );
if ( !var.IsValid() )
return;
float value = var.GetFloat();
if ( value < 0 )
{
m_bStartState = true;
}
else
{
m_bStartState = false;
}
SetSelected(m_bStartState);
}
bool CCvarNegateCheckButton::HasBeenModified()
{
return IsSelected() != m_bStartState;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *panel -
//-----------------------------------------------------------------------------
void CCvarNegateCheckButton::SetSelected( bool state )
{
BaseClass::SetSelected( state );
}
void CCvarNegateCheckButton::ApplyChanges()
{
if ( !m_pszCvarName || !m_pszCvarName[ 0 ] )
return;
ConVarRef var( m_pszCvarName );
float value = var.GetFloat();
value = (float)fabs( value );
if (value < 0.00001)
{
// correct the value if it's not set
value = 0.022f;
}
m_bStartState = IsSelected();
value = -value;
float ans = m_bStartState ? value : -value;
var.SetValue( ans );
}
void CCvarNegateCheckButton::OnButtonChecked()
{
if (HasBeenModified())
{
PostActionSignal(new KeyValues("ControlModified"));
}
}

View File

@ -0,0 +1,39 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CVARNEGATECHECKBUTTON_H
#define CVARNEGATECHECKBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/CheckButton.h>
class CCvarNegateCheckButton : public vgui::CheckButton
{
DECLARE_CLASS_SIMPLE( CCvarNegateCheckButton, vgui::CheckButton );
public:
CCvarNegateCheckButton( vgui::Panel *parent, const char *panelName, const char *text,
char const *cvarname );
~CCvarNegateCheckButton();
virtual void SetSelected( bool state );
virtual void Paint();
void Reset();
void ApplyChanges();
bool HasBeenModified();
private:
MESSAGE_FUNC( OnButtonChecked, "CheckButtonChecked" );
char *m_pszCvarName;
bool m_bStartState;
};
#endif // CVARNEGATECHECKBUTTON_H

112
gameui/CvarTextEntry.cpp Normal file
View File

@ -0,0 +1,112 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "CvarTextEntry.h"
#include "EngineInterface.h"
#include <vgui/IVGui.h>
#include "IGameUIFuncs.h"
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
static const int MAX_CVAR_TEXT = 64;
CCvarTextEntry::CCvarTextEntry( Panel *parent, const char *panelName, char const *cvarname )
: TextEntry( parent, panelName)
{
m_pszCvarName = cvarname ? strdup( cvarname ) : NULL;
m_pszStartValue[0] = 0;
if ( m_pszCvarName )
{
Reset();
}
AddActionSignalTarget( this );
}
CCvarTextEntry::~CCvarTextEntry()
{
if ( m_pszCvarName )
{
free( m_pszCvarName );
}
}
void CCvarTextEntry::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
if (GetMaximumCharCount() < 0 || GetMaximumCharCount() > MAX_CVAR_TEXT)
{
SetMaximumCharCount(MAX_CVAR_TEXT - 1);
}
}
void CCvarTextEntry::ApplyChanges( bool immediate )
{
if ( !m_pszCvarName )
return;
char szText[ MAX_CVAR_TEXT ];
GetText( szText, MAX_CVAR_TEXT );
if ( !szText[ 0 ] )
return;
if ( immediate )
{
// set immediately - don't wait for the next frame
ConVarRef newCvar( m_pszCvarName );
newCvar.SetValue( szText );
}
else
{
char szCommand[ 256 ];
sprintf( szCommand, "%s \"%s\"\n", m_pszCvarName, szText );
engine->ClientCmd_Unrestricted( szCommand );
}
Q_strncpy( m_pszStartValue, szText, sizeof( m_pszStartValue ) );
}
void CCvarTextEntry::Reset()
{
// char *value = engine->pfnGetCvarString( m_pszCvarName );
ConVarRef var( m_pszCvarName );
if ( !var.IsValid() )
return;
const char *value = var.GetString();
if ( value && value[ 0 ] )
{
SetText( value );
Q_strncpy( m_pszStartValue, value, sizeof( m_pszStartValue ) );
}
}
bool CCvarTextEntry::HasBeenModified()
{
char szText[ MAX_CVAR_TEXT ];
GetText( szText, MAX_CVAR_TEXT );
return stricmp( szText, m_pszStartValue );
}
void CCvarTextEntry::OnTextChanged()
{
if ( !m_pszCvarName )
return;
if (HasBeenModified())
{
PostActionSignal(new KeyValues("ControlModified"));
}
}

35
gameui/CvarTextEntry.h Normal file
View File

@ -0,0 +1,35 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CVARTEXTENTRY_H
#define CVARTEXTENTRY_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/TextEntry.h>
class CCvarTextEntry : public vgui::TextEntry
{
DECLARE_CLASS_SIMPLE( CCvarTextEntry, vgui::TextEntry );
public:
CCvarTextEntry( vgui::Panel *parent, const char *panelName, char const *cvarname );
~CCvarTextEntry();
MESSAGE_FUNC( OnTextChanged, "TextChanged" );
void ApplyChanges( bool immediate = false );
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
void Reset();
bool HasBeenModified();
private:
char *m_pszCvarName;
char m_pszStartValue[64];
};
#endif // CVARTEXTENTRY_H

View File

@ -0,0 +1,159 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "CvarToggleCheckButton.h"
#include "EngineInterface.h"
#include <vgui/IVGui.h>
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
#include "IGameUIFuncs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
vgui::Panel *CvarToggleCheckButton_Factory()
{
return new CCvarToggleCheckButton( NULL, NULL, "CvarToggleCheckButton", NULL );
}
DECLARE_BUILD_FACTORY_CUSTOM( CCvarToggleCheckButton, CvarToggleCheckButton_Factory );
CCvarToggleCheckButton::CCvarToggleCheckButton( Panel *parent, const char *panelName, const char *text,
char const *cvarname )
: CheckButton( parent, panelName, text )
{
m_pszCvarName = cvarname ? strdup( cvarname ) : NULL;
if (m_pszCvarName)
{
Reset();
}
AddActionSignalTarget( this );
}
CCvarToggleCheckButton::~CCvarToggleCheckButton()
{
if ( m_pszCvarName )
{
free( m_pszCvarName );
}
}
void CCvarToggleCheckButton::Paint()
{
if ( !m_pszCvarName || !m_pszCvarName[ 0 ] )
{
BaseClass::Paint();
return;
}
// Look up current value
// bool value = engine->pfnGetCvarFloat( m_pszCvarName ) > 0.0f ? true : false;
ConVarRef var( m_pszCvarName, true );
if ( !var.IsValid() )
return;
bool value = var.GetBool();
if ( value != m_bStartValue )
//if ( value != IsSelected() )
{
SetSelected( value );
m_bStartValue = value;
}
BaseClass::Paint();
}
void CCvarToggleCheckButton::ApplyChanges()
{
if ( !m_pszCvarName || !m_pszCvarName[ 0 ] )
return;
m_bStartValue = IsSelected();
// engine->Cvar_SetValue( m_pszCvarName, m_bStartValue ? 1.0f : 0.0f );
ConVarRef var( m_pszCvarName, true );
if ( !var.IsValid() )
return;
var.SetValue( m_bStartValue );
}
void CCvarToggleCheckButton::Reset()
{
// m_bStartValue = engine->pfnGetCvarFloat( m_pszCvarName ) > 0.0f ? true : false;
if ( !m_pszCvarName || !m_pszCvarName[ 0 ] )
return;
ConVarRef var( m_pszCvarName, true );
if ( !var.IsValid() )
return;
m_bStartValue = var.GetBool();
SetSelected(m_bStartValue);
}
bool CCvarToggleCheckButton::HasBeenModified()
{
return IsSelected() != m_bStartValue;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *panel -
//-----------------------------------------------------------------------------
void CCvarToggleCheckButton::SetSelected( bool state )
{
BaseClass::SetSelected( state );
if ( !m_pszCvarName || !m_pszCvarName[ 0 ] )
return;
/*
// Look up current value
bool value = state;
engine->Cvar_SetValue( m_pszCvarName, value ? 1.0f : 0.0f );*/
}
//-----------------------------------------------------------------------------
void CCvarToggleCheckButton::OnButtonChecked()
{
if (HasBeenModified())
{
PostActionSignal(new KeyValues("ControlModified"));
}
}
//-----------------------------------------------------------------------------
void CCvarToggleCheckButton::ApplySettings( KeyValues *inResourceData )
{
BaseClass::ApplySettings( inResourceData );
const char *cvarName = inResourceData->GetString("cvar_name", "");
const char *cvarValue = inResourceData->GetString("cvar_value", "");
if( Q_stricmp( cvarName, "") == 0 )
return;// Doesn't have cvar set up in res file, must have been constructed with it.
if( m_pszCvarName )
free( m_pszCvarName );// got a "", not a NULL from the create-control call
m_pszCvarName = cvarName ? strdup( cvarName ) : NULL;
if( Q_stricmp( cvarValue, "1") == 0 )
m_bStartValue = true;
else
m_bStartValue = false;
const ConVar *var = cvar->FindVar( m_pszCvarName );
if ( var )
{
if( var->GetBool() )
SetSelected( true );
else
SetSelected( false );
}
}

View File

@ -0,0 +1,41 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CVARTOGGLECHECKBUTTON_H
#define CVARTOGGLECHECKBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/CheckButton.h>
class CCvarToggleCheckButton : public vgui::CheckButton
{
DECLARE_CLASS_SIMPLE( CCvarToggleCheckButton, vgui::CheckButton );
public:
CCvarToggleCheckButton( vgui::Panel *parent, const char *panelName, const char *text,
char const *cvarname );
~CCvarToggleCheckButton();
virtual void SetSelected( bool state );
virtual void Paint();
void Reset();
void ApplyChanges();
bool HasBeenModified();
virtual void ApplySettings( KeyValues *inResourceData );
private:
MESSAGE_FUNC( OnButtonChecked, "CheckButtonChecked" );
char *m_pszCvarName;
bool m_bStartValue;
};
#endif // CVARTOGGLECHECKBUTTON_H

34
gameui/EngineInterface.h Normal file
View File

@ -0,0 +1,34 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Includes all the headers/declarations necessary to access the
// engine interface
//
// $NoKeywords: $
//=============================================================================//
#ifndef ENGINEINTERFACE_H
#define ENGINEINTERFACE_H
#ifdef _WIN32
#pragma once
#endif
// these stupid set of includes are required to use the cdll_int interface
#include "mathlib/vector.h"
//#include "wrect.h"
#define IN_BUTTONS_H
// engine interface
#include "cdll_int.h"
#include "icvar.h"
// engine interface singleton accessors
extern IVEngineClient *engine;
extern class IGameUIFuncs *gameuifuncs;
extern class IEngineSound *enginesound;
extern class IMatchmaking *matchmaking;
extern class IXboxSystem *xboxsystem;
extern class IAchievementMgr *achievementmgr;
extern class CSteamAPIContext *steamapicontext;
#endif // ENGINEINTERFACE_H

1
gameui/GameApp.cpp Normal file
View File

@ -0,0 +1 @@
//========= Copyright Valve Corporation, All rights reserved. ============//

1
gameui/GameApp.h Normal file
View File

@ -0,0 +1 @@
//========= Copyright Valve Corporation, All rights reserved. ============//

169
gameui/GameConsole.cpp Normal file
View File

@ -0,0 +1,169 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <stdio.h>
#include "GameConsole.h"
#include "GameConsoleDialog.h"
#include "LoadingDialog.h"
#include "vgui/ISurface.h"
#include "KeyValues.h"
#include "vgui/VGUI.h"
#include "vgui/IVGui.h"
#include "vgui_controls/Panel.h"
#include "convar.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
static CGameConsole g_GameConsole;
//-----------------------------------------------------------------------------
// Purpose: singleton accessor
//-----------------------------------------------------------------------------
CGameConsole &GameConsole()
{
return g_GameConsole;
}
EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CGameConsole, IGameConsole, GAMECONSOLE_INTERFACE_VERSION, g_GameConsole);
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CGameConsole::CGameConsole()
{
m_bInitialized = false;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CGameConsole::~CGameConsole()
{
m_bInitialized = false;
}
//-----------------------------------------------------------------------------
// Purpose: sets up the console for use
//-----------------------------------------------------------------------------
void CGameConsole::Initialize()
{
#ifndef _XBOX
m_pConsole = vgui::SETUP_PANEL( new CGameConsoleDialog() ); // we add text before displaying this so set it up now!
// set the console to taking up most of the right-half of the screen
int swide, stall;
vgui::surface()->GetScreenSize(swide, stall);
int offsetx = vgui::scheme()->GetProportionalScaledValue(16);
int offsety = vgui::scheme()->GetProportionalScaledValue(64);
m_pConsole->SetBounds(
swide / 2 - offsetx,
offsety,
swide / 2,
stall - (offsety * 2));
m_bInitialized = true;
#endif
}
//-----------------------------------------------------------------------------
// Purpose: activates the console, makes it visible and brings it to the foreground
//-----------------------------------------------------------------------------
void CGameConsole::Activate()
{
#ifndef _XBOX
if (!m_bInitialized)
return;
vgui::surface()->RestrictPaintToSinglePanel(NULL);
m_pConsole->Activate();
#endif
}
//-----------------------------------------------------------------------------
// Purpose: hides the console
//-----------------------------------------------------------------------------
void CGameConsole::Hide()
{
#ifndef _XBOX
if (!m_bInitialized)
return;
m_pConsole->Hide();
#endif
}
//-----------------------------------------------------------------------------
// Purpose: clears the console
//-----------------------------------------------------------------------------
void CGameConsole::Clear()
{
#ifndef _XBOX
if (!m_bInitialized)
return;
m_pConsole->Clear();
#endif
}
//-----------------------------------------------------------------------------
// Purpose: returns true if the console is currently in focus
//-----------------------------------------------------------------------------
bool CGameConsole::IsConsoleVisible()
{
#ifndef _XBOX
if (!m_bInitialized)
return false;
return m_pConsole->IsVisible();
#else
return false;
#endif
}
//-----------------------------------------------------------------------------
// Purpose: activates the console after a delay
//-----------------------------------------------------------------------------
void CGameConsole::ActivateDelayed(float time)
{
#ifndef _XBOX
if (!m_bInitialized)
return;
m_pConsole->PostMessage(m_pConsole, new KeyValues("Activate"), time);
#endif
}
void CGameConsole::SetParent( int parent )
{
#ifndef _XBOX
if (!m_bInitialized)
return;
m_pConsole->SetParent( static_cast<vgui::VPANEL>( parent ));
#endif
}
//-----------------------------------------------------------------------------
// Purpose: static command handler
//-----------------------------------------------------------------------------
void CGameConsole::OnCmdCondump()
{
#ifndef _XBOX
g_GameConsole.m_pConsole->DumpConsoleTextToFile();
#endif
}
#ifndef _XBOX
CON_COMMAND( condump, "dump the text currently in the console to condumpXX.log" )
{
g_GameConsole.OnCmdCondump();
}
#endif

54
gameui/GameConsole.h Normal file
View File

@ -0,0 +1,54 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMECONSOLE_H
#define GAMECONSOLE_H
#ifdef _WIN32
#pragma once
#endif
#include "GameUI/IGameConsole.h"
class CGameConsoleDialog;
//-----------------------------------------------------------------------------
// Purpose: VGui implementation of the game/dev console
//-----------------------------------------------------------------------------
class CGameConsole : public IGameConsole
{
public:
CGameConsole();
~CGameConsole();
// sets up the console for use
void Initialize();
// activates the console, makes it visible and brings it to the foreground
virtual void Activate();
// hides the console
virtual void Hide();
// clears the console
virtual void Clear();
// returns true if the console is currently in focus
virtual bool IsConsoleVisible();
// activates the console after a delay
void ActivateDelayed(float time);
void SetParent( int parent );
static void OnCmdCondump();
private:
bool m_bInitialized;
CGameConsoleDialog *m_pConsole;
};
extern CGameConsole &GameConsole();
#endif // GAMECONSOLE_H

View File

@ -0,0 +1,99 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "GameConsoleDialog.h"
#include "GameUI_Interface.h"
#include "vgui/IInput.h"
#include "vgui/ISurface.h"
#include "vgui/KeyCode.h"
#include "LoadingDialog.h"
#include "IGameUIFuncs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CGameConsoleDialog::CGameConsoleDialog() : BaseClass( NULL, "GameConsole", false )
{
AddActionSignalTarget( this );
}
//-----------------------------------------------------------------------------
// Purpose: generic vgui command handler
//-----------------------------------------------------------------------------
void CGameConsoleDialog::OnCommand(const char *command)
{
if ( !Q_stricmp( command, "Close" ) )
{
if ( GameUI().IsInBackgroundLevel() )
{
// Tell the engine we've hid the console, so that it unpauses the game
// even though we're still sitting at the menu.
engine->ClientCmd_Unrestricted( "unpause" );
}
}
BaseClass::OnCommand(command);
}
//-----------------------------------------------------------------------------
// HACK: Allow F key bindings to operate even when typing in the text entry field
//-----------------------------------------------------------------------------
void CGameConsoleDialog::OnKeyCodeTyped(KeyCode code)
{
BaseClass::OnKeyCodeTyped(code);
// check for processing
if ( m_pConsolePanel->TextEntryHasFocus() )
{
// HACK: Allow F key bindings to operate even here
if ( code >= KEY_F1 && code <= KEY_F12 )
{
// See if there is a binding for the FKey
const char *binding = gameuifuncs->GetBindingForButtonCode( code );
if ( binding && binding[0] )
{
// submit the entry as a console commmand
char szCommand[256];
Q_strncpy( szCommand, binding, sizeof( szCommand ) );
engine->ClientCmd_Unrestricted( szCommand );
}
}
}
}
//-----------------------------------------------------------------------------
// Submits a command
//-----------------------------------------------------------------------------
void CGameConsoleDialog::OnCommandSubmitted( const char *pCommand )
{
engine->ClientCmd_Unrestricted( pCommand );
}
//-----------------------------------------------------------------------------
// Submits a command
//-----------------------------------------------------------------------------
void CGameConsoleDialog::OnClosedByHittingTilde()
{
if ( !LoadingDialog() )
{
GameUI().HideGameUI();
}
else
{
vgui::surface()->RestrictPaintToSinglePanel( LoadingDialog()->GetVPanel() );
}
}

View File

@ -0,0 +1,40 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef GAMECONSOLEDIALOG_H
#define GAMECONSOLEDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/consoledialog.h"
#include <Color.h>
#include "utlvector.h"
#include "EngineInterface.h"
#include "vgui_controls/Frame.h"
//-----------------------------------------------------------------------------
// Purpose: Game/dev console dialog
//-----------------------------------------------------------------------------
class CGameConsoleDialog : public vgui::CConsoleDialog
{
DECLARE_CLASS_SIMPLE( CGameConsoleDialog, vgui::CConsoleDialog );
public:
CGameConsoleDialog();
private:
MESSAGE_FUNC( OnClosedByHittingTilde, "ClosedByHittingTilde" );
MESSAGE_FUNC_CHARPTR( OnCommandSubmitted, "CommandSubmitted", command );
virtual void OnKeyCodeTyped( vgui::KeyCode code );
virtual void OnCommand( const char *command );
};
#endif // GAMECONSOLEDIALOG_H

25
gameui/GameUI.h Normal file
View File

@ -0,0 +1,25 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMEUI_H
#define GAMEUI_H
#ifdef _WIN32
#pragma once
#endif
class IGameUI;
//-----------------------------------------------------------------------------
// Purpose: Accessor function to get game ui interface
//-----------------------------------------------------------------------------
inline IGameUI *gameui()
{
extern IGameUI *g_pGameUI;
return g_pGameUI;
}
#endif // GAMEUI_H

258
gameui/GameUI.vpc Normal file
View File

@ -0,0 +1,258 @@
//-----------------------------------------------------------------------------
// GAMEUI.VPC
//
// Project Script
//-----------------------------------------------------------------------------
$macro SRCDIR ".."
$Macro OUTBINDIR "$SRCDIR\..\game\bin"
$include "$SRCDIR\vpc_scripts\source_dll_base.vpc"
$Include "$SRCDIR\vpc_scripts\source_saxxyawards.vpc"
$include "$SRCDIR\vpc_scripts\source_cryptlib_include.vpc"
$Configuration
{
$Compiler
{
$AdditionalIncludeDirectories "$BASE;.\;$SRCDIR\vgui2\include;$SRCDIR\vgui2\controls;$SRCDIR\common\GameUI"
$PreprocessorDefinitions "$BASE;GAMEUI_EXPORTS;VERSION_SAFE_STEAM_API_INTERFACES"
}
$Linker
{
$AdditionalDependencies "$BASE Ws2_32.lib odbc32.lib odbccp32.lib Shlwapi.lib" [$WIN32]
$SystemLibraries "iconv;z" [$OSXALL]
$SystemLibraries "rt" [$LINUXALL && !$DEDICATED]
$GCC_ExtraLinkerFlags "-L/usr/lib32 -L/usr/lib" [$LINUXALL && !$DEDICATED]
}
}
$Configuration "Debug"
{
$Linker [$X360]
{
$AdditionalDependencies "$BASE Xonlined.lib"
}
}
$Configuration "Release"
{
$Linker [$X360]
{
$AdditionalDependencies "$BASE Xonline.lib"
}
}
$Project "GameUI"
{
$Folder "Source Files"
{
$File "BackgroundMenuButton.cpp"
$File "BasePanel.cpp"
$File "GameConsole.cpp"
$File "GameUI_Interface.cpp"
$File "LogoFile.cpp" [!$POSIX]
$File "ModInfo.cpp"
$File "MouseMessageForwardingPanel.cpp"
$File "$SRCDIR\Tracker\common\msgbuffer.cpp" [!$POSIX]
$File "$SRCDIR\Tracker\common\netapi.cpp" [!$POSIX]
$File "$SRCDIR\common\GameUI\ObjectList.cpp"
$File "PanelListPanel.cpp"
$File "RunGameEngine.cpp"
$File "$SRCDIR\common\GameUI\scriptobject.cpp"
$File "$SRCDIR\Tracker\common\Socket.cpp" [!$POSIX]
$File "Sys_Utils.cpp"
$File "TextEntryBox.cpp"
$File "TGAImagePanel.cpp"
$File "$SRCDIR\public\vgui_controls\vgui_controls.cpp"
$File "VGuiSystemModuleLoader.cpp"
$File "BonusMapsDatabase.cpp"
$File "BonusMapsDatabase.h"
$File "$SRCDIR\common\language.cpp"
$File "$SRCDIR\common\imageutils.cpp"
$File "SaveGameBrowserDialog.cpp"
$File "gameui_util.cpp"
$File "gameui_util.h"
}
$Folder "Header Files"
{
$File "BackgroundMenuButton.h"
$File "BasePanel.h"
$File "BaseSaveGameDialog.h"
$File "CDKeyEntryDialog.h"
$File "ChangeGameDialog.h"
$File "CreateMultiplayerGameBotPage.h"
$File "CreateMultiplayerGameDialog.h"
$File "CreateMultiplayerGameGameplayPage.h"
$File "CreateMultiplayerGameServerPage.h"
$File "EngineInterface.h"
$File "GameConsole.h"
$File "GameUI_Interface.h"
$File "LoadingDialog.h"
$File "$SRCDIR\vgui2\src\Memorybitmap.h"
$File "ModInfo.h"
$File "MouseMessageForwardingPanel.h"
$File "PanelListPanel.h"
$File "$SRCDIR\common\GameUI\scriptobject.h"
$File "Sys_Utils.h"
$File "TextEntryBox.h"
$File "TGAImagePanel.h"
$File "VGuiSystemModuleLoader.h"
$File "SaveGameBrowserDialog.h"
}
$Folder "Public Header Files"
{
$File "$SRCDIR\public\iachievementmgr.h"
$File "$SRCDIR\public\game\client\IGameClientExports.h"
$File "$SRCDIR\common\GameUI\IGameUI.h"
$File "$SRCDIR\public\IGameUIFuncs.h"
$File "$SRCDIR\public\tier1\interface.h"
$File "$SRCDIR\common\IObjectContainer.h"
$File "$SRCDIR\common\IRunGameEngine.h"
$File "$SRCDIR\common\IVguiModule.h"
$File "$SRCDIR\common\IVGuiModuleLoader.h"
$File "$SRCDIR\common\GameUI\ObjectList.h"
$File "$SRCDIR\public\savegame_version.h"
$File "$SRCDIR\Tracker\common\TrackerMessageFlags.h"
$File "$SRCDIR\common\ValveCDKeyGameAndTerritoryCodes.h"
$File "$SRCDIR\common\language.h"
$File "$SRCDIR\common\imageutils.h"
}
$Folder "Controls"
{
$File "BitmapImagePanel.cpp"
$File "BitmapImagePanel.h"
$File "CommandCheckButton.cpp"
$File "CommandCheckButton.h"
$File "CvarNegateCheckButton.cpp"
$File "CvarNegateCheckButton.h"
$File "$SRCDIR\common\GameUI\cvarslider.cpp"
$File "$SRCDIR\common\GameUI\cvarslider.h"
$File "CvarTextEntry.cpp"
$File "CvarTextEntry.h"
$File "CvarToggleCheckButton.cpp"
$File "CvarToggleCheckButton.h"
$File "HapticControlBox.cpp"
$File "HapticControlBox.h"
$File "KeyToggleCheckButton.cpp"
$File "KeyToggleCheckButton.h"
$File "LabeledCommandComboBox.cpp"
$File "LabeledCommandComboBox.h"
$File "URLButton.cpp"
$File "URLButton.h"
$File "vcontrolslistpanel.cpp"
$File "vcontrolslistpanel.h"
}
$Folder "Dialogs"
{
$File "BenchmarkDialog.cpp"
$File "BenchmarkDialog.h"
$File "BonusMapsDialog.cpp"
$File "BonusMapsDialog.h"
$File "CommentaryDialog.cpp"
$File "CommentaryDialog.h"
$File "CommentaryExplanationDialog.cpp"
$File "CommentaryExplanationDialog.h"
$File "ContentControlDialog.cpp"
$File "ContentControlDialog.h"
$File "CustomTabExplanationDialog.cpp"
$File "CustomTabExplanationDialog.h"
$File "GameConsoleDialog.cpp"
$File "GameConsoleDialog.h"
$File "LoadGameDialog_Xbox.cpp"
$File "LoadGameDialog.cpp"
$File "LoadGameDialog.h"
$File "MultiplayerAdvancedDialog.cpp"
$File "MultiplayerAdvancedDialog.h"
$File "NewGameDialog.cpp"
$File "NewGameDialog.h"
$File "PlayerListDialog.cpp"
$File "PlayerListDialog.h"
$File "SaveGameDialog_Xbox.cpp"
$File "SaveGameDialog.cpp"
$File "SaveGameDialog.h"
$File "LoadCommentaryDialog.cpp"
$File "LoadingDialog.cpp"
$File "BaseSaveGameDialog.cpp"
$File "ChangeGameDialog.cpp" [!$POSIX]
$File "CreateMultiplayerGameBotPage.cpp"
$File "CreateMultiplayerGameDialog.cpp"
$File "CreateMultiplayerGameGameplayPage.cpp"
$File "CreateMultiplayerGameServerPage.cpp"
$File "OptionsDialog_Xbox.cpp"
$File "ControllerDialog.cpp"
$File "ControllerDialog.h"
}
$Folder "Matchmaking"
{
$File "matchmaking\achievementsdialog.cpp"
$File "matchmaking\achievementsdialog.h"
$File "matchmaking\basedialog.cpp"
$File "matchmaking\basedialog.h"
$File "matchmaking\dialogmenu.cpp"
$File "matchmaking\dialogmenu.h"
$File "matchmaking\leaderboarddialog.cpp"
$File "matchmaking\leaderboarddialog.h"
$File "matchmaking\matchmakingbasepanel.cpp"
$File "matchmaking\matchmakingbasepanel.h"
$File "matchmaking\pausedialog.cpp"
$File "matchmaking\pausedialog.h"
$File "matchmaking\sessionlobbydialog.cpp"
$File "matchmaking\sessionlobbydialog.h"
$File "matchmaking\sessionoptionsdialog.cpp"
$File "matchmaking\sessionoptionsdialog.h"
$File "matchmaking\sessionbrowserdialog.cpp"
$File "matchmaking\sessionbrowserdialog.h"
$File "matchmaking\welcomedialog.cpp"
$File "matchmaking\welcomedialog.h"
}
$Folder "Options Dialog"
{
$File "OptionsDialog.cpp"
$File "OptionsDialog.h"
$File "OptionsSubAudio.cpp"
$File "OptionsSubAudio.h"
$File "OptionsSubDifficulty.cpp"
$File "OptionsSubDifficulty.h"
$File "OptionsSubGame.cpp"
$File "OptionsSubGame.h"
$File "OptionsSubHaptics.cpp" [$WIN32]
$File "OptionsSubHaptics.h" [$WIN32]
$File "OptionsSubKeyboard.cpp"
$File "OptionsSubKeyboard.h"
$File "OptionsSubMouse.cpp"
$File "OptionsSubMouse.h"
$File "OptionsSubMultiplayer.cpp"
$File "OptionsSubMultiplayer.h"
$File "OptionsSubPortal.cpp"
$File "OptionsSubPortal.h"
$File "OptionsSubVideo.cpp"
$File "OptionsSubVideo.h"
$File "OptionsSubVoice.cpp"
$File "OptionsSubVoice.h"
}
$Folder "Link Libraries"
{
$Lib bitmap
$Lib mathlib
$Lib matsys_controls
$Lib tier2
$Lib tier3
$Lib vgui_controls
$Lib vtf
$Lib "$LIBCOMMON/libjpeg" [!$DEDICATED]
$ImpLib steam_api
$Lib libpng [!$VS2015&&!$DEDICATED]
$Lib $LIBCOMMON/libpng [$VS2015&&!$DEDICATED]
$Lib libz [!$DEDICATED]
$ImpLib SDL2 [$SDL]
}
}

22
gameui/GameUIPanel.h Normal file
View File

@ -0,0 +1,22 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMEUIPANEL_H
#define GAMEUIPANEL_H
#ifdef _WIN32
#pragma once
#endif
// Retrieve the root panel for the GameUI subsystem
namespace vgui
{
class Panel;
};
vgui::Panel *GetGameUIRootPanel( void );
#endif // GAMEUIPANEL_H

1285
gameui/GameUI_Interface.cpp Normal file

File diff suppressed because it is too large Load Diff

159
gameui/GameUI_Interface.h Normal file
View File

@ -0,0 +1,159 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Defines the interface that the GameUI dll exports
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMEUI_INTERFACE_H
#define GAMEUI_INTERFACE_H
#pragma once
#include "GameUI/IGameUI.h"
#include <vgui_controls/Panel.h>
#include <vgui_controls/PHandle.h>
class IGameClientExports;
//-----------------------------------------------------------------------------
// Purpose: Implementation of GameUI's exposed interface
//-----------------------------------------------------------------------------
class CGameUI : public IGameUI
{
public:
CGameUI();
~CGameUI();
virtual void Initialize( CreateInterfaceFn appFactory );
virtual void Connect( CreateInterfaceFn gameFactory );
virtual void Start();
virtual void Shutdown();
virtual void RunFrame();
virtual void PostInit();
// plays the startup mp3 when GameUI starts
void PlayGameStartupSound();
// Engine wrappers for activating / hiding the gameUI
void ActivateGameUI();
void HideGameUI();
// Toggle allowing the engine to hide the game UI with the escape key
void PreventEngineHideGameUI();
void AllowEngineHideGameUI();
virtual void SetLoadingBackgroundDialog( vgui::VPANEL panel );
// Bonus maps interfaces
virtual void BonusMapUnlock( const char *pchFileName = NULL, const char *pchMapName = NULL );
virtual void BonusMapComplete( const char *pchFileName = NULL, const char *pchMapName = NULL );
virtual void BonusMapChallengeUpdate( const char *pchFileName, const char *pchMapName, const char *pchChallengeName, int iBest );
virtual void BonusMapChallengeNames( char *pchFileName, char *pchMapName, char *pchChallengeName );
virtual void BonusMapChallengeObjectives( int &iBronze, int &iSilver, int &iGold );
virtual void BonusMapDatabaseSave( void );
virtual int BonusMapNumAdvancedCompleted( void );
virtual void BonusMapNumMedals( int piNumMedals[ 3 ] );
// notifications
virtual void OnGameUIActivated();
virtual void OnGameUIHidden();
virtual void OLD_OnConnectToServer( const char *game, int IP, int port ); // OLD: use OnConnectToServer2
virtual void OnConnectToServer2( const char *game, int IP, int connectionPort, int queryPort );
virtual void OnDisconnectFromServer( uint8 eSteamLoginFailure );
virtual void OnLevelLoadingStarted( bool bShowProgressDialog );
virtual void OnLevelLoadingFinished( bool bError, const char *failureReason, const char *extendedReason );
virtual void OnDisconnectFromServer_OLD( uint8 eSteamLoginFailure, const char *username ) { OnDisconnectFromServer( eSteamLoginFailure ); }
// progress
virtual bool UpdateProgressBar(float progress, const char *statusText);
// Shows progress desc, returns previous setting... (used with custom progress bars )
virtual bool SetShowProgressText( bool show );
// brings up the new game dialog
virtual void ShowNewGameDialog( int chapter );
// Xbox 360
virtual void SessionNotification( const int notification, const int param = 0 );
virtual void SystemNotification( const int notification );
virtual void ShowMessageDialog( const uint nType, vgui::Panel *pOwner = NULL );
virtual void CloseMessageDialog( const uint nType = 0 );
virtual void UpdatePlayerInfo( uint64 nPlayerId, const char *pName, int nTeam, byte cVoiceState, int nPlayersNeeded, bool bHost );
virtual void SessionSearchResult( int searchIdx, void *pHostData, XSESSION_SEARCHRESULT *pResult, int ping );
virtual void OnCreditsFinished( void );
// X360 Storage device validation:
// returns true right away if storage device has been previously selected.
// otherwise returns false and will set the variable pointed by pStorageDeviceValidated to 1
// once the storage device is selected by user.
virtual bool ValidateStorageDevice( int *pStorageDeviceValidated );
virtual void SetProgressOnStart();
virtual void OnConfirmQuit( void );
virtual bool IsMainMenuVisible( void );
// Client DLL is providing us with a panel that it wants to replace the main menu with
virtual void SetMainMenuOverride( vgui::VPANEL panel );
// Client DLL is telling us that a main menu command was issued, probably from its custom main menu panel
virtual void SendMainMenuCommand( const char *pszCommand );
// state
bool IsInLevel();
bool IsInBackgroundLevel();
bool IsInMultiplayer();
bool IsInReplay();
bool IsConsoleUI();
bool HasSavedThisMenuSession();
void SetSavedThisMenuSession( bool bState );
void ShowLoadingBackgroundDialog();
void HideLoadingBackgroundDialog();
bool HasLoadingBackgroundDialog();
private:
void SendConnectedToGameMessage();
virtual void StartProgressBar();
virtual bool ContinueProgressBar(float progressFraction);
virtual void StopProgressBar(bool bError, const char *failureReason, const char *extendedReason = NULL);
virtual bool SetProgressBarStatusText(const char *statusText);
//!! these functions currently not implemented
virtual void SetSecondaryProgressBar(float progress /* range [0..1] */);
virtual void SetSecondaryProgressBarText(const char *statusText);
bool FindPlatformDirectory(char *platformDir, int bufferSize);
void GetUpdateVersion( char *pszProd, char *pszVer);
void ValidateCDKey();
CreateInterfaceFn m_GameFactory;
bool m_bPlayGameStartupSound : 1;
bool m_bTryingToLoadFriends : 1;
bool m_bActivatedUI : 1;
bool m_bIsConsoleUI : 1;
bool m_bHasSavedThisMenuSession : 1;
bool m_bOpenProgressOnStart : 1;
int m_iGameIP;
int m_iGameConnectionPort;
int m_iGameQueryPort;
int m_iFriendsLoadPauseFrames;
char m_szPreviousStatusText[128];
char m_szPlatformDir[MAX_PATH];
vgui::DHANDLE<class CCDKeyEntryDialog> m_hCDKeyEntryDialog;
};
// Purpose: singleton accessor
extern CGameUI &GameUI();
// expose client interface
extern IGameClientExports *GameClientExports();
#endif // GAMEUI_INTERFACE_H

191
gameui/HapticControlBox.cpp Normal file
View File

@ -0,0 +1,191 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
#include "HapticControlBox.h"
#include <vgui_controls/Controls.h>
#include <vgui_controls/Panel.h>
#include "cvarslider.h"
#include "mathlib/vmatrix.h"
#include <vgui/ISurface.h>
#include "KeyValues.h"
#include <vgui/ISystem.h>
ControlBoxVisual::ControlBoxVisual(vgui::Panel *parent,const char *panelName, CCvarSlider *n, CCvarSlider *r, CCvarSlider *u, CCvarSlider *f, CCvarSlider *l, CCvarSlider *d) :
BaseClass(parent,panelName)
{
m_iMouseOver = -1;
m_flTime=0;
//disable mouse input.
SetMouseInputEnabled(false);
SlideValues = new CCvarSliderCube(n, r, u, f, l, d);
SlideValues->Down->AddActionSignalTarget(GetVPanel());
SlideValues->Far->AddActionSignalTarget(GetVPanel());
SlideValues->Up->AddActionSignalTarget(GetVPanel());
SlideValues->Near->AddActionSignalTarget(GetVPanel());
SlideValues->Left->AddActionSignalTarget(GetVPanel());
SlideValues->Right->AddActionSignalTarget(GetVPanel());
SetWide(64);
SetTall(64);
}
void ControlBoxVisual::OnSlideEnter(KeyValues*data)
{
vgui::VPANEL fromPanel = data->GetInt("VPANEL");
if(fromPanel == SlideValues->Up->GetVPanel())
m_iMouseOver = HUI_BOX_UP;
else if(fromPanel == SlideValues->Down->GetVPanel())
m_iMouseOver = HUI_BOX_DOWN;
else if(fromPanel == SlideValues->Right->GetVPanel())
m_iMouseOver = HUI_BOX_RIGHT;
else if(fromPanel == SlideValues->Left->GetVPanel())
m_iMouseOver = HUI_BOX_LEFT;
else if(fromPanel == SlideValues->Far->GetVPanel())
m_iMouseOver = HUI_BOX_FAR;
else if(fromPanel == SlideValues->Near->GetVPanel())
m_iMouseOver = HUI_BOX_NEAR;
}
void ControlBoxVisual::OnSlideExit(KeyValues*data)
{
//vgui::VPANEL fromPanel = data->GetInt("VPANEL");
m_iMouseOver=-1;
}
void ControlBoxVisual::Paint()
{
m_flTime = vgui::system()->GetFrameTime();
BaseClass::Paint();
vgui::surface()->DrawSetColor(0,0,0,255);
DrawCube();
vgui::surface()->DrawSetColor(255,255,255,255);
//first draw the cube once.
DrawCube( SlideValues->Near->GetSliderValue()*-1,
SlideValues->Right->GetSliderValue()*-1,
SlideValues->Up->GetSliderValue()*-1,
SlideValues->Far->GetSliderValue(),
SlideValues->Left->GetSliderValue(),
SlideValues->Down->GetSliderValue());
//then check if we have something selected
if(m_iMouseOver!=-1)
{
vgui::surface()->DrawSetColor(255,0,0,255);
// if we do, draw a special cube.
DrawCube( SlideValues->Near->GetSliderValue()*-1,
SlideValues->Right->GetSliderValue()*-1,
SlideValues->Up->GetSliderValue()*-1,
SlideValues->Far->GetSliderValue(),
SlideValues->Left->GetSliderValue(),
SlideValues->Down->GetSliderValue(),
m_iMouseOver);
}
}
void ControlBoxVisual::DrawCube(float n, float r, float u, float f, float l, float d, int specialside)
{
l*=-1;
r*=-1;//flip
Vector right[4];
//right side
right[0]= Vector(f,r,d);
right[1]= Vector(f,r,u);
right[2]= Vector(n,r,u);
right[3]= Vector(n,r,d);
Vector left[4];
//left side
left[0]= Vector(f,l,d);
left[1]= Vector(f,l,u);
left[2]= Vector(n,l,u);
left[3]= Vector(n,l,d);
//yikes, this is kind of alot of typing.
switch(specialside)
{
case HUI_BOX_UP:
left[0] = left[1];
left[3] = left[2];
left[1] =Vector(1,-1,-1);
left[2] =Vector(-1,-1,-1);
right[0]= right[1];
right[3]= right[2];
right[1]=Vector(1,1,-1);
right[2]=Vector(-1,1,-1);
break;
case HUI_BOX_DOWN:
left[1] = left[0];
left[2] = left[3];
left[0] =Vector(1,-1,1);
left[3] =Vector(-1,-1,1);
right[1] = right[0];
right[2] = right[3];
right[0] =Vector(1,1,1);
right[3] =Vector(-1,1,1);
break;
case HUI_BOX_LEFT:
right[0] = left[0];
right[1] = left[1];
right[2] = left[2];
right[3] = left[3];
left[0] =Vector(1,-1,1);
left[1] =Vector(1,-1,-1);
left[2] =Vector(-1,-1,-1);
left[3] =Vector(-1,-1,1);
break;
case HUI_BOX_RIGHT:
left[0] = right[0];
left[1] = right[1];
left[2] = right[2];
left[3] = right[3];
right[0] =Vector(1,1,1);
right[1] =Vector(1,1,-1);
right[2] =Vector(-1,1,-1);
right[3] =Vector(-1,1,1);
break;
case HUI_BOX_FAR:
left[3] = left[0];
left[2] = left[1];
left[0] =Vector(1,-1,1);
left[1] =Vector(1,-1,-1);
right[3] = right[0];
right[2] = right[1];
right[0] =Vector(1,1,1);
right[1] =Vector(1,1,-1);
break;
case HUI_BOX_NEAR:
left[0] = left[3];
left[1] = left[2];
left[3] =Vector(-1,-1,1);
left[2] =Vector(-1,-1,-1);
right[0] = right[3];
right[1] = right[2];
right[3] =Vector(-1,1,1);
right[2] =Vector(-1,1,-1);
break;
default:
break;
}
Vector pos = Vector(0,0.25 + sin(m_flTime),0.5);
VMatrix Project = SetupMatrixProjection(pos,VPlane(Vector(1,0,0),-3));
Vector vdrawsize = Vector(1,(float)GetWide()/10.0f,(float)GetTall()/10.0f);
for(int i=0;i!=4;i++)
{
right[i] = Project.VMul3x3(right[i])*vdrawsize;
left[i] = Project.VMul3x3(left[i])*vdrawsize;
}
vdrawsize *=5;
for(int i = 0;i!=4;i++)
{
int next = i+1;
if(next>3)
next = 0;
vgui::surface()->DrawLine(vdrawsize.y+left[i].y,vdrawsize.z+left[i].z,vdrawsize.y+left[next].y,vdrawsize.z+left[next].z);
vgui::surface()->DrawLine(vdrawsize.y+right[i].y,vdrawsize.z+right[i].z,vdrawsize.y+right[next].y,vdrawsize.z+right[next].z);
vgui::surface()->DrawLine(vdrawsize.y+left[i].y,vdrawsize.z+left[i].z,vdrawsize.y+right[i].y,vdrawsize.z+right[i].z);
}
}

53
gameui/HapticControlBox.h Normal file
View File

@ -0,0 +1,53 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
#ifndef HAPTICCONTROLBOX_H
#define HAPTICCONTROLBOX_H
#include <vgui_controls/Controls.h>
#include <vgui_controls/Panel.h>
#include "cvarslider.h"
class ControlBoxVisual : public vgui::Panel
{
DECLARE_CLASS_SIMPLE(ControlBoxVisual,vgui::Panel);
public:
ControlBoxVisual(vgui::Panel *parent, const char *panelName, CCvarSlider *near, CCvarSlider *right, CCvarSlider *up, CCvarSlider *far, CCvarSlider *left, CCvarSlider *down);
virtual void Paint();
MESSAGE_FUNC_PARAMS(OnSlideEnter, "CursorEnteredSlider", data);
MESSAGE_FUNC_PARAMS(OnSlideExit, "CursorExitedSlider", data);
protected:
void DrawCube(float Near=-1, float Right=-1, float Up=-1, float Far=1, float Left=1, float Down=1, int specialside=-1);
enum eBoxID
{
HUI_BOX_UP =0,
HUI_BOX_RIGHT,
HUI_BOX_NEAR,
HUI_BOX_DOWN,
HUI_BOX_LEFT,
HUI_BOX_FAR,
HUI_BOX_SLIDERCOUNT,
};
struct CCvarSliderCube
{
CCvarSliderCube(CCvarSlider *n,CCvarSlider *r,CCvarSlider *u,CCvarSlider *f,CCvarSlider *l,CCvarSlider *d)
{
Near = n;
Right = r;
Up = u;
Far = f;
Left = l;
Down = d;
};
CCvarSlider *Near;
CCvarSlider *Right;
CCvarSlider *Up;
CCvarSlider *Far;
CCvarSlider *Left;
CCvarSlider *Down;
};
CCvarSliderCube *SlideValues;// up right near down left far and spingk
int m_iMouseOver;
float m_flTime;
};
#endif

View File

@ -0,0 +1,118 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "KeyToggleCheckButton.h"
#include "EngineInterface.h"
#include <vgui/IVGui.h>
#include "IGameUIFuncs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
CKeyToggleCheckButton::CKeyToggleCheckButton( Panel *parent, const char *panelName, const char *text,
char const *key, char const *cmdname )
: CheckButton( parent, panelName, text )
{
m_pszKeyName = key ? strdup( key ) : NULL;
m_pszCmdName = cmdname ? strdup( cmdname ) : NULL;
if (m_pszKeyName)
{
Reset();
}
//m_bNoCommand = false;
}
CKeyToggleCheckButton::~CKeyToggleCheckButton()
{
free( m_pszKeyName );
free( m_pszCmdName );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CKeyToggleCheckButton::Paint()
{
BaseClass::Paint();
if ( !m_pszKeyName )
return;
// Fixme, look up key state
bool isdown;
if ( gameuifuncs->IsKeyDown( m_pszKeyName, isdown ) )
{
// if someone changed the value using the consoel
if ( m_bStartValue != isdown )
{
SetSelected( isdown );
m_bStartValue = isdown;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *panel -
//-----------------------------------------------------------------------------
/*
void CKeyToggleCheckButton::SetSelected( bool state )
{
BaseClass::SetSelected( state );
if ( !m_pszCmdName || !m_pszCmdName[ 0 ] )
return;
if ( m_bNoCommand )
return;
char szCommand[ 256 ];
Q_snprintf( szCommand, sizeof( szCommand ), "%c%s\n", IsSelected() ? '+' : '-',
m_pszCmdName );
engine->pfnClientCmd( szCommand );
}*/
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CKeyToggleCheckButton::Reset()
{
gameuifuncs->IsKeyDown( m_pszKeyName, m_bStartValue );
if ( IsSelected() != m_bStartValue)
{
SetSelected( m_bStartValue );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CKeyToggleCheckButton::ApplyChanges()
{
if ( !m_pszCmdName || !m_pszCmdName[ 0 ] )
return;
char szCommand[ 256 ];
Q_snprintf( szCommand, sizeof( szCommand ), "%c%s\n", IsSelected() ? '+' : '-',
m_pszCmdName );
engine->ClientCmd_Unrestricted( szCommand );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CKeyToggleCheckButton::HasBeenModified()
{
return IsSelected() != m_bStartValue;
}

View File

@ -0,0 +1,38 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef KEYTOGGLECHECKBUTTON_H
#define KEYTOGGLECHECKBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/CheckButton.h>
class CKeyToggleCheckButton : public vgui::CheckButton
{
public:
CKeyToggleCheckButton( vgui::Panel *parent, const char *panelName, const char *text,
char const *keyname, char const *cmdname );
~CKeyToggleCheckButton();
//virtual void SetSelected( bool state );
virtual void Paint();
void Reset();
void ApplyChanges();
bool HasBeenModified();
private:
typedef vgui::CheckButton BaseClass;
char *m_pszKeyName;
char *m_pszCmdName;
bool m_bStartValue;
};
#endif // KEYTOGGLECHECKBUTTON_H

View File

@ -0,0 +1,131 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "LabeledCommandComboBox.h"
#include "EngineInterface.h"
#include <KeyValues.h>
#include <vgui/ILocalize.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
CLabeledCommandComboBox::CLabeledCommandComboBox( vgui::Panel *parent, const char *panelName ) : vgui::ComboBox( parent, panelName, 6, false )
{
AddActionSignalTarget(this);
m_iCurrentSelection = -1;
m_iStartSelection = -1;
}
CLabeledCommandComboBox::~CLabeledCommandComboBox( void )
{
}
void CLabeledCommandComboBox::DeleteAllItems()
{
BaseClass::DeleteAllItems();
m_Items.RemoveAll();
}
void CLabeledCommandComboBox::AddItem( char const *text, char const *engineCommand )
{
int idx = m_Items.AddToTail();
COMMANDITEM *item = &m_Items[ idx ];
item->comboBoxID = BaseClass::AddItem( text, NULL );
Q_strncpy( item->name, text, sizeof( item->name ) );
if (text[0] == '#')
{
// need to localize the string
wchar_t *localized = g_pVGuiLocalize->Find(text);
if (localized)
{
g_pVGuiLocalize->ConvertUnicodeToANSI(localized, item->name, sizeof(item->name));
}
}
Q_strncpy( item->command, engineCommand, sizeof( item->command ) );
}
void CLabeledCommandComboBox::ActivateItem(int index)
{
if ( index< m_Items.Count() )
{
int comboBoxID = m_Items[index].comboBoxID;
BaseClass::ActivateItem(comboBoxID);
m_iCurrentSelection = index;
}
}
void CLabeledCommandComboBox::SetInitialItem(int index)
{
if ( index< m_Items.Count() )
{
m_iStartSelection = index;
int comboBoxID = m_Items[index].comboBoxID;
ActivateItem(comboBoxID);
}
}
void CLabeledCommandComboBox::OnTextChanged( char const *text )
{
int i;
for ( i = 0; i < m_Items.Size(); i++ )
{
COMMANDITEM *item = &m_Items[ i ];
if ( !stricmp( item->name, text ) )
{
// engine->pfnClientCmd( item->command );
m_iCurrentSelection = i;
break;
}
}
if (HasBeenModified())
{
PostActionSignal(new KeyValues("ControlModified"));
}
// PostMessage( GetParent()->GetVPanel(), new vgui::KeyValues( "TextChanged", "text", text ) );
}
const char *CLabeledCommandComboBox::GetActiveItemCommand()
{
if (m_iCurrentSelection == -1)
return NULL;
COMMANDITEM *item = &m_Items[ m_iCurrentSelection ];
return item->command;
}
void CLabeledCommandComboBox::ApplyChanges()
{
if (m_iCurrentSelection == -1)
return;
if (m_Items.Size() < 1)
return;
Assert( m_iCurrentSelection < m_Items.Size() );
COMMANDITEM *item = &m_Items[ m_iCurrentSelection ];
engine->ClientCmd_Unrestricted( item->command );
m_iStartSelection = m_iCurrentSelection;
}
bool CLabeledCommandComboBox::HasBeenModified()
{
return m_iStartSelection != m_iCurrentSelection;
}
void CLabeledCommandComboBox::Reset()
{
if (m_iStartSelection != -1)
{
ActivateItem(m_iStartSelection);
}
}

View File

@ -0,0 +1,59 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef LABELEDCOMMANDCOMBOBOX_H
#define LABELEDCOMMANDCOMBOBOX_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/Panel.h>
#include "utlvector.h"
class CLabeledCommandComboBox : public vgui::ComboBox
{
DECLARE_CLASS_SIMPLE( CLabeledCommandComboBox, vgui::ComboBox );
public:
CLabeledCommandComboBox(vgui::Panel *parent, const char *panelName);
~CLabeledCommandComboBox();
virtual void DeleteAllItems();
virtual void AddItem(char const *text, char const *engineCommand);
virtual void ActivateItem(int itemIndex);
const char *GetActiveItemCommand();
void SetInitialItem(int itemIndex);
void ApplyChanges();
void Reset();
bool HasBeenModified();
enum
{
MAX_NAME_LEN = 256,
MAX_COMMAND_LEN = 256
};
private:
MESSAGE_FUNC_CHARPTR( OnTextChanged, "TextChanged", text );
struct COMMANDITEM
{
char name[ MAX_NAME_LEN ];
char command[ MAX_COMMAND_LEN ];
int comboBoxID;
};
CUtlVector< COMMANDITEM > m_Items;
int m_iCurrentSelection;
int m_iStartSelection;
};
#endif // LABELEDCOMMANDCOMBOBOX_H

View File

@ -0,0 +1,411 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "LoadCommentaryDialog.h"
#include "EngineInterface.h"
#include "IGameUIFuncs.h"
#include "vgui/ISystem.h"
#include "vgui/IVGui.h"
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
#include "filesystem.h"
#include "vgui_controls/PanelListPanel.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/ImagePanel.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/PanelListPanel.h"
#include "vgui_controls/QueryBox.h"
#include <stdio.h>
#include <stdlib.h>
#include "BasePanel.h"
#include "GameUI_Interface.h"
#include "MouseMessageForwardingPanel.h"
#include "TGAImagePanel.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
void OpenLoadCommentaryDialog( void )
{
DHANDLE<CLoadCommentaryDialog> hCommentaryDialog;
if ( !hCommentaryDialog.Get() )
{
hCommentaryDialog = new CLoadCommentaryDialog( BasePanel() );
}
GameUI().ActivateGameUI();
hCommentaryDialog->Activate();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CC_LoadCommentary_Test( void )
{
OpenLoadCommentaryDialog();
}
static ConCommand commentary_testfirstrun("loadcommentary", CC_LoadCommentary_Test, 0 );
//-----------------------------------------------------------------------------
// Purpose: Describes the layout of a commentary map list item
//-----------------------------------------------------------------------------
class CCommentaryItemPanel : public vgui::EditablePanel
{
DECLARE_CLASS_SIMPLE( CCommentaryItemPanel, vgui::EditablePanel );
public:
CCommentaryItemPanel( PanelListPanel *parent, const char *name, int iListItemID ) : BaseClass( parent, name )
{
m_iListItemID = iListItemID;
m_pParent = parent;
m_pCommentaryScreenshot = new CTGAImagePanel( this, "CommentaryMapScreenshot" );
m_pCommentaryScreenshotBackground = new ImagePanel( this, "CommentaryScreenshotBackground" );
// map name
m_pMapNameLabel = new Label( this, "MapName", "" );
// description
m_pDescriptionLabel = new Label( this, "Description", "" );
CMouseMessageForwardingPanel *panel = new CMouseMessageForwardingPanel(this, NULL);
panel->SetZPos(2);
SetSize( 200, 140 );
LoadControlSettings( "resource/CommentaryItem.res" );
m_FillColor = m_pCommentaryScreenshotBackground->GetFillColor();
}
void SetCommentaryInfo( CommentaryItem_t &item )
{
// set the bitmap to display
char tga[_MAX_PATH];
Q_strncpy( tga, item.szMapFileName, sizeof(tga) );
char *ext = strstr( tga, ".txt" );
if ( ext )
{
strcpy( ext, ".tga" );
}
m_pCommentaryScreenshot->SetTGA( tga );
// set the title text
m_pMapNameLabel->SetText( item.szPrintName );
m_pDescriptionLabel->SetText( item.szDescription );
}
MESSAGE_FUNC_INT( OnPanelSelected, "PanelSelected", state )
{
if ( state )
{
// set the text color to be orange, and the pic border to be orange
m_pCommentaryScreenshotBackground->SetFillColor( m_SelectedColor );
m_pMapNameLabel->SetFgColor( m_SelectedColor );
m_pDescriptionLabel->SetFgColor( m_SelectedColor );
}
else
{
m_pCommentaryScreenshotBackground->SetFillColor( m_FillColor );
m_pMapNameLabel->SetFgColor( m_TextColor );
m_pDescriptionLabel->SetFgColor( m_TextColor );
}
PostMessage( m_pParent->GetVParent(), new KeyValues("PanelSelected") );
}
virtual void OnMousePressed( vgui::MouseCode code )
{
m_pParent->SetSelectedPanel( this );
}
virtual void ApplySchemeSettings( IScheme *pScheme )
{
m_TextColor = pScheme->GetColor( "NewGame.TextColor", Color(255, 255, 255, 255) );
m_SelectedColor = pScheme->GetColor( "NewGame.SelectionColor", Color(255, 255, 255, 255) );
BaseClass::ApplySchemeSettings( pScheme );
}
virtual void OnMouseDoublePressed( vgui::MouseCode code )
{
// call the panel
OnMousePressed( code );
PostMessage( m_pParent->GetParent(), new KeyValues("Command", "command", "loadcommentary") );
}
int GetListItemID()
{
return m_iListItemID;
}
private:
vgui::PanelListPanel *m_pParent;
vgui::Label *m_pMapNameLabel;
vgui::Label *m_pDescriptionLabel;
CTGAImagePanel *m_pCommentaryScreenshot;
ImagePanel *m_pCommentaryScreenshotBackground;
Color m_TextColor, m_FillColor, m_SelectedColor;
int m_iListItemID;
};
//-----------------------------------------------------------------------------
// Purpose:Constructor
//-----------------------------------------------------------------------------
CLoadCommentaryDialog::CLoadCommentaryDialog(vgui::Panel *parent) : BaseClass(parent, "LoadCommentaryDialog")
{
SetDeleteSelfOnClose(true);
SetBounds(0, 0, 512, 384);
SetMinimumSize( 256, 300 );
SetSizeable( true );
SetTitle("#GameUI_LoadCommentary", true);
vgui::Button *cancel = new vgui::Button( this, "Cancel", "#GameUI_Cancel" );
cancel->SetCommand( "Close" );
CreateCommentaryItemList();
new vgui::Button( this, "loadcommentary", "" );
SetControlEnabled( "loadcommentary", false );
LoadControlSettings("resource/LoadCommentaryDialog.res");
// Look for commentary .txt files in the map directory
ScanCommentaryFiles();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLoadCommentaryDialog::OnCommand( const char *command )
{
if ( !Q_stricmp( command, "loadcommentary" ) )
{
int itemIndex = GetSelectedItemIndex();
if ( m_CommentaryItems.IsValidIndex(itemIndex) )
{
const char *mapName = m_CommentaryItems[itemIndex].szMapName;
if ( mapName && mapName[ 0 ] )
{
// Load the game, return to top and switch to engine
char sz[ 256 ];
Q_snprintf(sz, sizeof( sz ), "progress_enable\ncommentary 1\nmap %s\n", mapName );
// Close this dialog
OnClose();
engine->ClientCmd_Unrestricted( sz );
}
}
}
else
{
BaseClass::OnCommand( command );
}
}
void CLoadCommentaryDialog::OnKeyCodePressed( vgui::KeyCode code )
{
if ( code == KEY_XBUTTON_A || code == STEAMCONTROLLER_A )
{
OnCommand( "loadcommentary" );
return;
}
else if ( code == KEY_XBUTTON_B )
{
OnCommand( "Close" );
return;
}
BaseClass::OnKeyCodePressed(code);
}
//-----------------------------------------------------------------------------
// Purpose: Creates the load game display list
//-----------------------------------------------------------------------------
void CLoadCommentaryDialog::CreateCommentaryItemList()
{
m_pGameList = new vgui::PanelListPanel( this, "listpanel_commentary" );
m_pGameList->SetFirstColumnWidth( 0 );
}
//-----------------------------------------------------------------------------
// Purpose: returns the save file name of the selected item
//-----------------------------------------------------------------------------
int CLoadCommentaryDialog::GetSelectedItemIndex()
{
CCommentaryItemPanel *panel = dynamic_cast<CCommentaryItemPanel *>(m_pGameList->GetSelectedPanel());
if ( panel )
{
// find the panel in the list
for ( int i = 0; i < m_CommentaryItems.Count(); i++ )
{
if ( i == panel->GetListItemID() )
{
return i;
}
}
}
return m_CommentaryItems.InvalidIndex();
}
//-----------------------------------------------------------------------------
// Purpose: builds save game list from directory
//-----------------------------------------------------------------------------
void CLoadCommentaryDialog::ScanCommentaryFiles()
{
// populate list box with all saved games on record:
char szDirectory[_MAX_PATH];
Q_snprintf( szDirectory, sizeof( szDirectory ), "maps/*commentary.txt" );
// clear the current list
m_pGameList->DeleteAllItems();
m_CommentaryItems.RemoveAll();
// iterate the files
FileFindHandle_t handle;
const char *pFileName = g_pFullFileSystem->FindFirst( szDirectory, &handle );
while (pFileName)
{
char szFileName[_MAX_PATH];
Q_snprintf(szFileName, sizeof( szFileName ), "maps/%s", pFileName);
// Only load save games from the current mod's save dir
if( !g_pFullFileSystem->FileExists( szFileName, "MOD" ) )
{
pFileName = g_pFullFileSystem->FindNext( handle );
continue;
}
ParseCommentaryFile( szFileName, pFileName );
pFileName = g_pFullFileSystem->FindNext( handle );
}
g_pFullFileSystem->FindClose( handle );
// sort the save list
qsort( m_CommentaryItems.Base(), m_CommentaryItems.Count(), sizeof(CommentaryItem_t), &SaveGameSortFunc );
// add to the list
for ( int saveIndex = 0; saveIndex < m_CommentaryItems.Count() && saveIndex < MAX_LISTED_COMMENTARY_ITEMS; saveIndex++ )
{
// add the item to the panel
AddCommentaryItemToList( saveIndex );
}
// display a message if there are no save games
if ( !m_CommentaryItems.Count() )
{
vgui::Label *pNoCommentaryItemsLabel = SETUP_PANEL(new Label(m_pGameList, "NoCommentaryItemsLabel", "#GameUI_NoCommentaryItemsToDisplay"));
pNoCommentaryItemsLabel->SetTextColorState(vgui::Label::CS_DULL);
m_pGameList->AddItem( NULL, pNoCommentaryItemsLabel );
}
SetControlEnabled( "loadcommentary", false );
}
//-----------------------------------------------------------------------------
// Purpose: Adds an item to the list
//-----------------------------------------------------------------------------
void CLoadCommentaryDialog::AddCommentaryItemToList( int itemIndex )
{
// create the new panel and add to the list
CCommentaryItemPanel *commentaryItemPanel = new CCommentaryItemPanel( m_pGameList, "CommentaryItemPanel", itemIndex );
commentaryItemPanel->SetCommentaryInfo( m_CommentaryItems[itemIndex] );
m_pGameList->AddItem( NULL, commentaryItemPanel );
}
//-----------------------------------------------------------------------------
// Purpose: Parses the save game info out of the .sav file header
//-----------------------------------------------------------------------------
void CLoadCommentaryDialog::ParseCommentaryFile( char const *pszFileName, char const *pszShortName )
{
if ( !pszFileName || !pszShortName )
return;
// load the file as keyvalues
KeyValues *pData = new KeyValues( "commentary_data" );
if ( false == pData->LoadFromFile( g_pFullFileSystem, pszFileName, "MOD" ) )
{
pData->deleteThis();
return;
}
// walk the platform menu loading all the interfaces
KeyValues *menuKeys = pData->FindKey("trackinfo", false);
if ( menuKeys )
{
for (KeyValues *track = menuKeys->GetFirstSubKey(); track != NULL; track = track->GetNextKey())
{
//Msg( "track found: %s %s\n", track->GetString("map", "?"), track->GetString( "description", "asdf" ) );
CommentaryItem_t item;
Q_strncpy( item.szMapFileName, pszFileName, sizeof(item.szMapFileName) );
Q_strncpy( item.szMapName, track->GetString( "map", "" ), sizeof(item.szMapName) );
Q_strncpy( item.szPrintName, track->GetString( "printname", "" ), sizeof(item.szPrintName) );
Q_strncpy( item.szDescription, track->GetString( "description", "" ), sizeof(item.szDescription) );
//item.iChannel = track->GetInt( "channel" );
m_CommentaryItems.AddToTail( item );
}
}
else
{
CommentaryItem_t item;
Q_strncpy( item.szMapFileName, pszFileName, sizeof(item.szMapFileName) );
char mapname[_MAX_PATH];
Q_strncpy( mapname, pszFileName, sizeof(item.szMapName) );
char *ext = strstr( mapname, "_commentary" );
if ( !ext )
return;
*ext = '\0';
Q_FileBase( mapname, item.szMapName, sizeof(item.szMapName) );
Q_strncpy( item.szPrintName, "No trackinfo found.", sizeof(item.szPrintName) );
Q_strncpy( item.szDescription, "No trackinfo found.", sizeof(item.szDescription) );
m_CommentaryItems.AddToTail( item );
}
return;
}
//-----------------------------------------------------------------------------
// Purpose: timestamp sort function for savegames
//-----------------------------------------------------------------------------
int CLoadCommentaryDialog::SaveGameSortFunc( const void *lhs, const void *rhs )
{
// Sort by map name
const CommentaryItem_t *s1 = (const CommentaryItem_t *)lhs;
const CommentaryItem_t *s2 = (const CommentaryItem_t *)rhs;
return Q_stricmp( s1->szPrintName, s2->szPrintName );
}
//-----------------------------------------------------------------------------
// Purpose: One item has been selected
//-----------------------------------------------------------------------------
void CLoadCommentaryDialog::OnPanelSelected()
{
SetControlEnabled( "loadcommentary", true );
}

View File

@ -0,0 +1,63 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef LOADCOMMENTARYDIALOG_H
#define LOADCOMMENTARYDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "filesystem.h"
#include "utlvector.h"
#define COMMENTARY_MAPFILENAME_MAX_LEN MAX_PATH
#define COMMENTARY_MAPNAME_MAX_LEN 32
#define COMMENTARY_DESCRIP_MAX_LEN 512
#define MAX_LISTED_COMMENTARY_ITEMS 32
struct CommentaryItem_t
{
char szMapFileName[COMMENTARY_MAPFILENAME_MAX_LEN]; // file location of the map
char szMapName[COMMENTARY_MAPNAME_MAX_LEN]; // clean name of the map, eg "dod_kalt"
char szPrintName[COMMENTARY_MAPNAME_MAX_LEN]; // printable name "Kalt"
char szDescription[COMMENTARY_DESCRIP_MAX_LEN]; // track description "This map is fun, and people like it!"
//int iChannel; // TODO: multiple channels within a single map, loaded into separate commentary tracks
};
//-----------------------------------------------------------------------------
// Purpose: Base class for save & load game dialogs
//-----------------------------------------------------------------------------
class CLoadCommentaryDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CLoadCommentaryDialog, vgui::Frame );
public:
CLoadCommentaryDialog( vgui::Panel *parent );
protected:
CUtlVector<CommentaryItem_t> m_CommentaryItems;
vgui::PanelListPanel *m_pGameList;
virtual void OnCommand( const char *command );
virtual void OnKeyCodePressed( vgui::KeyCode code );
void ScanCommentaryFiles();
void CreateCommentaryItemList();
int GetSelectedItemIndex();
void AddCommentaryItemToList( int saveIndex );
void ParseCommentaryFile( char const *pszFileName, char const *pszShortName );
static int __cdecl SaveGameSortFunc( const void *lhs, const void *rhs );
private:
MESSAGE_FUNC( OnPanelSelected, "PanelSelected" );
};
#endif // LOADCOMMENTARYDIALOG_H

107
gameui/LoadGameDialog.cpp Normal file
View File

@ -0,0 +1,107 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "LoadGameDialog.h"
#include "EngineInterface.h"
#include "vgui/ISystem.h"
#include "vgui/ISurface.h"
#include "vgui/IVGui.h"
#include "KeyValues.h"
#include "filesystem.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/PanelListPanel.h"
#include "vgui_controls/QueryBox.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose:Constructor
//-----------------------------------------------------------------------------
CLoadGameDialog::CLoadGameDialog(vgui::Panel *parent) : BaseClass(parent, "LoadGameDialog")
{
SetDeleteSelfOnClose(true);
SetBounds(0, 0, 512, 384);
SetMinimumSize( 256, 300 );
SetSizeable( true );
SetTitle("#GameUI_LoadGame", true);
vgui::Button *cancel = new vgui::Button( this, "Cancel", "#GameUI_Cancel" );
cancel->SetCommand( "Close" );
LoadControlSettings("resource/LoadGameDialog.res");
SetControlEnabled( "delete", false );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CLoadGameDialog::~CLoadGameDialog()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLoadGameDialog::OnCommand( const char *command )
{
if ( !stricmp( command, "loadsave" ) )
{
int saveIndex = GetSelectedItemSaveIndex();
if ( m_SaveGames.IsValidIndex(saveIndex) )
{
const char *shortName = m_SaveGames[saveIndex].szShortName;
if ( shortName && shortName[ 0 ] )
{
// Load the game, return to top and switch to engine
char sz[ 256 ];
Q_snprintf(sz, sizeof( sz ), "progress_enable\nload %s\n", shortName );
engine->ClientCmd_Unrestricted( sz );
// Close this dialog
OnClose();
}
}
}
else if ( !stricmp( command, "Delete" ) )
{
int saveIndex = GetSelectedItemSaveIndex();
if ( m_SaveGames.IsValidIndex(saveIndex) )
{
// confirm the deletion
QueryBox *box = new QueryBox( "#GameUI_ConfirmDeleteSaveGame_Title", "#GameUI_ConfirmDeleteSaveGame_Info" );
box->AddActionSignalTarget(this);
box->SetOKButtonText("#GameUI_ConfirmDeleteSaveGame_OK");
box->SetOKCommand(new KeyValues("Command", "command", "DeleteConfirmed"));
box->DoModal();
}
}
else if ( !stricmp( command, "DeleteConfirmed" ) )
{
int saveIndex = GetSelectedItemSaveIndex();
if ( m_SaveGames.IsValidIndex(saveIndex) )
{
DeleteSaveGame( m_SaveGames[saveIndex].szFileName );
// reset the list
ScanSavedGames();
m_pGameList->MoveScrollBarToTop();
}
}
else
{
BaseClass::OnCommand( command );
}
}

54
gameui/LoadGameDialog.h Normal file
View File

@ -0,0 +1,54 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef LOADGAMEDIALOG_H
#define LOADGAMEDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "BaseSaveGameDialog.h"
#include "SaveGameDialog.h"
#include "SaveGameBrowserDialog.h"
#include "BasePanel.h"
#include "vgui_controls/KeyRepeat.h"
//-----------------------------------------------------------------------------
// Purpose: Displays game loading options
//-----------------------------------------------------------------------------
class CLoadGameDialog : public CBaseSaveGameDialog
{
DECLARE_CLASS_SIMPLE( CLoadGameDialog, CBaseSaveGameDialog );
public:
CLoadGameDialog(vgui::Panel *parent);
~CLoadGameDialog();
virtual void OnCommand( const char *command );
};
//
//
//
class CLoadGameDialogXbox : public CSaveGameBrowserDialog
{
DECLARE_CLASS_SIMPLE( CLoadGameDialogXbox, CSaveGameBrowserDialog );
public:
CLoadGameDialogXbox( vgui::Panel *parent );
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void OnCommand(const char *command);
virtual void PerformSelectedAction( void );
virtual void PerformDeletion( void );
virtual void UpdateFooterOptions( void );
private:
void DeleteSaveGame( const SaveGameDescription_t *pSaveDesc );
};
#endif // LOADGAMEDIALOG_H

View File

@ -0,0 +1,219 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "BasePanel.h"
#include "LoadGameDialog.h"
#include "winlite.h"
#include "vgui/ISurface.h"
#include "EngineInterface.h"
#include "GameUI_Interface.h"
#include "ixboxsystem.h"
#include "filesystem.h"
#include "SaveGameBrowserDialog.h"
using namespace vgui;
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
CLoadGameDialogXbox::CLoadGameDialogXbox( vgui::Panel *parent ) : BaseClass( parent )
{
m_bFilterAutosaves = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLoadGameDialogXbox::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
vgui::Label *pTitle = (Label *) FindChildByName( "TitleLabel" );
if ( pTitle )
{
pTitle->SetText( "#GameUI_LoadGame" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLoadGameDialogXbox::PerformSelectedAction( void )
{
BaseClass::PerformSelectedAction();
if ( !GetNumPanels() )
return;
SetControlDisabled( true );
// Warn the player if they're already in a map
if ( !GameUI().HasSavedThisMenuSession() && GameUI().IsInLevel() && engine->GetMaxClients() == 1 )
{
BasePanel()->ShowMessageDialog( MD_SAVE_BEFORE_LOAD, this );
}
else
{
// Otherwise just do it
OnCommand( "LoadGame" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLoadGameDialogXbox::PerformDeletion( void )
{
// Cannot delete autosaves!
CGameSavePanel *pPanel = GetActivePanel();
if ( pPanel == NULL || ( pPanel && pPanel->IsAutoSaveType() ) )
return;
BaseClass::PerformDeletion();
SetControlDisabled( true );
vgui::surface()->PlaySound( "UI/buttonclickrelease.wav" );
BasePanel()->ShowMessageDialog( MD_DELETE_SAVE_CONFIRM, this );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : bNewSaveSelected -
//-----------------------------------------------------------------------------
void CLoadGameDialogXbox::UpdateFooterOptions( void )
{
CFooterPanel *pFooter = GetFooterPanel();
// Show available buttons
pFooter->ClearButtons();
// Make sure we have panels to show
if ( HasActivePanels() )
{
pFooter->AddNewButtonLabel( "#GameUI_Load", "#GameUI_Icons_A_BUTTON" );
// Don't allow deletions of autosaves!
CGameSavePanel *pPanel = GetActivePanel();
if ( pPanel && pPanel->IsAutoSaveType() == false )
{
pFooter->AddNewButtonLabel( "#GameUI_Delete", "#GameUI_Icons_X_BUTTON" );
}
}
// Always allow storage devices changes and cancelling
pFooter->AddNewButtonLabel( "#GameUI_Close", "#GameUI_Icons_B_BUTTON" );
pFooter->AddNewButtonLabel( "#GameUI_Console_StorageChange", "#GameUI_Icons_Y_BUTTON" );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *command -
//-----------------------------------------------------------------------------
void CLoadGameDialogXbox::OnCommand( const char *command )
{
m_KeyRepeat.Reset();
if ( !Q_stricmp( command, "LoadGame" ) )
{
// Must have an active panel to perform this action
if ( GetNumPanels() == 0 )
{
SetControlDisabled( false );
return;
}
const SaveGameDescription_t *pSave = GetActivePanelSaveDescription();
// Load the saved game
char szCmd[ 256 ];
Q_snprintf( szCmd, sizeof( szCmd ), "xload %s", pSave->szShortName );
engine->ClientCmd_Unrestricted( szCmd );
// Ignore all other input while we're open
OnClose();
}
else if ( !Q_stricmp( command, "DeleteGame" ) )
{
// Must have an active panel to perform this action
if ( GetNumPanels() == 0 )
{
SetControlDisabled( false );
return;
}
// Delete the game they've selected
const SaveGameDescription_t *pSave = GetActivePanelSaveDescription();
DeleteSaveGame( pSave );
RemoveActivePanel();
}
else if ( !Q_stricmp( command, "RefreshSaveGames" ) )
{
// FIXME: At this point the rug has been pulled out from undereath us!
RefreshSaveGames();
}
else if ( !Q_stricmp( command, "LoadGameCancelled" ) )
{
SetControlDisabled( false );
}
else if ( !Q_stricmp( command, "ReleaseModalWindow" ) )
{
vgui::surface()->RestrictPaintToSinglePanel( NULL );
}
else if ( !Q_stricmp( command, "DeleteGameCancelled" ) )
{
SetControlDisabled( false );
}
else
{
BaseClass::OnCommand(command);
}
}
//-----------------------------------------------------------------------------
// Purpose: deletes an existing save game
//-----------------------------------------------------------------------------
void CLoadGameDialogXbox::DeleteSaveGame( const SaveGameDescription_t *pSaveDesc )
{
if ( pSaveDesc == NULL )
{
SetControlDisabled( false );
return;
}
// If we're deleting our more recent save game, we need to make sure we setup the engine to properly load the last most recent
if ( Q_stristr( engine->GetMostRecentSaveGame(), pSaveDesc->szShortName ) )
{
// We must have at least two active save games that we know about
if ( GetNumPanels() > 1 )
{
// The panels are sorted by how recent they are, so the first element is the most recent
const SaveGameDescription_t *pDesc = GetPanelSaveDecription( 0 );
if ( pDesc == pSaveDesc )
{
// If we're deleting our most recent, we need to pick the next most recent
pDesc = GetPanelSaveDecription( 1 );
}
// Remember this filename for the next time we need to reload
if ( pDesc )
{
engine->SetMostRecentSaveGame( pDesc->szShortName );
}
}
}
// Delete the save game file
g_pFullFileSystem->RemoveFile( pSaveDesc->szFileName, "MOD" );
vgui::surface()->PlaySound( "UI/buttonclick.wav" );
// Return control
SetControlDisabled( false );
}

669
gameui/LoadingDialog.cpp Normal file
View File

@ -0,0 +1,669 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "LoadingDialog.h"
#include "EngineInterface.h"
#include "IGameUIFuncs.h"
#include <vgui/IInput.h>
#include <vgui/ISurface.h>
#include <vgui/ILocalize.h>
#include <vgui/IScheme.h>
#include <vgui/ISystem.h>
#include <vgui_controls/ProgressBar.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/HTML.h>
#include <vgui_controls/RichText.h>
#include "tier0/icommandline.h"
#include "GameUI_Interface.h"
#include "ModInfo.h"
#include "BasePanel.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CLoadingDialog::CLoadingDialog( vgui::Panel *parent ) : Frame(parent, "LoadingDialog")
{
SetDeleteSelfOnClose(true);
// Use console style
m_bConsoleStyle = GameUI().IsConsoleUI();
if ( !m_bConsoleStyle )
{
SetSize( 416, 100 );
SetTitle( "#GameUI_Loading", true );
}
// center the loading dialog, unless we have another dialog to show in the background
m_bCenter = !GameUI().HasLoadingBackgroundDialog();
m_bShowingSecondaryProgress = false;
m_flSecondaryProgress = 0.0f;
m_flLastSecondaryProgressUpdateTime = 0.0f;
m_flSecondaryProgressStartTime = 0.0f;
m_pProgress = new ProgressBar( this, "Progress" );
m_pProgress2 = new ProgressBar( this, "Progress2" );
m_pInfoLabel = new Label( this, "InfoLabel", "" );
m_pCancelButton = new Button( this, "CancelButton", "#GameUI_Cancel" );
m_pTimeRemainingLabel = new Label( this, "TimeRemainingLabel", "" );
m_pCancelButton->SetCommand( "Cancel" );
if ( ModInfo().IsSinglePlayerOnly() == false && m_bConsoleStyle == true )
{
m_pLoadingBackground = new Panel( this, "LoadingDialogBG" );
}
else
{
m_pLoadingBackground = NULL;
}
SetMinimizeButtonVisible( false );
SetMaximizeButtonVisible( false );
SetCloseButtonVisible( false );
SetSizeable( false );
SetMoveable( false );
if ( m_bConsoleStyle )
{
m_bCenter = false;
m_pProgress->SetVisible( false );
m_pProgress2->SetVisible( false );
m_pInfoLabel->SetVisible( false );
m_pCancelButton->SetVisible( false );
m_pTimeRemainingLabel->SetVisible( false );
m_pCancelButton->SetVisible( false );
SetMinimumSize( 0, 0 );
SetTitleBarVisible( false );
m_flProgressFraction = 0;
}
else
{
m_pInfoLabel->SetBounds(20, 32, 392, 24);
m_pProgress->SetBounds(20, 64, 300, 24);
m_pCancelButton->SetBounds(330, 64, 72, 24);
m_pProgress2->SetVisible(false);
}
SetupControlSettings( false );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CLoadingDialog::~CLoadingDialog()
{
if ( input()->GetAppModalSurface() == GetVPanel() )
{
vgui::surface()->RestrictPaintToSinglePanel( NULL );
}
}
void CLoadingDialog::PaintBackground()
{
if ( !m_bConsoleStyle )
{
BaseClass::PaintBackground();
return;
}
// draw solid progress bar with curved endcaps
int panelWide, panelTall;
GetSize( panelWide, panelTall );
int barWide, barTall;
m_pProgress->GetSize( barWide, barTall );
int x = ( panelWide - barWide )/2;
int y = panelTall - barTall;
if ( m_pLoadingBackground )
{
vgui::HScheme scheme = vgui::scheme()->GetScheme( "ClientScheme" );
Color color = GetSchemeColor( "TanDarker", Color(255, 255, 255, 255), vgui::scheme()->GetIScheme(scheme) );
m_pLoadingBackground->SetFgColor( color );
m_pLoadingBackground->SetBgColor( color );
m_pLoadingBackground->SetPaintBackgroundEnabled( true );
}
if ( ModInfo().IsSinglePlayerOnly() )
{
DrawBox( x, y, barWide, barTall, Color( 0, 0, 0, 255 ), 1.0f );
}
DrawBox( x+2, y+2, barWide-4, barTall-4, Color( 100, 100, 100, 255 ), 1.0f );
barWide = m_flProgressFraction * ( barWide - 4 );
if ( barWide >= 12 )
{
// cannot draw a curved box smaller than 12 without artifacts
DrawBox( x+2, y+2, barWide, barTall-4, Color( 200, 100, 0, 255 ), 1.0f );
}
}
//-----------------------------------------------------------------------------
// Purpose: sets up dialog layout
//-----------------------------------------------------------------------------
void CLoadingDialog::SetupControlSettings( bool bForceShowProgressText )
{
m_bShowingVACInfo = false;
if ( GameUI().IsConsoleUI() )
{
KeyValues *pControlSettings = BasePanel()->GetConsoleControlSettings()->FindKey( "LoadingDialogNoBanner.res" );
LoadControlSettings( "null", NULL, pControlSettings );
return;
}
if ( ModInfo().IsSinglePlayerOnly() && !bForceShowProgressText )
{
LoadControlSettings("Resource/LoadingDialogNoBannerSingle.res");
}
else if ( gameuifuncs->IsConnectedToVACSecureServer() )
{
LoadControlSettings("Resource/LoadingDialogVAC.res");
m_bShowingVACInfo = true;
}
else
{
LoadControlSettings("Resource/LoadingDialogNoBanner.res");
}
}
//-----------------------------------------------------------------------------
// Purpose: Activates the loading screen, initializing and making it visible
//-----------------------------------------------------------------------------
void CLoadingDialog::Open()
{
if ( !m_bConsoleStyle )
{
SetTitle( "#GameUI_Loading", true );
}
HideOtherDialogs( true );
BaseClass::Activate();
if ( !m_bConsoleStyle )
{
m_pProgress->SetVisible( true );
if ( !ModInfo().IsSinglePlayerOnly() )
{
m_pInfoLabel->SetVisible( true );
}
m_pInfoLabel->SetText("");
m_pCancelButton->SetText("#GameUI_Cancel");
m_pCancelButton->SetCommand("Cancel");
}
}
//-----------------------------------------------------------------------------
// Purpose: error display file
//-----------------------------------------------------------------------------
void CLoadingDialog::SetupControlSettingsForErrorDisplay( const char *settingsFile )
{
if ( m_bConsoleStyle )
{
return;
}
m_bCenter = true;
SetTitle("#GameUI_Disconnected", true);
m_pInfoLabel->SetText("");
LoadControlSettings( settingsFile );
HideOtherDialogs( true );
BaseClass::Activate();
m_pProgress->SetVisible(false);
m_pInfoLabel->SetVisible(true);
m_pCancelButton->SetText("#GameUI_Close");
m_pCancelButton->SetCommand("Close");
m_pInfoLabel->InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose: shows or hides other top-level dialogs
//-----------------------------------------------------------------------------
void CLoadingDialog::HideOtherDialogs( bool bHide )
{
if ( bHide )
{
if ( GameUI().HasLoadingBackgroundDialog() )
{
// if we have a loading background dialog, hide any other dialogs by moving the full-screen background dialog to the
// front, then moving ourselves in front of it
GameUI().ShowLoadingBackgroundDialog();
vgui::ipanel()->MoveToFront( GetVPanel() );
vgui::input()->SetAppModalSurface( GetVPanel() );
}
else
{
// if there is no loading background dialog, use VGUI paint restrictions to hide other dialogs
vgui::surface()->RestrictPaintToSinglePanel(GetVPanel());
}
}
else
{
if ( GameUI().HasLoadingBackgroundDialog() )
{
GameUI().HideLoadingBackgroundDialog();
vgui::input()->SetAppModalSurface( NULL );
}
else
{
// remove any rendering restrictions
vgui::surface()->RestrictPaintToSinglePanel(NULL);
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Turns dialog into error display
//-----------------------------------------------------------------------------
void CLoadingDialog::DisplayGenericError(const char *failureReason, const char *extendedReason)
{
if ( m_bConsoleStyle )
{
return;
}
// In certain race conditions, DisplayGenericError can get called AFTER OnClose() has been called.
// If that happens and we don't call Activate(), then it'll continue closing when we don't want it to.
Activate();
SetupControlSettingsForErrorDisplay("Resource/LoadingDialogError.res");
if ( extendedReason && strlen( extendedReason ) > 0 )
{
wchar_t compositeReason[256], finalMsg[512], formatStr[256];
if ( extendedReason[0] == '#' )
{
wcsncpy(compositeReason, g_pVGuiLocalize->Find(extendedReason), sizeof( compositeReason ) / sizeof( wchar_t ) );
}
else
{
g_pVGuiLocalize->ConvertANSIToUnicode(extendedReason, compositeReason, sizeof( compositeReason ));
}
if ( failureReason[0] == '#' )
{
wcsncpy(formatStr, g_pVGuiLocalize->Find(failureReason), sizeof( formatStr ) / sizeof( wchar_t ) );
}
else
{
g_pVGuiLocalize->ConvertANSIToUnicode(failureReason, formatStr, sizeof( formatStr ));
}
g_pVGuiLocalize->ConstructString(finalMsg, sizeof( finalMsg ), formatStr, 1, compositeReason);
m_pInfoLabel->SetText(finalMsg);
}
else
{
m_pInfoLabel->SetText(failureReason);
}
int wide, tall;
int x,y;
m_pInfoLabel->GetContentSize( wide, tall );
m_pInfoLabel->GetPos( x, y );
SetTall( tall + y + 50 );
int buttonX, buttonY;
m_pCancelButton->GetPos( buttonX, buttonY );
m_pCancelButton->SetPos( buttonX, tall + y + 6 );
m_pCancelButton->RequestFocus();
}
//-----------------------------------------------------------------------------
// Purpose: explain to the user they can't join secure servers due to a VAC ban
//-----------------------------------------------------------------------------
void CLoadingDialog::DisplayVACBannedError()
{
if ( m_bConsoleStyle )
{
return;
}
SetupControlSettingsForErrorDisplay("Resource/LoadingDialogErrorVACBanned.res");
SetTitle("#VAC_ConnectionRefusedTitle", true);
}
//-----------------------------------------------------------------------------
// Purpose: explain to the user they can't connect to public servers due to
// not having a valid connection to Steam
// this should only happen if they are a pirate
//-----------------------------------------------------------------------------
void CLoadingDialog::DisplayNoSteamConnectionError()
{
if ( m_bConsoleStyle )
{
return;
}
SetupControlSettingsForErrorDisplay("Resource/LoadingDialogErrorNoSteamConnection.res");
}
//-----------------------------------------------------------------------------
// Purpose: explain to the user they got kicked from a server due to that same account
// logging in from another location. This also triggers the refresh login dialog on OK
// being pressed.
//-----------------------------------------------------------------------------
void CLoadingDialog::DisplayLoggedInElsewhereError()
{
if ( m_bConsoleStyle )
{
return;
}
SetupControlSettingsForErrorDisplay("Resource/LoadingDialogErrorLoggedInElsewhere.res");
m_pCancelButton->SetText("#GameUI_RefreshLogin_Login");
m_pCancelButton->SetCommand("Login");
}
//-----------------------------------------------------------------------------
// Purpose: sets status info text
//-----------------------------------------------------------------------------
void CLoadingDialog::SetStatusText(const char *statusText)
{
if ( m_bConsoleStyle )
{
return;
}
m_pInfoLabel->SetText(statusText);
}
//-----------------------------------------------------------------------------
// Purpose: returns the previous state
//-----------------------------------------------------------------------------
bool CLoadingDialog::SetShowProgressText( bool show )
{
if ( m_bConsoleStyle )
{
return false;
}
bool bret = m_pInfoLabel->IsVisible();
if ( bret != show )
{
SetupControlSettings( show );
m_pInfoLabel->SetVisible( show );
}
return bret;
}
//-----------------------------------------------------------------------------
// Purpose: updates time remaining
//-----------------------------------------------------------------------------
void CLoadingDialog::OnThink()
{
BaseClass::OnThink();
if ( !m_bConsoleStyle && m_bShowingSecondaryProgress )
{
// calculate the time remaining string
wchar_t unicode[512];
if (m_flSecondaryProgress >= 1.0f)
{
m_pTimeRemainingLabel->SetText("complete");
}
else if (ProgressBar::ConstructTimeRemainingString(unicode, sizeof(unicode), m_flSecondaryProgressStartTime, (float)system()->GetFrameTime(), m_flSecondaryProgress, m_flLastSecondaryProgressUpdateTime, true))
{
m_pTimeRemainingLabel->SetText(unicode);
}
else
{
m_pTimeRemainingLabel->SetText("");
}
}
SetAlpha( 255 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLoadingDialog::PerformLayout()
{
if ( m_bConsoleStyle )
{
// place in lower center
int screenWide, screenTall;
surface()->GetScreenSize( screenWide, screenTall );
int wide,tall;
GetSize( wide, tall );
int x = 0;
int y = 0;
if ( ModInfo().IsSinglePlayerOnly() )
{
x = ( screenWide - wide ) * 0.50f;
y = ( screenTall - tall ) * 0.86f;
}
else
{
x = ( screenWide - ( wide * 1.30f ) );
y = ( ( screenTall * 0.875f ) );
}
SetPos( x, y );
}
else if ( m_bCenter )
{
MoveToCenterOfScreen();
}
else
{
// if we're not supposed to be centered, move ourselves to the lower right hand corner of the screen
int x, y, screenWide, screenTall;
surface()->GetWorkspaceBounds( x, y, screenWide, screenTall );
int wide,tall;
GetSize( wide, tall );
if ( IsPC() )
{
x = screenWide - ( wide + 10 );
y = screenTall - ( tall + 10 );
}
else
{
// Move farther in so we're title safe
x = screenWide - wide - (screenWide * 0.05);
y = screenTall - tall - (screenTall * 0.05);
}
x -= m_iAdditionalIndentX;
y -= m_iAdditionalIndentY;
SetPos( x, y );
}
BaseClass::PerformLayout();
vgui::ipanel()->MoveToFront( GetVPanel() );
}
//-----------------------------------------------------------------------------
// Purpose: returns true if the number of ticks has changed
//-----------------------------------------------------------------------------
bool CLoadingDialog::SetProgressPoint( float fraction )
{
if ( m_bConsoleStyle )
{
if ( fraction >= 0.99f )
{
// show the progress artifically completed to fill in 100%
fraction = 1.0f;
}
fraction = clamp( fraction, 0.0f, 1.0f );
if ( (int)(fraction * 25) != (int)(m_flProgressFraction * 25) )
{
m_flProgressFraction = fraction;
return true;
}
return IsX360();
}
if ( !m_bShowingVACInfo && gameuifuncs->IsConnectedToVACSecureServer() )
{
SetupControlSettings( false );
}
int nOldDrawnSegments = m_pProgress->GetDrawnSegmentCount();
m_pProgress->SetProgress( fraction );
int nNewDrawSegments = m_pProgress->GetDrawnSegmentCount();
return (nOldDrawnSegments != nNewDrawSegments) || IsX360();
}
//-----------------------------------------------------------------------------
// Purpose: sets and shows the secondary progress bar
//-----------------------------------------------------------------------------
void CLoadingDialog::SetSecondaryProgress( float progress )
{
if ( m_bConsoleStyle )
return;
// don't show the progress if we've jumped right to completion
if (!m_bShowingSecondaryProgress && progress > 0.99f)
return;
// if we haven't yet shown secondary progress then reconfigure the dialog
if (!m_bShowingSecondaryProgress)
{
LoadControlSettings("Resource/LoadingDialogDualProgress.res");
m_bShowingSecondaryProgress = true;
m_pProgress2->SetVisible(true);
m_flSecondaryProgressStartTime = (float)system()->GetFrameTime();
}
// if progress has increased then update the progress counters
if (progress > m_flSecondaryProgress)
{
m_pProgress2->SetProgress(progress);
m_flSecondaryProgress = progress;
m_flLastSecondaryProgressUpdateTime = (float)system()->GetFrameTime();
}
// if progress has decreased then reset progress counters
if (progress < m_flSecondaryProgress)
{
m_pProgress2->SetProgress(progress);
m_flSecondaryProgress = progress;
m_flLastSecondaryProgressUpdateTime = (float)system()->GetFrameTime();
m_flSecondaryProgressStartTime = (float)system()->GetFrameTime();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLoadingDialog::SetSecondaryProgressText(const char *statusText)
{
if ( m_bConsoleStyle )
{
return;
}
SetControlString( "SecondaryProgressLabel", statusText );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLoadingDialog::OnClose()
{
// remove any rendering restrictions
HideOtherDialogs( false );
BaseClass::OnClose();
}
//-----------------------------------------------------------------------------
// Purpose: command handler
//-----------------------------------------------------------------------------
void CLoadingDialog::OnCommand(const char *command)
{
if ( !stricmp(command, "Cancel") )
{
// disconnect from the server
engine->ClientCmd_Unrestricted("disconnect\n");
// close
Close();
}
else
{
BaseClass::OnCommand(command);
}
}
void CLoadingDialog::OnKeyCodeTyped(KeyCode code)
{
if ( m_bConsoleStyle )
{
return;
}
if ( code == KEY_ESCAPE )
{
OnCommand("Cancel");
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
//-----------------------------------------------------------------------------
// Purpose: Maps ESC to quiting loading
//-----------------------------------------------------------------------------
void CLoadingDialog::OnKeyCodePressed(KeyCode code)
{
if ( m_bConsoleStyle )
{
return;
}
ButtonCode_t nButtonCode = GetBaseButtonCode( code );
if ( nButtonCode == KEY_XBUTTON_B || nButtonCode == KEY_XBUTTON_A || nButtonCode == STEAMCONTROLLER_A || nButtonCode == STEAMCONTROLLER_B )
{
OnCommand("Cancel");
}
else
{
BaseClass::OnKeyCodePressed(code);
}
}
//-----------------------------------------------------------------------------
// Purpose: Singleton accessor
//-----------------------------------------------------------------------------
extern vgui::DHANDLE<CLoadingDialog> g_hLoadingDialog;
CLoadingDialog *LoadingDialog()
{
return g_hLoadingDialog.Get();
}

77
gameui/LoadingDialog.h Normal file
View File

@ -0,0 +1,77 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef LOADINGDIALOG_H
#define LOADINGDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Frame.h>
#include <vgui_controls/HTML.h>
//-----------------------------------------------------------------------------
// Purpose: Dialog for displaying level loading status
//-----------------------------------------------------------------------------
class CLoadingDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CLoadingDialog, vgui::Frame );
public:
CLoadingDialog( vgui::Panel *parent );
~CLoadingDialog();
void Open();
bool SetProgressPoint(float fraction);
void SetStatusText(const char *statusText);
void SetSecondaryProgress(float progress);
void SetSecondaryProgressText(const char *statusText);
bool SetShowProgressText( bool show );
void DisplayGenericError(const char *failureReason, const char *extendedReason = NULL);
void DisplayVACBannedError();
void DisplayNoSteamConnectionError();
void DisplayLoggedInElsewhereError();
protected:
virtual void OnCommand(const char *command);
virtual void PerformLayout();
virtual void OnThink();
virtual void OnClose();
virtual void OnKeyCodeTyped(vgui::KeyCode code);
virtual void OnKeyCodePressed(vgui::KeyCode code);
virtual void PaintBackground( void );
private:
void SetupControlSettings( bool bForceShowProgressText );
void SetupControlSettingsForErrorDisplay( const char *settingsFile );
void HideOtherDialogs( bool bHide );
vgui::ProgressBar *m_pProgress;
vgui::ProgressBar *m_pProgress2;
vgui::Label *m_pInfoLabel;
vgui::Label *m_pTimeRemainingLabel;
vgui::Button *m_pCancelButton;
vgui::Panel *m_pLoadingBackground;
bool m_bShowingSecondaryProgress;
float m_flSecondaryProgress;
float m_flLastSecondaryProgressUpdateTime;
float m_flSecondaryProgressStartTime;
bool m_bShowingVACInfo;
bool m_bCenter;
bool m_bConsoleStyle;
float m_flProgressFraction;
CPanelAnimationVar( int, m_iAdditionalIndentX, "AdditionalIndentX", "0" );
CPanelAnimationVar( int, m_iAdditionalIndentY, "AdditionalIndentY", "0" );
};
// singleton accessor
CLoadingDialog *LoadingDialog();
#endif // LOADINGDIALOG_H

287
gameui/LogoFile.cpp Normal file
View File

@ -0,0 +1,287 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#if !defined( _X360 )
#include <windows.h>
#endif
#include <stdio.h>
#include "tier1/utlbuffer.h"
#include <vgui/VGUI.h>
#include <vgui_controls/Controls.h>
#include "filesystem.h"
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
#define TYP_LUMPY 64 // 64 + grab command number
typedef struct
{
char identification[4]; // should be WAD2 or 2DAW
int numlumps;
int infotableofs;
} wadinfo_t;
typedef struct
{
int filepos;
int disksize;
int size; // uncompressed
char type;
char compression;
char pad1, pad2;
char name[16]; // must be null terminated
} lumpinfo_t;
typedef struct
{
char name[16];
unsigned width, height;
unsigned offsets[4]; // four mip maps stored
} miptex_t;
unsigned char pixdata[256];
float linearpalette[256][3];
float d_red, d_green, d_blue;
int colors_used;
int color_used[256];
float maxdistortion;
unsigned char palLogo[768];
/*
=============
AveragePixels
=============
*/
unsigned char AveragePixels (int count)
{
return pixdata[0];
}
/*
==============
GrabMip
filename MIP x y width height
must be multiples of sixteen
==============
*/
int GrabMip ( HANDLE hdib, unsigned char *lump_p, char *lumpname, COLORREF crf, int *width, int *height)
{
int i,x,y,xl,yl,xh,yh,w,h;
unsigned char *screen_p, *source;
miptex_t *qtex;
int miplevel, mipstep;
int xx, yy;
int count;
int byteimagewidth, byteimageheight;
unsigned char *byteimage;
LPBITMAPINFO lpbmi; // pointer to BITMAPINFO structure (Win3.0)
/* get pointer to BITMAPINFO (Win 3.0) */
lpbmi = (LPBITMAPINFO)::GlobalLock((HGLOBAL)hdib);
unsigned char *lump_start = lump_p;
xl = yl = 0;
w = lpbmi->bmiHeader.biWidth;
h = lpbmi->bmiHeader.biHeight;
*width = w;
*height = h;
byteimage = (unsigned char *)((LPSTR)lpbmi + sizeof( BITMAPINFOHEADER ) + 256 * sizeof( RGBQUAD ) );
if ( (w & 15) || (h & 15) )
return 0; //Error ("line %i: miptex sizes must be multiples of 16", scriptline);
xh = xl+w;
yh = yl+h;
qtex = (miptex_t *)lump_p;
qtex->width = (unsigned)(w);
qtex->height = (unsigned)(h);
Q_strncpy (qtex->name, lumpname, sizeof( qtex->name) );
lump_p = (unsigned char *)&qtex->offsets[4];
byteimagewidth = w;
byteimageheight = h;
source = (unsigned char *)lump_p;
qtex->offsets[0] = (unsigned)((unsigned char *)lump_p - (unsigned char *)qtex);
// We're reading from a dib, so go bottom up
screen_p = byteimage + (h - 1) * w;
for (y=yl ; y<yh ; y++)
{
for (x=xl ; x<xh ; x++)
*lump_p++ = *screen_p++;
screen_p -= 2 * w;
}
// calculate gamma corrected linear palette
for (i = 0; i < 256; i++)
{
for (int j = 0; j < 3; j++)
{
float f = (float)(palLogo[i*3+j] / 255.0);
linearpalette[i][j] = f; //pow((double)f, 2); // assume textures are done at 2.2, we want to remap them at 1.0
}
}
maxdistortion = 0;
// assume palette full if it's a transparent texture
colors_used = 256;
for (i = 0; i < 256; i++)
color_used[i] = 1;
//
// subsample for greater mip levels
//
for (miplevel = 1 ; miplevel<4 ; miplevel++)
{
d_red = d_green = d_blue = 0; // no distortion yet
qtex->offsets[miplevel] = (unsigned)(lump_p - (unsigned char *)qtex);
mipstep = 1<<miplevel;
for (y=0 ; y<h ; y+=mipstep)
{
for (x = 0 ; x<w ; x+= mipstep)
{
count = 0;
for (yy=0 ; yy<mipstep ; yy++)
{
for (xx=0 ; xx<mipstep ; xx++)
pixdata[count++] = source[(y+yy)*w + x + xx ];
}
*lump_p++ = AveragePixels (count);
}
}
}
::GlobalUnlock(lpbmi);
// Write out palette in 16bit mode
*(unsigned short *) lump_p = 256; // palette size
lump_p += sizeof(short);
memcpy(lump_p, &palLogo[0], 765);
lump_p += 765;
*lump_p++ = (unsigned char)(crf & 0xFF);
*lump_p++ = (unsigned char)((crf >> 8) & 0xFF);
*lump_p++ = (unsigned char)((crf >> 16) & 0xFF);
return lump_p - lump_start;
}
void UpdateLogoWAD( void *phdib, int r, int g, int b )
{
char logoname[ 32 ];
char *pszName;
Q_strncpy( logoname, "LOGO", sizeof( logoname ) );
pszName = &logoname[ 0 ];
HANDLE hdib = (HANDLE)phdib;
COLORREF crf = RGB( r, g, b );
if ((!pszName) || (pszName[0] == 0) || (hdib == NULL))
return;
// Generate lump
unsigned char *buf = (unsigned char *)_alloca( 16384 );
CUtlBuffer buffer( 0, 16384 );
int width, height;
int length = GrabMip (hdib, buf, pszName, crf, &width, &height);
if ( length == 0 )
{
return;
}
bool sizevalid = false;
if ( width == height )
{
if ( width == 16 ||
width == 32 ||
width == 64 )
{
sizevalid = true;
}
}
if ( !sizevalid )
return;
while (length & 3)
length++;
// Write Header
wadinfo_t header;
header.identification[0] = 'W';
header.identification[1] = 'A';
header.identification[2] = 'D';
header.identification[3] = '3';
header.numlumps = 1;
header.infotableofs = 0;
buffer.Put( &header, sizeof( wadinfo_t ) );
// Fill Ino info table
lumpinfo_t info;
Q_memset (&info, 0, sizeof(info));
Q_strncpy(info.name, pszName, sizeof( info.name ) );
info.filepos = (int)sizeof(wadinfo_t);
info.size = info.disksize = length;
info.type = TYP_LUMPY;
info.compression = 0;
// Write Lump
buffer.Put( buf, length );
// Write info table
buffer.Put( &info, sizeof( lumpinfo_t ) );
int savepos = buffer.TellPut();
buffer.SeekPut( CUtlBuffer::SEEK_HEAD, 0 );
header.infotableofs = length + sizeof(wadinfo_t);
buffer.Put( &header, sizeof( wadinfo_t ) );
buffer.SeekPut( CUtlBuffer::SEEK_HEAD, savepos );
// Output to file
FileHandle_t file;
file = g_pFullFileSystem->Open( "pldecal.wad", "wb" );
if ( file != FILESYSTEM_INVALID_HANDLE )
{
g_pFullFileSystem->Write( buffer.Base(), buffer.TellPut(), file );
g_pFullFileSystem->Close( file );
}
}

251
gameui/ModInfo.cpp Normal file
View File

@ -0,0 +1,251 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "ModInfo.h"
#include "KeyValues.h"
#include "vgui_controls/Controls.h"
#include "filesystem.h"
#include "EngineInterface.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
//-----------------------------------------------------------------------------
// Purpose: singleton accessor
//-----------------------------------------------------------------------------
CModInfo &ModInfo()
{
static CModInfo s_ModInfo;
return s_ModInfo;
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CModInfo::CModInfo()
{
m_pModData = new KeyValues("ModData");
m_wcsGameTitle[0] = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CModInfo::~CModInfo()
{
FreeModInfo();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CModInfo::FreeModInfo()
{
if (m_pModData)
{
m_pModData->deleteThis();
m_pModData = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::IsMultiplayerOnly()
{
return (stricmp(m_pModData->GetString("type", ""), "multiplayer_only") == 0);
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::IsSinglePlayerOnly()
{
#ifndef _XBOX
return (stricmp(m_pModData->GetString("type", ""), "singleplayer_only") == 0);
#else
// xboxissue - no support for disparate mounted content
return true;
#endif
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
const char *CModInfo::GetFallbackDir()
{
return m_pModData->GetString("fallback_dir", "");
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
const wchar_t *CModInfo::GetGameTitle()
{
if (!m_wcsGameTitle[0])
{
// for some reason, the standard ILocalize::ConvertANSIToUnicode() strips off
// the '<27>' character in 'HALF-LIFE<46>' - so just do a straight upconvert to unicode
const char *title = m_pModData->GetString("title", "");
int i = 0;
for (; title[i] != 0; ++i)
{
m_wcsGameTitle[i] = (wchar_t)title[i];
}
m_wcsGameTitle[i] = 0;
}
return m_wcsGameTitle;
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
const wchar_t *CModInfo::GetGameTitle2()
{
if (!m_wcsGameTitle2[0])
{
// for some reason, the standard ILocalize::ConvertANSIToUnicode() strips off
// the '<27>' character in 'HALF-LIFE<46>' - so just do a straight upconvert to unicode
const char *title2 = m_pModData->GetString("title2", "");
int i = 0;
for (; title2[i] != 0; ++i)
{
m_wcsGameTitle2[i] = (wchar_t)title2[i];
}
m_wcsGameTitle2[i] = 0;
}
return m_wcsGameTitle2;
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
const char *CModInfo::GetGameName()
{
return m_pModData->GetString("game", "");
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
KeyValues *CModInfo::GetHiddenMaps()
{
return m_pModData->FindKey( "hidden_maps" );
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::HasPortals()
{
return (stricmp(m_pModData->GetString("hasportals", "0"), "1") == 0);
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::HasHDContent()
{
return (stricmp(m_pModData->GetString("hashdcontent", "0"), "1") == 0);
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::NoDifficulty()
{
return (stricmp(m_pModData->GetString("nodifficulty", "0"), "1") == 0);
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::NoModels()
{
return (stricmp(m_pModData->GetString("nomodels", "0"), "1") == 0);
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::NoHiModel()
{
return (stricmp(m_pModData->GetString("nohimodel", "0"), "1") == 0);
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::NoCrosshair()
{
return (stricmp(m_pModData->GetString("nocrosshair", "1"), "1") == 0);
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::AdvCrosshair()
{
return ( m_pModData->GetInt( "advcrosshair" ) > 0 );
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
int CModInfo::AdvCrosshairLevel()
{
return m_pModData->GetInt( "advcrosshair" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CModInfo::LoadCurrentGameInfo()
{
// Load up gameinfo for the current mod
char const *filename = "gameinfo.txt";
m_pModData->LoadFromFile( g_pFullFileSystem, filename );
}
//-----------------------------------------------------------------------------
// Purpose: loads file from null-terminated buffer
//-----------------------------------------------------------------------------
void CModInfo::LoadGameInfoFromBuffer( const char *buffer )
{
// Load up gameinfo.txt for the current mod
m_pModData->LoadFromBuffer( "", buffer );
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::UseGameLogo()
{
return ( Q_stricmp( m_pModData->GetString( "gamelogo", "0" ), "1" ) == 0 );
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::UseBots()
{
return ( Q_stricmp( m_pModData->GetString( "bots", "0" ), "1" ) == 0 );
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
bool CModInfo::SupportsVR()
{
return (m_pModData->GetInt( "supportsvr" ) > 0);
}

68
gameui/ModInfo.h Normal file
View File

@ -0,0 +1,68 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MODINFO_H
#define MODINFO_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
class KeyValues;
//-----------------------------------------------------------------------------
// Purpose: contains all the data entered about a mod in gameinfo.txt
//-----------------------------------------------------------------------------
class CModInfo
{
public:
CModInfo();
~CModInfo();
void FreeModInfo();
// loads mod info from gameinfo.txt
void LoadCurrentGameInfo();
// loads gameinfo from null-terminated string
void LoadGameInfoFromBuffer( const char *buffer );
// data accessors
const wchar_t *GetGameTitle();
const wchar_t *GetGameTitle2();
const char *GetGameName();
bool IsMultiplayerOnly();
bool IsSinglePlayerOnly();
bool HasPortals();
bool NoDifficulty();
bool NoModels();
bool NoHiModel();
bool NoCrosshair();
bool AdvCrosshair();
int AdvCrosshairLevel();
const char *GetFallbackDir();
bool UseGameLogo();
bool UseBots();
bool HasHDContent();
bool SupportsVR();
KeyValues *GetHiddenMaps();
private:
wchar_t m_wcsGameTitle[128];
wchar_t m_wcsGameTitle2[128];
KeyValues *m_pModData;
};
// singleton accessor
extern CModInfo &ModInfo();
#endif // MODINFO_H

View File

@ -0,0 +1,39 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "MouseMessageForwardingPanel.h"
#include "KeyValues.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
CMouseMessageForwardingPanel::CMouseMessageForwardingPanel( Panel *parent, const char *name ) : BaseClass( parent, name )
{
// don't draw an
SetPaintEnabled(false);
SetPaintBackgroundEnabled(false);
SetPaintBorderEnabled(false);
}
void CMouseMessageForwardingPanel::PerformLayout()
{
// fill out the whole area
int w, t;
GetParent()->GetSize(w, t);
SetBounds(0, 0, w, t);
}
void CMouseMessageForwardingPanel::OnMousePressed( vgui::MouseCode code )
{
CallParentFunction( new KeyValues("MousePressed", "code", code) );
}
void CMouseMessageForwardingPanel::OnMouseDoublePressed( vgui::MouseCode code )
{
CallParentFunction( new KeyValues("MouseDoublePressed", "code", code) );
}

View File

@ -0,0 +1,29 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef MOUSEMESSAGEFORWARDINGPANEL_H
#define MOUSEMESSAGEFORWARDINGPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Panel.h"
//-----------------------------------------------------------------------------
// Purpose: Invisible panel that forwards up mouse movement
//-----------------------------------------------------------------------------
class CMouseMessageForwardingPanel : public vgui::Panel
{
DECLARE_CLASS_SIMPLE( CMouseMessageForwardingPanel, vgui::Panel );
public:
CMouseMessageForwardingPanel( Panel *parent, const char *name );
virtual void PerformLayout( void );
virtual void OnMousePressed( vgui::MouseCode code );
virtual void OnMouseDoublePressed( vgui::MouseCode code );
};
#endif //MOUSEMESSAGEFORWARDINGPANEL_H

View File

@ -0,0 +1,431 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <time.h>
#include "MultiplayerAdvancedDialog.h"
#include <vgui/ILocalize.h>
#include <vgui/ISurface.h>
#include <vgui_controls/ListPanel.h>
#include <KeyValues.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/MessageBox.h>
#include <vgui_controls/CheckButton.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/TextEntry.h>
#include "cvarslider.h"
#include "PanelListPanel.h"
#include <vgui/IInput.h>
#include <steam/steam_api.h>
#include "EngineInterface.h"
#include "fmtstr.h"
#include "filesystem.h"
#include <tier0/vcrmode.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
#define OPTIONS_DIR "cfg"
#define DEFAULT_OPTIONS_FILE OPTIONS_DIR "/user_default.scr"
#define OPTIONS_FILE OPTIONS_DIR "/user.scr"
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMultiplayerAdvancedDialog::CMultiplayerAdvancedDialog(vgui::Panel *parent) : BaseClass(NULL, "MultiplayerAdvancedDialog")
{
SetBounds(0, 0, 372, 160);
SetSizeable( false );
SetTitle("#GameUI_MultiplayerAdvanced", true);
Button *cancel = new Button( this, "Cancel", "#GameUI_Cancel" );
cancel->SetCommand( "Close" );
Button *ok = new Button( this, "OK", "#GameUI_OK" );
ok->SetCommand( "Ok" );
m_pListPanel = new CPanelListPanel( this, "PanelListPanel" );
m_pList = NULL;
m_pDescription = new CInfoDescription();
m_pDescription->InitFromFile( DEFAULT_OPTIONS_FILE );
m_pDescription->InitFromFile( OPTIONS_FILE );
m_pDescription->TransferCurrentValues( NULL );
LoadControlSettings("Resource\\MultiplayerAdvancedDialog.res");
CreateControls();
MoveToCenterOfScreen();
SetSizeable( false );
SetDeleteSelfOnClose( true );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CMultiplayerAdvancedDialog::~CMultiplayerAdvancedDialog()
{
delete m_pDescription;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMultiplayerAdvancedDialog::Activate()
{
BaseClass::Activate();
input()->SetAppModalSurface(GetVPanel());
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMultiplayerAdvancedDialog::OnClose()
{
BaseClass::OnClose();
MarkForDeletion();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *command -
//-----------------------------------------------------------------------------
void CMultiplayerAdvancedDialog::OnCommand( const char *command )
{
if ( !stricmp( command, "Ok" ) )
{
// OnApplyChanges();
SaveValues();
OnClose();
return;
}
BaseClass::OnCommand( command );
}
void CMultiplayerAdvancedDialog::OnKeyCodeTyped(KeyCode code)
{
// force ourselves to be closed if the escape key it pressed
if (code == KEY_ESCAPE)
{
Close();
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMultiplayerAdvancedDialog::GatherCurrentValues()
{
if ( !m_pDescription )
return;
// OK
CheckButton *pBox;
TextEntry *pEdit;
ComboBox *pCombo;
CCvarSlider *pSlider;
mpcontrol_t *pList;
CScriptObject *pObj;
CScriptListItem *pItem;
char szValue[256];
char strValue[ 256 ];
pList = m_pList;
while ( pList )
{
pObj = pList->pScrObj;
if ( pObj->type == O_CATEGORY )
{
pList = pList->next;
continue;
}
if ( !pList->pControl )
{
pObj->SetCurValue( pObj->defValue );
pList = pList->next;
continue;
}
switch ( pObj->type )
{
case O_BOOL:
pBox = (CheckButton *)pList->pControl;
sprintf( szValue, "%s", pBox->IsSelected() ? "1" : "0" );
break;
case O_NUMBER:
pEdit = ( TextEntry * )pList->pControl;
pEdit->GetText( strValue, sizeof( strValue ) );
sprintf( szValue, "%s", strValue );
break;
case O_STRING:
pEdit = ( TextEntry * )pList->pControl;
pEdit->GetText( strValue, sizeof( strValue ) );
sprintf( szValue, "%s", strValue );
break;
case O_LIST:
{
pCombo = (ComboBox *)pList->pControl;
// pCombo->GetText( strValue, sizeof( strValue ) );
int activeItem = pCombo->GetActiveItem();
pItem = pObj->pListItems;
// int n = (int)pObj->fdefValue;
while ( pItem )
{
if (!activeItem--)
break;
pItem = pItem->pNext;
}
if ( pItem )
{
sprintf( szValue, "%s", pItem->szValue );
}
else // Couln't find index
{
//assert(!("Couldn't find string in list, using default value"));
sprintf( szValue, "%s", pObj->defValue );
}
break;
}
case O_SLIDER:
pSlider = ( CCvarSlider * )pList->pControl;
sprintf( szValue, "%.2f", pSlider->GetSliderValue() );
break;
}
// Remove double quotes and % characters
UTIL_StripInvalidCharacters( szValue, sizeof(szValue) );
strcpy( strValue, szValue );
pObj->SetCurValue( strValue );
pList = pList->next;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMultiplayerAdvancedDialog::CreateControls()
{
DestroyControls();
// Go through desciption creating controls
CScriptObject *pObj;
pObj = m_pDescription->pObjList;
// Build out the clan dropdown
CScriptObject *pClanObj = m_pDescription->FindObject( "cl_clanid" );
ISteamFriends *pFriends = steamapicontext->SteamFriends();
if ( pFriends && pClanObj )
{
pClanObj->RemoveAndDeleteAllItems();
int iGroupCount = pFriends->GetClanCount();
pClanObj->AddItem( new CScriptListItem( "#Cstrike_ClanTag_None", "0" ) );
for ( int k = 0; k < iGroupCount; ++ k )
{
CSteamID clanID = pFriends->GetClanByIndex( k );
const char *pName = pFriends->GetClanName( clanID );
const char *pTag = pFriends->GetClanTag( clanID );
char id[12];
Q_snprintf( id, sizeof( id ), "%d", clanID.GetAccountID() );
pClanObj->AddItem( new CScriptListItem( CFmtStr( "%s (%s)", pTag, pName ), id ) );
}
}
mpcontrol_t *pCtrl;
CheckButton *pBox;
TextEntry *pEdit;
ComboBox *pCombo;
CCvarSlider *pSlider;
CScriptListItem *pListItem;
Panel *objParent = m_pListPanel;
while ( pObj )
{
if ( pObj->type == O_OBSOLETE || pObj->type == O_CATEGORY )
{
pObj = pObj->pNext;
continue;
}
pCtrl = new mpcontrol_t( objParent, "mpcontrol_t" );
pCtrl->type = pObj->type;
switch ( pCtrl->type )
{
case O_BOOL:
pBox = new CheckButton( pCtrl, "DescCheckButton", pObj->prompt );
pBox->SetSelected( pObj->fdefValue != 0.0f ? true : false );
pCtrl->pControl = (Panel *)pBox;
break;
case O_STRING:
case O_NUMBER:
pEdit = new TextEntry( pCtrl, "DescTextEntry");
pEdit->InsertString(pObj->defValue);
pCtrl->pControl = (Panel *)pEdit;
break;
case O_LIST:
{
pCombo = new ComboBox( pCtrl, "DescComboBox", 5, false );
// track which row matches the current value
int iRow = -1;
int iCount = 0;
pListItem = pObj->pListItems;
while ( pListItem )
{
if ( iRow == -1 && !Q_stricmp( pListItem->szValue, pObj->curValue ) )
iRow = iCount;
pCombo->AddItem( pListItem->szItemText, NULL );
pListItem = pListItem->pNext;
++iCount;
}
pCombo->ActivateItemByRow( iRow );
pCtrl->pControl = (Panel *)pCombo;
}
break;
case O_SLIDER:
pSlider = new CCvarSlider( pCtrl, "DescSlider", "Test", pObj->fMin, pObj->fMax, pObj->cvarname, false );
pCtrl->pControl = (Panel *)pSlider;
break;
default:
break;
}
if ( pCtrl->type != O_BOOL )
{
pCtrl->pPrompt = new vgui::Label( pCtrl, "DescLabel", "" );
pCtrl->pPrompt->SetContentAlignment( vgui::Label::a_west );
pCtrl->pPrompt->SetTextInset( 5, 0 );
pCtrl->pPrompt->SetText( pObj->prompt );
}
pCtrl->pScrObj = pObj;
switch ( pCtrl->type )
{
case O_BOOL:
case O_STRING:
case O_NUMBER:
case O_LIST:
pCtrl->SetSize( 100, 28 );
break;
case O_SLIDER:
pCtrl->SetSize( 100, 40 );
break;
default:
break;
}
//pCtrl->SetBorder( scheme()->GetBorder(1, "DepressedButtonBorder") );
m_pListPanel->AddItem( pCtrl );
// Link it in
if ( !m_pList )
{
m_pList = pCtrl;
pCtrl->next = NULL;
}
else
{
mpcontrol_t *p;
p = m_pList;
while ( p )
{
if ( !p->next )
{
p->next = pCtrl;
pCtrl->next = NULL;
break;
}
p = p->next;
}
}
pObj = pObj->pNext;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMultiplayerAdvancedDialog::DestroyControls()
{
mpcontrol_t *p, *n;
p = m_pList;
while ( p )
{
n = p->next;
//
delete p->pControl;
delete p->pPrompt;
delete p;
p = n;
}
m_pList = NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMultiplayerAdvancedDialog::SaveValues()
{
// Get the values from the controls:
GatherCurrentValues();
// Create the game.cfg file
if ( m_pDescription )
{
FileHandle_t fp;
// Add settings to config.cfg
m_pDescription->WriteToConfig();
g_pFullFileSystem->CreateDirHierarchy( OPTIONS_DIR );
fp = g_pFullFileSystem->Open( OPTIONS_FILE, "wb" );
if ( fp )
{
m_pDescription->WriteToScriptFile( fp );
g_pFullFileSystem->Close( fp );
}
}
}

View File

@ -0,0 +1,52 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MULTIPLAYERADVANCEDDIALOG_H
#define MULTIPLAYERADVANCEDDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Frame.h>
#include "scriptobject.h"
#include <vgui/KeyCode.h>
class CPanelListPanel;
//-----------------------------------------------------------------------------
// Purpose: Displays a game-specific list of options
//-----------------------------------------------------------------------------
class CMultiplayerAdvancedDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CMultiplayerAdvancedDialog, vgui::Frame );
public:
CMultiplayerAdvancedDialog(vgui::Panel *parent);
~CMultiplayerAdvancedDialog();
virtual void Activate();
private:
void CreateControls();
void DestroyControls();
void GatherCurrentValues();
void SaveValues();
CInfoDescription *m_pDescription;
mpcontrol_t *m_pList;
CPanelListPanel *m_pListPanel;
virtual void OnCommand( const char *command );
virtual void OnClose();
virtual void OnKeyCodeTyped(vgui::KeyCode code);
};
#endif // MULTIPLAYERADVANCEDDIALOG_H

1724
gameui/NewGameDialog.cpp Normal file

File diff suppressed because it is too large Load Diff

155
gameui/NewGameDialog.h Normal file
View File

@ -0,0 +1,155 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef NEWGAMEDIALOG_H
#define NEWGAMEDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "vgui_controls/KeyRepeat.h"
#include "utlvector.h"
class CGameChapterPanel;
class CSkillSelectionDialog;
// Slot indices in new game menu
#define INVALID_INDEX -1
#define SLOT_OFFLEFT 0
#define SLOT_LEFT 1
#define SLOT_CENTER 2
#define SLOT_RIGHT 3
#define SLOT_OFFRIGHT 4
#define NUM_SLOTS 5
class CNewGamePlayButton : public vgui::Button
{
DECLARE_CLASS_SIMPLE( CNewGamePlayButton, vgui::Button );
public:
CNewGamePlayButton( Panel *parent, const char *panelName, const char *text, Panel *pActionSignalTarget=NULL, const char *pCmd=NULL )
: vgui::Button( parent, panelName, text, pActionSignalTarget, pCmd )
{
}
void OnKeyCodePressed( vgui::KeyCode code )
{
if ( code == KEY_XBUTTON_A || code == STEAMCONTROLLER_A )
{
ConVarRef var( "joystick" );
if ( var.IsValid() && !var.GetBool() )
{
var.SetValue( true );
}
ConVarRef var2( "hud_fastswitch" );
if ( var2.IsValid() && var2.GetInt() != 2 )
{
var2.SetValue( 2 );
}
DoClick();
return;
}
BaseClass::OnKeyCodePressed( code );
}
};
//-----------------------------------------------------------------------------
// Purpose: Handles starting a new game, skill and chapter selection
//-----------------------------------------------------------------------------
class CNewGameDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CNewGameDialog, vgui::Frame );
public:
MESSAGE_FUNC( FinishScroll, "FinishScroll" );
MESSAGE_FUNC( StartGame, "StartGame" );
CNewGameDialog(vgui::Panel *parent, bool bCommentaryMode );
~CNewGameDialog();
virtual void Activate( void );
virtual void ApplySettings( KeyValues *inResourceData );
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void OnCommand( const char *command );
virtual void OnClose( void );
virtual void PaintBackground();
void SetSelectedChapterIndex( int index );
void SetSelectedChapter( const char *chapter );
void UpdatePanelLockedStatus( int iUnlockedChapter, int i, CGameChapterPanel *pChapterPanel );
void SetCommentaryMode( bool bCommentary ) { m_bCommentaryMode = bCommentary; }
virtual void OnKeyCodePressed( vgui::KeyCode code );
virtual void OnKeyCodeReleased( vgui::KeyCode code );
virtual void OnThink();
// Xbox: Defined values are also used to shift the slot indices
enum EScrollDirection
{
SCROLL_RIGHT = -1,
SCROLL_NONE = 0,
SCROLL_LEFT = 1
};
EScrollDirection m_ScrollDirection;
private:
int m_iSelectedChapter;
CUtlVector<CGameChapterPanel *> m_ChapterPanels;
vgui::DHANDLE<CSkillSelectionDialog> m_hSkillSelectionDialog;
vgui::Button *m_pPlayButton;
vgui::Button *m_pNextButton;
vgui::Button *m_pPrevButton;
vgui::Panel *m_pCenterBg;
vgui::Label *m_pChapterTitleLabels[2];
vgui::Label *m_pBonusSelection;
vgui::ImagePanel *m_pBonusSelectionBorder;
CFooterPanel *m_pFooter;
bool m_bCommentaryMode;
vgui::Label *m_pCommentaryLabel;
// Xbox
void ScrollSelectionPanels( EScrollDirection dir );
void ScrollBonusSelection( EScrollDirection dir );
void PreScroll( EScrollDirection dir );
void PostScroll( EScrollDirection dir );
void SetFastScroll( bool fast );
void ContinueScrolling( void );
void AnimateSelectionPanels( void );
void ShiftPanelIndices( int offset );
bool IsValidPanel( const int idx );
void InitPanelIndexForDisplay( const int idx );
void UpdateMenuComponents( EScrollDirection dir );
void UpdateBonusSelection( void );
int m_PanelXPos[ NUM_SLOTS ];
int m_PanelYPos[ NUM_SLOTS ];
float m_PanelAlpha[ NUM_SLOTS ];
int m_PanelIndex[ NUM_SLOTS ];
float m_ScrollSpeed;
int m_ButtonPressed;
int m_ScrollCt;
bool m_bScrolling;
char m_ActiveTitleIdx;
bool m_bMapStarting;
int m_iBonusSelection;
bool m_bScrollToFirstBonusMap;
struct BonusMapDescription_t *m_pBonusMapDescription;
vgui::CKeyRepeatHandler m_KeyRepeat;
};
#endif // NEWGAMEDIALOG_H

155
gameui/OptionsDialog.cpp Normal file
View File

@ -0,0 +1,155 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "BasePanel.h"
#include "OptionsDialog.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/CheckButton.h"
#include "vgui_controls/PropertySheet.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/QueryBox.h"
#include "vgui/ILocalize.h"
#include "vgui/ISurface.h"
#include "vgui/ISystem.h"
#include "vgui/IVGui.h"
#include "KeyValues.h"
#include "OptionsSubKeyboard.h"
#include "OptionsSubMouse.h"
#include "OptionsSubAudio.h"
#include "OptionsSubVideo.h"
#include "OptionsSubVoice.h"
#include "OptionsSubMultiplayer.h"
#include "OptionsSubDifficulty.h"
#include "OptionsSubPortal.h"
#ifdef WIN32
// NVNT haptic configuration dialog
#include "OptionsSubHaptics.h"
#endif
#include "ModInfo.h"
using namespace vgui;
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
//-----------------------------------------------------------------------------
// Purpose: Basic help dialog
//-----------------------------------------------------------------------------
COptionsDialog::COptionsDialog(vgui::Panel *parent) : PropertyDialog(parent, "OptionsDialog")
{
SetDeleteSelfOnClose(true);
SetBounds(0, 0, 512, 406);
SetSizeable( false );
SetTitle("#GameUI_Options", true);
// debug timing code, this function takes too long
// double s4 = system()->GetCurrentTime();
#if defined( WIN32 ) && !defined( _X360 )
// NVNT START see if the user has a haptic device via convar. if so create haptics dialog.
ConVarRef checkHap("hap_HasDevice");
checkHap.Init("hap_HasDevice",true);
if(checkHap.GetBool())
{
AddPage(new COptionsSubHaptics(this), "#GameUI_Haptics_TabTitle");
}
// NVNT END
#endif
if (ModInfo().IsSinglePlayerOnly() && !ModInfo().NoDifficulty())
{
AddPage(new COptionsSubDifficulty(this), "#GameUI_Difficulty");
}
if (ModInfo().HasPortals())
{
AddPage(new COptionsSubPortal(this), "#GameUI_Portal");
}
AddPage(new COptionsSubKeyboard(this), "#GameUI_Keyboard");
AddPage(new COptionsSubMouse(this), "#GameUI_Mouse");
m_pOptionsSubAudio = new COptionsSubAudio(this);
AddPage(m_pOptionsSubAudio, "#GameUI_Audio");
m_pOptionsSubVideo = new COptionsSubVideo(this);
AddPage(m_pOptionsSubVideo, "#GameUI_Video");
if ( !ModInfo().IsSinglePlayerOnly() )
{
AddPage(new COptionsSubVoice(this), "#GameUI_Voice");
}
// add the multiplay page last, if we're combo single/multi or just multi
if ( (ModInfo().IsMultiplayerOnly() && !ModInfo().IsSinglePlayerOnly()) ||
(!ModInfo().IsMultiplayerOnly() && !ModInfo().IsSinglePlayerOnly()) )
{
m_pOptionsSubMultiplayer = new COptionsSubMultiplayer(this);
AddPage(m_pOptionsSubMultiplayer, "#GameUI_Multiplayer");
}
// double s5 = system()->GetCurrentTime();
// Msg("COptionsDialog::COptionsDialog(): %.3fms\n", (float)(s5 - s4) * 1000.0f);
SetApplyButtonVisible(true);
GetPropertySheet()->SetTabWidth(84);
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
COptionsDialog::~COptionsDialog()
{
}
//-----------------------------------------------------------------------------
// Purpose: Brings the dialog to the fore
//-----------------------------------------------------------------------------
void COptionsDialog::Activate()
{
BaseClass::Activate();
EnableApplyButton(false);
}
void COptionsDialog::OnKeyCodePressed( KeyCode code )
{
switch ( GetBaseButtonCode( code ) )
{
case KEY_XBUTTON_B:
OnCommand( "Cancel" );
return;
}
BaseClass::OnKeyCodePressed( code );
}
//-----------------------------------------------------------------------------
// Purpose: Opens the dialog
//-----------------------------------------------------------------------------
void COptionsDialog::Run()
{
SetTitle("#GameUI_Options", true);
Activate();
}
//-----------------------------------------------------------------------------
// Purpose: Called when the GameUI is hidden
//-----------------------------------------------------------------------------
void COptionsDialog::OnGameUIHidden()
{
// tell our children about it
for ( int i = 0 ; i < GetChildCount() ; i++ )
{
Panel *pChild = GetChild( i );
if ( pChild )
{
PostMessage( pChild, new KeyValues( "GameUIHidden" ) );
}
}
}

141
gameui/OptionsDialog.h Normal file
View File

@ -0,0 +1,141 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONSDIALOG_H
#define OPTIONSDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/PropertyDialog.h"
#include "vgui_controls/KeyRepeat.h"
//-----------------------------------------------------------------------------
// Purpose: Holds all the game option pages
//-----------------------------------------------------------------------------
class COptionsDialog : public vgui::PropertyDialog
{
DECLARE_CLASS_SIMPLE( COptionsDialog, vgui::PropertyDialog );
public:
COptionsDialog(vgui::Panel *parent);
~COptionsDialog();
void Run();
virtual void Activate();
void OnKeyCodePressed( vgui::KeyCode code );
vgui::PropertyPage* GetOptionsSubMultiplayer( void ) { return m_pOptionsSubMultiplayer; }
MESSAGE_FUNC( OnGameUIHidden, "GameUIHidden" ); // called when the GameUI is hidden
private:
class COptionsSubAudio *m_pOptionsSubAudio;
class COptionsSubVideo *m_pOptionsSubVideo;
vgui::PropertyPage *m_pOptionsSubMultiplayer;
};
#define OPTIONS_MAX_NUM_ITEMS 15
struct OptionData_t;
//-----------------------------------------------------------------------------
// Purpose: Holds all the game option pages
//-----------------------------------------------------------------------------
class COptionsDialogXbox : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( COptionsDialogXbox, vgui::Frame );
public:
COptionsDialogXbox( vgui::Panel *parent, bool bControllerOptions = false );
~COptionsDialogXbox();
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void ApplySettings( KeyValues *inResourceData );
virtual void OnClose();
virtual void OnKeyCodePressed( vgui::KeyCode code );
virtual void OnCommand(const char *command);
virtual void OnKeyCodeReleased( vgui::KeyCode code);
virtual void OnThink();
private:
void HandleInactiveKeyCodePressed( vgui::KeyCode code );
void HandleActiveKeyCodePressed( vgui::KeyCode code );
void HandleBindKeyCodePressed( vgui::KeyCode code );
int GetSelectionLabel( void ) { return m_iSelection - m_iScroll; }
void ActivateSelection( void );
void DeactivateSelection( void );
void ChangeSelection( int iChange );
void UpdateFooter( void );
void UpdateSelection( void );
void UpdateScroll( void );
void UncacheChoices( void );
void GetChoiceFromConvar( OptionData_t *pOption );
void ChangeValue( float fChange );
void UnbindOption( OptionData_t *pOption, int iLabel );
void UpdateValue( OptionData_t *pOption, int iLabel );
void UpdateBind( OptionData_t *pOption, int iLabel, ButtonCode_t codeIgnore = BUTTON_CODE_INVALID, ButtonCode_t codeAdd = BUTTON_CODE_INVALID );
void UpdateAllBinds( ButtonCode_t code );
void FillInDefaultBindings( void );
bool ShouldSkipOption( KeyValues *pKey );
void ReadOptionsFromFile( const char *pchFileName );
void SortOptions( void );
void InitializeSliderDefaults( void );
private:
bool m_bControllerOptions;
bool m_bOptionsChanged;
bool m_bOldForceEnglishAudio;
CFooterPanel *m_pFooter;
CUtlVector<OptionData_t*> *m_pOptions;
bool m_bSelectionActive;
OptionData_t *m_pSelectedOption;
int m_iSelection;
int m_iScroll;
int m_iSelectorYStart;
int m_iOptionSpacing;
int m_iNumItems;
int m_iXAxisState;
int m_iYAxisState;
float m_fNextChangeTime;
vgui::Panel *m_pOptionsSelectionLeft;
vgui::Panel *m_pOptionsSelectionLeft2;
vgui::Label *m_pOptionsUpArrow;
vgui::Label *m_pOptionsDownArrow;
vgui::Label *(m_pOptionLabels[ OPTIONS_MAX_NUM_ITEMS ]);
vgui::Label *(m_pValueLabels[ OPTIONS_MAX_NUM_ITEMS ]);
vgui::AnalogBar *(m_pValueBars[ OPTIONS_MAX_NUM_ITEMS ]);
vgui::HFont m_hLabelFont;
vgui::HFont m_hButtonFont;
Color m_SelectedColor;
vgui::CKeyRepeatHandler m_KeyRepeat;
int m_nButtonGap;
};
#endif // OPTIONSDIALOG_H

File diff suppressed because it is too large Load Diff

432
gameui/OptionsSubAudio.cpp Normal file
View File

@ -0,0 +1,432 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "OptionsSubAudio.h"
#include "cvarslider.h"
#include "EngineInterface.h"
#include "ModInfo.h"
#include "vgui_controls/ComboBox.h"
#include "vgui_controls/QueryBox.h"
#include "CvarToggleCheckButton.h"
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
#include <vgui/IInput.h>
#include <steam/steam_api.h>
#include <tier1/strtools.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
// This member is static so that the updated audio language can be referenced during shutdown
char* COptionsSubAudio::m_pchUpdatedAudioLanguage = (char*)GetLanguageShortName( k_Lang_English );
enum SoundQuality_e
{
SOUNDQUALITY_LOW,
SOUNDQUALITY_MEDIUM,
SOUNDQUALITY_HIGH,
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
COptionsSubAudio::COptionsSubAudio(vgui::Panel *parent) : PropertyPage(parent, NULL)
{
m_pSFXSlider = new CCvarSlider( this, "SFXSlider", "#GameUI_SoundEffectVolume", 0.0f, 1.0f, "volume" );
m_pMusicSlider = new CCvarSlider( this, "MusicSlider", "#GameUI_MusicVolume", 0.0f, 1.0f, "Snd_MusicVolume" );
m_pCloseCaptionCombo = new ComboBox( this, "CloseCaptionCheck", 6, false );
m_pCloseCaptionCombo->AddItem( "#GameUI_NoClosedCaptions", NULL );
m_pCloseCaptionCombo->AddItem( "#GameUI_SubtitlesAndSoundEffects", NULL );
m_pCloseCaptionCombo->AddItem( "#GameUI_Subtitles", NULL );
m_pSoundQualityCombo = new ComboBox( this, "SoundQuality", 6, false );
m_pSoundQualityCombo->AddItem( "#GameUI_High", new KeyValues("SoundQuality", "quality", SOUNDQUALITY_HIGH) );
m_pSoundQualityCombo->AddItem( "#GameUI_Medium", new KeyValues("SoundQuality", "quality", SOUNDQUALITY_MEDIUM) );
m_pSoundQualityCombo->AddItem( "#GameUI_Low", new KeyValues("SoundQuality", "quality", SOUNDQUALITY_LOW) );
m_pSpeakerSetupCombo = new ComboBox( this, "SpeakerSetup", 6, false );
#ifndef POSIX
m_pSpeakerSetupCombo->AddItem( "#GameUI_Headphones", new KeyValues("SpeakerSetup", "speakers", 0) );
#endif
m_pSpeakerSetupCombo->AddItem( "#GameUI_2Speakers", new KeyValues("SpeakerSetup", "speakers", 2) );
#ifndef POSIX
m_pSpeakerSetupCombo->AddItem( "#GameUI_4Speakers", new KeyValues("SpeakerSetup", "speakers", 4) );
m_pSpeakerSetupCombo->AddItem( "#GameUI_5Speakers", new KeyValues("SpeakerSetup", "speakers", 5) );
m_pSpeakerSetupCombo->AddItem( "#GameUI_7Speakers", new KeyValues("SpeakerSetup", "speakers", 7) );
#endif
m_pSpokenLanguageCombo = new ComboBox (this, "AudioSpokenLanguage", 6, false );
m_pSoundMuteLoseFocusCheckButton = new CCvarToggleCheckButton( this, "snd_mute_losefocus", "#GameUI_SndMuteLoseFocus", "snd_mute_losefocus" );
LoadControlSettings("Resource\\OptionsSubAudio.res");
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
COptionsSubAudio::~COptionsSubAudio()
{
}
//-----------------------------------------------------------------------------
// Purpose: Reloads data
//-----------------------------------------------------------------------------
void COptionsSubAudio::OnResetData()
{
m_bRequireRestart = false;
m_pSFXSlider->Reset();
m_pMusicSlider->Reset();
// reset the combo boxes
// close captions
ConVarRef closecaption("closecaption");
ConVarRef cc_subtitles("cc_subtitles");
if (closecaption.GetBool())
{
if (cc_subtitles.GetBool())
{
m_pCloseCaptionCombo->ActivateItem(2);
}
else
{
m_pCloseCaptionCombo->ActivateItem(1);
}
}
else
{
m_pCloseCaptionCombo->ActivateItem(0);
}
// speakers
ConVarRef snd_surround_speakers("Snd_Surround_Speakers");
int speakers = snd_surround_speakers.GetInt();
#ifdef POSIX
// On Posix there is no headphone option, so we upgrade to 2 speakers if Snd_Surround_Speakers == 0
if ( speakers == 0 )
speakers = 2;
#endif
// if Snd_Surround_Speakers is -1, then upgrade to 2 speakers
if ( speakers < 0 )
speakers = 2;
{for (int itemID = 0; itemID < m_pSpeakerSetupCombo->GetItemCount(); itemID++)
{
KeyValues *kv = m_pSpeakerSetupCombo->GetItemUserData( itemID );
if (kv && kv->GetInt( "speakers" ) == speakers)
{
m_pSpeakerSetupCombo->ActivateItem( itemID );
break;
}
}}
// sound quality is made up from several cvars
ConVarRef Snd_PitchQuality("Snd_PitchQuality");
ConVarRef dsp_slow_cpu("dsp_slow_cpu");
int quality = SOUNDQUALITY_LOW;
if (dsp_slow_cpu.GetBool() == false)
{
quality = SOUNDQUALITY_MEDIUM;
}
if (Snd_PitchQuality.GetBool())
{
quality = SOUNDQUALITY_HIGH;
}
// find the item in the list and activate it
{for (int itemID = 0; itemID < m_pSoundQualityCombo->GetItemCount(); itemID++)
{
KeyValues *kv = m_pSoundQualityCombo->GetItemUserData(itemID);
if (kv && kv->GetInt("quality") == quality)
{
m_pSoundQualityCombo->ActivateItem(itemID);
}
}}
//
// Audio Languages
//
char szCurrentLanguage[50];
char szAvailableLanguages[512];
szCurrentLanguage[0] = 0;
szAvailableLanguages[0] = 0;
// Fallback to current engine language
engine->GetUILanguage( szCurrentLanguage, sizeof( szCurrentLanguage ));
// In a Steam environment we get the current language
#if !defined( NO_STEAM )
// When Steam isn't running we can't get the language info...
if ( steamapicontext->SteamApps() )
{
Q_strncpy( szCurrentLanguage, steamapicontext->SteamApps()->GetCurrentGameLanguage(), sizeof(szCurrentLanguage) );
Q_strncpy( szAvailableLanguages, steamapicontext->SteamApps()->GetAvailableGameLanguages(), sizeof(szAvailableLanguages) );
}
#endif
// Get the spoken language and store it for comparison purposes
m_nCurrentAudioLanguage = PchLanguageToELanguage( szCurrentLanguage );
// Check to see if we have a list of languages from Steam
if ( V_strlen( szAvailableLanguages ) )
{
// Populate the combo box with each available language
CUtlVector<char*> languagesList;
V_SplitString( szAvailableLanguages, ",", languagesList );
for ( int i=0; i < languagesList.Count(); i++ )
{
const ELanguage languageCode = PchLanguageToELanguage( languagesList[i] );
m_pSpokenLanguageCombo->AddItem( GetLanguageVGUILocalization( languageCode ), new KeyValues ("Audio Languages", "language", languageCode) );
}
languagesList.PurgeAndDeleteElements();
}
else
{
// Add the current language to the combo
m_pSpokenLanguageCombo->AddItem( GetLanguageVGUILocalization( m_nCurrentAudioLanguage ), new KeyValues ("Audio Languages", "language", m_nCurrentAudioLanguage) );
}
// Activate the current language in the combo
{for (int itemID = 0; itemID < m_pSpokenLanguageCombo->GetItemCount(); itemID++)
{
KeyValues *kv = m_pSpokenLanguageCombo->GetItemUserData( itemID );
if ( kv && kv->GetInt( "language" ) == m_nCurrentAudioLanguage )
{
m_pSpokenLanguageCombo->ActivateItem( itemID );
break;
}
}}
m_pSoundMuteLoseFocusCheckButton->Reset();
}
//-----------------------------------------------------------------------------
// Purpose: Applies changes
//-----------------------------------------------------------------------------
void COptionsSubAudio::OnApplyChanges()
{
m_pSFXSlider->ApplyChanges();
m_pMusicSlider->ApplyChanges();
// set the cvars appropriately
// Tracker 28933: Note we can't do this because closecaption is marked
// FCVAR_USERINFO and it won't get sent to server is we direct set it, we
// need to pass it along to the engine parser!!!
// ConVar *closecaption = (ConVar *)cvar->FindVar("closecaption");
int closecaption_value = 0;
ConVarRef cc_subtitles( "cc_subtitles" );
switch (m_pCloseCaptionCombo->GetActiveItem())
{
default:
case 0:
closecaption_value = 0;
cc_subtitles.SetValue( 0 );
break;
case 1:
closecaption_value = 1;
cc_subtitles.SetValue( 0 );
break;
case 2:
closecaption_value = 1;
cc_subtitles.SetValue( 1 );
break;
}
// Stuff the close caption change to the console so that it can be
// sent to the server (FCVAR_USERINFO) so that you don't have to restart
// the level for the change to take effect.
char cmd[ 64 ];
Q_snprintf( cmd, sizeof( cmd ), "closecaption %i\n", closecaption_value );
engine->ClientCmd_Unrestricted( cmd );
ConVarRef snd_surround_speakers( "Snd_Surround_Speakers" );
int speakers = m_pSpeakerSetupCombo->GetActiveItemUserData()->GetInt( "speakers" );
snd_surround_speakers.SetValue( speakers );
// quality
ConVarRef Snd_PitchQuality( "Snd_PitchQuality" );
ConVarRef dsp_slow_cpu( "dsp_slow_cpu" );
int quality = m_pSoundQualityCombo->GetActiveItemUserData()->GetInt( "quality" );
switch ( quality )
{
case SOUNDQUALITY_LOW:
dsp_slow_cpu.SetValue(true);
Snd_PitchQuality.SetValue(false);
break;
case SOUNDQUALITY_MEDIUM:
dsp_slow_cpu.SetValue(false);
Snd_PitchQuality.SetValue(false);
break;
default:
Assert("Undefined sound quality setting.");
case SOUNDQUALITY_HIGH:
dsp_slow_cpu.SetValue(false);
Snd_PitchQuality.SetValue(true);
break;
};
// headphones at high quality get enhanced stereo turned on
ConVarRef dsp_enhance_stereo( "dsp_enhance_stereo" );
if (speakers == 0 && quality == SOUNDQUALITY_HIGH)
{
dsp_enhance_stereo.SetValue( 1 );
}
else
{
dsp_enhance_stereo.SetValue( 0 );
}
// Audio spoken language
KeyValues *kv = m_pSpokenLanguageCombo->GetItemUserData( m_pSpokenLanguageCombo->GetActiveItem() );
const ELanguage nUpdatedAudioLanguage = (ELanguage)( kv ? kv->GetInt( "language" ) : k_Lang_English );
if ( nUpdatedAudioLanguage != m_nCurrentAudioLanguage )
{
// Store new language in static member so that it can be accessed during shutdown when this instance is gone
m_pchUpdatedAudioLanguage = (char *) GetLanguageShortName( nUpdatedAudioLanguage );
// Inform user that they need to restart in order change language at this time
QueryBox *qb = new QueryBox( "#GameUI_ChangeLanguageRestart_Title", "#GameUI_ChangeLanguageRestart_Info", GetParent()->GetParent()->GetParent() );
if (qb != NULL)
{
qb->SetOKCommand( new KeyValues( "Command", "command", "RestartWithNewLanguage" ) );
qb->SetOKButtonText( "#GameUI_ChangeLanguageRestart_OkButton" );
qb->SetCancelButtonText( "#GameUI_ChangeLanguageRestart_CancelButton" );
qb->AddActionSignalTarget( GetParent()->GetParent()->GetParent() );
qb->DoModal();
}
}
m_pSoundMuteLoseFocusCheckButton->ApplyChanges();
}
//-----------------------------------------------------------------------------
// Purpose: Called on controls changing, enables the Apply button
//-----------------------------------------------------------------------------
void COptionsSubAudio::OnControlModified()
{
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
//-----------------------------------------------------------------------------
// Purpose: returns true if the engine needs to be restarted
//-----------------------------------------------------------------------------
bool COptionsSubAudio::RequiresRestart()
{
// nothing in audio requires a restart like now
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubAudio::OnCommand( const char *command )
{
if ( !stricmp( command, "TestSpeakers" ) )
{
// ask them if they REALLY want to test the speakers if they're in a game already.
if (engine->IsConnected())
{
QueryBox *qb = new QueryBox("#GameUI_TestSpeakersWarning_Title", "#GameUI_TestSpeakersWarning_Info" );
if (qb != NULL)
{
qb->SetOKCommand(new KeyValues("RunTestSpeakers"));
qb->SetOKButtonText("#GameUI_TestSpeakersWarning_OkButton");
qb->SetCancelButtonText("#GameUI_TestSpeakersWarning_CancelButton");
qb->AddActionSignalTarget( this );
qb->DoModal();
}
else
{
// couldn't create the warning dialog for some reason, so just test the speakers.
RunTestSpeakers();
}
}
else
{
// player isn't connected to a game so there's no reason to warn them about being disconnected.
// create the command to execute
RunTestSpeakers();
}
}
else if ( !stricmp( command, "ShowThirdPartyAudioCredits" ) )
{
OpenThirdPartySoundCreditsDialog();
}
BaseClass::OnCommand( command );
}
//-----------------------------------------------------------------------------
// Purpose: Run the test speakers map.
//-----------------------------------------------------------------------------
void COptionsSubAudio::RunTestSpeakers()
{
engine->ClientCmd_Unrestricted( "disconnect\nwait\nwait\nsv_lan 1\nsetmaster enable\nmaxplayers 1\n\nhostname \"Speaker Test\"\nprogress_enable\nmap test_speakers\n" );
}
//-----------------------------------------------------------------------------
// Purpose: third-party audio credits dialog
//-----------------------------------------------------------------------------
class COptionsSubAudioThirdPartyCreditsDlg : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( COptionsSubAudioThirdPartyCreditsDlg, vgui::Frame );
public:
COptionsSubAudioThirdPartyCreditsDlg( vgui::VPANEL hParent ) : BaseClass( NULL, NULL )
{
// parent is ignored, since we want look like we're steal focus from the parent (we'll become modal below)
SetTitle("#GameUI_ThirdPartyAudio_Title", true);
SetSize( 500, 200 );
LoadControlSettings( "resource/OptionsSubAudioThirdPartyDlg.res" );
MoveToCenterOfScreen();
SetSizeable( false );
SetDeleteSelfOnClose( true );
}
virtual void Activate()
{
BaseClass::Activate();
input()->SetAppModalSurface(GetVPanel());
}
void OnKeyCodeTyped(KeyCode code)
{
// force ourselves to be closed if the escape key it pressed
if (code == KEY_ESCAPE)
{
Close();
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
};
//-----------------------------------------------------------------------------
// Purpose: Open third party audio credits dialog
//-----------------------------------------------------------------------------
void COptionsSubAudio::OpenThirdPartySoundCreditsDialog()
{
if (!m_OptionsSubAudioThirdPartyCreditsDlg.Get())
{
m_OptionsSubAudioThirdPartyCreditsDlg = new COptionsSubAudioThirdPartyCreditsDlg(GetVParent());
}
m_OptionsSubAudioThirdPartyCreditsDlg->Activate();
}

65
gameui/OptionsSubAudio.h Normal file
View File

@ -0,0 +1,65 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONS_SUB_AUDIO_H
#define OPTIONS_SUB_AUDIO_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/PropertyPage.h"
#include <language.h>
class CLabeledCommandComboBox;
class CCvarSlider;
class CCvarToggleCheckButton;
//-----------------------------------------------------------------------------
// Purpose: Audio Details, Part of OptionsDialog
//-----------------------------------------------------------------------------
class COptionsSubAudio : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( COptionsSubAudio, vgui::PropertyPage );
public:
COptionsSubAudio(vgui::Panel *parent);
~COptionsSubAudio();
virtual void OnResetData();
virtual void OnApplyChanges();
virtual void OnCommand( const char *command );
bool RequiresRestart();
static char* GetUpdatedAudioLanguage() { return m_pchUpdatedAudioLanguage; }
private:
MESSAGE_FUNC( OnControlModified, "ControlModified" );
MESSAGE_FUNC( OnTextChanged, "TextChanged" )
{
OnControlModified();
}
MESSAGE_FUNC( RunTestSpeakers, "RunTestSpeakers" );
vgui::ComboBox *m_pSpeakerSetupCombo;
vgui::ComboBox *m_pSoundQualityCombo;
CCvarSlider *m_pSFXSlider;
CCvarSlider *m_pMusicSlider;
vgui::ComboBox *m_pCloseCaptionCombo;
bool m_bRequireRestart;
vgui::ComboBox *m_pSpokenLanguageCombo;
MESSAGE_FUNC( OpenThirdPartySoundCreditsDialog, "OpenThirdPartySoundCreditsDialog" );
vgui::DHANDLE<class COptionsSubAudioThirdPartyCreditsDlg> m_OptionsSubAudioThirdPartyCreditsDlg;
ELanguage m_nCurrentAudioLanguage;
static char *m_pchUpdatedAudioLanguage;
CCvarToggleCheckButton *m_pSoundMuteLoseFocusCheckButton;
};
#endif // OPTIONS_SUB_AUDIO_H

View File

@ -0,0 +1,79 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "OptionsSubDifficulty.h"
#include "tier1/convar.h"
#include "EngineInterface.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/RadioButton.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
COptionsSubDifficulty::COptionsSubDifficulty(vgui::Panel *parent) : BaseClass(parent, NULL)
{
m_pEasyRadio = new RadioButton(this, "Skill1Radio", "#GameUI_SkillEasy");
m_pNormalRadio = new RadioButton(this, "Skill2Radio", "#GameUI_SkillNormal");
m_pHardRadio = new RadioButton(this, "Skill3Radio", "#GameUI_SkillHard");
LoadControlSettings("Resource/OptionsSubDifficulty.res");
}
//-----------------------------------------------------------------------------
// Purpose: resets controls
//-----------------------------------------------------------------------------
void COptionsSubDifficulty::OnResetData()
{
ConVarRef var( "skill" );
if (var.GetInt() == 1)
{
m_pEasyRadio->SetSelected(true);
}
else if (var.GetInt() == 3)
{
m_pHardRadio->SetSelected(true);
}
else
{
m_pNormalRadio->SetSelected(true);
}
}
//-----------------------------------------------------------------------------
// Purpose: sets data based on control settings
//-----------------------------------------------------------------------------
void COptionsSubDifficulty::OnApplyChanges()
{
ConVarRef var( "skill" );
if ( m_pEasyRadio->IsSelected() )
{
var.SetValue( 1 );
}
else if ( m_pHardRadio->IsSelected() )
{
var.SetValue( 3 );
}
else
{
var.SetValue( 2 );
}
}
//-----------------------------------------------------------------------------
// Purpose: enables apply button on radio buttons being pressed
//-----------------------------------------------------------------------------
void COptionsSubDifficulty::OnRadioButtonChecked()
{
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}

View File

@ -0,0 +1,38 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONS_SUB_DIFFICULTY_H
#define OPTIONS_SUB_DIFFICULTY_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/PropertyPage.h"
//-----------------------------------------------------------------------------
// Purpose: Difficulty selection options
//-----------------------------------------------------------------------------
class COptionsSubDifficulty : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( COptionsSubDifficulty, vgui::PropertyPage );
public:
COptionsSubDifficulty(vgui::Panel *parent);
virtual void OnResetData();
virtual void OnApplyChanges();
MESSAGE_FUNC( OnRadioButtonChecked, "RadioButtonChecked" );
private:
vgui::RadioButton *m_pEasyRadio;
vgui::RadioButton *m_pNormalRadio;
vgui::RadioButton *m_pHardRadio;
};
#endif // OPTIONS_SUB_DIFFICULTY_H

41
gameui/OptionsSubGame.cpp Normal file
View File

@ -0,0 +1,41 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "OptionsSubGame.h"
#include "BasePanel.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
COptionsSubGame::COptionsSubGame( vgui::Panel *parent, const char *name ) : BaseClass( parent, name )
{
SetDeleteSelfOnClose( true );
LoadControlSettings( "Resource/OptionsSubGame.res" );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
COptionsSubGame::~COptionsSubGame()
{
}
void COptionsSubGame::OnClose( void )
{
BasePanel()->RunCloseAnimation( "CloseOptionsSubGame" );
BaseClass::OnClose();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubGame::OnCommand( const char *command )
{
BaseClass::OnCommand( command );
}

35
gameui/OptionsSubGame.h Normal file
View File

@ -0,0 +1,35 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONS_SUB_GAME_H
#define OPTIONS_SUB_GAME_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
//-----------------------------------------------------------------------------
// Purpose: Game Settings, Part of OptionsDialog
//-----------------------------------------------------------------------------
class COptionsSubGame : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( COptionsSubGame, vgui::Frame );
public:
COptionsSubGame( vgui::Panel *parent, const char *name );
~COptionsSubGame( void );
virtual void OnCommand( const char *command );
virtual void OnClose( void );
private:
};
#endif // OPTIONS_SUB_GAME_H

View File

@ -0,0 +1,196 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "OptionsSubHaptics.h"
//#include "CommandCheckButton.h"
#include "KeyToggleCheckButton.h"
#include "CvarNegateCheckButton.h"
#include "CvarToggleCheckButton.h"
#include "cvarslider.h"
#include "EngineInterface.h"
#include <KeyValues.h>
#include <vgui/IScheme.h>
#include "tier1/convar.h"
#include <stdio.h>
#include <vgui_controls/TextEntry.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
bool HasFalcon() {
ConVarRef hap_hasDevice("hap_hasDevice");
return (hap_hasDevice.IsValid() && hap_hasDevice.GetBool());
}
void COptionsSubHaptics::OnCommand(const char *command)
{
if ( !stricmp( command, "DoDefaults" ) )
{
engine->ClientCmd_Unrestricted("exec haptics_default.cfg");
OnResetData();
}
}
COptionsSubHaptics::COptionsSubHaptics(vgui::Panel *parent) : PropertyPage(parent, NULL)
{
m_pForceMasterPreLabel = new Label(this, "ForceMasterPreLabel", "#GameUI_Haptics_ForceMasterScale" );
m_pForceMasterSlider = new CCvarSlider( this, "ForceMasterSlider", "#GameUI_Haptics_ForceMasterScale",
0.000001f, 3.0f, "hap_ForceMasterScale", true );
m_pForceRecoilPreLabel = new Label(this, "ForceRecoilPreLabel", "#GameUI_Haptics_RecoilScale" );
m_pForceRecoilSlider = new CCvarSlider( this, "ForceRecoilSlider", "#GameUI_Haptics_RecoilScale",
0.000001f, 3.0f, "hap_ForceRecoilScale", true );
m_pForceDamagePreLabel = new Label(this, "ForceDamagePreLabel", "#GameUI_Haptics_DamageScale" );
m_pForceDamageSlider = new CCvarSlider( this, "ForceDamageSlider", "#GameUI_Haptics_DamageScale",
0.000001f, 5.0f, "hap_ForceDamageScale" , true );
m_pForceMovementPreLabel = new Label(this, "ForceMovementPreLabel", "#GameUI_Haptics_MovementScale" );
m_pForceMovementSlider = new CCvarSlider( this, "ForceMovementSlider", "#GameUI_Haptics_MovementScale",
0.000001f, 3.0f, "hap_ForceMovementScale", true );
//Player scaling
m_pPlayerBoxPreLabel = new Label(this, "PlayerBoxPreLabel", "#GameUI_Haptics_PlayerBoxLabel" );
m_pPlayerBoxScalePreLabel = new Label(this, "PlayerScalePreLabel", "#GameUI_Haptics_Scale" );
m_pPlayerBoxScale = new CCvarSlider( this, "PlayerBoxScaleSlider", "#GameUI_Haptics_PlayerBoxScale",
0.1f, 0.9f, "hap_PlayerBoxScale", true );
m_pPlayerBoxVisual = new ControlBoxVisual(this, "PlayerBoxVisual", m_pPlayerBoxScale, m_pPlayerBoxScale, m_pPlayerBoxScale, m_pPlayerBoxScale, m_pPlayerBoxScale, m_pPlayerBoxScale);
m_pPlayerBoxStiffnessPreLabel = new Label(this, "PlayerStiffnessPreLabel", "#GameUI_Haptics_PlayerBoxStiffness" );
m_pPlayerBoxStiffnessSlider = new CCvarSlider( this, "PlayerStiffnessSlider", "#GameUI_Haptics_PlayerBoxScale",
0.0f, 3.0f, "hap_PlayerBoxStiffness", true );
m_pPlayerBoxTurnPreLabel = new Label(this, "PlayerTurnPreLabel", "#GameUI_Haptics_Turning" );
m_pPlayerBoxTurnSlider = new CCvarSlider( this, "PlayerTurnSlider", "#GameUI_Haptics_Turning",
0.0f, 2.0f, "hap_PlayerTurnScale", true );
m_pPlayerBoxAimPreLabel = new Label(this, "PlayerAimPreLabel", "#GameUI_Haptics_Aiming" );
m_pPlayerBoxAimSlider = new CCvarSlider( this, "PlayerAimSlider", "#GameUI_Haptics_Aiming",
0.0f, 2.0f, "hap_PlayerAimScale", true );
//Vehicle Scaling
m_pVehicleBoxPreLabel = new Label(this, "VehicleBoxPreLabel", "#GameUI_Haptics_VehicleBoxLabel" );
m_pVehicleBoxScalePreLabel = new Label(this, "VehicleScalePreLabel", "#GameUI_Haptics_Scale" );
m_pVehicleBoxScale = new CCvarSlider( this, "VehicleBoxScaleSlider", "#GameUI_Haptics_VehicleBoxScale",
0.1f, 0.6f, "hap_VehicleBoxScale", true );
m_pVehicleBoxVisual = new ControlBoxVisual(this, "VehicleBoxVisual", m_pVehicleBoxScale, m_pVehicleBoxScale, m_pVehicleBoxScale, m_pVehicleBoxScale, m_pVehicleBoxScale, m_pVehicleBoxScale);
m_pVehicleBoxStiffnessPreLabel = new Label(this, "VehicleStiffnessPreLabel", "#GameUI_Haptics_VehicleBoxStiffness" );
m_pVehicleBoxStiffnessSlider = new CCvarSlider( this, "VehicleStiffnessSlider", "#GameUI_Haptics_VehicleBoxScale",
0.0f, 3.0f, "hap_VehicleBoxStiffness", true );
m_pVehicleBoxTurnPreLabel = new Label(this, "VehicleTurnPreLabel", "#GameUI_Haptics_Turning" );
m_pVehicleBoxTurnSlider = new CCvarSlider( this, "VehicleTurnSlider", "#GameUI_Haptics_Turning",
0.0f, 2.0f, "hap_VehicleTurnScale", true );
m_pVehicleBoxAimPreLabel = new Label(this, "VehicleAimPreLabel", "#GameUI_Haptics_Aiming" );
m_pVehicleBoxAimSlider = new CCvarSlider( this, "VehicleAimSlider", "#GameUI_Haptics_Aiming",
0.0f, 2.0f, "hap_VehicleAimScale", true );
vgui::Button *defaults = new vgui::Button( this, "Defaults", "Use Defaults" );
defaults->SetCommand("DoDefaults");
LoadControlSettings("Resource\\OptionsSubHaptics.res");
UpdateVehicleEnabled();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
COptionsSubHaptics::~COptionsSubHaptics()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubHaptics::OnResetData()
{
m_pForceMasterSlider->Reset();
m_pForceDamageSlider->Reset();
m_pForceRecoilSlider->Reset();
m_pForceMovementSlider->Reset();
m_pPlayerBoxScale->Reset();
m_pPlayerBoxStiffnessSlider->Reset();
m_pPlayerBoxTurnSlider->Reset();
m_pPlayerBoxAimSlider->Reset();
m_pVehicleBoxScale->Reset();
m_pVehicleBoxStiffnessSlider->Reset();
m_pVehicleBoxTurnSlider->Reset();
m_pVehicleBoxAimSlider->Reset();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubHaptics::OnApplyChanges()
{
m_pForceMasterSlider->ApplyChanges();
m_pForceDamageSlider->ApplyChanges();
m_pForceRecoilSlider->ApplyChanges();
m_pForceMovementSlider->ApplyChanges();
m_pPlayerBoxScale->ApplyChanges();
m_pPlayerBoxStiffnessSlider->ApplyChanges();
m_pPlayerBoxTurnSlider->ApplyChanges();
m_pPlayerBoxAimSlider->ApplyChanges();
m_pVehicleBoxScale->ApplyChanges();
m_pVehicleBoxStiffnessSlider->ApplyChanges();
m_pVehicleBoxTurnSlider->ApplyChanges();
m_pVehicleBoxAimSlider->ApplyChanges();
//Write out our config file
engine->ClientCmd_Unrestricted("writehapticconfig");
engine->ClientCmd_Unrestricted("reloadhaptics");
}
//-----------------------------------------------------------------------------
// Purpose: sets background color & border
//-----------------------------------------------------------------------------
void COptionsSubHaptics::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubHaptics::OnControlModified(Panel *panel)
{
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubHaptics::OnTextChanged(Panel *panel)
{
}
void COptionsSubHaptics::UpdateVehicleEnabled()
{
ConVarRef checkVehicle("hap_ui_vehicles");
checkVehicle.Init("hap_ui_vehicles",true);
bool bEnabled = checkVehicle.GetBool();
m_pVehicleBoxPreLabel->SetEnabled( bEnabled );
m_pVehicleBoxScalePreLabel->SetEnabled( bEnabled );
m_pVehicleBoxScale->SetEnabled( bEnabled );
m_pVehicleBoxStiffnessPreLabel->SetEnabled( bEnabled );
m_pVehicleBoxStiffnessSlider->SetEnabled( bEnabled );
m_pVehicleBoxTurnPreLabel->SetEnabled( bEnabled );
m_pVehicleBoxTurnSlider->SetEnabled( bEnabled );
m_pVehicleBoxAimPreLabel ->SetEnabled( bEnabled );
m_pVehicleBoxAimSlider ->SetEnabled( bEnabled );
}

100
gameui/OptionsSubHaptics.h Normal file
View File

@ -0,0 +1,100 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONS_SUB_HAPTICS_H
#define OPTIONS_SUB_HAPTICS_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/PropertyPage.h>
#include "HapticControlBox.h"
class CCvarNegateCheckButton;
class CKeyToggleCheckButton;
class CCvarToggleCheckButton;
class CCvarSlider;
namespace vgui
{
class Label;
class Panel;
}
//-----------------------------------------------------------------------------
// Purpose: Mouse Details, Part of OptionsDialog
//-----------------------------------------------------------------------------
class COptionsSubHaptics : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( COptionsSubHaptics, vgui::PropertyPage );
public:
COptionsSubHaptics(vgui::Panel *parent);
~COptionsSubHaptics();
virtual void OnResetData();
virtual void OnApplyChanges();
virtual void OnCommand(const char *command);
virtual void UpdateVehicleEnabled(void);
protected:
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
private:
MESSAGE_FUNC_PTR( OnControlModified, "ControlModified", panel );
MESSAGE_FUNC_PTR( OnTextChanged, "TextChanged", panel );
MESSAGE_FUNC_PTR( OnCheckButtonChecked, "CheckButtonChecked", panel )
{
OnControlModified( panel );
}
vgui::Label *m_pForceMasterPreLabel;
CCvarSlider *m_pForceMasterSlider;
vgui::Label *m_pForceRecoilPreLabel;
CCvarSlider *m_pForceRecoilSlider;
vgui::Label *m_pForceDamagePreLabel;
CCvarSlider *m_pForceDamageSlider;
vgui::Label *m_pForceMovementPreLabel;
CCvarSlider *m_pForceMovementSlider;
//Player
vgui::Label *m_pPlayerBoxPreLabel;
vgui::Label *m_pPlayerBoxScalePreLabel;
CCvarSlider * m_pPlayerBoxScale;
ControlBoxVisual* m_pPlayerBoxVisual;
vgui::Label *m_pPlayerBoxStiffnessPreLabel;
CCvarSlider *m_pPlayerBoxStiffnessSlider;
vgui::Label *m_pPlayerBoxTurnPreLabel;
CCvarSlider *m_pPlayerBoxTurnSlider;
vgui::Label *m_pPlayerBoxAimPreLabel;
CCvarSlider *m_pPlayerBoxAimSlider;
//Vehicle
vgui::Label *m_pVehicleBoxPreLabel;
vgui::Label *m_pVehicleBoxScalePreLabel;
CCvarSlider * m_pVehicleBoxScale;
ControlBoxVisual* m_pVehicleBoxVisual;
vgui::Label *m_pVehicleBoxStiffnessPreLabel;
CCvarSlider * m_pVehicleBoxStiffnessSlider;
vgui::Label *m_pVehicleBoxTurnPreLabel;
CCvarSlider *m_pVehicleBoxTurnSlider;
vgui::Label *m_pVehicleBoxAimPreLabel;
CCvarSlider *m_pVehicleBoxAimSlider;
//Control Box Stuff
};
#endif // OPTIONS_SUB_MOUSE_H

View File

@ -0,0 +1,839 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//===========================================================================//
#include "OptionsSubKeyboard.h"
#include "EngineInterface.h"
#include "vcontrolslistpanel.h"
#include <vgui_controls/Button.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/ListPanel.h>
#include <vgui_controls/QueryBox.h>
#include <vgui/Cursor.h>
#include <vgui/IVGui.h>
#include <vgui/ISurface.h>
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
#include <vgui/KeyCode.h>
#include <vgui/MouseCode.h>
#include <vgui/ISystem.h>
#include <vgui/IInput.h>
#include "filesystem.h"
#include "tier1/utlbuffer.h"
#include "IGameUIFuncs.h"
#include <vstdlib/IKeyValuesSystem.h>
#include "tier2/tier2.h"
#include "inputsystem/iinputsystem.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
COptionsSubKeyboard::COptionsSubKeyboard(vgui::Panel *parent) : PropertyPage(parent, NULL)
{
memset( m_Bindings, 0, sizeof( m_Bindings ));
// create the key bindings list
CreateKeyBindingList();
// Store all current key bindings
SaveCurrentBindings();
// Parse default descriptions
ParseActionDescriptions();
m_pSetBindingButton = new Button(this, "ChangeKeyButton", "");
m_pClearBindingButton = new Button(this, "ClearKeyButton", "");
LoadControlSettings("Resource/OptionsSubKeyboard.res");
m_pSetBindingButton->SetEnabled(false);
m_pClearBindingButton->SetEnabled(false);
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
COptionsSubKeyboard::~COptionsSubKeyboard()
{
DeleteSavedBindings();
}
//-----------------------------------------------------------------------------
// Purpose: reloads current keybinding
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::OnResetData()
{
// Populate list based on current settings
FillInCurrentBindings();
if ( IsVisible() )
{
m_pKeyBindList->SetSelectedItem(0);
}
}
//-----------------------------------------------------------------------------
// Purpose: saves out keybinding changes
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::OnApplyChanges()
{
ApplyAllBindings();
}
//-----------------------------------------------------------------------------
// Purpose: Create key bindings list control
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::CreateKeyBindingList()
{
// Create the control
m_pKeyBindList = new VControlsListPanel(this, "listpanel_keybindlist");
}
//-----------------------------------------------------------------------------
// Purpose: binds double-clicking or hitting enter in the keybind list to changing the key
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::OnKeyCodeTyped(vgui::KeyCode code)
{
if (code == KEY_ENTER)
{
OnCommand("ChangeKey");
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
//-----------------------------------------------------------------------------
// Purpose: command handler
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::OnCommand( const char *command )
{
if ( !stricmp( command, "Defaults" ) )
{
// open a box asking if we want to restore defaults
QueryBox *box = new QueryBox("#GameUI_KeyboardSettings", "#GameUI_KeyboardSettingsText");
box->AddActionSignalTarget(this);
box->SetOKCommand(new KeyValues("Command", "command", "DefaultsOK"));
box->DoModal();
}
else if ( !stricmp(command, "DefaultsOK"))
{
// Restore defaults from default keybindings file
FillInDefaultBindings();
m_pKeyBindList->RequestFocus();
}
else if ( !m_pKeyBindList->IsCapturing() && !stricmp( command, "ChangeKey" ) )
{
m_pKeyBindList->StartCaptureMode(dc_blank);
}
else if ( !m_pKeyBindList->IsCapturing() && !stricmp( command, "ClearKey" ) )
{
OnKeyCodePressed(KEY_DELETE);
m_pKeyBindList->RequestFocus();
}
else if ( !stricmp(command, "Advanced") )
{
OpenKeyboardAdvancedDialog();
}
else
{
BaseClass::OnCommand( command );
}
}
const char *UTIL_Parse( const char *data, char *token, int sizeofToken )
{
data = engine->ParseFile( data, token, sizeofToken );
return data;
}
static char *UTIL_CopyString( const char *in )
{
int len = strlen( in ) + 1;
char *out = new char[ len ];
Q_strncpy( out, in, len );
return out;
}
#ifndef _XBOX
char *UTIL_va(char *format, ...)
{
va_list argptr;
static char string[4][1024];
static int curstring = 0;
curstring = ( curstring + 1 ) % 4;
va_start (argptr, format);
Q_vsnprintf( string[curstring], 1024, format, argptr );
va_end (argptr);
return string[curstring];
}
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::ParseActionDescriptions( void )
{
char szBinding[256];
char szDescription[256];
KeyValues *item;
// Load the default keys list
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
if ( !g_pFullFileSystem->ReadFile( "scripts/kb_act.lst", NULL, buf ) )
return;
const char *data = (const char*)buf.Base();
int sectionIndex = 0;
char token[512];
while ( 1 )
{
data = UTIL_Parse( data, token, sizeof(token) );
// Done.
if ( strlen( token ) <= 0 )
break;
Q_strncpy( szBinding, token, sizeof( szBinding ) );
data = UTIL_Parse( data, token, sizeof(token) );
if ( strlen(token) <= 0 )
{
break;
}
Q_strncpy(szDescription, token, sizeof( szDescription ) );
// Skip '======' rows
if ( szDescription[ 0 ] != '=' )
{
// Flag as special header row if binding is "blank"
if (!stricmp(szBinding, "blank"))
{
// add header item
m_pKeyBindList->AddSection(++sectionIndex, szDescription);
m_pKeyBindList->AddColumnToSection(sectionIndex, "Action", szDescription, SectionedListPanel::COLUMN_BRIGHT, 286);
m_pKeyBindList->AddColumnToSection(sectionIndex, "Key", "#GameUI_KeyButton", SectionedListPanel::COLUMN_BRIGHT, 128);
}
else
{
// Create a new: blank item
item = new KeyValues( "Item" );
// fill in data
item->SetString("Action", szDescription);
item->SetString("Binding", szBinding);
item->SetString("Key", "");
// Add to list
m_pKeyBindList->AddItem(sectionIndex, item);
item->deleteThis();
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Search current data set for item which has the specified binding string
// Input : *binding - string to find
// Output : KeyValues or NULL on failure
//-----------------------------------------------------------------------------
KeyValues *COptionsSubKeyboard::GetItemForBinding( const char *binding )
{
static int bindingSymbol = KeyValuesSystem()->GetSymbolForString("Binding");
// Loop through all items
for (int i = 0; i < m_pKeyBindList->GetItemCount(); i++)
{
KeyValues *item = m_pKeyBindList->GetItemData(m_pKeyBindList->GetItemIDFromRow(i));
if ( !item )
continue;
KeyValues *bindingItem = item->FindKey(bindingSymbol);
const char *bindString = bindingItem->GetString();
// Check the "Binding" key
if (!stricmp(bindString, binding))
return item;
}
// Didn't find it
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Bind the specified keyname to the specified item
// Input : *item - Item to which to add the key
// *keyname - The key to be added
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::AddBinding( KeyValues *item, const char *keyname )
{
// See if it's already there as a binding
if ( !stricmp( item->GetString( "Key", "" ), keyname ) )
return;
// Make sure it doesn't live anywhere
RemoveKeyFromBindItems( item, keyname );
const char *binding = item->GetString( "Binding", "" );
// Loop through all the key bindings and set all entries that have
// the same binding. This allows us to have multiple entries pointing
// to the same binding.
for (int i = 0; i < m_pKeyBindList->GetItemCount(); i++)
{
KeyValues *curitem = m_pKeyBindList->GetItemData(m_pKeyBindList->GetItemIDFromRow(i));
if ( !curitem )
continue;
const char *curbinding = curitem->GetString( "Binding", "" );
if (!stricmp(curbinding, binding))
{
curitem->SetString( "Key", keyname );
m_pKeyBindList->InvalidateItem(i);
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Remove all keys from list
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::ClearBindItems( void )
{
for (int i = 0; i < m_pKeyBindList->GetItemCount(); i++)
{
KeyValues *item = m_pKeyBindList->GetItemData(m_pKeyBindList->GetItemIDFromRow(i));
if ( !item )
continue;
// Reset keys
item->SetString( "Key", "" );
m_pKeyBindList->InvalidateItem(i);
}
m_pKeyBindList->InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose: Remove all instances of the specified key from bindings
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::RemoveKeyFromBindItems( KeyValues *org_item, const char *key )
{
Assert( key && key[ 0 ] );
if ( !key || !key[ 0 ] )
return;
int len = Q_strlen( key );
char *pszKey = new char[len + 1];
if ( !pszKey )
return;
Q_memcpy( pszKey, key, len+1 );
for (int i = 0; i < m_pKeyBindList->GetItemCount(); i++)
{
KeyValues *item = m_pKeyBindList->GetItemData(m_pKeyBindList->GetItemIDFromRow(i));
if ( !item )
continue;
// If it's bound to the primary: then remove it
if ( !stricmp( pszKey, item->GetString( "Key", "" ) ) )
{
bool bClearEntry = true;
if ( org_item )
{
// Only clear it out if the actual binding isn't the same. This allows
// us to have the same key bound to multiple entries in the keybinding list
// if they point to the same command.
const char *org_binding = org_item->GetString( "Binding", "" );
const char *binding = item->GetString( "Binding", "" );
if ( !stricmp( org_binding, binding ) )
{
bClearEntry = false;
}
}
if ( bClearEntry )
{
item->SetString( "Key", "" );
m_pKeyBindList->InvalidateItem(i);
}
}
}
delete [] pszKey;
// Make sure the display is up to date
m_pKeyBindList->InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose: Ask the engine for all bindings and set up the list
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::FillInCurrentBindings( void )
{
// reset the unbind list
// we only unbind keys used by the normal config items (not custom binds)
m_KeysToUnbind.RemoveAll();
// Clear any current settings
ClearBindItems();
bool bJoystick = false;
ConVarRef var( "joystick" );
if ( var.IsValid() )
{
bJoystick = var.GetBool();
}
// NVNT see if we have a falcon connected.
bool bFalcon = false;
ConVarRef falconVar("hap_HasDevice");
if ( var.IsValid() )
{
bFalcon = var.GetBool();
}
for ( int i = 0; i < BUTTON_CODE_LAST; i++ )
{
// Look up binding
const char *binding = gameuifuncs->GetBindingForButtonCode( (ButtonCode_t)i );
if ( !binding )
continue;
// See if there is an item for this one?
KeyValues *item = GetItemForBinding( binding );
if ( item )
{
// Bind it by name
const char *keyName = g_pInputSystem->ButtonCodeToString( (ButtonCode_t)i );
// Already in list, means user had two keys bound to this item. We'll only note the first one we encounter
char const *currentKey = item->GetString( "Key", "" );
if ( currentKey && currentKey[ 0 ] )
{
ButtonCode_t currentBC = (ButtonCode_t)gameuifuncs->GetButtonCodeForBind( currentKey );
// If we're using a joystick, joystick bindings override keyboard ones
bool bShouldOverride = bJoystick && IsJoystickCode((ButtonCode_t)i) && !IsJoystickCode(currentBC);
// NVNT If we're not using a joystick, falcon bindings override keyboard ones
if( !bShouldOverride && bFalcon && IsNovintCode((ButtonCode_t)i) && !IsNovintCode(currentBC) )
bShouldOverride = true;
if ( !bShouldOverride )
continue;
// Remove the key we're about to override from the unbinding list
m_KeysToUnbind.FindAndRemove( currentKey );
}
AddBinding( item, keyName );
// remember to apply unbinding of this key when we apply
m_KeysToUnbind.AddToTail( keyName );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Clean up memory used by saved bindings
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::DeleteSavedBindings( void )
{
for ( int i = 0; i < BUTTON_CODE_LAST; i++ )
{
if ( m_Bindings[ i ].binding )
{
delete[] m_Bindings[ i ].binding;
m_Bindings[ i ].binding = NULL;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Copy all bindings into save array
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::SaveCurrentBindings( void )
{
DeleteSavedBindings();
for (int i = 0; i < BUTTON_CODE_LAST; i++)
{
const char *binding = gameuifuncs->GetBindingForButtonCode( (ButtonCode_t)i );
if ( !binding || !binding[0])
continue;
// Copy the binding string
m_Bindings[ i ].binding = UTIL_CopyString( binding );
}
}
//-----------------------------------------------------------------------------
// Purpose: Tells the engine to bind a key
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::BindKey( const char *key, const char *binding )
{
#ifndef _XBOX
engine->ClientCmd_Unrestricted( UTIL_va( "bind \"%s\" \"%s\"\n", key, binding ) );
#else
char buff[256];
Q_snprintf(buff, sizeof(buff), "bind \"%s\" \"%s\"\n", key, binding);
engine->ClientCmd_Unrestricted(buff);
#endif
}
//-----------------------------------------------------------------------------
// Purpose: Tells the engine to unbind a key
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::UnbindKey( const char *key )
{
#ifndef _XBOX
engine->ClientCmd_Unrestricted( UTIL_va( "unbind \"%s\"\n", key ) );
#else
char buff[256];
Q_snprintf(buff, sizeof(buff), "unbind \"%s\"\n", key);
engine->ClientCmd_Unrestricted(buff);
#endif
}
//-----------------------------------------------------------------------------
// Purpose: Go through list and bind specified keys to actions
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::ApplyAllBindings( void )
{
// unbind everything that the user unbound
{for (int i = 0; i < m_KeysToUnbind.Count(); i++)
{
UnbindKey(m_KeysToUnbind[i].String());
}}
m_KeysToUnbind.RemoveAll();
// free binding memory
DeleteSavedBindings();
for (int i = 0; i < m_pKeyBindList->GetItemCount(); i++)
{
KeyValues *item = m_pKeyBindList->GetItemData(m_pKeyBindList->GetItemIDFromRow(i));
if ( !item )
continue;
// See if it has a binding
const char *binding = item->GetString( "Binding", "" );
if ( !binding || !binding[ 0 ] )
continue;
const char *keyname;
// Check main binding
keyname = item->GetString( "Key", "" );
if ( keyname && keyname[ 0 ] )
{
// Tell the engine
BindKey( keyname, binding );
ButtonCode_t code = g_pInputSystem->StringToButtonCode( keyname );
if ( code != BUTTON_CODE_INVALID )
{
m_Bindings[ code ].binding = UTIL_CopyString( binding );
}
}
}
// Now exec their custom bindings
engine->ClientCmd_Unrestricted( "exec userconfig.cfg\nhost_writeconfig\n" );
}
//-----------------------------------------------------------------------------
// Purpose: Read in defaults from game's default config file and populate list
// using those defaults
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::FillInDefaultBindings( void )
{
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
if ( !g_pFullFileSystem->ReadFile( "cfg/config_default.cfg", NULL, buf ) )
return;
// Clear out all current bindings
ClearBindItems();
const char *data = (const char*)buf.Base();
// loop through all the binding
while ( data != NULL )
{
char cmd[64];
data = UTIL_Parse( data, cmd, sizeof(cmd) );
if ( strlen( cmd ) <= 0 )
break;
if ( !stricmp(cmd, "bind") )
{
// Key name
char szKeyName[256];
data = UTIL_Parse( data, szKeyName, sizeof(szKeyName) );
if ( strlen( szKeyName ) <= 0 )
break; // Error
char szBinding[256];
data = UTIL_Parse( data, szBinding, sizeof(szBinding) );
if ( strlen( szKeyName ) <= 0 )
break; // Error
// Find item
KeyValues *item = GetItemForBinding( szBinding );
if ( item )
{
// Bind it
AddBinding( item, szKeyName );
}
}
}
PostActionSignal(new KeyValues("ApplyButtonEnable"));
// Make sure console and escape key are always valid
KeyValues *item = GetItemForBinding( "toggleconsole" );
if (item)
{
// Bind it
AddBinding( item, "`" );
}
item = GetItemForBinding( "cancelselect" );
if (item)
{
// Bind it
AddBinding( item, "ESCAPE" );
}
}
//-----------------------------------------------------------------------------
// Purpose: User clicked on item: remember where last active row/column was
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::ItemSelected(int itemID)
{
m_pKeyBindList->SetItemOfInterest(itemID);
if (m_pKeyBindList->IsItemIDValid(itemID))
{
// find the details, see if we should be enabled/clear/whatever
m_pSetBindingButton->SetEnabled(true);
KeyValues *kv = m_pKeyBindList->GetItemData(itemID);
if (kv)
{
const char *key = kv->GetString("Key", NULL);
if (key && *key)
{
m_pClearBindingButton->SetEnabled(true);
}
else
{
m_pClearBindingButton->SetEnabled(false);
}
if (kv->GetInt("Header"))
{
m_pSetBindingButton->SetEnabled(false);
}
}
}
else
{
m_pSetBindingButton->SetEnabled(false);
m_pClearBindingButton->SetEnabled(false);
}
}
//-----------------------------------------------------------------------------
// Purpose: called when the capture has finished
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::Finish( ButtonCode_t code )
{
int r = m_pKeyBindList->GetItemOfInterest();
// Retrieve clicked row and column
m_pKeyBindList->EndCaptureMode( dc_arrow );
// Find item for this row
KeyValues *item = m_pKeyBindList->GetItemData(r);
if ( item )
{
// Handle keys: but never rebind the escape key
// Esc just exits bind mode silently
if ( code != BUTTON_CODE_NONE && code != KEY_ESCAPE && code != BUTTON_CODE_INVALID )
{
// Bind the named key
AddBinding( item, g_pInputSystem->ButtonCodeToString( code ) );
PostActionSignal( new KeyValues( "ApplyButtonEnable" ) );
}
m_pKeyBindList->InvalidateItem(r);
}
m_pSetBindingButton->SetEnabled(true);
m_pClearBindingButton->SetEnabled(true);
}
//-----------------------------------------------------------------------------
// Purpose: Scans for captured key presses
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::OnThink()
{
BaseClass::OnThink();
if ( m_pKeyBindList->IsCapturing() )
{
ButtonCode_t code = BUTTON_CODE_INVALID;
if ( engine->CheckDoneKeyTrapping( code ) )
{
Finish( code );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Check for enter key and go into keybinding mode if it was pressed
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::OnKeyCodePressed(vgui::KeyCode code)
{
// Enter key pressed and not already trapping next key/button press
if ( !m_pKeyBindList->IsCapturing() )
{
// Grab which item was set as interesting
int r = m_pKeyBindList->GetItemOfInterest();
// Check that it's visible
int x, y, w, h;
bool visible = m_pKeyBindList->GetCellBounds(r, 1, x, y, w, h);
if (visible)
{
if ( KEY_DELETE == code )
{
// find the current binding and remove it
KeyValues *kv = m_pKeyBindList->GetItemData(r);
const char *key = kv->GetString("Key", NULL);
if (key && *key)
{
RemoveKeyFromBindItems(NULL, key);
}
m_pClearBindingButton->SetEnabled(false);
m_pKeyBindList->InvalidateItem(r);
PostActionSignal(new KeyValues("ApplyButtonEnable"));
// message handled, don't pass on
return;
}
}
}
// Allow base class to process message instead
BaseClass::OnKeyCodePressed( code );
}
//-----------------------------------------------------------------------------
// Purpose: advanced keyboard settings dialog
//-----------------------------------------------------------------------------
class COptionsSubKeyboardAdvancedDlg : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( COptionsSubKeyboardAdvancedDlg, vgui::Frame );
public:
COptionsSubKeyboardAdvancedDlg( vgui::VPANEL hParent ) : BaseClass( NULL, NULL )
{
// parent is ignored, since we want look like we're steal focus from the parent (we'll become modal below)
SetTitle("#GameUI_KeyboardAdvanced_Title", true);
SetSize( 280, 140 );
LoadControlSettings( "resource/OptionsSubKeyboardAdvancedDlg.res" );
MoveToCenterOfScreen();
SetSizeable( false );
SetDeleteSelfOnClose( true );
}
virtual void Activate()
{
BaseClass::Activate();
input()->SetAppModalSurface(GetVPanel());
// reset the data
ConVarRef con_enable( "con_enable" );
if ( con_enable.IsValid() )
{
SetControlInt("ConsoleCheck", con_enable.GetInt() ? 1 : 0);
}
ConVarRef hud_fastswitch( "hud_fastswitch" );
if ( hud_fastswitch.IsValid() )
{
SetControlInt("FastSwitchCheck", hud_fastswitch.GetInt() ? 1 : 0);
}
}
virtual void OnApplyData()
{
// apply data
ConVarRef con_enable( "con_enable" );
con_enable.SetValue( GetControlInt( "ConsoleCheck", 0 ) );
ConVarRef hud_fastswitch( "hud_fastswitch" );
hud_fastswitch.SetValue( GetControlInt( "FastSwitchCheck", 0 ) );
}
virtual void OnCommand( const char *command )
{
if ( !stricmp(command, "OK") )
{
// apply the data
OnApplyData();
Close();
}
else
{
BaseClass::OnCommand( command );
}
}
void OnKeyCodeTyped(KeyCode code)
{
// force ourselves to be closed if the escape key it pressed
if (code == KEY_ESCAPE)
{
Close();
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
};
//-----------------------------------------------------------------------------
// Purpose: Open advanced keyboard options
//-----------------------------------------------------------------------------
void COptionsSubKeyboard::OpenKeyboardAdvancedDialog()
{
if (!m_OptionsSubKeyboardAdvancedDlg.Get())
{
m_OptionsSubKeyboardAdvancedDlg = new COptionsSubKeyboardAdvancedDlg(GetVParent());
}
m_OptionsSubKeyboardAdvancedDlg->Activate();
}

101
gameui/OptionsSubKeyboard.h Normal file
View File

@ -0,0 +1,101 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef OPTIONS_SUB_KEYBOARD_H
#define OPTIONS_SUB_KEYBOARD_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "utlsymbol.h"
#include <vgui_controls/PropertyPage.h>
class VControlsListPanel;
//-----------------------------------------------------------------------------
// Purpose: Keyboard Details, Part of OptionsDialog
//-----------------------------------------------------------------------------
class COptionsSubKeyboard : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( COptionsSubKeyboard, vgui::PropertyPage );
public:
COptionsSubKeyboard(vgui::Panel *parent);
~COptionsSubKeyboard();
virtual void OnResetData();
virtual void OnApplyChanges();
virtual void OnKeyCodePressed( vgui::KeyCode code );
virtual void OnThink();
// Trap row selection message
MESSAGE_FUNC_INT( ItemSelected, "ItemSelected", itemID );
private:
void Finish( ButtonCode_t code );
//-----------------------------------------------------------------------------
// Purpose: Used for saving engine keybindings in case user hits cancel button
//-----------------------------------------------------------------------------
struct KeyBinding
{
char *binding;
};
// Create the key binding list control
void CreateKeyBindingList( void );
virtual void OnCommand( const char *command );
// Tell engine to bind/unbind a key
void BindKey( const char *key, const char *binding );
void UnbindKey( const char *key );
// Save/restore/cleanup engine's current bindings ( for handling cancel button )
void SaveCurrentBindings( void );
void DeleteSavedBindings( void );
// Get column 0 action descriptions for all keys
void ParseActionDescriptions( void );
// Populate list of actions with current engine keybindings
void FillInCurrentBindings( void );
// Remove all current bindings from list of bindings
void ClearBindItems( void );
// Fill in bindings with mod-specified defaults
void FillInDefaultBindings( void );
// Copy bindings out of list and set them in the engine
void ApplyAllBindings( void );
// Bind a key to the item
void AddBinding( KeyValues *item, const char *keyname );
// Remove all instances of a key from all bindings
void RemoveKeyFromBindItems( KeyValues *org_item, const char *key );
// Find item by binding name
KeyValues *GetItemForBinding( const char *binding );
private:
void OpenKeyboardAdvancedDialog();
vgui::DHANDLE<class COptionsSubKeyboardAdvancedDlg> m_OptionsSubKeyboardAdvancedDlg;
virtual void OnKeyCodeTyped(vgui::KeyCode code);
VControlsListPanel *m_pKeyBindList;
vgui::Button *m_pSetBindingButton;
vgui::Button *m_pClearBindingButton;
// List of saved bindings for the keys
KeyBinding m_Bindings[ BUTTON_CODE_LAST ];
// List of all the keys that need to have their binding removed
CUtlVector<CUtlSymbol> m_KeysToUnbind;
};
#endif // OPTIONS_SUB_KEYBOARD_H

261
gameui/OptionsSubMouse.cpp Normal file
View File

@ -0,0 +1,261 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "OptionsSubMouse.h"
//#include "CommandCheckButton.h"
#include "KeyToggleCheckButton.h"
#include "CvarNegateCheckButton.h"
#include "CvarToggleCheckButton.h"
#include "cvarslider.h"
#include "EngineInterface.h"
#include <KeyValues.h>
#include <vgui/IScheme.h>
#include "tier1/convar.h"
#include <stdio.h>
#include <vgui_controls/TextEntry.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
COptionsSubMouse::COptionsSubMouse(vgui::Panel *parent) : PropertyPage(parent, NULL)
{
m_pReverseMouseCheckBox = new CCvarNegateCheckButton(
this,
"ReverseMouse",
"#GameUI_ReverseMouse",
"m_pitch" );
m_pMouseFilterCheckBox = new CCvarToggleCheckButton(
this,
"MouseFilter",
"#GameUI_MouseFilter",
"m_filter" );
m_pMouseRawCheckBox = new CCvarToggleCheckButton(
this,
"MouseRaw",
"#GameUI_MouseRaw",
"m_rawinput" );
m_pMouseAccelerationCheckBox = new CheckButton(
this,
"MouseAccelerationCheckbox",
"#GameUI_MouseCustomAccel" );
m_pJoystickCheckBox = new CCvarToggleCheckButton(
this,
"Joystick",
"#GameUI_Joystick",
"joystick" );
m_pJoystickSouthpawCheckBox = new CCvarToggleCheckButton(
this,
"JoystickSouthpaw",
"#GameUI_JoystickSouthpaw",
"joy_movement_stick" );
m_pReverseJoystickCheckBox = new CCvarToggleCheckButton(
this,
"ReverseJoystick",
"#GameUI_ReverseJoystick",
"joy_inverty" );
m_pQuickInfoCheckBox = new CCvarToggleCheckButton(
this,
"HudQuickInfo",
"#GameUI_HudQuickInfo",
"hud_quickinfo" );
m_pMouseSensitivitySlider = new CCvarSlider( this, "Slider", "#GameUI_MouseSensitivity",
0.1f, 6.0f, "sensitivity", true );
m_pMouseSensitivityLabel = new TextEntry(this, "SensitivityLabel");
m_pMouseSensitivityLabel->AddActionSignalTarget(this);
m_pMouseAccelExponentSlider = new CCvarSlider( this, "MouseAccelerationSlider", "#GameUI_MouseAcceleration",
1.0f, 1.4f, "m_customaccel_exponent", true );
m_pMouseAccelExponentLabel = new TextEntry(this, "MouseAccelerationLabel");
m_pMouseAccelExponentLabel->AddActionSignalTarget(this);
m_pJoyYawSensitivitySlider = new CCvarSlider( this, "JoystickYawSlider", "#GameUI_JoystickYawSensitivity",
-0.5f, -7.0f, "joy_yawsensitivity", true );
m_pJoyYawSensitivityPreLabel = new Label(this, "JoystickYawSensitivityPreLabel", "#GameUI_JoystickLookSpeedYaw" );
m_pJoyPitchSensitivitySlider = new CCvarSlider( this, "JoystickPitchSlider", "#GameUI_JoystickPitchSensitivity",
0.5f, 7.0f, "joy_pitchsensitivity", true );
m_pJoyPitchSensitivityPreLabel = new Label(this, "JoystickPitchSensitivityPreLabel", "#GameUI_JoystickLookSpeedPitch" );
LoadControlSettings("Resource\\OptionsSubMouse.res");
UpdateSensitivityLabel();
UpdateAccelerationLabel();
UpdateJoystickPanels();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
COptionsSubMouse::~COptionsSubMouse()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubMouse::OnResetData()
{
m_pReverseMouseCheckBox->Reset();
m_pMouseFilterCheckBox->Reset();
m_pMouseRawCheckBox->Reset();
m_pJoystickCheckBox->Reset();
m_pJoystickSouthpawCheckBox->Reset();
m_pMouseSensitivitySlider->Reset();
m_pMouseAccelExponentSlider->Reset();
m_pQuickInfoCheckBox->Reset();
m_pReverseJoystickCheckBox->Reset();
m_pJoyYawSensitivitySlider->Reset();
m_pJoyPitchSensitivitySlider->Reset();
ConVarRef m_customacel("m_customaccel");
if ( m_customacel.IsValid() )
m_pMouseAccelerationCheckBox->SetSelected( m_customacel.GetBool() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubMouse::OnApplyChanges()
{
m_pReverseMouseCheckBox->ApplyChanges();
m_pMouseFilterCheckBox->ApplyChanges();
m_pMouseRawCheckBox->ApplyChanges();
m_pJoystickCheckBox->ApplyChanges();
m_pJoystickSouthpawCheckBox->ApplyChanges();
m_pMouseSensitivitySlider->ApplyChanges();
m_pMouseAccelExponentSlider->ApplyChanges();
m_pQuickInfoCheckBox->ApplyChanges();
m_pReverseJoystickCheckBox->ApplyChanges();
m_pJoyYawSensitivitySlider->ApplyChanges();
m_pJoyPitchSensitivitySlider->ApplyChanges();
engine->ClientCmd_Unrestricted( "joyadvancedupdate" );
ConVarRef m_customacel("m_customaccel");
if ( m_customacel.IsValid() )
m_customacel.SetValue(m_pMouseAccelerationCheckBox->IsSelected() ? 3 : 0);
}
//-----------------------------------------------------------------------------
// Purpose: sets background color & border
//-----------------------------------------------------------------------------
void COptionsSubMouse::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubMouse::OnControlModified(Panel *panel)
{
PostActionSignal(new KeyValues("ApplyButtonEnable"));
// the HasBeenModified() check is so that if the value is outside of the range of the
// slider, it won't use the slider to determine the display value but leave the
// real value that we determined in the constructor
if (panel == m_pMouseSensitivitySlider && m_pMouseSensitivitySlider->HasBeenModified())
{
UpdateSensitivityLabel();
}
else if (panel == m_pMouseAccelExponentSlider && m_pMouseAccelExponentSlider->HasBeenModified())
{
UpdateAccelerationLabel();
}
else if (panel == m_pJoystickCheckBox)
{
UpdateJoystickPanels();
}
else if (panel == m_pMouseAccelerationCheckBox)
{
m_pMouseAccelExponentSlider->SetEnabled(m_pMouseAccelerationCheckBox->IsSelected());
m_pMouseAccelExponentLabel->SetEnabled(m_pMouseAccelerationCheckBox->IsSelected());
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubMouse::OnTextChanged(Panel *panel)
{
if ( panel == m_pMouseSensitivityLabel )
{
char buf[64];
m_pMouseSensitivityLabel->GetText(buf, 64);
float fValue;
int numParsed = sscanf(buf, "%f", &fValue);
if ( ( numParsed == 1 ) && ( fValue >= 0.0f ) )
{
m_pMouseSensitivitySlider->SetSliderValue(fValue);
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
return;
}
if ( panel == m_pMouseAccelExponentLabel )
{
char buf[64];
m_pMouseAccelExponentLabel->GetText(buf, 64);
float fValue = (float) atof(buf);
if (fValue >= 1.0)
{
m_pMouseAccelExponentSlider->SetSliderValue(fValue);
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubMouse::UpdateSensitivityLabel()
{
char buf[64];
Q_snprintf(buf, sizeof( buf ), " %.2f", m_pMouseSensitivitySlider->GetSliderValue());
m_pMouseSensitivityLabel->SetText(buf);
}
void COptionsSubMouse::UpdateAccelerationLabel()
{
char buf[64];
Q_snprintf(buf, sizeof( buf ), " %.2f", m_pMouseAccelExponentSlider->GetSliderValue());
m_pMouseAccelExponentLabel->SetText(buf);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubMouse::UpdateJoystickPanels()
{
bool bEnabled = m_pJoystickCheckBox->IsSelected();
m_pReverseJoystickCheckBox->SetEnabled( bEnabled );
m_pJoystickSouthpawCheckBox->SetEnabled( bEnabled );
m_pJoyYawSensitivitySlider->SetEnabled( bEnabled );
m_pJoyYawSensitivityPreLabel->SetEnabled( bEnabled );
m_pJoyPitchSensitivitySlider->SetEnabled( bEnabled );
m_pJoyPitchSensitivityPreLabel->SetEnabled( bEnabled );
}

80
gameui/OptionsSubMouse.h Normal file
View File

@ -0,0 +1,80 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONS_SUB_MOUSE_H
#define OPTIONS_SUB_MOUSE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/PropertyPage.h>
class CCvarNegateCheckButton;
class CKeyToggleCheckButton;
class CCvarToggleCheckButton;
class CCvarSlider;
namespace vgui
{
class Label;
class Panel;
}
//-----------------------------------------------------------------------------
// Purpose: Mouse Details, Part of OptionsDialog
//-----------------------------------------------------------------------------
class COptionsSubMouse : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( COptionsSubMouse, vgui::PropertyPage );
public:
COptionsSubMouse(vgui::Panel *parent);
~COptionsSubMouse();
virtual void OnResetData();
virtual void OnApplyChanges();
protected:
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
MESSAGE_FUNC_PTR( OnControlModified, "ControlModified", panel );
MESSAGE_FUNC_PTR( OnTextChanged, "TextChanged", panel );
MESSAGE_FUNC_PTR( OnCheckButtonChecked, "CheckButtonChecked", panel )
{
OnControlModified( panel );
}
void UpdateSensitivityLabel();
void UpdateAccelerationLabel();
void UpdateJoystickPanels();
private:
CCvarNegateCheckButton *m_pReverseMouseCheckBox;
CCvarToggleCheckButton *m_pMouseFilterCheckBox;
CCvarToggleCheckButton *m_pMouseRawCheckBox;
vgui::CheckButton *m_pMouseAccelerationCheckBox;
CCvarToggleCheckButton *m_pJoystickCheckBox;
CCvarToggleCheckButton *m_pJoystickSouthpawCheckBox;
CCvarToggleCheckButton *m_pQuickInfoCheckBox;
CCvarToggleCheckButton *m_pReverseJoystickCheckBox;
CCvarSlider *m_pMouseSensitivitySlider;
vgui::TextEntry *m_pMouseSensitivityLabel;
CCvarSlider *m_pMouseAccelExponentSlider;
vgui::TextEntry *m_pMouseAccelExponentLabel;
CCvarSlider *m_pJoyYawSensitivitySlider;
vgui::Label *m_pJoyYawSensitivityPreLabel;
CCvarSlider *m_pJoyPitchSensitivitySlider;
vgui::Label *m_pJoyPitchSensitivityPreLabel;
};
#endif // OPTIONS_SUB_MOUSE_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,113 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONSSUBMULTIPLAYER_H
#define OPTIONSSUBMULTIPLAYER_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/PropertyPage.h>
#include <vgui_controls/ImagePanel.h>
#include "imageutils.h"
class CLabeledCommandComboBox;
class CBitmapImagePanel;
class CCvarToggleCheckButton;
class CCvarTextEntry;
class CCvarSlider;
class CMultiplayerAdvancedDialog;
class COptionsSubMultiplayer;
class CrosshairImagePanelBase : public vgui::ImagePanel
{
DECLARE_CLASS_SIMPLE( CrosshairImagePanelBase, vgui::ImagePanel );
public:
CrosshairImagePanelBase( Panel *parent, const char *name ) : BaseClass(parent, name) {}
virtual void ResetData() {}
virtual void ApplyChanges() {}
virtual void UpdateVisibility() {}
};
//-----------------------------------------------------------------------------
// Purpose: multiplayer options property page
//-----------------------------------------------------------------------------
class COptionsSubMultiplayer : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( COptionsSubMultiplayer, vgui::PropertyPage );
public:
COptionsSubMultiplayer(vgui::Panel *parent);
~COptionsSubMultiplayer();
virtual vgui::Panel *CreateControlByName(const char *controlName);
MESSAGE_FUNC( OnControlModified, "ControlModified" );
protected:
// Called when page is loaded. Data should be reloaded from document into controls.
virtual void OnResetData();
// Called when the OK / Apply button is pressed. Changed data should be written into document.
virtual void OnApplyChanges();
virtual void OnCommand( const char *command );
private:
void InitModelList(CLabeledCommandComboBox *cb);
void InitLogoList(CLabeledCommandComboBox *cb);
void RemapModel();
void RemapLogo();
void ConversionError( ConversionErrorType nError );
MESSAGE_FUNC_PTR( OnTextChanged, "TextChanged", panel );
MESSAGE_FUNC_CHARPTR( OnFileSelected, "FileSelected", fullpath );
void ColorForName(char const *pszColorName, int &r, int &g, int &b);
CBitmapImagePanel *m_pModelImage;
CLabeledCommandComboBox *m_pModelList;
char m_ModelName[128];
vgui::ImagePanel *m_pLogoImage;
CLabeledCommandComboBox *m_pLogoList;
char m_LogoName[128];
CCvarSlider *m_pPrimaryColorSlider;
CCvarSlider *m_pSecondaryColorSlider;
CCvarToggleCheckButton *m_pHighQualityModelCheckBox;
// Mod specific general checkboxes
vgui::Dar< CCvarToggleCheckButton * > m_cvarToggleCheckButtons;
CCvarToggleCheckButton *m_pLockRadarRotationCheckbox;
CrosshairImagePanelBase *m_pCrosshairImage;
// --- client download filter
vgui::ComboBox *m_pDownloadFilterCombo;
// Begin Spray Import Functions
ConversionErrorType WriteSprayVMT(const char *vtfPath);
void SelectLogo(const char *logoName);
// End Spray Import Functions
int m_nLogoR;
int m_nLogoG;
int m_nLogoB;
#ifndef _XBOX
vgui::DHANDLE<CMultiplayerAdvancedDialog> m_hMultiplayerAdvancedDialog;
#endif
vgui::FileOpenDialog *m_hImportSprayDialog;
};
#endif // OPTIONSSUBMULTIPLAYER_H

View File

@ -0,0 +1,98 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "OptionsSubPortal.h"
#include "CvarToggleCheckButton.h"
#include "vgui_controls/ComboBox.h"
#include "EngineInterface.h"
#include <KeyValues.h>
#include <vgui/IScheme.h>
#include "tier1/convar.h"
#include <stdio.h>
#include <vgui_controls/TextEntry.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
COptionsSubPortal::COptionsSubPortal(vgui::Panel *parent) : PropertyPage(parent, NULL)
{
m_pPortalFunnelCheckBox = new CCvarToggleCheckButton(
this,
"PortalFunnel",
"#GameUI_PortalFunnel",
"sv_player_funnel_into_portals" );
m_pPortalDepthCombo = new ComboBox( this, "PortalDepth", 6, false );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth0", new KeyValues("PortalDepth", "depth", 0) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth1", new KeyValues("PortalDepth", "depth", 1) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth2", new KeyValues("PortalDepth", "depth", 2) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth3", new KeyValues("PortalDepth", "depth", 3) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth4", new KeyValues("PortalDepth", "depth", 4) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth5", new KeyValues("PortalDepth", "depth", 5) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth6", new KeyValues("PortalDepth", "depth", 6) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth7", new KeyValues("PortalDepth", "depth", 7) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth8", new KeyValues("PortalDepth", "depth", 8) );
m_pPortalDepthCombo->AddItem( "#GameUI_PortalDepth9", new KeyValues("PortalDepth", "depth", 9) );
LoadControlSettings("Resource\\OptionsSubPortal.res");
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
COptionsSubPortal::~COptionsSubPortal()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubPortal::OnResetData()
{
m_pPortalFunnelCheckBox->Reset();
// Portal render depth
ConVarRef r_portal_stencil_depth("r_portal_stencil_depth");
if ( r_portal_stencil_depth.IsValid() )
{
m_pPortalDepthCombo->ActivateItem(r_portal_stencil_depth.GetInt());
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubPortal::OnApplyChanges()
{
m_pPortalFunnelCheckBox->ApplyChanges();
// Portal render depth
if ( m_pPortalDepthCombo->IsEnabled() )
{
ConVarRef r_portal_stencil_depth( "r_portal_stencil_depth" );
r_portal_stencil_depth.SetValue( m_pPortalDepthCombo->GetActiveItem() );
}
}
//-----------------------------------------------------------------------------
// Purpose: sets background color & border
//-----------------------------------------------------------------------------
void COptionsSubPortal::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubPortal::OnControlModified()
{
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}

59
gameui/OptionsSubPortal.h Normal file
View File

@ -0,0 +1,59 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONS_SUB_PORTAL_H
#define OPTIONS_SUB_PORTAL_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/PropertyPage.h>
class CLabeledCommandComboBox;
class CCvarToggleCheckButton;
namespace vgui
{
class Label;
class Panel;
}
//-----------------------------------------------------------------------------
// Purpose: Mouse Details, Part of OptionsDialog
//-----------------------------------------------------------------------------
class COptionsSubPortal : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( COptionsSubPortal, vgui::PropertyPage );
public:
COptionsSubPortal(vgui::Panel *parent);
~COptionsSubPortal();
virtual void OnResetData();
virtual void OnApplyChanges();
protected:
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
private:
MESSAGE_FUNC( OnCheckButtonChecked, "CheckButtonChecked" )
{
OnControlModified();
}
MESSAGE_FUNC( OnControlModified, "ControlModified" );
MESSAGE_FUNC( OnTextChanged, "TextChanged" )
{
OnControlModified();
}
CCvarToggleCheckButton *m_pPortalFunnelCheckBox;
vgui::ComboBox *m_pPortalDepthCombo;
};
#endif // OPTIONS_SUB_MOUSE_H

1763
gameui/OptionsSubVideo.cpp Normal file

File diff suppressed because it is too large Load Diff

80
gameui/OptionsSubVideo.h Normal file
View File

@ -0,0 +1,80 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef OPTIONS_SUB_VIDEO_H
#define OPTIONS_SUB_VIDEO_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Panel.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/PropertyPage.h>
#include "EngineInterface.h"
#include "IGameUIFuncs.h"
#include "URLButton.h"
class CCvarSlider;
//-----------------------------------------------------------------------------
// Purpose: Video Details, Part of OptionsDialog
//-----------------------------------------------------------------------------
class COptionsSubVideo : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( COptionsSubVideo, vgui::PropertyPage );
public:
COptionsSubVideo(vgui::Panel *parent);
~COptionsSubVideo();
virtual void OnResetData();
virtual void OnApplyChanges();
virtual void PerformLayout();
virtual bool RequiresRestart();
private:
void SetCurrentResolutionComboItem();
void EnableOrDisableWindowedForVR();
MESSAGE_FUNC( OnDataChanged, "ControlModified" );
MESSAGE_FUNC_PTR_CHARPTR( OnTextChanged, "TextChanged", panel, text );
MESSAGE_FUNC( OpenAdvanced, "OpenAdvanced" );
MESSAGE_FUNC( LaunchBenchmark, "LaunchBenchmark" );
MESSAGE_FUNC( OpenGammaDialog, "OpenGammaDialog" );
void PrepareResolutionList();
bool BUseHDContent();
void SetUseHDContent( bool bUse );
int m_nSelectedMode; // -1 if we are running in a nonstandard mode
bool m_bDisplayedVRModeMessage;
vgui::ComboBox *m_pMode;
vgui::ComboBox *m_pWindowed;
vgui::ComboBox *m_pAspectRatio;
vgui::ComboBox *m_pVRMode;
vgui::Button *m_pGammaButton;
vgui::Button *m_pAdvanced;
vgui::Button *m_pBenchmark;
vgui::CheckButton *m_pHDContent;
vgui::DHANDLE<class COptionsSubVideoAdvancedDlg> m_hOptionsSubVideoAdvancedDlg;
vgui::DHANDLE<class CGammaDialog> m_hGammaDialog;
bool m_bRequireRestart;
MESSAGE_FUNC( OpenThirdPartyVideoCreditsDialog, "OpenThirdPartyVideoCreditsDialog" );
vgui::URLButton *m_pThirdPartyCredits;
vgui::DHANDLE<class COptionsSubVideoThirdPartyCreditsDlg> m_OptionsSubVideoThirdPartyCreditsDlg;
};
#endif // OPTIONS_SUB_VIDEO_H

334
gameui/OptionsSubVoice.cpp Normal file
View File

@ -0,0 +1,334 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "OptionsSubVoice.h"
#include "cvarslider.h"
#include <vgui/IVGui.h>
#include <vgui_controls/ImagePanel.h>
#include <vgui_controls/CheckButton.h>
#include <vgui_controls/Slider.h>
#include "EngineInterface.h"
#include "ivoicetweak.h"
#include "CvarToggleCheckButton.h"
#include "tier1/KeyValues.h"
#include "tier1/convar.h"
#include <steam/steam_api.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
COptionsSubVoice::COptionsSubVoice(vgui::Panel *parent) : PropertyPage(parent, NULL)
{
#if !defined( NO_VOICE ) //#ifndef _XBOX
m_pVoiceTweak = engine->GetVoiceTweakAPI();
#endif
m_pMicMeter = new ImagePanel(this, "MicMeter");
m_pMicMeter2 = new ImagePanel(this, "MicMeter2");
m_pReceiveSliderLabel = new Label(this, "ReceiveLabel", "#GameUI_VoiceReceiveVolume");
m_pReceiveVolume = new CCvarSlider( this, "VoiceReceive", "#GameUI_ReceiveVolume",
0.0f, 1.0f, "voice_scale" );
m_pMicrophoneSliderLabel = new Label(this, "MicrophoneLabel", "#GameUI_VoiceTransmitVolume");
m_pMicrophoneVolume = new Slider( this, "#GameUI_MicrophoneVolume" );
m_pMicrophoneVolume->SetRange( 0, 100 );
m_pMicrophoneVolume->AddActionSignalTarget( this );
m_pVoiceEnableCheckButton = new CCvarToggleCheckButton( this, "voice_modenable", "#GameUI_EnableVoice", "voice_modenable" );
m_pMicBoost = new CheckButton(this, "MicBoost", "#GameUI_BoostMicrophone" );
m_pMicBoost->AddActionSignalTarget( this );
m_pTestMicrophoneButton = new Button(this, "TestMicrophone", "#GameUI_TestMicrophone");
LoadControlSettings("Resource\\OptionsSubVoice.res");
m_bVoiceOn = false;
m_pMicMeter2->SetVisible(false);
// no voice tweak - then disable all buttons
if (!m_pVoiceTweak)
{
m_pReceiveVolume->SetEnabled(false);
m_pMicrophoneVolume->SetEnabled(false);
m_pVoiceEnableCheckButton->SetEnabled(false);
m_pMicBoost->SetEnabled(false);
m_pTestMicrophoneButton->SetEnabled(false);
}
else
{
OnResetData();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
COptionsSubVoice::~COptionsSubVoice()
{
// turn off voice if it was on, since we're leaving this page
if (m_bVoiceOn)
{
EndTestMicrophone();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::OnResetData()
{
if (!m_pVoiceTweak)
return;
float micVolume = m_pVoiceTweak->GetControlFloat( MicrophoneVolume );
m_pMicrophoneVolume->SetValue( (int)( 100.0f * micVolume ) );
m_nMicVolumeValue = m_pMicrophoneVolume->GetValue();
float fMicBoost = m_pVoiceTweak->GetControlFloat( MicBoost );
m_pMicBoost->SetSelected( fMicBoost != 0.0f );
m_bMicBoostSelected = m_pMicBoost->IsSelected();
m_pReceiveVolume->Reset();
m_fReceiveVolume = m_pReceiveVolume->GetSliderValue();
m_pVoiceEnableCheckButton->Reset();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::OnSliderMoved( int position )
{
if (m_pVoiceTweak)
{
if (m_pMicrophoneVolume->GetValue() != m_nMicVolumeValue)
{
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::OnCheckButtonChecked( int state )
{
if (m_pVoiceTweak)
{
// if our state is different
if ( m_pMicBoost->IsSelected() != m_bMicBoostSelected)
{
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::OnApplyChanges()
{
if (!m_pVoiceTweak)
return;
m_nMicVolumeValue = m_pMicrophoneVolume->GetValue();
float fMicVolume = (float) m_nMicVolumeValue / 100.0f;
m_pVoiceTweak->SetControlFloat( MicrophoneVolume, fMicVolume );
m_bMicBoostSelected = m_pMicBoost->IsSelected();
m_pVoiceTweak->SetControlFloat( MicBoost, m_bMicBoostSelected ? 1.0f : 0.0f );
m_pReceiveVolume->ApplyChanges();
m_fReceiveVolume = m_pReceiveVolume->GetSliderValue();
m_pVoiceEnableCheckButton->ApplyChanges();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::StartTestMicrophone()
{
if (!m_pVoiceTweak || m_bVoiceOn)
return;
m_bVoiceOn = true;
UseCurrentVoiceParameters();
if (m_pVoiceTweak->StartVoiceTweakMode())
{
m_pTestMicrophoneButton->SetText("#GameUI_StopTestMicrophone");
m_pReceiveVolume->SetEnabled(false);
m_pMicrophoneVolume->SetEnabled(false);
m_pVoiceEnableCheckButton->SetEnabled(false);
m_pMicBoost->SetEnabled(false);
m_pMicrophoneSliderLabel->SetEnabled(false);
m_pReceiveSliderLabel->SetEnabled(false);
m_pMicMeter2->SetVisible(true);
}
else
{
ResetVoiceParameters();
// we couldn't start it
m_bVoiceOn = false;
return;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::UseCurrentVoiceParameters()
{
int nVal = m_pMicrophoneVolume->GetValue();
float val = (float) nVal / 100.0f;
m_pVoiceTweak->SetControlFloat( MicrophoneVolume, val );
bool bSelected = m_pMicBoost->IsSelected();
val = bSelected ? 1.0f : 0.0f;
m_pVoiceTweak->SetControlFloat( MicBoost, val );
// get where the current slider is
m_nReceiveSliderValue = m_pReceiveVolume->GetValue();
m_pReceiveVolume->ApplyChanges();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::ResetVoiceParameters()
{
float fMicVolume = (float) m_nMicVolumeValue / 100.0f;
m_pVoiceTweak->SetControlFloat( MicrophoneVolume, fMicVolume );
m_pVoiceTweak->SetControlFloat( MicBoost, m_bMicBoostSelected ? 1.0f : 0.0f );
// restore the old value
ConVarRef voice_scale( "voice_scale" );
voice_scale.SetValue( m_fReceiveVolume );
m_pReceiveVolume->Reset();
// set the slider to 'new' value, but we've reset the 'start' value where it was
m_pReceiveVolume->SetValue(m_nReceiveSliderValue);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::EndTestMicrophone()
{
if (!m_pVoiceTweak || !m_bVoiceOn)
return;
if ( m_pVoiceTweak->IsStillTweaking() )
{
m_pVoiceTweak->EndVoiceTweakMode();
}
ResetVoiceParameters();
m_pTestMicrophoneButton->SetText("#GameUI_TestMicrophone");
m_bVoiceOn = false;
m_pReceiveVolume->SetEnabled(true);
m_pMicrophoneVolume->SetEnabled(true);
m_pVoiceEnableCheckButton->SetEnabled(true);
m_pMicBoost->SetEnabled(true);
m_pMicrophoneSliderLabel->SetEnabled(true);
m_pReceiveSliderLabel->SetEnabled(true);
m_pMicMeter2->SetVisible(false);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::OnCommand( const char *command)
{
if (!stricmp(command, "TestMicrophone"))
{
if (!m_bVoiceOn)
{
StartTestMicrophone();
}
else
{
EndTestMicrophone();
}
}
else if (!stricmp(command, "SteamVoiceSettings"))
{
if ( steamapicontext && steamapicontext->SteamFriends() )
{
steamapicontext->SteamFriends()->ActivateGameOverlay( "voicesettings" );
}
}
else
{
BaseClass::OnCommand(command);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::OnPageHide()
{
// turn off voice if it was on, since we're leaving this page
if (m_bVoiceOn)
{
EndTestMicrophone();
}
BaseClass::OnPageHide();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::OnControlModified()
{
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
#define BAR_WIDTH 160
#define BAR_INCREMENT 8
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void COptionsSubVoice::OnThink()
{
BaseClass::OnThink();
if (m_bVoiceOn)
{
if ( !m_pVoiceTweak->IsStillTweaking() )
{
DevMsg( 1, "Lost Voice Tweak channels, resetting\n" );
EndTestMicrophone();
}
else
{
float val = m_pVoiceTweak->GetControlFloat( SpeakingVolume );
int nValue = static_cast<int>( val*32768.0f + 0.5f );
int width = (BAR_WIDTH * nValue) / 32768;
width = ((width + (BAR_INCREMENT-1)) / BAR_INCREMENT) * BAR_INCREMENT; // round to nearest BAR_INCREMENT
int wide, tall;
m_pMicMeter2->GetSize(wide, tall);
m_pMicMeter2->SetSize(width, tall);
m_pMicMeter2->Repaint();
}
}
}

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