This commit is contained in:
2022-09-04 13:29:00 +03:00
parent 0c300339e1
commit 3226676b2d
351 changed files with 67885 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: A button with no borders that shows a left-pointing or down-pointing triangle
//
// $NoKeywords: $
//===========================================================================//
#ifndef EXPANDBUTTON_H
#define EXPANDBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/ToggleButton.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: A button with no borders that shows a left-pointing or down-pointing arrow
//-----------------------------------------------------------------------------
class ExpandButton : public ToggleButton
{
DECLARE_CLASS_SIMPLE( ExpandButton, ToggleButton );
public:
ExpandButton( Panel *parent, const char *panelName );
~ExpandButton();
// Expand the button (selected == expanded)
virtual void SetSelected( bool bExpand );
// sets whether or not the state of the check can be changed
// if this is set to false, then no input in the code or by the user can change it's state
void SetExpandable(bool state);
virtual void Paint();
protected:
virtual void ApplySchemeSettings(IScheme *pScheme);
MESSAGE_FUNC_PTR( OnExpanded, "Expanded", panel );
virtual IBorder *GetBorder(bool depressed, bool armed, bool selected, bool keyfocus);
/* MESSAGES SENT
"Expanded" - sent when the expand button state is changed
"state" - button state: 1 is expanded, 0 is unexpanded
*/
private:
bool m_bExpandable;
HFont m_hFont;
Color m_Color;
};
} // namespace vgui
#endif // EXPANDBUTTON_H

View File

@@ -0,0 +1,160 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Declaration of FileOpenDialog class, a generic open/save as file dialog
//
// $NoKeywords: $
//===========================================================================//
#ifndef FILEOPENDIALOG_H
#define FILEOPENDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
namespace vgui
{
class FileCompletionEdit; // local
class InputDialog;
//-----------------------------------------------------------------------------
// Purpose: generic open/save as file dialog
//-----------------------------------------------------------------------------
enum FileOpenDialogType_t
{
FOD_SAVE = 0,
FOD_OPEN,
FOD_SELECT_DIRECTORY,
};
class FileOpenDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( FileOpenDialog, Frame );
public:
// NOTE: Backward compat constructor
FileOpenDialog( Panel *parent, const char *title, bool bOpenFile, KeyValues *pContextKeyValues = 0 );
// The context keyvalues are added to all messages sent by this dialog if they are specified
FileOpenDialog( Panel *parent, const char *title, FileOpenDialogType_t type, KeyValues *pContextKeyValues = 0 );
~FileOpenDialog();
// Set the directory the file search starts in
void SetStartDirectory(const char *dir);
// Sets the start directory context (and resets the start directory in the process)
// NOTE: If you specify a startdir context, then if you've already opened
// a file with that same start dir context before, it will start in the
// same directory it ended up in.
void SetStartDirectoryContext( const char *pContext, const char *pDefaultDir );
// Add filters for the drop down combo box
// The filter info, if specified, gets sent back to the app in the FileSelected message
void AddFilter( const char *filter, const char *filterName, bool bActive, const char *pFilterInfo = NULL );
// Activate the dialog
// NOTE: The argument is there for backward compat
void DoModal( bool bUnused = false );
// Get the directory this is currently in
void GetCurrentDirectory( char *buf, int bufSize );
// Get the last selected file name
void GetSelectedFileName( char *buf, int bufSize );
/*
messages sent:
"FileSelected"
"fullpath" // specifies the fullpath of the file
"filterinfo" // Returns the filter info associated with the active filter
"FileSelectionCancelled"
*/
protected:
virtual void OnCommand( const char *command );
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void OnClose();
virtual void OnKeyCodeTyped(KeyCode code);
// handles the open button being pressed
// checks on what has changed and acts accordingly
MESSAGE_FUNC( OnOpen, "OnOpen" );
MESSAGE_FUNC( OnSelectFolder, "SelectFolder" );
MESSAGE_FUNC( OnFolderUp, "OnFolderUp" );
MESSAGE_FUNC( OnNewFolder, "OnNewFolder" );
MESSAGE_FUNC( OnOpenInExplorer, "OpenInExplorer" );
MESSAGE_FUNC( PopulateFileList, "PopulateFileList" );
MESSAGE_FUNC( PopulateDriveList, "PopulateDriveList" );
MESSAGE_FUNC( PopulateFileNameCompletion, "PopulateFileNameCompletion" );
// moves the directory structure up
virtual void MoveUpFolder();
// validates that the current path is valid
virtual void ValidatePath();
// handles an item in the list being selected
MESSAGE_FUNC( OnItemSelected, "ItemSelected" );
MESSAGE_FUNC( OnListItemSelected, "ListItemSelected" )
{
OnItemSelected();
}
// changes directories in response to selecting drives from the combo box
MESSAGE_FUNC_PARAMS( OnTextChanged, "TextChanged", kv );
MESSAGE_FUNC( OnInputCanceled, "InputCanceled" );
MESSAGE_FUNC_PARAMS( OnInputCompleted, "InputCompleted", data );
private:
// Necessary because we have 2 constructors
void Init( const char *title, KeyValues *pContextKeyValues );
// Does the specified extension match something in the filter list?
bool ExtensionMatchesFilter( const char *pExt );
// Choose the first non *.* filter in the filter list
void ChooseExtension( char *pExt, int nBufLen );
// Saves the file to the start dir context
void SaveFileToStartDirContext( const char *pFullPath );
// Posts a file selected message
void PostFileSelectedMessage( const char *pFileName );
// Creates a new folder
void NewFolder( char const *folderName );
vgui::ComboBox *m_pFullPathEdit;
vgui::ListPanel *m_pFileList;
FileCompletionEdit *m_pFileNameEdit;
vgui::ComboBox *m_pFileTypeCombo;
vgui::Button *m_pOpenButton;
vgui::Button *m_pCancelButton;
vgui::Button *m_pFolderUpButton;
vgui::Button *m_pNewFolderButton;
vgui::Button *m_pOpenInExplorerButton;
vgui::ImagePanel *m_pFolderIcon;
vgui::Label *m_pFileTypeLabel;
KeyValues *m_pContextKeyValues;
char m_szLastPath[1024];
unsigned short m_nStartDirContext;
FileOpenDialogType_t m_DialogType;
bool m_bFileSelected : 1;
VPANEL m_SaveModal;
vgui::DHANDLE< vgui::InputDialog > m_hInputDialog;
};
} // namespace vgui
#endif // FILEOPENDIALOG_H

View File

@@ -0,0 +1,172 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// This is a helper class designed to help with the chains of modal dialogs
// encountered when trying to open or save a particular file
//
//=============================================================================
#ifndef FILEOPENSTATEMACHINE_H
#define FILEOPENSTATEMACHINE_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Panel.h"
#include "tier1/utlstring.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
namespace vgui
{
//-----------------------------------------------------------------------------
// Interface for things using the file open state machine
//-----------------------------------------------------------------------------
abstract_class IFileOpenStateMachineClient
{
public:
// Called by to allow clients to set up the save dialog
virtual void SetupFileOpenDialog( vgui::FileOpenDialog *pDialog, bool bOpenFile, const char *pFileFormat, KeyValues *pContextKeyValues ) = 0;
// Called by to allow clients to actually read the file in
virtual bool OnReadFileFromDisk( const char *pFileName, const char *pFileFormat, KeyValues *pContextKeyValues ) = 0;
// Called by to allow clients to actually write the file out
virtual bool OnWriteFileToDisk( const char *pFileName, const char *pFileFormat, KeyValues *pContextKeyValues ) = 0;
};
//-----------------------------------------------------------------------------
// This is a helper class designed to help with chains of modal dialogs
//-----------------------------------------------------------------------------
enum FileOpenStateMachineFlags_t
{
FOSM_SHOW_PERFORCE_DIALOGS = 0x1,
FOSM_SHOW_SAVE_QUERY = 0x2,
};
class FileOpenStateMachine : public Panel
{
DECLARE_CLASS_SIMPLE( FileOpenStateMachine, Panel );
public:
enum CompletionState_t
{
IN_PROGRESS = 0, // Still not finished, not successful or error
SUCCESSFUL, // Operation finished successfully
FILE_SAVE_CANCELLED, // The user chose 'cancel' in the dialog asking if he wanted to save
FILE_SAVE_NAME_NOT_SPECIFIED, // User hit cancel in the SaveAs dialog
FILE_NOT_OVERWRITTEN, // Operation aborted; existed file and user chose to not write over it
FILE_NOT_CHECKED_OUT, // Operation aborted; file wasn't checked out so couldn't be written over
ERROR_WRITING_FILE, // Error occurred writing the file out
ERROR_MAKING_FILE_WRITEABLE, // Error occurred when making the file writeable
FILE_NOT_MADE_WRITEABLE, // User chose to not make the file be writeable
FILE_OPEN_NAME_NOT_SPECIFIED, // User hit cancel in the Open dialog
ERROR_READING_FILE, // Error occurred reading the file in
};
FileOpenStateMachine( vgui::Panel *pParent, IFileOpenStateMachineClient *pClient );
virtual ~FileOpenStateMachine();
// Opens a file, saves an existing one if necessary
void OpenFile( const char *pOpenFileType, KeyValues *pContextKeyValues, const char *pSaveFileName = NULL, const char *pSaveFileType = NULL, int nFlags = 0 );
// Version of OpenFile that skips browsing for a particular file to open
void OpenFile( const char *pOpenFileName, const char *pOpenFileType, KeyValues *pContextKeyValues, const char *pSaveFileName = NULL, const char *pSaveFileType = NULL, int nFlags = 0 );
// Used to save a specified file, and deal with all the lovely dialogs
// Pass in NULL to get a dialog to choose a filename to save
void SaveFile( KeyValues *pContextKeyValues, const char *pFileName, const char *pFileType, int nFlags = FOSM_SHOW_PERFORCE_DIALOGS );
// Returns the state machine completion state
CompletionState_t GetCompletionState();
/* MESSAGES SENT
"FileStateMachineFinished" - Called when we exit the state machine for any reason
"completionState" - See the CompletionState_t enum above
"wroteFile" - Indicates whether a file was written or not
"fullPath" - Indicates the full path of the file read for OpenFile or written for SaveFile
"fileType" - Indicates the file type of the file read for OpenFile or written for SaveFile
Use GetFirstTrueSubKey() to get the context passed into the OpenFile/SaveFile methods
*/
private:
enum FOSMState_t
{
STATE_NONE = -1,
STATE_SHOWING_SAVE_DIRTY_FILE_DIALOG = 0,
STATE_SHOWING_SAVE_DIALOG,
STATE_SHOWING_OVERWRITE_DIALOG,
STATE_SHOWING_CHECK_OUT_DIALOG,
STATE_SHOWING_MAKE_FILE_WRITEABLE_DIALOG,
STATE_WRITING_FILE,
STATE_SHOWING_PERFORCE_ADD_DIALOG,
STATE_SHOWING_OPEN_DIALOG,
STATE_READING_FILE,
};
MESSAGE_FUNC_PARAMS( OnFileSelected, "FileSelected", pKeyValues );
MESSAGE_FUNC( OnFileSelectionCancelled, "FileSelectionCancelled" );
MESSAGE_FUNC_PARAMS( OnPerforceQueryCompleted, "PerforceQueryCompleted", pKeyValues );
MESSAGE_FUNC( OnMakeFileWriteable, "MakeFileWriteable" );
MESSAGE_FUNC( OnCancelMakeFileWriteable, "CancelMakeFileWriteable" );
// These messages are related to the dialog in OverwriteFileDialog
MESSAGE_FUNC( OnOverwriteFile, "OverwriteFile" );
MESSAGE_FUNC( OnCancelOverwriteFile, "CancelOverwriteFile" );
// These messages come from the savedocumentquery dialog
MESSAGE_FUNC( OnSaveFile, "OnSaveFile" );
MESSAGE_FUNC( OnMarkNotDirty, "OnMarkNotDirty" );
MESSAGE_FUNC( OnCancelSaveDocument, "OnCancelSaveDocument" );
// Cleans up keyvalues
void CleanUpContextKeyValues();
// Utility to set the completion state
void SetCompletionState( CompletionState_t state );
// Show the save document query dialog
void ShowSaveQuery( );
// Shows the overwrite existing file dialog
void OverwriteFileDialog( );
// Shows the open file for edit dialog
void CheckOutDialog( );
// Shows the make file writeable dialog
void MakeFileWriteableDialog( );
// Writes the file out
void WriteFile();
// Shows the open file dialog
void OpenFileDialog( );
// Reads the file in
void ReadFile();
IFileOpenStateMachineClient *m_pClient;
KeyValues *m_pContextKeyValues;
FOSMState_t m_CurrentState;
CompletionState_t m_CompletionState;
CUtlString m_FileName;
CUtlString m_SaveFileType;
CUtlString m_OpenFileType;
CUtlString m_OpenFileName;
bool m_bShowPerforceDialogs : 1;
bool m_bShowSaveQuery : 1;
bool m_bIsOpeningFile : 1;
bool m_bWroteFile : 1;
};
} // end namespace vgui
#endif // FILEOPENSTATEMACHINE_H

View File

@@ -0,0 +1,61 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef FOCUSNAVGROUP_H
#define FOCUSNAVGROUP_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/PHandle.h>
namespace vgui
{
class Panel;
//-----------------------------------------------------------------------------
// Purpose: Handles navigation through a set of panels, with tab order & hotkeys
//-----------------------------------------------------------------------------
class FocusNavGroup
{
public:
FocusNavGroup(Panel *panel);
~FocusNavGroup();
virtual Panel *GetDefaultPanel(); // returns a pointer to the panel with the default focus
virtual void SetDefaultButton(Panel *panel); // sets which panel should receive input when ENTER is hit
virtual VPANEL GetDefaultButton(); // panel which receives default input when ENTER is hit, if current focused item cannot accept ENTER
virtual VPANEL GetCurrentDefaultButton(); // panel which receives input when ENTER is hit
virtual Panel *FindPanelByHotkey(wchar_t key); // finds the panel which is activated by the specified key
virtual bool RequestFocusPrev(VPANEL panel = NULL); // if panel is NULL, then the tab increment is based last known panel that had key focus
virtual bool RequestFocusNext(VPANEL panel = NULL);
virtual Panel *GetCurrentFocus();
virtual VPANEL SetCurrentFocus(VPANEL panel, VPANEL defaultPanel); // returns the Default panel
// sets the panel that owns this FocusNavGroup to be the root in the focus traversal heirarchy
// focus change via KEY_TAB will only travel to children of this main panel
virtual void SetFocusTopLevel(bool state);
virtual void SetCurrentDefaultButton(VPANEL panel, bool sendCurrentDefaultButtonMessage = true);
private:
bool CanButtonBeDefault(VPANEL panel);
VPanelHandle _defaultButton;
VPanelHandle _currentDefaultButton;
VPanelHandle _currentFocus;
Panel *_mainPanel;
bool _topLevelFocus;
};
} // namespace vgui
#endif // FOCUSNAVGROUP_H

View File

@@ -0,0 +1,260 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef VGUI_FRAME_H
#define VGUI_FRAME_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui/Dar.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/EditablePanel.h>
#include <vgui_controls/FocusNavGroup.h>
namespace vgui
{
class FrameButton;
class FrameSystemButton;
//-----------------------------------------------------------------------------
// Purpose: Windowed frame
//-----------------------------------------------------------------------------
class Frame : public EditablePanel
{
DECLARE_CLASS_SIMPLE( Frame, EditablePanel );
public:
Frame(Panel *parent, const char *panelName, bool showTaskbarIcon = true, bool bPopup = true );
virtual ~Frame();
// Set the text in the title bar. Set surfaceTitle=true if you want this to be the taskbar text as well.
virtual void SetTitle(const char *title, bool surfaceTitle);
virtual void SetTitle(const wchar_t *title, bool surfaceTitle);
// Bring the frame to the front and requests focus, ensures it's not minimized
virtual void Activate();
// activates the dialog; if dialog is not currently visible it starts it minimized and flashing in the taskbar
virtual void ActivateMinimized();
// closes the dialog
MESSAGE_FUNC( Close, "Close" );
MESSAGE_FUNC( CloseModal, "CloseModal" );
// sets the dialog to delete self on close
virtual void SetDeleteSelfOnClose( bool state );
// Move the dialog to the center of the screen
virtual void MoveToCenterOfScreen();
// Set the movability of the panel
virtual void SetMoveable(bool state);
// Check the movability of the panel
virtual bool IsMoveable();
// Set the resizability of the panel
virtual void SetSizeable(bool state);
// Check the resizability of the panel
virtual bool IsSizeable();
// Toggle visibility of the system menu button
virtual void SetMenuButtonVisible(bool state);
void SetMenuButtonResponsive(bool state);
// Toggle visibility of the minimize button
virtual void SetMinimizeButtonVisible(bool state);
// Toggle visibility of the maximize button
virtual void SetMaximizeButtonVisible(bool state);
// Toggles visibility of the minimize-to-systray icon (defaults to false)
virtual void SetMinimizeToSysTrayButtonVisible(bool state);
// Toggle visibility of the close button
virtual void SetCloseButtonVisible(bool state);
// returns true if the dialog is currently minimized
virtual bool IsMinimized();
// Flash the window system tray button until the frame gets focus
virtual void FlashWindow();
// Stops any window flashing
virtual void FlashWindowStop();
// command handling
virtual void OnCommand(const char *command);
// Get the system menu
virtual Menu *GetSysMenu();
// Set the system menu
virtual void SetSysMenu(Menu *menu);
// Set the system menu images
void SetImages( const char *pEnabledImage, const char *pDisabledImage = NULL );
// set whether the title bar should be rendered
virtual void SetTitleBarVisible( bool state );
// When moving via caption, don't let any part of window go outside parent's bounds
virtual void SetClipToParent( bool state );
virtual bool GetClipToParent() const;
// Set to true to make the caption height small
virtual void SetSmallCaption( bool state );
virtual bool IsSmallCaption() const;
virtual int GetDraggerSize();
virtual int GetCornerSize();
virtual int GetBottomRightSize();
virtual int GetCaptionHeight();
/* CUSTOM MESSAGE HANDLING
"SetTitle"
input: "text" - string to set the title to be
*/
// Load the control settings
virtual void LoadControlSettings( const char *dialogResourceName, const char *pathID = NULL, KeyValues *pPreloadedKeyValues = NULL, KeyValues *pConditions = NULL );
void SetChainKeysToParent( bool state );
bool CanChainKeysToParent() const;
// Shows the dialog in a modal fashion
virtual void DoModal();
void PlaceUnderCursor( );
// Disables the fade-in/out-effect even if configured in the scheme settings
void DisableFadeEffect( void );
// Temporarily enables or disables the fade effect rather than zeroing the fade times as done in DisableFadeEffect
void SetFadeEffectDisableOverride( bool disabled );
protected:
// Respond to mouse presses
virtual void OnMousePressed(MouseCode code);
// Respond to Key typing
virtual void OnKeyCodeTyped(KeyCode code);
virtual void OnKeyTyped(wchar_t unichar);
// Respond to Key releases
virtual void OnKeyCodeReleased(KeyCode code);
// Respond to Key focus ticks
virtual void OnKeyFocusTicked();
virtual void ApplySchemeSettings(IScheme *pScheme);
// Recalculate the position of all items
virtual void PerformLayout();
// Respond when a close message is recieved. Can be called directly to close a frame.
virtual void OnClose();
// Respond to a window finishing its closure. i.e. when a fading window has fully finished its fadeout.
virtual void OnFinishedClose();
// Minimize the window on the taskbar.
MESSAGE_FUNC( OnMinimize, "Minimize" );
// Called when minimize-to-systray button is pressed (does nothing by default)
virtual void OnMinimizeToSysTray();
// the frame close button was pressed
MESSAGE_FUNC( OnCloseFrameButtonPressed, "CloseFrameButtonPressed" );
// Add the child to the focus nav group
virtual void OnChildAdded(VPANEL child);
// settings
virtual void ApplySettings(KeyValues *inResourceData);
// records the settings into the resource data
virtual void GetSettings(KeyValues *outResourceData);
virtual const char *GetDescription( void );
// gets the default position and size on the screen to appear the first time (defaults to centered)
virtual bool GetDefaultScreenPosition(int &x, int &y, int &wide, int &tall);
// painting
virtual void PaintBackground();
// per-frame thinking, used for transition effects
virtual void OnThink();
// screen size
virtual void OnScreenSizeChanged(int iOldWide, int iOldTall);
// Get the size of the panel inside the frame edges.
virtual void GetClientArea(int &x, int &y, int &wide, int &tall);
// user configuration settings
// this is used for any control details the user wants saved between sessions
// eg. dialog positions, last directory opened, list column width
virtual void ApplyUserConfigSettings(KeyValues *userConfig);
// returns user config settings for this control
virtual void GetUserConfigSettings(KeyValues *userConfig);
// optimization, return true if this control has any user config settings
virtual bool HasUserConfigSettings();
private:
MESSAGE_FUNC_CHARPTR( InternalSetTitle, "SetTitle", text );
MESSAGE_FUNC( InternalFlashWindow, "FlashWindow" );
MESSAGE_FUNC_PARAMS( OnDialogVariablesChanged, "DialogVariables", dialogVariables );
void SetupResizeCursors();
void LayoutProportional( FrameButton *bt);
void FinishClose();
void OnFrameFocusChanged(bool bHasFocus);
Color _titleBarBgColor;
Color _titleBarDisabledBgColor;
Color _titleBarFgColor;
Color _titleBarDisabledFgColor;
Color m_InFocusBgColor;
Color m_OutOfFocusBgColor;
TextImage *_title;
#if !defined( _X360 )
Panel *_topGrip;
Panel *_bottomGrip;
Panel *_leftGrip;
Panel *_rightGrip;
Panel *_topLeftGrip;
Panel *_topRightGrip;
Panel *_bottomLeftGrip;
Panel *_bottomRightGrip;
Panel *_captionGrip;
FrameButton *_minimizeButton;
FrameButton *_maximizeButton;
FrameButton *_minimizeToSysTrayButton;
FrameButton *_closeButton;
FrameSystemButton *_menuButton;
Menu *_sysMenu;
#endif
float m_flTransitionEffectTime;
float m_flFocusTransitionEffectTime;
int m_iClientInsetX;
int m_iClientInsetY;
int m_iTitleTextInsetX;
int m_nGripperWidth;
VPANEL m_hPreviousModal;
HFont m_hCustomTitleFont;
bool _sizeable : 1;
bool _moveable : 1;
bool m_bHasFocus : 1;
bool _flashWindow : 1;
bool _nextFlashState : 1;
bool _drawTitleBar : 1;
bool m_bPreviouslyVisible : 1;
bool m_bFadingOut : 1;
bool m_bDeleteSelfOnClose : 1;
bool m_bDisableFadeEffect : 1;
bool m_bClipToParent : 1;
bool m_bSmallCaption : 1;
bool m_bChainKeysToParent : 1;
bool m_bPrimed : 1;
bool m_iClientInsetXOverridden : 1;
CPanelAnimationVarAliasType( int, m_iTitleTextInsetXOverride, "titletextinsetX", "0", "proportional_int" );
CPanelAnimationVar( int, m_iTitleTextInsetYOverride, "titletextinsetY", "0" );
};
} // namespace vgui
#endif // VGUI_FRAME_H

View File

@@ -0,0 +1,81 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef GRAPHPANEL_H
#define GRAPHPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Panel.h>
#include "utllinkedlist.h"
#include "utlvector.h"
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Holds and displays a chart
//-----------------------------------------------------------------------------
class GraphPanel : public Panel
{
DECLARE_CLASS_SIMPLE( GraphPanel, Panel );
public:
GraphPanel(Panel *parent, const char *name);
// domain settings (x-axis settings)
// sets the window of samples to display
void SetDisplayDomainSize(float size);
// sets the range of samples the graph should keep
// should be set to the max you would set the display domain size
void SetMaxDomainSize(float size);
// sets the minimum domain that will be displayed; used to collapse samples
void SetMinDomainSize(float size);
// range settings (y-axis settings)
void SetUseFixedRange(float lowRange, float highRange);
void SetUseDynamicRange(float *rangeList, int numRanges);
void GetDisplayedRange(float &lowRange, float &highRange);
// adds an item to the end of the list
// sampleEnd is assumed to be the trailing edge of the sample
// assumes that the samples are fairly evenly spaced (not much more work to do to fix this though)
void AddItem(float sampleEnd, float sampleValue);
protected:
virtual void Paint();
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme *pScheme);
private:
int GetVisibleItemCount();
struct Sample_t
{
float sampleEnd;
float value;
};
CUtlLinkedList<Sample_t, int> m_Samples;
// the window to show
float m_flDomainSize;
float m_flMaxDomainSize, m_flMinDomainSize;
bool m_bMaxDomainSizeSet;
// range
float m_flLowRange, m_flHighRange;
bool m_bUseDynamicRange;
CUtlVector<float> m_RangeList;
// rendering
int m_iGraphBarWidth;
int m_iGraphBarGapWidth;
};
} // namespace vgui
#endif // GRAPHPANEL_H

View File

@@ -0,0 +1,336 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Creates a HTML control
//
// $NoKeywords: $
//=============================================================================//
#ifndef HTML_H
#define HTML_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui/IImage.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/PHandle.h>
#include <vgui_controls/FileOpenDialog.h>
#include <vgui_controls/TextEntry.h>
#include <tier1/utlmap.h>
#ifndef VERSION_SAFE_STEAM_API_INTERFACES
#define VERSION_SAFE_STEAM_API_INTERFACES
#endif
#include "steam/steam_api.h"
class HTMLComboBoxHost;
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Control to display HTML content
// This control utilises a hidden IE window to render a HTML page for you.
// It can load any valid URL (i.e local files or web pages), you cannot dynamically change the
// content however (internally to the control that is).
//-----------------------------------------------------------------------------
class HTML: public Panel
{
DECLARE_CLASS_SIMPLE( HTML, Panel );
// TODO::STYLE
//DECLARE_STYLE_BASE( "HTML" );
public:
HTML(Panel *parent,const char *name, bool allowJavaScript = false, bool bPopupWindow = false);
~HTML();
// IHTML pass through functions
virtual void OpenURL( const char *URL, const char *pchPostData, bool bForce = false );
virtual bool StopLoading();
virtual bool Refresh();
virtual void OnMove();
virtual void RunJavascript( const char *pchScript );
virtual void GoBack();
virtual void GoForward();
virtual bool BCanGoBack();
virtual bool BCanGoFoward();
// event functions you can override and specialize behavior of
virtual bool OnStartRequest( const char *url, const char *target, const char *pchPostData, bool bIsRedirect );
virtual void OnFinishRequest(const char *url, const char *pageTitle, const CUtlMap < CUtlString, CUtlString > &headers ) {}
virtual void OnSetHTMLTitle( const char *pchTitle ) {}
virtual void OnLinkAtPosition( const char *pchURL ) {}
virtual void OnURLChanged( const char *url, const char *pchPostData, bool bIsRedirect ) {}
virtual bool OnOpenNewTab( const char *pchURL, bool bForeground ) { return false; }
// configuration
virtual void SetScrollbarsEnabled(bool state);
virtual void SetContextMenuEnabled(bool state);
virtual void SetViewSourceEnabled( bool state );
virtual void NewWindowsOnly( bool state );
bool IsScrolledToBottom();
bool IsScrollbarVisible();
// url handlers, lets you have web page links fire vgui events
// use to have custom web page links, eg. "steam://open/subscriptionpage"
// message contains "CustomURL", "url"
virtual void AddCustomURLHandler(const char *customProtocolName, vgui::Panel *target);
// overridden to paint our special web browser texture
virtual void Paint();
// pass messages to the texture component to tell it about resizes
virtual void OnSizeChanged(int wide,int tall);
// pass mouse clicks through
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code);
virtual void OnCursorMoved(int x,int y);
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnKeyTyped(wchar_t unichar);
virtual void OnKeyCodeTyped(KeyCode code);
virtual void OnKeyCodeReleased(KeyCode code);
virtual void PerformLayout();
virtual void OnMouseWheeled(int delta);
virtual void PostChildPaint();
/* message posting:
"HTMLSliderMoved" - indicates the scrollbar has moved
"OnURLChanged" - indicates a new URL is being loaded
"url"
"postdata"
"OnFinishRequest" - indicates all url loaded has completed
"HTMLBackRequested" - mouse4 has been pressed on the dialog
"HTMLForwardRequested" - mouse5 has been pressed on the dialog
"SecurityStatus" - indicates the SSL status of the page (disabled,good,bad)
"url"
"secure" - true if an ssl page
"certerror" - true if there is a cert error loading the page
"isevcert" - true if this is an EV style cert
"certname" - name of the entity this cert is issued to
*/
MESSAGE_FUNC_INT( OnSetCursorVGUI, "SetCursor", cursor );
virtual void OnCommand( const char *pchCommand );
void AddHeader( const char *pchHeader, const char *pchValue );
void OnKillFocus();
void OnSetFocus();
void Find( const char *pchSubStr );
void StopFind();
void FindNext();
void FindPrevious();
void ShowFindDialog();
void HideFindDialog();
bool FindDialogVisible();
int HorizontalScrollMax() { return m_scrollHorizontal.m_nMax; }
int VerticalScrollMax() { return m_scrollVertical.m_nMax; }
void GetLinkAtPosition( int x, int y );
void HidePopup();
#ifdef DBGFLAG_VALIDATE
virtual void Validate( CValidator &validator, const char *pchName )
{
ValidateObj( m_CustomURLHandlers );
BaseClass::Validate( validator, pchName );
}
#endif // DBGFLAG_VALIDATE
void PaintComboBox();
ISteamHTMLSurface *SteamHTMLSurface() { return m_SteamAPIContext.SteamHTMLSurface(); }
void OnHTMLMouseMoved( int x, int y )
{
if ( m_SteamAPIContext.SteamHTMLSurface() )
m_SteamAPIContext.SteamHTMLSurface()->MouseMove( m_unBrowserHandle, x, y );
}
protected:
virtual void ApplySchemeSettings( IScheme *pScheme );
friend class HTMLComboBoxHost;
vgui::Menu *m_pContextMenu;
private:
STEAM_CALLBACK( HTML, BrowserNeedsPaint, HTML_NeedsPaint_t, m_NeedsPaint );
STEAM_CALLBACK( HTML, BrowserComboNeedsPaint, HTML_ComboNeedsPaint_t, m_ComboNeedsPaint );
STEAM_CALLBACK( HTML, BrowserStartRequest, HTML_StartRequest_t, m_StartRequest );
STEAM_CALLBACK( HTML, BrowserURLChanged, HTML_URLChanged_t, m_URLChanged );
STEAM_CALLBACK( HTML, BrowserFinishedRequest, HTML_FinishedRequest_t, m_FinishedRequest );
STEAM_CALLBACK( HTML, BrowserShowPopup, HTML_ShowPopup_t, m_ShowPopup );
STEAM_CALLBACK( HTML, BrowserHidePopup, HTML_HidePopup_t, m_HidePopup );
STEAM_CALLBACK( HTML, BrowserSizePopup, HTML_SizePopup_t, m_SizePopup );
STEAM_CALLBACK( HTML, BrowserOpenNewTab, HTML_OpenLinkInNewTab_t, m_LinkInNewTab );
STEAM_CALLBACK( HTML, BrowserSetHTMLTitle, HTML_ChangedTitle_t, m_ChangeTitle );
STEAM_CALLBACK( HTML, BrowserPopupHTMLWindow, HTML_NewWindow_t, m_NewWindow );
STEAM_CALLBACK( HTML, BrowserFileLoadDialog, HTML_FileOpenDialog_t, m_FileLoadDialog );
STEAM_CALLBACK( HTML, BrowserSearchResults, HTML_SearchResults_t, m_SearchResults );
STEAM_CALLBACK( HTML, BrowserClose, HTML_CloseBrowser_t, m_CloseBrowser );
STEAM_CALLBACK( HTML, BrowserHorizontalScrollBarSizeResponse, HTML_HorizontalScroll_t, m_HorizScroll );
STEAM_CALLBACK( HTML, BrowserVerticalScrollBarSizeResponse, HTML_VerticalScroll_t, m_VertScroll );
STEAM_CALLBACK( HTML, BrowserLinkAtPositionResponse, HTML_LinkAtPosition_t, m_LinkAtPosResp );
STEAM_CALLBACK( HTML, BrowserJSAlert, HTML_JSAlert_t, m_JSAlert );
STEAM_CALLBACK( HTML, BrowserJSConfirm, HTML_JSConfirm_t, m_JSConfirm );
STEAM_CALLBACK( HTML, BrowserCanGoBackandForward, HTML_CanGoBackAndForward_t, m_CanGoBackForward );
STEAM_CALLBACK( HTML, BrowserSetCursor, HTML_SetCursor_t, m_SetCursor );
STEAM_CALLBACK( HTML, BrowserStatusText, HTML_StatusText_t, m_StatusText );
STEAM_CALLBACK( HTML, BrowserShowToolTip, HTML_ShowToolTip_t, m_ShowTooltip );
STEAM_CALLBACK( HTML, BrowserUpdateToolTip, HTML_UpdateToolTip_t, m_UpdateTooltip );
STEAM_CALLBACK( HTML, BrowserHideToolTip, HTML_HideToolTip_t, m_HideTooltip );
void OnBrowserReady( HTML_BrowserReady_t *pBrowserReady, bool bIOFailure );
void PostURL(const char *URL, const char *pchPostData, bool force);
virtual void BrowserResize();
void UpdateSizeAndScrollBars();
MESSAGE_FUNC( OnSliderMoved, "ScrollBarSliderMoved" );
MESSAGE_FUNC_CHARPTR( OnFileSelected, "FileSelected", fullpath );
MESSAGE_FUNC( OnFileSelectionCancelled, "FileSelectionCancelled" );
MESSAGE_FUNC_PTR( OnTextChanged, "TextChanged", panel );
MESSAGE_FUNC_PTR( OnEditNewLine, "TextNewLine", panel );
MESSAGE_FUNC_INT( DismissJSDialog, "DismissJSDialog", result );
vgui::Panel *m_pInteriorPanel;
vgui::ScrollBar *_hbar,*_vbar;
vgui::DHANDLE<vgui::FileOpenDialog> m_hFileOpenDialog;
class CHTMLFindBar : public vgui::EditablePanel
{
DECLARE_CLASS_SIMPLE( CHTMLFindBar, EditablePanel );
public:
CHTMLFindBar( HTML *parent );
void SetText( const char *pchText ) { m_pFindBar->SetText( pchText ); }
void GetText( char *pText, int ccText ) { m_pFindBar->GetText( pText, ccText ); }
void OnCommand( const char *pchCmd );
void ShowCountLabel() { m_pFindCountLabel->SetVisible( true ); }
void HideCountLabel() { m_pFindCountLabel->SetVisible( false ); }
void SetHidden( bool bState ) { m_bHidden = bState; }
bool BIsHidden() { return m_bHidden; }
private:
vgui::TextEntry *m_pFindBar;
vgui::HTML *m_pParent;
vgui::Label *m_pFindCountLabel;
bool m_bHidden;
};
CHTMLFindBar *m_pFindBar;
HTMLComboBoxHost *m_pComboBoxHost;
int m_iMouseX,m_iMouseY; // where the mouse is on the control
int m_iScrollBorderX,m_iScrollBorderY;
int m_iWideLastHTMLSize, m_iTalLastHTMLSize;
int m_iCopyLinkMenuItemID;
bool m_bScrollBarEnabled;
bool m_bContextMenuEnabled;
int m_iScrollbarSize;
bool m_bNewWindowsOnly;
int m_nViewSourceAllowedIndex;
CUtlString m_sDragURL;
int m_iDragStartX, m_iDragStartY;
struct CustomURLHandler_t
{
PHandle hPanel;
char url[32];
};
CUtlVector<CustomURLHandler_t> m_CustomURLHandlers;
int m_iHTMLTextureID; // vgui texture id
// Track the texture width and height requested so we can tell
// when the size has changed and reallocate the texture.
int m_allocedTextureWidth;
int m_allocedTextureHeight;
int m_iComboBoxTextureID; // vgui texture id of the combo box
bool m_bNeedsFullTextureUpload;
int m_allocedComboBoxWidth;
int m_allocedComboBoxHeight;
CUtlString m_sCurrentURL; // the url of our current page
// find in page state
bool m_bInFind;
CUtlString m_sLastSearchString;
bool m_bCanGoBack; // cache of forward and back state
bool m_bCanGoForward;
struct LinkAtPos_t
{
LinkAtPos_t() { m_nX = m_nY = 0; }
uint32 m_nX;
uint32 m_nY;
CUtlString m_sURL;
};
LinkAtPos_t m_LinkAtPos; // cache for link at pos requests, because the request is async
bool m_bRequestingDragURL; // true if we need a response for a drag url loc
bool m_bRequestingCopyLink; // true if we wanted to copy the link under the cursor
struct ScrollData_t
{
ScrollData_t()
{
m_bVisible = false;
m_nMax = m_nScroll = 0;
}
bool operator==( ScrollData_t const &src ) const
{
return m_bVisible == src.m_bVisible &&
m_nMax == src.m_nMax &&
m_nScroll == src.m_nScroll;
}
bool operator!=( ScrollData_t const &src ) const
{
return !operator==(src);
}
bool m_bVisible; // is the scroll bar visible
int m_nMax; // most amount of pixels we can scroll
int m_nScroll; // currently scrolled amount of pixels
float m_flZoom; // zoom level this scroll bar is for
};
ScrollData_t m_scrollHorizontal; // details of horizontal scroll bar
ScrollData_t m_scrollVertical; // details of vertical scroll bar
float m_flZoom; // current page zoom level
CUtlString m_sPendingURLLoad; // cache of url to load if we get a PostURL before the cef object is mage
CUtlString m_sPendingPostData; // cache of the post data for above
struct CustomCursorCache_t
{
CustomCursorCache_t() {}
CustomCursorCache_t( const void *pchData ) { m_pchData = pchData; }
float m_CacheTime; // the time we cached the cursor
CursorCode m_Cursor; // the vgui handle to it
const void *m_pchData; // the pointer to the cursor char data so we can detect the same cursor being used
bool operator==(const CustomCursorCache_t& rhs) const
{
return m_pchData == rhs.m_pchData ;
}
};
CUtlVector<CustomCursorCache_t> m_vecHCursor;
CSteamAPIContext m_SteamAPIContext;
HHTMLBrowser m_unBrowserHandle;
CCallResult< HTML, HTML_BrowserReady_t > m_SteamCallResultBrowserReady;
};
} // namespace vgui
#endif // HTML_H

View File

@@ -0,0 +1,80 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef IMAGE_H
#define IMAGE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <Color.h>
#include <vgui/IImage.h>
namespace vgui
{
class Panel;
//-----------------------------------------------------------------------------
// Purpose: Basic image control
//-----------------------------------------------------------------------------
class Image : public IImage
{
public:
Image();
virtual ~Image();
// Set the position of the image
virtual void SetPos( int x, int y );
// Get the position of the image
virtual void GetPos( int &x, int &y );
// Get the size of the image
virtual void GetSize( int &wide, int &tall );
virtual void GetContentSize( int &wide, int &tall );
// Set the draw color
virtual void SetColor( Color color );
// set the background color
virtual void SetBkColor( Color color ) { DrawSetColor( color ); }
// Get the draw color
virtual Color GetColor();
virtual bool Evict();
virtual int GetNumFrames();
virtual void SetFrame( int nFrame );
virtual HTexture GetID();
virtual void SetRotation( int iRotation ) { return; };
protected:
virtual void SetSize(int wide, int tall);
virtual void DrawSetColor(Color color);
virtual void DrawSetColor(int r, int g, int b, int a);
virtual void DrawFilledRect(int x0, int y0, int x1, int y1);
virtual void DrawOutlinedRect(int x0, int y0, int x1, int y1);
virtual void DrawLine(int x0,int y0,int x1,int y1);
virtual void DrawPolyLine(int *px, int *py, int numPoints);
virtual void DrawSetTextFont(HFont font);
virtual void DrawSetTextColor(Color color);
virtual void DrawSetTextColor(int r, int g, int b, int a);
virtual void DrawSetTextPos(int x,int y);
virtual void DrawPrintText(const wchar_t *str, int strlen);
virtual void DrawPrintText(int x, int y, const wchar_t *str, int strlen);
virtual void DrawPrintChar(wchar_t ch);
virtual void DrawPrintChar(int x, int y, wchar_t ch);
virtual void DrawSetTexture(int id);
virtual void DrawTexturedRect(int x0, int y0, int x1, int y1);
virtual void Paint() = 0;
private:
int _pos[2];
int _size[2];
Color _color;
};
} // namespace vgui
#endif // IMAGE_H

View File

@@ -0,0 +1,56 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef IMAGELIST_H
#define IMAGELIST_H
#ifdef _WIN32
#pragma once
#endif
#include <utlvector.h>
#include <vgui/VGUI.h>
#include <vgui/IImage.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: holds a collection of images
// used by controls so that images can be refered to by indices
//-----------------------------------------------------------------------------
class ImageList
{
public:
ImageList(bool deleteImagesWhenDone);
~ImageList();
// adds a new image to the list, returning the index it was placed at
int AddImage(vgui::IImage *image);
// returns the number of images
int GetImageCount();
// returns true if an index is valid
bool IsValidIndex(int imageIndex);
// sets an image at a specified index, growing and adding NULL images if necessary
void SetImageAtIndex(int index, vgui::IImage *image);
// gets an image, imageIndex is of range [0, GetImageCount)
// image index 0 is always the blank image
vgui::IImage *GetImage(int imageIndex);
private:
CUtlVector<vgui::IImage *> m_Images;
bool m_bDeleteImagesWhenDone;
};
} // namespace vgui
#endif // IMAGELIST_H

View File

@@ -0,0 +1,92 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef IMAGEPANEL_H
#define IMAGEPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
namespace vgui
{
class IImage;
//-----------------------------------------------------------------------------
// Purpose: Panel that holds a single image
//-----------------------------------------------------------------------------
class ImagePanel : public Panel
{
DECLARE_CLASS_SIMPLE( ImagePanel, Panel );
public:
ImagePanel(Panel *parent, const char *name);
~ImagePanel();
virtual void SetImage(IImage *image);
virtual void SetImage(const char *imageName);
virtual IImage *GetImage();
char *GetImageName();
void SetShouldCenterImage( bool state ) { m_bCenterImage = state; }
bool GetShouldCenterImage() const { return m_bCenterImage; }
// sets whether or not the image should scale to fit the size of the ImagePanel (defaults to false)
void SetShouldScaleImage( bool state );
bool GetShouldScaleImage();
void SetScaleAmount( float scale );
float GetScaleAmount( void );
void SetTileImage( bool bTile ) { m_bTileImage = bTile; }
// set the color to fill with, if no image is specified
void SetFillColor( Color col );
Color GetFillColor();
virtual Color GetDrawColor( void );
virtual void SetDrawColor( Color drawColor );
virtual void ApplySettings(KeyValues *inResourceData);
// unhooks and evicts image if possible, caller must re-establish
bool EvictImage();
int GetNumFrames();
void SetFrame( int nFrame );
void SetRotation( int iRotation ) { m_iRotation = iRotation; }
protected:
virtual void PaintBackground();
virtual void GetSettings(KeyValues *outResourceData);
virtual const char *GetDescription();
virtual void OnSizeChanged(int newWide, int newTall);
virtual void ApplySchemeSettings( IScheme *pScheme );
private:
IImage *m_pImage;
char *m_pszImageName;
char *m_pszFillColorName;
char *m_pszDrawColorName;
bool m_bPositionImage;
bool m_bCenterImage;
bool m_bScaleImage;
bool m_bTileImage;
bool m_bTileHorizontally;
bool m_bTileVertically;
float m_fScaleAmount;
Color m_FillColor;
Color m_DrawColor;
int m_iRotation;
};
} // namespace vgui
#endif // IMAGEPANEL_H

View File

@@ -0,0 +1,106 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef INPUTDIALOG_H
#define INPUTDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Controls.h>
#include <vgui_controls/Frame.h>
namespace vgui
{
class Label;
class Button;
class TextEntry;
//-----------------------------------------------------------------------------
// Purpose: Utility dialog base class - just has context kv and ok/cancel buttons
//-----------------------------------------------------------------------------
class BaseInputDialog : public Frame
{
DECLARE_CLASS_SIMPLE( BaseInputDialog, Frame );
public:
BaseInputDialog( vgui::Panel *parent, const char *title );
~BaseInputDialog();
void DoModal( KeyValues *pContextKeyValues = NULL );
protected:
virtual void PerformLayout();
virtual void PerformLayout( int x, int y, int w, int h ) {}
// command buttons
virtual void OnCommand( const char *command );
void CleanUpContextKeyValues();
KeyValues *m_pContextKeyValues;
private:
vgui::Button *m_pCancelButton;
vgui::Button *m_pOKButton;
};
//-----------------------------------------------------------------------------
// Purpose: Utility dialog, used to ask yes/no questions of the user
//-----------------------------------------------------------------------------
class InputMessageBox : public BaseInputDialog
{
DECLARE_CLASS_SIMPLE( InputMessageBox, BaseInputDialog );
public:
InputMessageBox( vgui::Panel *parent, const char *title, char const *prompt );
~InputMessageBox();
protected:
virtual void PerformLayout( int x, int y, int w, int h );
private:
vgui::Label *m_pPrompt;
};
//-----------------------------------------------------------------------------
// Purpose: Utility dialog, used to let user type in some text
//-----------------------------------------------------------------------------
class InputDialog : public BaseInputDialog
{
DECLARE_CLASS_SIMPLE( InputDialog, BaseInputDialog );
public:
InputDialog( vgui::Panel *parent, const char *title, char const *prompt, char const *defaultValue = "" );
~InputDialog();
void SetMultiline( bool state );
/* action signals
"InputCompleted"
"text" - the text entered
"InputCanceled"
*/
void AllowNumericInputOnly( bool bOnlyNumeric );
protected:
virtual void PerformLayout( int x, int y, int w, int h );
// command buttons
virtual void OnCommand(const char *command);
private:
vgui::Label *m_pPrompt;
vgui::TextEntry *m_pInput;
};
} // namespace vgui
#endif // INPUTDIALOG_H

View File

@@ -0,0 +1,63 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef KEYBINDINGHELPDIALOG_H
#define KEYBINDINGHELPDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "vgui/KeyCode.h"
namespace vgui
{
class ListPanel;
class CKeyBoardEditorDialog;
//-----------------------------------------------------------------------------
// Purpose: Dialog for use in editing keybindings
//-----------------------------------------------------------------------------
class CKeyBindingHelpDialog : public Frame
{
DECLARE_CLASS_SIMPLE( CKeyBindingHelpDialog, Frame );
public:
CKeyBindingHelpDialog( Panel *parent, Panel *panelToView, KeyBindingContextHandle_t handle, KeyCode code, int modifiers );
~CKeyBindingHelpDialog();
virtual void OnCommand( char const *cmd );
virtual void OnKeyCodeTyped(vgui::KeyCode code);
// The key originally bound to help was pressed
void HelpKeyPressed();
private:
virtual void OnTick();
bool IsHelpKeyStillBeingHeld();
void PopulateList();
void GetMappingList( Panel *panel, CUtlVector< PanelKeyBindingMap * >& maps );
void AnsiText( char const *token, char *out, size_t buflen );
vgui::PHandle m_hPanel;
KeyBindingContextHandle_t m_Handle;
KeyCode m_KeyCode;
int m_Modifiers;
ListPanel *m_pList;
double m_flShowTime;
bool m_bPermanent;
DHANDLE< CKeyBoardEditorDialog > m_hKeyBindingsEditor;
};
}
#endif // KEYBINDINGHELPDIALOG_H

View File

@@ -0,0 +1,225 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef KEYBINDINGMAP_H
#define KEYBINDINGMAP_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlvector.h"
// more flexible than default pointers to members code required for casting member function pointers
//#pragma pointers_to_members( full_generality, virtual_inheritance )
namespace vgui
{
class Panel;
enum
{
MODIFIER_SHIFT = ( 1 << 0 ),
MODIFIER_CONTROL = ( 1 << 1 ),
MODIFIER_ALT = ( 1 << 2 ),
};
//-----------------------------------------------------------------------------
// Purpose: An actual keybinding, where bindingname references a bindingmap mentioned below
//-----------------------------------------------------------------------------
struct BoundKey_t
{
BoundKey_t();
BoundKey_t( const BoundKey_t& src );
~BoundKey_t();
BoundKey_t& operator =( const BoundKey_t& src );
bool isbuiltin; // whether this was by the #DECLARE macros or via code/parsing a config file
char const *bindingname; // what it's bound to
int keycode; // vgui keycode
int modifiers; // which modifiers
};
//-----------------------------------------------------------------------------
// Purpose: Single item in a message map
// Contains the information to map a string message name with parameters
// to a function call
//-----------------------------------------------------------------------------
struct KeyBindingMap_t
{
KeyBindingMap_t();
KeyBindingMap_t( const KeyBindingMap_t& src );
~KeyBindingMap_t();
char const *bindingname; // for the script file
ALIGN16 MessageFunc_t func;
char const *helpstring; // e.g., #KeybindingPasteHelp
char const *docstring; // e.g., #KeybindingPasteHelp
bool passive; // dispatch command, but still chain
};
#define DECLARE_KEYBINDINGMAP( className ) \
static void KB_AddToMap \
( \
char const *bindingname, \
vgui::KeyCode defaultcode, \
int default_modifiers, \
vgui::MessageFunc_t function, \
char const *helpstring, \
char const *docstring, \
bool passive \
) \
{ \
vgui::PanelKeyBindingMap *map = vgui::FindOrAddPanelKeyBindingMap( GetPanelClassName() ); \
\
vgui::KeyBindingMap_t entry; \
entry.bindingname = bindingname; \
\
entry.func = function; \
\
entry.helpstring = helpstring; \
entry.docstring = docstring; \
\
entry.passive = passive; \
\
map->entries.AddToTail( entry ); \
\
vgui::BoundKey_t kb; \
kb.isbuiltin = true; \
kb.bindingname = bindingname; \
kb.keycode = defaultcode; \
kb.modifiers = default_modifiers; \
map->defaultkeys.AddToTail( kb ); \
map->boundkeys.AddToTail( kb ); \
} \
\
static void KB_ChainToMap( void ) \
{ \
static bool chained = false; \
if ( chained ) \
return; \
chained = true; \
vgui::PanelKeyBindingMap *map = vgui::FindOrAddPanelKeyBindingMap( GetPanelClassName() ); \
map->pfnClassName = &GetPanelClassName; \
if ( map && GetPanelBaseClassName() && GetPanelBaseClassName()[0] ) \
{ \
map->baseMap = vgui::FindOrAddPanelKeyBindingMap( GetPanelBaseClassName() ); \
} \
} \
\
static void KB_AddBoundKey \
( \
char const *bindingname, \
int keycode, \
int modifiers \
) \
{ \
vgui::PanelKeyBindingMap *map = vgui::FindOrAddPanelKeyBindingMap( GetPanelClassName() ); \
vgui::BoundKey_t kb; \
kb.isbuiltin = true; \
kb.bindingname = bindingname; \
kb.keycode = keycode; \
kb.modifiers = modifiers; \
map->defaultkeys.AddToTail( kb ); \
map->boundkeys.AddToTail( kb ); \
} \
\
class className##_RegisterKBMap; \
friend class className##_RegisterKBMap; \
class className##_RegisterKBMap \
{ \
public: \
className##_RegisterKBMap() \
{ \
className::KB_ChainToMap(); \
} \
}; \
className##_RegisterKBMap m_RegisterClassKB; \
\
virtual vgui::PanelKeyBindingMap *GetKBMap() \
{ \
static vgui::PanelKeyBindingMap *s_pMap = vgui::FindOrAddPanelKeyBindingMap( GetPanelClassName() ); \
return s_pMap; \
}
#define _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, passive ) \
class PanelKBMapFunc_##name; \
friend class PanelKBMapFunc_##name; \
class PanelKBMapFunc_##name \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
KB_AddToMap( #name, keycode, modifiers, (vgui::MessageFunc_t)&ThisClass::function, help, doc, passive ); \
} \
} \
PanelKBMapFunc_##name() \
{ \
PanelKBMapFunc_##name::InitVar(); \
} \
}; \
PanelKBMapFunc_##name m_##name##_register;
#define _KBBindKeyCommon( name, keycode, modifiers, _classname ) \
class PanelKBBindFunc_##_classname; \
friend class PanelKBBindFunc_##_classname; \
class PanelKBBindFunc_##_classname \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
KB_AddBoundKey( #name, keycode, modifiers ); \
} \
} \
PanelKBBindFunc_##_classname() \
{ \
PanelKBBindFunc_##_classname::InitVar(); \
} \
}; \
PanelKBBindFunc_##_classname m_##_classname##_bindkey_register;
#define KEYBINDING_FUNC( name, keycode, modifiers, function, help, doc ) _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, false ); virtual void function()
#define KEYBINDING_FUNC_NODECLARE( name, keycode, modifiers, function, help, doc ) _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, false );
#define KEYBINDING_FUNC_PASSIVE( name, keycode, modifiers, function, help, doc ) _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, true ); virtual void function()
#define KEYBINDING_FUNC_PASSIVE_NODECLARE( name, keycode, modifiers, function, help, doc ) _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, true );
// For definding additional (non-default) keybindings
#define KEYBINDING_ADDBINDING( name, keycode, modifiers ) _KBBindKeyCommon( name, keycode, modifiers, name );
#define KEYBINDING_ADDBINDING_MULTIPLE( name, keycode, modifiers, _classname ) _KBBindKeyCommon( name, keycode, modifiers, _classname );
// mapping, one per class
struct PanelKeyBindingMap
{
PanelKeyBindingMap()
{
baseMap = NULL;
pfnClassName = NULL;
processed = false;
}
CUtlVector< KeyBindingMap_t > entries;
bool processed;
PanelKeyBindingMap *baseMap;
CUtlVector< BoundKey_t > defaultkeys;
CUtlVector< BoundKey_t > boundkeys;
char const *(*pfnClassName)( void );
};
PanelKeyBindingMap *FindPanelKeyBindingMap( char const *className );
PanelKeyBindingMap *FindOrAddPanelKeyBindingMap( char const *className );
} // namespace vgui
#endif // KEYBINDINGMAP_H

View File

@@ -0,0 +1,138 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef KEYBOARDEDITORDIALOG_H
#define KEYBOARDEDITORDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "vgui_controls/PropertySheet.h"
#include "vgui_controls/PropertyPage.h"
class VControlsListPanel;
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Dialog for use in editing keybindings
//-----------------------------------------------------------------------------
class CKeyBoardEditorPage : public EditablePanel
{
DECLARE_CLASS_SIMPLE( CKeyBoardEditorPage, EditablePanel );
public:
CKeyBoardEditorPage( Panel *parent, Panel *panelToEdit, KeyBindingContextHandle_t handle );
~CKeyBoardEditorPage();
void SetKeybindingsSaveFile( char const *filename, char const *pathID = 0 );
virtual void OnKeyCodeTyped(vgui::KeyCode code);
virtual void ApplySchemeSettings( IScheme *scheme );
void OnSaveChanges();
void OnRevert();
void OnUseDefaults();
protected:
virtual void OnPageHide();
virtual void OnCommand( char const *cmd );
void PopulateList();
void GetMappingList( Panel *panel, CUtlVector< PanelKeyBindingMap * >& maps );
int GetMappingCount( Panel *panel );
void BindKey( vgui::KeyCode code );
// Trap row selection message
MESSAGE_FUNC( ItemSelected, "ItemSelected" );
MESSAGE_FUNC_INT( OnClearBinding, "ClearBinding", item );
void SaveMappings();
void UpdateCurrentMappings();
void RestoreMappings();
void ApplyMappings();
protected:
void AnsiText( char const *token, char *out, size_t buflen );
Panel *m_pPanel;
KeyBindingContextHandle_t m_Handle;
VControlsListPanel *m_pList;
struct SaveMapping_t
{
SaveMapping_t();
SaveMapping_t( const SaveMapping_t& src );
PanelKeyBindingMap *map;
CUtlVector< BoundKey_t > current;
CUtlVector< BoundKey_t > original;
};
CUtlVector< SaveMapping_t * > m_Save;
};
//-----------------------------------------------------------------------------
// Purpose: Dialog for use in editing keybindings
//-----------------------------------------------------------------------------
class CKeyBoardEditorSheet : public PropertySheet
{
DECLARE_CLASS_SIMPLE( CKeyBoardEditorSheet, PropertySheet );
public:
CKeyBoardEditorSheet( Panel *parent, Panel *panelToEdit, KeyBindingContextHandle_t handle );
void SetKeybindingsSaveFile( char const *filename, char const *pathID = 0 );
void OnSaveChanges();
void OnRevert();
void OnUseDefaults();
protected:
vgui::PHandle m_hPanel;
KeyBindingContextHandle_t m_Handle;
bool m_bSaveToExternalFile;
CUtlSymbol m_SaveFileName;
CUtlSymbol m_SaveFilePathID;
Color m_clrAlteredItem;
};
//-----------------------------------------------------------------------------
// Purpose: Dialog for use in editing keybindings
//-----------------------------------------------------------------------------
class CKeyBoardEditorDialog : public Frame
{
DECLARE_CLASS_SIMPLE( CKeyBoardEditorDialog, Frame );
public:
CKeyBoardEditorDialog( Panel *parent, Panel *panelToEdit, KeyBindingContextHandle_t handle );
void SetKeybindingsSaveFile( char const *filename, char const *pathID = 0 );
virtual void OnCommand( char const *cmd );
private:
CKeyBoardEditorSheet *m_pKBEditor;
Button *m_pSave;
Button *m_pCancel;
Button *m_pRevert;
Button *m_pUseDefaults;
};
}
#endif // KEYBOARDEDITORDIALOG_H

View File

@@ -0,0 +1,79 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef KEYREPEAT_H
#define KEYREPEAT_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Panel.h>
namespace vgui
{
enum KEYREPEAT_ALIASES
{
KR_ALIAS_UP,
KR_ALIAS_DOWN,
KR_ALIAS_LEFT,
KR_ALIAS_RIGHT,
FM_NUM_KEYREPEAT_ALIASES,
};
class CKeyRepeatHandler
{
public:
CKeyRepeatHandler()
{
Reset();
for ( int i = 0; i < FM_NUM_KEYREPEAT_ALIASES; i++ )
{
m_flRepeatTimes[i] = 0.16;
}
}
void Reset( void ) { memset( m_bAliasDown, 0, sizeof(bool) * FM_NUM_KEYREPEAT_ALIASES ); m_bHaveKeyDown = false; }
void KeyDown( vgui::KeyCode code );
void KeyUp( vgui::KeyCode code );
vgui::KeyCode KeyRepeated( void );
void SetKeyRepeatTime( vgui::KeyCode code, float flRepeat );
private:
int GetIndexForCode( vgui::KeyCode code )
{
switch ( code )
{
case KEY_XBUTTON_DOWN:
case KEY_XSTICK1_DOWN:
return KR_ALIAS_DOWN; break;
case KEY_XBUTTON_UP:
case KEY_XSTICK1_UP:
return KR_ALIAS_UP; break;
case KEY_XBUTTON_LEFT:
case KEY_XSTICK1_LEFT:
return KR_ALIAS_LEFT; break;
case KEY_XBUTTON_RIGHT:
case KEY_XSTICK1_RIGHT:
return KR_ALIAS_RIGHT; break;
default:
break;
}
return -1;
}
private:
bool m_bAliasDown[FM_NUM_KEYREPEAT_ALIASES];
float m_flRepeatTimes[FM_NUM_KEYREPEAT_ALIASES];
float m_flNextKeyRepeat;
bool m_bHaveKeyDown;
};
} // namespace vgui
#endif // KEYREPEAT_H

View File

@@ -0,0 +1,225 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef LABEL_H
#define LABEL_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "vgui/VGUI.h"
#include "vgui_controls/Panel.h"
#include "vgui_controls/PHandle.h"
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Contains and displays a set of images
// By default starts with one TextImage
//-----------------------------------------------------------------------------
class Label : public Panel
{
DECLARE_CLASS_SIMPLE( Label, Panel );
public:
// Constructors
Label(Panel *parent, const char *panelName, const char *text);
Label(Panel *parent, const char *panelName, const wchar_t *wszText);
~Label();
public:
// Take the string and looks it up in the localization file to convert it to unicode
virtual void SetText(const char *tokenName);
// Set unicode text directly
virtual void SetText(const wchar_t *unicodeString, bool bClearUnlocalizedSymbol = false );
// Get the current text
virtual void GetText(OUT_Z_BYTECAP(bufferLen) char *textOut, int bufferLen);
virtual void GetText(OUT_Z_BYTECAP(bufLenInBytes) wchar_t *textOut, int bufLenInBytes);
// Content alignment
// Get the size of the content within the label
virtual void GetContentSize(int &wide, int &tall);
// Set how the content aligns itself within the label
// alignment code, used to determine how the images are layed out within the Label
enum Alignment
{
a_northwest = 0,
a_north,
a_northeast,
a_west,
a_center,
a_east,
a_southwest,
a_south,
a_southeast,
};
virtual void SetContentAlignment(Alignment alignment);
virtual void SetEnabled(bool state);
// Additional offset at the Start of the text (from whichever sides it is aligned)
virtual void SetTextInset(int xInset, int yInset);
virtual void GetTextInset(int *xInset, int *yInset );
// Text colors
virtual void SetFgColor(Color color);
virtual Color GetFgColor();
// colors to use when the label is disabled
virtual void SetDisabledFgColor1(Color color);
virtual void SetDisabledFgColor2(Color color);
virtual Color GetDisabledFgColor1();
virtual Color GetDisabledFgColor2();
// Set whether the text is displayed bright or dull
enum EColorState
{
CS_NORMAL,
CS_DULL,
CS_BRIGHT,
};
virtual void SetTextColorState(EColorState state);
// Font
virtual void SetFont(HFont font);
virtual HFont GetFont();
// Hotkey
virtual Panel *HasHotkey(wchar_t key);
virtual void SetHotkey(wchar_t key);
virtual wchar_t GetHotKey();
// Labels can be associated with controls, and alter behaviour based on the associates behaviour
// If the associate is disabled, so are we
// If the associate has focus, we may alter how we draw
// If we get a hotkey press or focus message, we forward the focus to the associate
virtual void SetAssociatedControl(Panel *control);
// Multiple image handling
// Images are drawn from left to right across the label, ordered by index
// By default there is a TextImage in position 0 (see GetTextImage()/SetTextImageIndex())
virtual int AddImage(IImage *image, int preOffset); // Return the index the image was placed in
virtual void SetImageAtIndex(int index, IImage *image, int preOffset);
virtual void SetImagePreOffset(int index, int preOffset); // Set the offset in pixels before the image
virtual IImage *GetImageAtIndex(int index);
virtual int GetImageCount();
virtual void ClearImages();
virtual void ResetToSimpleTextImage();
// fixes the layout bounds of the image within the label
virtual void SetImageBounds(int index, int x, int width);
// Teturns a pointer to the default text image
virtual TextImage *GetTextImage();
// Moves where the default text image is within the image array (it starts in position 0)
// Setting it to -1 removes it from the image list
// Returns the index the default text image was previously in
virtual int SetTextImageIndex(int newIndex);
// Message handling
// outputData - keyName is the name of the attribute requested.
// for Labels "text" is an option that returns the default text image text
// returns true on success in finding the requested value. false on failure.
virtual bool RequestInfo(KeyValues *outputData);
/* INFO HANDLING
"GetText"
returns:
"text" - text contained in the label
*/
/* CUSTOM MESSAGE HANDLING
"SetText"
input: "text" - label text is set to be this string
*/
virtual void SizeToContents();
// the +8 is padding to the content size
// the code which uses it should really set that itself;
// however a lot of existing code relies on this
enum Padding
{
Content = 8,
};
void SetWrap( bool bWrap );
void SetCenterWrap( bool bWrap );
void SetAllCaps( bool bAllCaps );
protected:
virtual void PerformLayout();
virtual wchar_t CalculateHotkey(const char *text);
virtual wchar_t CalculateHotkey(const wchar_t *text);
virtual void ComputeAlignment(int &tx0, int &ty0, int &tx1, int &ty1);
virtual void Paint();
MESSAGE_FUNC_PARAMS( OnSetText, "SetText", params );
virtual void DrawDashedLine(int x0, int y0, int x1, int y1, int dashLen, int gapLen);
virtual void OnRequestFocus(VPANEL subFocus, VPANEL defaultPanel);
MESSAGE_FUNC( OnHotkeyPressed, "Hotkey" );
virtual void OnMousePressed(MouseCode code);
virtual void OnSizeChanged(int wide, int tall);
// makes sure that the maxIndex will be a valid index
virtual void EnsureImageCapacity(int maxIndex);
// editing
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void GetSettings( KeyValues *outResourceData );
virtual void ApplySettings( KeyValues *inResourceData );
virtual const char *GetDescription( void );
MESSAGE_FUNC_PARAMS( OnDialogVariablesChanged, "DialogVariables", dialogVariables );
void HandleAutoSizing( void );
private:
void Init();
Alignment _contentAlignment;
TextImage *_textImage; // this is the textImage, if the full text will not
// fit we put as much as we can and add an elipsis (...)
struct TImageInfo
{
IImage *image;
short offset;
short xpos;
short width;
};
CUtlVector<TImageInfo> _imageDar;
int _textInset[2];
Color _disabledFgColor1;
Color _disabledFgColor2;
Color _associateColor;
int _textImageIndex; // index in the image array that the default _textimage resides
EColorState _textColorState;
PHandle _associate;
char *_associateName;
char *_fontOverrideName;
wchar_t _hotkey; // the hotkey contained in the text
bool m_bWrap;
bool m_bCenterWrap;
bool m_bAllCaps;
bool m_bAutoWideToContents;
bool m_bAutoWideDirty;
bool m_bUseProportionalInsets;
};
} // namespace vgui
#endif // LABEL_H

View File

@@ -0,0 +1,371 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef LISTPANEL_H
#define LISTPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <utllinkedlist.h>
#include <utlvector.h>
#include <utlrbtree.h>
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
class KeyValues;
namespace vgui
{
class ScrollBar;
class TextImage;
class ImagePanel;
class Label;
class Button;
class IDraggerEvent;
class FastSortListPanelItem;
//-----------------------------------------------------------------------------
// Purpose: Generic class for ListPanel items
//-----------------------------------------------------------------------------
class ListPanelItem
{
public:
ListPanelItem() :
kv( 0 ),
userData( 0 ),
m_pDragData( 0 ),
m_bImage( false ),
m_nImageIndex( -1 ),
m_nImageIndexSelected( -1 ),
m_pIcon( 0 )
{
}
KeyValues *kv;
unsigned int userData;
KeyValues *m_pDragData;
bool m_bImage;
int m_nImageIndex;
int m_nImageIndexSelected;
IImage *m_pIcon;
};
typedef int __cdecl SortFunc(
ListPanel *pPanel,
const ListPanelItem &item1,
const ListPanelItem &item2 );
//-----------------------------------------------------------------------------
// Purpose: A spread-sheet type data view, similar to MFC's
//-----------------------------------------------------------------------------
class ListPanel : public Panel
{
DECLARE_CLASS_SIMPLE( ListPanel, Panel );
public:
ListPanel(Panel *parent, const char *panelName);
~ListPanel();
// COLUMN HANDLING
// all indices are 0 based, limit of 255 columns
// columns are resizable by default
enum ColumnFlags_e
{
COLUMN_FIXEDSIZE = 0x01, // set to have the column be a fixed size
COLUMN_RESIZEWITHWINDOW = 0x02, // set to have the column grow with the parent dialog growing
COLUMN_IMAGE = 0x04, // set if the column data is not text, but instead the index of the image to display
COLUMN_HIDDEN = 0x08, // column is hidden by default
COLUMN_UNHIDABLE = 0x10, // column is unhidable
};
// adds a column header
virtual void AddColumnHeader(int index, const char *columnName, const char *columnText, int startingWidth, int minWidth, int maxWidth, int columnFlags = 0);
virtual void AddColumnHeader(int index, const char *columnName, const char *columnText, int width, int columnFlags = 0);
virtual void RemoveColumn(int column); // removes a column
virtual int FindColumn(const char *columnName);
virtual void SetColumnHeaderHeight( int height );
virtual void SetColumnHeaderText(int column, const char *text);
virtual void SetColumnHeaderText(int column, wchar_t *text);
virtual void SetColumnHeaderImage(int column, int imageListIndex);
virtual void SetColumnHeaderTooltip(int column, const char *tooltipText);
virtual void SetColumnTextAlignment( int column, int align );
// Get information about the column headers.
virtual int GetNumColumnHeaders() const;
virtual bool GetColumnHeaderText( int index, char *pOut, int maxLen );
virtual void SetSortFunc(int column, SortFunc *func);
virtual void SetSortColumn(int column);
virtual void SortList( void );
virtual void SetColumnSortable(int column, bool sortable);
virtual void SetColumnVisible(int column, bool visible);
int GetSortColumn() const;
// sets whether the user can add/remove columns (defaults to off)
virtual void SetAllowUserModificationOfColumns(bool allowed);
// DATA HANDLING
// data->GetName() is used to uniquely identify an item
// data sub items are matched against column header name to be used in the table
virtual int AddItem(const KeyValues *data, unsigned int userData, bool bScrollToItem, bool bSortOnAdd); // Takes a copy of the data for use in the table. Returns the index the item is at.
void SetItemDragData( int itemID, const KeyValues *data ); // Makes a copy of the keyvalues to store in the table. Used when dragging from the table. Only used if the caller enables drag support
virtual int GetItemCount( void ); // returns the number of VISIBLE items
virtual int GetItem(const char *itemName); // gets the row index of an item by name (data->GetName())
virtual KeyValues *GetItem(int itemID); // returns pointer to data the row holds
virtual int GetItemCurrentRow(int itemID); // returns -1 if invalid index or item not visible
virtual int GetItemIDFromRow(int currentRow); // returns -1 if invalid row
virtual unsigned int GetItemUserData(int itemID);
virtual ListPanelItem *GetItemData(int itemID);
virtual void SetUserData( int itemID, unsigned int userData );
virtual int GetItemIDFromUserData( unsigned int userData );
virtual void ApplyItemChanges(int itemID); // applies any changes to the data, performed by modifying the return of GetItem() above
virtual void RemoveItem(int itemID); // removes an item from the table (changing the indices of all following items)
virtual void RereadAllItems(); // updates the view with the new data
virtual void RemoveAll(); // clears and deletes all the memory used by the data items
virtual void DeleteAllItems(); // obselete, use RemoveAll();
virtual void GetCellText(int itemID, int column, OUT_Z_BYTECAP(bufferSizeInBytes) wchar_t *buffer, int bufferSizeInBytes); // returns the data held by a specific cell
virtual IImage *GetCellImage(int itemID, int column); //, ImagePanel *&buffer); // returns the image held by a specific cell
// Use these until they return InvalidItemID to iterate all the items.
virtual int FirstItem() const;
virtual int NextItem( int iItem ) const;
virtual int InvalidItemID() const;
virtual bool IsValidItemID(int itemID);
// sets whether the dataitem is visible or not
// it is removed from the row list when it becomes invisible, but stays in the indexes
// this is much faster than a normal remove
virtual void SetItemVisible(int itemID, bool state);
virtual void SetItemDisabled(int itemID, bool state );
bool IsItemVisible( int itemID );
virtual void SetFont(HFont font);
// image handling
virtual void SetImageList(ImageList *imageList, bool deleteImageListWhenDone);
// SELECTION
// returns the count of selected items
virtual int GetSelectedItemsCount();
// returns the selected item by selection index, valid in range [0, GetNumSelectedRows)
virtual int GetSelectedItem(int selectionIndex);
// sets no item as selected
virtual void ClearSelectedItems();
virtual bool IsItemSelected( int itemID );
// adds a item to the select list
virtual void AddSelectedItem( int itemID );
// sets this single item as the only selected item
virtual void SetSingleSelectedItem( int itemID );
// returns the selected column, -1 for particular column selected
virtual int GetSelectedColumn();
// whether or not to select specific cells (off by default)
virtual void SetSelectIndividualCells(bool state);
// whether or not multiple cells/rows can be selected
void SetMultiselectEnabled( bool bState );
bool IsMultiselectEnabled() const;
// sets a single cell - all other previous rows are cleared
virtual void SetSelectedCell(int row, int column);
virtual bool GetCellAtPos(int x, int y, int &row, int &column); // returns true if any found, row and column are filled out. x, y are in screen space
virtual bool GetCellBounds( int row, int column, int& x, int& y, int& wide, int& tall );
// sets the text which is displayed when the list is empty
virtual void SetEmptyListText(const char *text);
virtual void SetEmptyListText(const wchar_t *text);
// relayout the scroll bar in response to changing the items in the list panel
// do this if you RemoveAll()
void ResetScrollBar();
// Attaches drag data to a particular item
virtual void OnCreateDragData( KeyValues *msg );
void SetIgnoreDoubleClick( bool state );
// set up a field for editing
virtual void EnterEditMode(int itemID, int column, vgui::Panel *editPanel);
// leaves editing mode
virtual void LeaveEditMode();
// returns true if we are currently in inline editing mode
virtual bool IsInEditMode();
MESSAGE_FUNC_INT( ResizeColumnToContents, "ResizeColumnToContents", column );
#ifdef _X360
virtual void NavigateTo();
#endif
/// Version number for file format of user config. This defaults to 1,
/// and if you rearrange columns you can increment it to cause any old
/// user configs (which will be screwed up) to be discarded.
int m_nUserConfigFileVersion;
protected:
// PAINTING
virtual Panel *GetCellRenderer(int row, int column);
// overrides
virtual void OnMouseWheeled(int delta);
virtual void OnSizeChanged(int wide, int tall);
virtual void PerformLayout();
virtual void Paint();
virtual void PaintBackground();
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void OnMousePressed( MouseCode code );
virtual void OnMouseDoublePressed( MouseCode code );
#ifdef _X360
virtual void OnKeyCodePressed(KeyCode code);
#else
virtual void OnKeyCodePressed( KeyCode code );
#endif
MESSAGE_FUNC( OnSliderMoved, "ScrollBarSliderMoved" );
MESSAGE_FUNC_INT_INT( OnColumnResized, "ColumnResized", column, delta );
MESSAGE_FUNC_INT( OnSetSortColumn, "SetSortColumn", column );
MESSAGE_FUNC( OpenColumnChoiceMenu, "OpenColumnChoiceMenu" );
MESSAGE_FUNC_INT( OnToggleColumnVisible, "ToggleColumnVisible", col );
virtual float GetRowsPerPage();
virtual int GetStartItem();
// user configuration
virtual void ApplyUserConfigSettings(KeyValues *userConfig);
virtual void GetUserConfigSettings(KeyValues *userConfig);
virtual bool HasUserConfigSettings();
/* MESSAGES SENT
"ItemSelected" - query which items are selected
"ItemDeselected" - query which items are selected
*/
public:
virtual void SetSortColumnEx( int iPrimarySortColumn, int iSecondarySortColumn, bool bSortAscending );
void GetSortColumnEx( int &iPrimarySortColumn, int &iSecondarySortColumn, bool &bSortAscending ) const;
private:
// Cleans up allocations associated with a particular item
void CleanupItem( FastSortListPanelItem *data );
// adds the item into the column indexes
void IndexItem(int itemID);
// Purpose:
void UpdateSelection( vgui::MouseCode code, int x, int y, int row, int column );
// Handles multiselect
void HandleMultiSelection( int itemID, int row, int column );
// Handles addselect
void HandleAddSelection( int itemID, int row, int column );
// pre-sorted columns
struct IndexItem_t
{
ListPanelItem *dataItem;
int duplicateIndex;
};
typedef CUtlRBTree<IndexItem_t, int> IndexRBTree_t;
struct column_t
{
Button *m_pHeader;
int m_iMinWidth;
int m_iMaxWidth;
bool m_bResizesWithWindow;
Panel *m_pResizer;
SortFunc *m_pSortFunc;
bool m_bTypeIsText;
bool m_bHidden;
bool m_bUnhidable;
IndexRBTree_t m_SortedTree;
int m_nContentAlignment;
};
// list of the column headers
CUtlLinkedList<column_t, unsigned char> m_ColumnsData;
// persistent list of all columns ever created, indexes into m_ColumnsData - used for matching up DATAITEM m_SortedTreeIndexes
CUtlVector<unsigned char> m_ColumnsHistory;
// current list of columns, indexes into m_ColumnsData
CUtlVector<unsigned char> m_CurrentColumns;
int m_iColumnDraggerMoved; // which column dragger was moved->which header to resize
int m_lastBarWidth;
CUtlLinkedList<FastSortListPanelItem*, int> m_DataItems;
CUtlVector<int> m_VisibleItems;
// set to true if the table needs to be sorted before it's drawn next
int m_iSortColumn;
int m_iSortColumnSecondary;
void ResortColumnRBTree(int col);
static bool RBTreeLessFunc(vgui::ListPanel::IndexItem_t &item1, vgui::ListPanel::IndexItem_t &item2);
TextImage *m_pTextImage; // used in rendering
ImagePanel *m_pImagePanel; // used in rendering
Label *m_pLabel; // used in rendering
ScrollBar *m_hbar;
ScrollBar *m_vbar;
int m_iSelectedColumn;
bool m_bNeedsSort : 1;
bool m_bSortAscending : 1;
bool m_bSortAscendingSecondary : 1;
bool m_bCanSelectIndividualCells : 1;
bool m_bShiftHeldDown : 1;
bool m_bMultiselectEnabled : 1;
bool m_bAllowUserAddDeleteColumns : 1;
bool m_bDeleteImageListWhenDone : 1;
bool m_bIgnoreDoubleClick : 1;
int m_iHeaderHeight;
int m_iRowHeight;
// selection data
CUtlVector<int> m_SelectedItems; // array of selected rows
int m_LastItemSelected; // remember the last row selected for future shift clicks
int m_iTableStartX;
int m_iTableStartY;
Color m_LabelFgColor;
Color m_DisabledColor;
Color m_SelectionFgColor;
Color m_DisabledSelectionFgColor;
ImageList *m_pImageList;
TextImage *m_pEmptyListText;
PHandle m_hEditModePanel;
int m_iEditModeItemID;
int m_iEditModeColumn;
void ResetColumnHeaderCommands();
};
}
#endif // LISTPANEL_H

View File

@@ -0,0 +1,121 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef LISTVIEWPANEL_H
#define LISTVIEWPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <utllinkedlist.h>
#include <utlvector.h>
namespace vgui
{
class ListViewPanel;
typedef bool (*ListViewSortFunc_t)(KeyValues *kv1, KeyValues *kv2);
class ListViewItem;
//-----------------------------------------------------------------------------
// Purpose: List Ctrl Panel with each item having an icon and text after it
//-----------------------------------------------------------------------------
class ListViewPanel : public Panel
{
DECLARE_CLASS_SIMPLE( ListViewPanel, Panel );
public:
ListViewPanel(Panel *parent, const char *panelName);
~ListViewPanel();
virtual int AddItem(const KeyValues *data, bool bScrollToItem, bool bSortOnAdd);
virtual int GetItemCount();
virtual KeyValues *GetItem(int itemID);
virtual void ApplyItemChanges(int itemID);
virtual void RemoveItem(int itemID);
virtual void DeleteAllItems();
virtual int GetItemIDFromPos(int iPos); // valid from [0, GetItemCount)
virtual int InvalidItemID();
virtual bool IsValidItemID(int itemID);
virtual void ScrollToItem(int itemID);
virtual void SetSortFunc(ListViewSortFunc_t func);
virtual void SortList();
// image handling
virtual void SetImageList(ImageList *imageList, bool deleteImageListWhenDone);
virtual void SetFont(HFont font);
// returns the count of selected items
virtual int GetSelectedItemsCount();
// returns the selected item by selection index, valid in range [0, GetNumSelectedRows)
virtual int GetSelectedItem(int selectionIndex);
// sets no item as selected
virtual void ClearSelectedItems();
// adds a item to the select list
virtual void AddSelectedItem(int itemID);
// sets this single item as the only selected item
virtual void SetSingleSelectedItem(int itemID);
protected:
// overrides
virtual void OnMouseWheeled(int delta);
virtual void OnSizeChanged(int wide, int tall);
virtual void PerformLayout();
virtual void Paint();
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void OnMousePressed( MouseCode code);
virtual void OnMouseDoublePressed( MouseCode code);
virtual void OnKeyCodeTyped( KeyCode code);
virtual void OnKeyTyped(wchar_t unichar);
MESSAGE_FUNC( OnSliderMoved, "ScrollBarSliderMoved" );
virtual int GetItemsPerColumn();
private:
ScrollBar *m_hbar;
friend class ListViewItem;
void OnItemMousePressed(ListViewItem* pItem, MouseCode code);
void OnItemMouseDoublePressed(ListViewItem* pItem, MouseCode code);
int GetItemsMaxWidth();
int GetItemIndex(int itemID);
void OnShiftSelect(int itemID);
void FinishKeyPress(int itemID);
CUtlLinkedList<ListViewItem*, int> m_DataItems;
CUtlVector<int> m_SortedItems;
ListViewSortFunc_t m_pSortFunc;
int m_iRowHeight;
HFont m_hFont;
Color m_LabelFgColor;
Color m_SelectionFgColor;
// selection data
CUtlVector<int> m_SelectedItems;
int m_LastSelectedItemID;
int m_ShiftStartItemID;
bool m_bNeedsSort;
bool m_bDeleteImageListWhenDone;
ImageList *m_pImageList;
};
}
#endif // LISTVIEWPANEL_H

View File

@@ -0,0 +1,356 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef MENU_H
#define MENU_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Panel.h>
#include <vgui_controls/Label.h>
#include <utllinkedlist.h>
#include <utlvector.h>
namespace vgui
{
class MenuItem;
class ScrollBar;
class MenuSeparator;
//-----------------------------------------------------------------------------
// Purpose: A menu is a list of items that can be selected with one click, navigated
// with arrow keys and/or hot keys, and have a lit behavior when mouse over.
// It is NOT the button which opens the menu, but only the menu itself.
//
// Behaviour spec:
// Menu navigation can be done in 2 modes, via keyboard keys and via mouse.
// Clicking on menu button opens menu.
// Only one item in a menu is highlighted at a time.
// Only one submenu in a menu is open at a time.
// Disabled menuitems get highlighted via mouse and keys but will not activate.
//
// Mouse:
// Moving mouse into a menuitem highlights it.
// If the menuitem has a cascading menu, the menu opens when the mouse enters
// the menuitem. The cascading menuitem stays highlighted while its menu is open.
// No submenu items are highlighted by default.
// Moving the mouse into another menuitem closes any previously open submenus in the list.
// Clicking once in the menu item activates the menu item and closes all menus.
// Moving the mouse off a menuitem unhighlights it.
// The scroll bar arrows can be used to move up/down the menu one item at a time.
// The clicking and dragging on the scroll bar nob also scrolls the menu items.
// If a highlighed menuitem scrolls off, and the user then begins navigating via keys,
// the menu will snap the scroll bar so the highlighted item is visible.
// If user has been navigating via keys, moving the mouse over a menu item
// highlights it.
// Mousewheel:
// You must have the mouse inside the menu/scroll bar to use the wheel.
// The mouse wheel moves the highlighted menuitem up or down the list.
// If the list has no scroll bar the wheel will cycle from the bottom of the list
// to the top of the list and vice versa.
// If the list has a scrollbar the mouse wheel will stop at the top or bottom
// of the list.
// If the mouse is over the scroll bar no items are highlighted.
// Keyboard:
// When a menu is opened, no items are highlighted.
// If a menuitem has a cascading menu it does not open when the item is highlighted.
// The down arrow selects the next item in the list.
// (first item if none are highlighted and there is a scrollbar).
// The up arrow selects the previous item in the list
// (first item if none are highlighted and there is a scrollbar, last item if none are
// highlighted and there is no scrollbar).
// Selecting a new menuitem closes any previously open submenus in the list.
// The enter key activates the selected item and closes all menus.
// If the selected item has a cascading menu, activating it opens its submenu.
// These may also be activated by pressing the right arrow.
// Pressing the left arrow closes the submenu.
// When the submenu is opened the cascading menuitem stays highlighted.
// No items in the submenu are highlighted when it is opened.
//
// Note: Cascading menuitems in menus with a scrollbar is not supported.
// Its a clunky UI and if we want this we should design a better solution,
// perhaps along the lines of how explorer's bookmarks does it.
// It currently functions, but there are some arm/disarm bugs.
//
//
//-----------------------------------------------------------------------------
class Menu : public Panel
{
DECLARE_CLASS_SIMPLE( Menu, Panel );
friend class MenuItem;
public:
enum MenuDirection_e
{
LEFT,
RIGHT,
UP,
DOWN,
CURSOR, // make the menu appear under the mouse cursor
ALIGN_WITH_PARENT, // make the menu appear under the parent
};
Menu(Panel *parent, const char *panelName);
~Menu();
static void PlaceContextMenu( Panel *parent, Menu *menu );
static void OnInternalMousePressed( Panel *other, MouseCode code );
virtual void PositionRelativeToPanel( Panel *reference, MenuDirection_e direction, int nAdditionalYOffset = 0, bool showMenu = false );
// the menu. For combo boxes, it's the edit/field, etc. etc.
// Add a simple text item to the menu
virtual int AddMenuItem( const char *itemName, const char *itemText, const char *command, Panel *target, const KeyValues *userData = NULL );
virtual int AddMenuItem( const char *itemName, const wchar_t *wszItemText, const char *command, Panel *target, const KeyValues *userData = NULL );
virtual int AddMenuItem( const char *itemName, const char *itemText, KeyValues *message, Panel *target , const KeyValues *userData = NULL);
virtual int AddMenuItem( const char *itemName, const wchar_t *wszItemText, KeyValues *message, Panel *target , const KeyValues *userData = NULL);
virtual int AddMenuItem( const char *itemText, const char *command, Panel *target , const KeyValues *userData = NULL);
virtual int AddMenuItem( const char *itemText, KeyValues *message, Panel *target, const KeyValues *userData = NULL );
virtual int AddMenuItem( const char *itemText, Panel *target, const KeyValues *userData = NULL );
// Add a checkable item to the menu
virtual int AddCheckableMenuItem( const char *itemName, const char *itemText, const char *command, Panel *target, const KeyValues *userData = NULL );
virtual int AddCheckableMenuItem( const char *itemName, const wchar_t *wszItemText, const char *command, Panel *target, const KeyValues *userData = NULL );
virtual int AddCheckableMenuItem( const char *itemName, const char *itemText, KeyValues *message, Panel *target, const KeyValues *userData = NULL );
virtual int AddCheckableMenuItem( const char *itemName, const wchar_t *wszItemText, KeyValues *message, Panel *target, const KeyValues *userData = NULL );
virtual int AddCheckableMenuItem( const char *itemText, const char *command, Panel *target , const KeyValues *userData = NULL);
virtual int AddCheckableMenuItem( const char *itemText, KeyValues *message, Panel *target, const KeyValues *userData = NULL );
virtual int AddCheckableMenuItem( const char *itemText, Panel *target, const KeyValues *userData = NULL );
// Add a cascading menu item to the menu
virtual int AddCascadingMenuItem( const char *itemName, const char *itemText, const char *command, Panel *target, Menu *cascadeMenu, const KeyValues *userData = NULL );
virtual int AddCascadingMenuItem( const char *itemName, const wchar_t *wszItemText, const char *command, Panel *target, Menu *cascadeMenu, const KeyValues *userData = NULL );
virtual int AddCascadingMenuItem( const char *itemName, const char *itemText, KeyValues *message, Panel *target, Menu *cascadeMenu, const KeyValues *userData = NULL );
virtual int AddCascadingMenuItem( const char *itemName, const wchar_t *wszItemText, KeyValues *message, Panel *target, Menu *cascadeMenu, const KeyValues *userData = NULL );
virtual int AddCascadingMenuItem( const char *itemText, const char *command, Panel *target, Menu *cascadeMenu, const KeyValues *userData = NULL );
virtual int AddCascadingMenuItem( const char *itemText, KeyValues *message, Panel *target, Menu *cascadeMenu, const KeyValues *userData = NULL );
virtual int AddCascadingMenuItem( const char *itemText, Panel *target, Menu *cascadeMenu, const KeyValues *userData = NULL );
// Add a custom panel to the menu
virtual int AddMenuItem( MenuItem *panel );
virtual void AddSeparator();
virtual void AddSeparatorAfterItem( int itemID );
// Sets the values of a menu item at the specified index
virtual void UpdateMenuItem(int itemID, const char *itemText,KeyValues *message, const KeyValues *userData = NULL);
virtual void UpdateMenuItem(int itemID, const wchar_t *wszItemText,KeyValues *message, const KeyValues *userData = NULL);
virtual void MoveMenuItem( int itemID, int moveBeforeThisItemID );
virtual bool IsValidMenuID(int itemID);
virtual int GetInvalidMenuID();
KeyValues *GetItemUserData(int itemID);
void GetItemText(int itemID, wchar_t *text, int bufLenInBytes);
void GetItemText(int itemID, char *text, int bufLenInBytes);
virtual void SetItemEnabled(const char *itemName, bool state);
virtual void SetItemEnabled(int itemID, bool state);
virtual void SetItemVisible(const char *itemName, bool visible);
virtual void SetItemVisible(int itemID, bool visible);
// Remove a single item
void DeleteItem( int itemID );
// Clear the menu, deleting all the menu items within
void DeleteAllItems();
// Override the auto-width setting with a single fixed width
virtual void SetFixedWidth( int width );
// Sets the content alignment of all items in the menu
void SetContentAlignment( Label::Alignment alignment );
// sets the height of each menu item
virtual void SetMenuItemHeight(int itemHeight);
virtual int GetMenuItemHeight() const;
// Set the max number of items visible (scrollbar appears with more)
virtual void SetNumberOfVisibleItems( int numItems );
// Add the menu to the menu manager (see Menu::SetVisible())?
void EnableUseMenuManager( bool bUseMenuManager );
// Set up the menu items layout
virtual void PerformLayout( void );
virtual void SetBorder(class IBorder *border);
virtual void ApplySchemeSettings(IScheme *pScheme);
// Set type ahead behaviour
enum MenuTypeAheadMode
{
COMPAT_MODE = 0,
HOT_KEY_MODE,
TYPE_AHEAD_MODE,
};
virtual void SetTypeAheadMode(MenuTypeAheadMode mode);
virtual int GetTypeAheadMode();
// Hotkey handling
virtual void OnKeyTyped(wchar_t unichar);
// Menu nagivation etc.
virtual void OnKeyCodeTyped( KeyCode code );
// Visibility
virtual void SetVisible(bool state);
// Activates item in the menu list, as if that menu item had been selected by the user
virtual void ActivateItem(int itemID);
virtual void SilentActivateItem(int itemID); // activate item, but don't fire the action signal
virtual void ActivateItemByRow(int row);
virtual int GetActiveItem(); // returns the itemID (not the row) of the active item
// Return the number of items currently in the menu list
virtual int GetItemCount();
// return the menuID of the n'th item in the menu list, valid from [0, GetItemCount)
virtual int GetMenuID(int index);
// Return the number of items currently visible in the menu list
int GetCurrentlyVisibleItemsCount();
MenuItem *GetMenuItem(int itemID);
void CloseOtherMenus(MenuItem *item);
virtual void OnKillFocus();
int GetMenuMode();
enum MenuMode
{
MOUSE = 0,
KEYBOARD,
};
void SetCurrentlyHighlightedItem(int itemID);
int GetCurrentlyHighlightedItem();
void ClearCurrentlyHighlightedItem();
// Set the checked state of a checkable menuItem
void SetMenuItemChecked(int itemID, bool state);
bool IsChecked(int index); // check if item is checked.
void SetMinimumWidth(int width);
int GetMinimumWidth();
// baseclass overrides to chain colors through to cascade menus
virtual void SetFgColor( Color newColor );
virtual void SetBgColor( Color newColor );
virtual void SetFont( HFont font );
// Pass in NULL hotkey to remove hotkey
void SetCurrentKeyBinding( int itemID, char const *hotkey );
void ForceCalculateWidth();
void SetUseFallbackFont( bool bState, HFont hFallback );
protected:
// helper functions
int AddMenuItemCharCommand(MenuItem *item, const char *command, Panel *target, const KeyValues *userData);
int AddMenuItemKeyValuesCommand(MenuItem *item, KeyValues *message, Panel *target, const KeyValues *userData);
// vgui result reporting
virtual void OnCommand( const char *command );
MESSAGE_FUNC_PTR( OnMenuItemSelected, "MenuItemSelected", panel );
virtual void AddScrollBar();
virtual void RemoveScrollBar();
MESSAGE_FUNC( OnSliderMoved, "ScrollBarSliderMoved" );
virtual void Paint();
virtual void LayoutMenuBorder();
virtual void MakeItemsVisibleInScrollRange( int maxVisibleItems, int nNumPixelsAvailable );
virtual void OnMouseWheeled(int delta);
// Alternate OnKeyTyped behaviors
virtual void OnHotKey(wchar_t unichar);
virtual void OnTypeAhead(wchar_t unichar);
int CountVisibleItems();
void ComputeWorkspaceSize( int& workWide, int& workTall );
int ComputeFullMenuHeightWithInsets();
void CalculateWidth();
void LayoutScrollBar();
void PositionCascadingMenu();
void SizeMenuItems();
void OnCursorMoved(int x, int y);
void OnKeyCodePressed(KeyCode code);
void OnMenuClose();
MESSAGE_FUNC( OnKeyModeSet, "KeyModeSet" );
void SetCurrentlySelectedItem(MenuItem *item);
void SetCurrentlySelectedItem(int itemID);
MESSAGE_FUNC_INT( OnCursorEnteredMenuItem, "CursorEnteredMenuItem", VPanel);
MESSAGE_FUNC_INT( OnCursorExitedMenuItem, "CursorExitedMenuItem", VPanel);
void MoveAlongMenuItemList(int direction, int loopCount);
enum
{
DEFAULT_MENU_ITEM_HEIGHT = 22, // height of items in the menu
MENU_UP = -1, // used for moving up/down list of menu items in the menu
MENU_DOWN = 1
};
#ifdef DBGFLAG_VALIDATE
virtual void Validate( CValidator &validator, char *pchName );
#endif // DBGFLAG_VALIDATE
private:
MenuItem *GetParentMenuItem();
int m_iMenuItemHeight;
int m_iFixedWidth;
int m_iMinimumWidth; // a minimum width the menu has to be if it is not fixed width
int m_iNumVisibleLines; // number of items in menu before scroll bar adds on
ScrollBar *m_pScroller;
CUtlLinkedList<MenuItem*, int> m_MenuItems;
CUtlVector<int> m_VisibleSortedItems;
CUtlVector<int> m_SortedItems; // used for visual
CUtlVector<int> m_Separators; // menu item ids after which separators should be shown
CUtlVector<MenuSeparator *> m_SeparatorPanels;
bool _sizedForScrollBar: 1 ; // whether menu has been sized for a scrollbar
bool m_bUseFallbackFont : 1;
bool _recalculateWidth : 1;
bool m_bUseMenuManager : 1;
int _menuWide;
int m_iCurrentlySelectedItemID;
int m_iInputMode;
int m_iCheckImageWidth; // the size of the check box spot on a checkable menu.
int m_iProportionalScrollBarSize;
Label::Alignment m_Alignment;
Color _borderDark;
int m_iActivatedItem;
HFont m_hItemFont;
HFont m_hFallbackItemFont;
// for managing type ahead
#define TYPEAHEAD_BUFSIZE 256
MenuTypeAheadMode m_eTypeAheadMode;
wchar_t m_szTypeAheadBuf[TYPEAHEAD_BUFSIZE];
int m_iNumTypeAheadChars;
double m_fLastTypeAheadTime;
};
} // namespace vgui
#endif // MENU_H

View File

@@ -0,0 +1,54 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MENUBAR_H
#define MENUBAR_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Panel.h>
#include <utlvector.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class MenuBar : public Panel
{
DECLARE_CLASS_SIMPLE( MenuBar, Panel );
public:
MenuBar(Panel *parent, const char *panelName);
~MenuBar();
virtual void AddButton(MenuButton *button); // add button to end of menu list
virtual void AddMenu( const char *pButtonName, Menu *pMenu );
virtual void GetContentSize( int& w, int&h );
protected:
virtual void OnKeyCodeTyped(KeyCode code);
virtual void OnKeyTyped(wchar_t unichar);
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void PerformLayout();
virtual void Paint();
MESSAGE_FUNC( OnMenuClose, "MenuClose" );
MESSAGE_FUNC_INT( OnCursorEnteredMenuButton, "CursorEnteredMenuButton", VPanel);
private:
CUtlVector<MenuButton *> m_pMenuButtons;
int m_nRightEdge;
};
} // namespace vgui
#endif // MENUBAR_H

View File

@@ -0,0 +1,82 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MENUBUTTON_H
#define MENUBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Button.h>
#include "vgui_controls/Menu.h"
namespace vgui
{
class Menu;
class TextImage;
//-----------------------------------------------------------------------------
// Purpose: Button that displays a menu when pressed
//-----------------------------------------------------------------------------
class MenuButton : public Button
{
DECLARE_CLASS_SIMPLE( MenuButton, Button );
public:
MenuButton(Panel *parent, const char *panelName, const char *text);
~MenuButton();
// functions designed to be overriden
virtual void OnShowMenu(Menu *menu) {}
virtual void OnHideMenu(Menu *menu) {}
virtual int OnCheckMenuItemCount() { return 0; }
virtual void SetMenu(Menu *menu);
virtual void HideMenu(void);
virtual void DrawFocusBorder(int tx0, int ty0, int tx1, int ty1);
MESSAGE_FUNC( OnMenuClose, "MenuClose" );
MESSAGE_FUNC_PARAMS( OnKillFocus, "KillFocus", kv ); // called after the panel loses the keyboard focus
virtual void DoClick();
virtual void SetOpenOffsetY(int yOffset);
virtual bool CanBeDefaultButton(void);
// sets the direction in which the menu opens from the button, defaults to down
virtual void SetOpenDirection(Menu::MenuDirection_e direction);
virtual void OnKeyCodeTyped(KeyCode code);
virtual void OnCursorEntered();
virtual void Paint();
virtual void PerformLayout();
virtual void ApplySchemeSettings( IScheme *pScheme );
virtual void OnCursorMoved( int x, int y );
// This style is like the IE "back" button where the left side acts like a regular button, the the right side has a little
// combo box dropdown indicator and presents and submenu
void SetDropMenuButtonStyle( bool state );
bool IsDropMenuButtonStyle() const;
Menu *GetMenu();
private:
Menu *m_pMenu;
Menu::MenuDirection_e m_iDirection;
int _openOffsetY; // vertical offset of menu from the menu button
bool m_bDropMenuButtonStyle : 1;
TextImage *m_pDropMenuImage;
int m_nImageIndex;
};
}; // namespace vgui
#endif // MENUBUTTON_H

View File

@@ -0,0 +1,136 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MENUITEM_H
#define MENUITEM_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/Menu.h>
namespace vgui
{
class IBorder;
class TextImage;
class Menu;
class Image;
//-----------------------------------------------------------------------------
// Purpose: The items in a menu
// MenuItems MUST have the Menu class as parents.
//-----------------------------------------------------------------------------
class MenuItem : public Button
{
DECLARE_CLASS_SIMPLE( MenuItem, Button );
public:
MenuItem(Menu *parent, const char *panelName, const char *text, Menu *cascadeMenu = NULL, bool checkable = false);
MenuItem(Menu *parent, const char *panelName, const wchar_t *wszText, Menu *cascadeMenu = NULL, bool checkable = false);
~MenuItem();
virtual void Paint();
// Activate the menu item as if it had been selected by the user
virtual void FireActionSignal();
virtual bool CanBeDefaultButton(void);
// Handle mouse cursor entering a MenuItem.
void OnCursorEntered();
// Handle mouse cursor exiting a MenuItem.
void OnCursorExited();
// Close the cascading menu if we have one.
void CloseCascadeMenu();
// Pass kill focus events up to parent on loss of focus
MESSAGE_FUNC( OnKillFocus, "MenuClose" );
// Return true if this item triggers a cascading menu
bool HasMenu();
// Set the size of the text portion of the label.
void SetTextImageSize(int wide, int tall);
//Return the size of the text portion of the label.
void GetTextImageSize(int &wide, int &tall);
// Return the size of the arrow portion of the label.
void GetArrowImageSize(int &wide, int &tall);
// Return the size of the check portion of the label.
void GetCheckImageSize(int &wide, int &tall);
// Return the menu that this menuItem contains
Menu *GetMenu();
virtual void PerformLayout();
// Respond to cursor movement
void OnCursorMoved(int x, int y);
// Highlight item
MESSAGE_FUNC( ArmItem, "ArmItem" );
// Unhighlight item.
MESSAGE_FUNC( DisarmItem, "DisarmItem" );
// is the item highlighted?
bool IsItemArmed();
// Open cascading menu if there is one.
void OpenCascadeMenu();
bool IsCheckable();
bool IsChecked();
// Set a checkable menuItem checked or unchecked.
void SetChecked(bool state);
KeyValues *GetUserData();
void SetUserData(const KeyValues *kv);
int GetActiveItem() { if ( m_pCascadeMenu ) { return m_pCascadeMenu->GetActiveItem(); } else { return 0; }}
Menu *GetParentMenu();
void SetCurrentKeyBinding( char const *keyName );
virtual void GetContentSize( int& cw, int &ch );
protected:
void OnKeyCodeReleased(KeyCode code);
void OnMenuClose();
MESSAGE_FUNC( OnKeyModeSet, "KeyModeSet" );
// vgui overrides
virtual void Init( void );
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual IBorder *GetBorder(bool depressed, bool armed, bool selected, bool keyfocus);
private:
enum { CHECK_INSET = 6 };
Menu *m_pCascadeMenu; // menu triggered to open upon selecting this menu item
bool m_bCheckable; // can this menu item have a little check to the left of it when you select it?
bool m_bChecked; // whether item is checked or not.
TextImage *m_pCascadeArrow; // little arrow that appears to the right of menuitems that open a menu
Image *m_pCheck; // the check that appears to the left of checked menu items
TextImage *m_pBlankCheck; // a blank image same size as the check for when items are not checked.
TextImage *m_pCurrentKeyBinding; // An optional indicator for the key currently bound to this menu item
KeyValues *m_pUserData;
};
} // namespace vgui
#endif // MENUITEM_H

View File

@@ -0,0 +1,98 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MESSAGEBOX_H
#define MESSAGEBOX_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Frame.h>
// prevent windows macros from messing with the class
#ifdef MessageBox
#undef MessageBox
#endif
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Popup discardable message box
//-----------------------------------------------------------------------------
class MessageBox : public Frame
{
DECLARE_CLASS_SIMPLE( MessageBox, Frame );
public:
// title - Text to be displayed in the title bar of the window
// text - Text message in the message box
// startMinimized - wether message box starts minimized. Starts invisible by default
// parent - parent panel of the message box, by default it has no parent. This will keep the box visible until the OK button is pressed.
MessageBox(const char *title, const char *text, Panel *parent = NULL);
MessageBox(const wchar_t *wszTitle, const wchar_t *wszText, Panel *parent = NULL);
~MessageBox();
// Put the message box into a modal state
virtual void DoModal(Frame *pFrameOver = NULL);
// make the message box appear and in a modeless state
virtual void ShowWindow(Frame *pFrameOver = NULL);
// Set a string command to be sent when the OK button is pressed
// Use AddActionSignalTarget() to mark yourself as a recipient of the command
virtual void SetCommand(const char *command);
virtual void SetCommand(KeyValues *command);
// Set the visibility of the OK button.
virtual void SetOKButtonVisible(bool state);
// Set the text on the OK button
virtual void SetOKButtonText(const char *buttonText);
virtual void SetOKButtonText(const wchar_t *wszButtonText);
// Cancel button (off by default)
void SetCancelButtonVisible(bool state);
void SetCancelButtonText(const char *buttonText);
void SetCancelButtonText(const wchar_t *wszButtonText);
void SetCancelCommand( KeyValues *command );
// Toggles visibility of the close box.
virtual void DisableCloseButton(bool state);
virtual void OnCommand( const char *pCommand );
// Shows the message box over the cursor
void ShowMessageBoxOverCursor( bool bEnable );
protected:
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme *pScheme);
protected:
Button *m_pOkButton;
Button *m_pCancelButton;
Label *m_pMessageLabel;
private:
MESSAGE_FUNC( OnShutdownRequest, "ShutdownRequest" );
void Init();
KeyValues *m_OkCommand;
KeyValues *m_CancelCommand;
vgui::Frame *m_pFrameOver;
bool m_bNoAutoClose : 1;
bool m_bShowMessageBoxOverCursor : 1;
};
} // namespace vgui
#endif // MESSAGEBOX_H

View File

@@ -0,0 +1,154 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Contains the CMessageDialog declaration
//
// $NoKeywords: $
//=============================================================================//
#ifndef MESSAGEDIALOG_H
#define MESSAGEDIALOG_H
#ifdef _WIN32
#pragma once
#endif
// styles
#define MD_WARNING 0x0001
#define MD_ERROR 0x0002
// button configurations
#define MD_OK 0x0004 // 1 button - OK
#define MD_CANCEL 0x0008 // 1 button - CANCEL
#define MD_OKCANCEL 0x0010 // 2 buttons - OK and CANCEL
#define MD_YESNO 0x0020 // 2 buttons - YES and NO
// behavior
#define MD_SIMPLEFRAME 0x0100 // legacy corners
#define MD_COMMANDAFTERCLOSE 0x0200 // send command at dialog termination (i.e. after fade)
#define MD_RESTRICTPAINT 0x0400 // only paint this dialog (hide any other ui elements)
#define MD_COMMANDONFORCECLOSE 0x0800 // send command when the dialog is closed assuming A input
// dialog type
enum EDialogType
{
MD_SAVE_BEFORE_QUIT,
MD_QUIT_CONFIRMATION,
MD_QUIT_CONFIRMATION_TF,
MD_KICK_CONFIRMATION,
MD_CLIENT_KICKED,
MD_LOST_HOST,
MD_LOST_SERVER,
MD_SEARCHING_FOR_GAMES,
MD_CREATING_GAME,
MD_MODIFYING_SESSION,
MD_SESSION_SEARCH_FAILED,
MD_SESSION_CREATE_FAILED,
MD_SESSION_CONNECTING,
MD_SESSION_CONNECT_NOTAVAILABLE,
MD_SESSION_CONNECT_SESSIONFULL,
MD_SESSION_CONNECT_FAILED,
MD_EXIT_SESSION_CONFIRMATION,
MD_STORAGE_DEVICES_NEEDED,
MD_STORAGE_DEVICES_CHANGED,
MD_STORAGE_DEVICES_TOO_FULL,
MD_NOT_ONLINE_ENABLED,
MD_NOT_ONLINE_SIGNEDIN,
MD_DEFAULT_CONTROLS_CONFIRM,
MD_AUTOSAVE_EXPLANATION,
MD_COMMENTARY_EXPLANATION,
MD_COMMENTARY_EXPLANATION_MULTI,
MD_COMMENTARY_CHAPTER_UNLOCK_EXPLANATION,
MD_SAVE_BEFORE_LANGUAGE_CHANGE,
MD_SAVE_BEFORE_NEW_GAME,
MD_SAVE_BEFORE_LOAD,
MD_DELETE_SAVE_CONFIRM,
MD_SAVE_OVERWRITE,
MD_SAVING_WARNING,
MD_SAVE_COMPLETE,
MD_STANDARD_SAMPLE,
MD_WARNING_SAMPLE,
MD_ERROR_SAMPLE,
MD_PROMPT_SIGNIN,
MD_PROMPT_SIGNIN_REQUIRED,
MD_PROMPT_STORAGE_DEVICE,
MD_PROMPT_STORAGE_DEVICE_REQUIRED,
MD_DISCONNECT_CONFIRMATION,
MD_DISCONNECT_CONFIRMATION_HOST,
MD_LOAD_FAILED_WARNING,
MD_OPTION_CHANGE_FROM_X360_DASHBOARD,
MD_STORAGE_DEVICES_CORRUPT,
MD_CHECKING_STORAGE_DEVICE
};
#include "vgui_controls/Frame.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/AnimatingImagePanel.h"
#include "vgui_controls/ImagePanel.h"
//-----------------------------------------------------------------------------
// Purpose: Simple modal dialog box for Xbox 360 warnings and messages
//-----------------------------------------------------------------------------
class CMessageDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CMessageDialog, vgui::Frame );
public:
CMessageDialog( vgui::Panel *parent, const uint nType, const char *pTitle, const char *pMsg, const char *pCmdA, const char *pCmdB, vgui::Panel *pParent, bool bShowActivity );
~CMessageDialog();
enum
{
BTN_INVALID = -1,
BTN_B,
BTN_A,
MAX_BUTTONS,
};
struct ButtonLabel_s
{
vgui::Label *pIcon;
vgui::Label *pText;
int nWide;
bool bCreated;
};
virtual void OnKeyCodePressed( vgui::KeyCode code );
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void ApplySettings( KeyValues *inResourceData );
virtual void PaintBackground();
uint GetType( void );
void SetControlSettingsKeys( KeyValues *pKeys );
private:
void CreateButtonLabel( ButtonLabel_s *pButton, const char *pIcon, const char *pText );
void DoCommand( int button );
vgui::Panel *m_pCreator;
vgui::Label *m_pTitle;
vgui::Label *m_pMsg;
vgui::ImagePanel *m_pBackground;
vgui::AnimatingImagePanel *m_pAnimatingPanel;
vgui::HFont m_hButtonFont;
vgui::HFont m_hTextFont;
uint m_nType;
Color m_ButtonTextColor;
int m_ButtonPressed;
KeyValues *m_pControlSettings;
int m_FooterTall;
int m_ButtonMargin;
Color m_clrNotSimpleBG;
Color m_clrNotSimpleBGBlack;
int m_ButtonIconLabelSpace;
int m_ActivityIndent;
bool m_bShowActivity; // should we show an animating image panel?
ButtonLabel_s m_Buttons[MAX_BUTTONS];
char *m_pCommands[MAX_BUTTONS];
};
#endif // MESSAGEDIALOG_H

View File

@@ -0,0 +1,381 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MESSAGEMAP_H
#define MESSAGEMAP_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlvector.h"
// more flexible than default pointers to members code required for casting member function pointers
//#pragma pointers_to_members( full_generality, virtual_inheritance )
namespace vgui
{
////////////// MESSAGEMAP DEFINITIONS //////////////
//-----------------------------------------------------------------------------
// Purpose: parameter data type enumeration
// used internal but the shortcut macros require this to be exposed
//-----------------------------------------------------------------------------
enum DataType_t
{
DATATYPE_VOID,
DATATYPE_CONSTCHARPTR,
DATATYPE_INT,
DATATYPE_FLOAT,
DATATYPE_PTR,
DATATYPE_BOOL,
DATATYPE_KEYVALUES,
DATATYPE_CONSTWCHARPTR,
DATATYPE_UINT64,
DATATYPE_HANDLE, // It's an int, really
};
#ifdef WIN32
class __virtual_inheritance Panel;
#else
class Panel;
#endif
typedef unsigned int VPANEL;
typedef void (Panel::*MessageFunc_t)(void);
//-----------------------------------------------------------------------------
// Purpose: Single item in a message map
// Contains the information to map a string message name with parameters
// to a function call
//-----------------------------------------------------------------------------
#pragma warning(disable:4121)
struct MessageMapItem_t
{
const char *name;
// VC6 aligns this to 16-bytes. Since some of the code has been compiled with VC6,
// we need to enforce the alignment on later compilers to remain compatible.
ALIGN16 MessageFunc_t func;
int numParams;
DataType_t firstParamType;
const char *firstParamName;
DataType_t secondParamType;
const char *secondParamName;
int nameSymbol;
int firstParamSymbol;
int secondParamSymbol;
};
#define DECLARE_PANELMESSAGEMAP( className ) \
static void AddToMap( char const *scriptname, vgui::MessageFunc_t function, int paramCount, int p1type, const char *p1name, int p2type, const char *p2name ) \
{ \
vgui::PanelMessageMap *map = vgui::FindOrAddPanelMessageMap( GetPanelClassName() ); \
\
vgui::MessageMapItem_t entry; \
entry.name = scriptname; \
entry.func = function; \
entry.numParams = paramCount; \
entry.firstParamType = (vgui::DataType_t)p1type; \
entry.firstParamName = p1name; \
entry.secondParamType = (vgui::DataType_t)p2type; \
entry.secondParamName = p2name; \
entry.nameSymbol = 0; \
entry.firstParamSymbol = 0; \
entry.secondParamSymbol = 0; \
\
map->entries.AddToTail( entry ); \
} \
\
static void ChainToMap( void ) \
{ \
static bool chained = false; \
if ( chained ) \
return; \
chained = true; \
vgui::PanelMessageMap *map = vgui::FindOrAddPanelMessageMap( GetPanelClassName() ); \
map->pfnClassName = &GetPanelClassName; \
if ( map && GetPanelBaseClassName() && GetPanelBaseClassName()[0] ) \
{ \
map->baseMap = vgui::FindOrAddPanelMessageMap( GetPanelBaseClassName() ); \
} \
} \
\
class className##_RegisterMap; \
friend class className##_RegisterMap; \
class className##_RegisterMap \
{ \
public: \
className##_RegisterMap() \
{ \
className::ChainToMap(); \
} \
}; \
className##_RegisterMap m_RegisterClass; \
\
virtual vgui::PanelMessageMap *GetMessageMap() \
{ \
static vgui::PanelMessageMap *s_pMap = vgui::FindOrAddPanelMessageMap( GetPanelClassName() ); \
return s_pMap; \
}
#if !defined( _XBOX )
#define VGUI_USEKEYBINDINGMAPS 1
#endif
#if defined( VGUI_USEKEYBINDINGMAPS )
#define DECLARE_CLASS_SIMPLE( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass; \
public: \
DECLARE_PANELMESSAGEMAP( className ); \
DECLARE_PANELANIMATION( className ); \
DECLARE_KEYBINDINGMAP( className ); \
static char const *GetPanelClassName() { return #className; } \
static char const *GetPanelBaseClassName() { return #baseClassName; }
#define DECLARE_CLASS_SIMPLE_NOBASE( className ) \
typedef className ThisClass; \
public: \
DECLARE_PANELMESSAGEMAP( className ); \
DECLARE_PANELANIMATION( className ); \
DECLARE_KEYBINDINGMAP( className ); \
static char const *GetPanelClassName() { return #className; } \
static char const *GetPanelBaseClassName() { return NULL; }
#else // no keybinding maps
#define DECLARE_CLASS_SIMPLE( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass; \
public: \
DECLARE_PANELMESSAGEMAP( className ); \
DECLARE_PANELANIMATION( className ); \
static char const *GetPanelClassName() { return #className; } \
static char const *GetPanelBaseClassName() { return #baseClassName; }
#define DECLARE_CLASS_SIMPLE_NOBASE( className ) \
typedef className ThisClass; \
public: \
DECLARE_PANELMESSAGEMAP( className ); \
DECLARE_PANELANIMATION( className ); \
static char const *GetPanelClassName() { return #className; } \
static char const *GetPanelBaseClassName() { return NULL; }
#endif // !VGUI_USEKEYBINDINGMAPS
#define _MessageFuncCommon( name, scriptname, paramCount, p1type, p1name, p2type, p2name ) \
class PanelMessageFunc_##name; \
friend class PanelMessageFunc_##name; \
class PanelMessageFunc_##name \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
AddToMap( scriptname, (vgui::MessageFunc_t)&ThisClass::name, paramCount, p1type, p1name, p2type, p2name ); \
} \
} \
PanelMessageFunc_##name() \
{ \
PanelMessageFunc_##name::InitVar(); \
} \
}; \
PanelMessageFunc_##name m_##name##_register; \
// Use this macro to define a message mapped function
// must end with a semicolon ';', or with a function
// no parameter
#define MESSAGE_FUNC( name, scriptname ) _MessageFuncCommon( name, scriptname, 0, 0, 0, 0, 0 ); virtual void name( void )
// one parameter
#define MESSAGE_FUNC_INT( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_INT, #p1, 0, 0 ); virtual void name( int p1 )
#define MESSAGE_FUNC_UINT64( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_UINT64, #p1, 0, 0 ); virtual void name( uint64 p1 )
#define MESSAGE_FUNC_PTR( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_PTR, #p1, 0, 0 ); virtual void name( vgui::Panel *p1 )
#define MESSAGE_FUNC_HANDLE( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_HANDLE, #p1, 0, 0 ); virtual void name( vgui::VPANEL p1 )
#define MESSAGE_FUNC_ENUM( name, scriptname, t1, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_INT, #p1, 0, 0 ); virtual void name( t1 p1 )
#define MESSAGE_FUNC_FLOAT( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_FLOAT, #p1, 0, 0 ); virtual void name( float p1 )
#define MESSAGE_FUNC_CHARPTR( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_CONSTCHARPTR, #p1, 0, 0 ); virtual void name( const char *p1 )
#define MESSAGE_FUNC_WCHARPTR( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_CONSTWCHARPTR, #p1, 0, 0 ); virtual void name( const wchar_t *p1 )
// two parameters
#define MESSAGE_FUNC_INT_INT( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_INT, #p1, vgui::DATATYPE_INT, #p2 ); virtual void name( int p1, int p2 )
#define MESSAGE_FUNC_PTR_INT( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_PTR, #p1, vgui::DATATYPE_INT, #p2 ); virtual void name( vgui::Panel *p1, int p2 )
#define MESSAGE_FUNC_HANDLE_INT( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_HANDLE, #p1, vgui::DATATYPE_INT, #p2 ); virtual void name( vgui::VPANEL p1, int p2 )
#define MESSAGE_FUNC_ENUM_ENUM( name, scriptname, t1, p1, t2, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_INT, #p1, vgui::DATATYPE_INT, #p2 ); virtual void name( t1 p1, t2 p2 )
#define MESSAGE_FUNC_INT_CHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_INT, #p1, vgui::DATATYPE_CONSTCHARPTR, #p2 ); virtual void name( int p1, const char *p2 )
#define MESSAGE_FUNC_PTR_CHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_PTR, #p1, vgui::DATATYPE_CONSTCHARPTR, #p2 ); virtual void name( vgui::Panel *p1, const char *p2 )
#define MESSAGE_FUNC_HANDLE_CHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_HANDLE, #p1, vgui::DATATYPE_CONSTCHARPTR, #p2 ); virtual void name( vgui::VPANEL p1, const char *p2 )
#define MESSAGE_FUNC_PTR_WCHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_PTR, #p1, vgui::DATATYPE_CONSTWCHARPTR, #p2 ); virtual void name( vgui::Panel *p1, const wchar_t *p2 )
#define MESSAGE_FUNC_HANDLE_WCHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_HANDLE, #p1, vgui::DATATYPE_CONSTWCHARPTR, #p2 ); virtual void name( vgui::VPANEL p1, const wchar_t *p2 )
#define MESSAGE_FUNC_CHARPTR_CHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_CONSTCHARPTR, #p1, vgui::DATATYPE_CONSTCHARPTR, #p2 ); virtual void name( const char *p1, const char *p2 )
// unlimited parameters (passed in the whole KeyValues)
#define MESSAGE_FUNC_PARAMS( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_KEYVALUES, NULL, 0, 0 ); virtual void name( KeyValues *p1 )
// no-virtual function version
#define MESSAGE_FUNC_NV( name, scriptname ) _MessageFuncCommon( name, scriptname, 0, 0, 0, 0, 0 ); void name( void )
#define MESSAGE_FUNC_NV_INT( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_INT, #p1, 0, 0 ); void name( int p1 )
#define MESSAGE_FUNC_NV_INT_INT( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_INT, #p1, vgui::DATATYPE_INT, #p2 ); void name( int p1, int p2 )
// mapping, one per class
struct PanelMessageMap
{
PanelMessageMap()
{
baseMap = NULL;
pfnClassName = NULL;
processed = false;
}
CUtlVector< MessageMapItem_t > entries;
bool processed;
PanelMessageMap *baseMap;
char const *(*pfnClassName)( void );
};
PanelMessageMap *FindPanelMessageMap( char const *className );
PanelMessageMap *FindOrAddPanelMessageMap( char const *className );
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// OBSELETE MAPPING FUNCTIONS, USE ABOVE
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// no parameters
#define MAP_MESSAGE( type, name, func ) { name, (vgui::MessageFunc_t)(&type::func), 0 }
// implicit single parameter (params is the data store)
#define MAP_MESSAGE_PARAMS( type, name, func ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_KEYVALUES, NULL }
// single parameter
#define MAP_MESSAGE_PTR( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_PTR, param1 }
#define MAP_MESSAGE_INT( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_INT, param1 }
#define MAP_MESSAGE_BOOL( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_BOOL, param1 }
#define MAP_MESSAGE_FLOAT( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_FLOAT, param1 }
#define MAP_MESSAGE_PTR( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_PTR, param1 }
#define MAP_MESSAGE_CONSTCHARPTR( type, name, func, param1) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_CONSTCHARPTR, param1 }
#define MAP_MESSAGE_CONSTWCHARPTR( type, name, func, param1) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_CONSTWCHARPTR, param1 }
// two parameters
#define MAP_MESSAGE_INT_INT( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_INT, param1, vgui::DATATYPE_INT, param2 }
#define MAP_MESSAGE_PTR_INT( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_PTR, param1, vgui::DATATYPE_INT, param2 }
#define MAP_MESSAGE_INT_CONSTCHARPTR( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_INT, param1, vgui::DATATYPE_CONSTCHARPTR, param2 }
#define MAP_MESSAGE_PTR_CONSTCHARPTR( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_PTR, param1, vgui::DATATYPE_CONSTCHARPTR, param2 }
#define MAP_MESSAGE_PTR_CONSTWCHARPTR( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_PTR, param1, vgui::DATATYPE_CONSTWCHARPTR, param2 }
#define MAP_MESSAGE_CONSTCHARPTR_CONSTCHARPTR( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_CONSTCHARPTR, param1, vgui::DATATYPE_CONSTCHARPTR, param2 }
// if more parameters are needed, just use MAP_MESSAGE_PARAMS() and pass the keyvalue set into the function
//-----------------------------------------------------------------------------
// Purpose: stores the list of objects in the hierarchy
// used to iterate through an object's message maps
//-----------------------------------------------------------------------------
struct PanelMap_t
{
MessageMapItem_t *dataDesc;
int dataNumFields;
const char *dataClassName;
PanelMap_t *baseMap;
int processed;
};
// for use in class declarations
// declares the static variables and functions needed for the data description iteration
#define DECLARE_PANELMAP() \
static vgui::PanelMap_t m_PanelMap; \
static vgui::MessageMapItem_t m_MessageMap[]; \
virtual vgui::PanelMap_t *GetPanelMap( void );
// could embed typeid() into here as well?
#define IMPLEMENT_PANELMAP( derivedClass, baseClass ) \
vgui::PanelMap_t derivedClass::m_PanelMap = { derivedClass::m_MessageMap, ARRAYSIZE(derivedClass::m_MessageMap), #derivedClass, &baseClass::m_PanelMap }; \
vgui::PanelMap_t *derivedClass::GetPanelMap( void ) { return &m_PanelMap; }
typedef vgui::Panel *( *PANELCREATEFUNC )( void );
//-----------------------------------------------------------------------------
// Purpose: Used by DECLARE_BUILD_FACTORY macro to create a linked list of
// instancing functions
//-----------------------------------------------------------------------------
class CBuildFactoryHelper
{
public:
// Static list of helpers
static CBuildFactoryHelper *m_sHelpers;
public:
// Construction
CBuildFactoryHelper( char const *className, PANELCREATEFUNC func );
// Accessors
CBuildFactoryHelper *GetNext( void );
char const *GetClassName() const;
vgui::Panel *CreatePanel();
static vgui::Panel *InstancePanel( char const *className );
static void GetFactoryNames( CUtlVector< char const * >& list );
private:
static bool HasFactory( char const *className );
// Next factory in list
CBuildFactoryHelper *m_pNext;
int m_Type;
PANELCREATEFUNC m_CreateFunc;
char const *m_pClassName;
};
// This is the macro which implements creation of each type of panel
// It creates a function which instances an object of the specified type
// It them hooks that function up to the helper list so that the CHud objects can create
// the elements by name, with no header file dependency, etc.
#define DECLARE_BUILD_FACTORY( className ) \
static vgui::Panel *Create_##className( void ) \
{ \
return new className( NULL, NULL ); \
}; \
static vgui::CBuildFactoryHelper g_##className##_Helper( #className, Create_##className );\
className *g_##className##LinkerHack = NULL;
#define DECLARE_BUILD_FACTORY_DEFAULT_TEXT( className, defaultText ) \
static vgui::Panel *Create_##className( void ) \
{ \
return new className( NULL, NULL, #defaultText ); \
}; \
static vgui::CBuildFactoryHelper g_##className##_Helper( #className, Create_##className );\
className *g_##className##LinkerHack = NULL;
// This one allows passing in a special function with calls new panel( xxx ) with arbitrary default parameters
#define DECLARE_BUILD_FACTORY_CUSTOM( className, createFunc ) \
static vgui::CBuildFactoryHelper g_##className##_Helper( #className, createFunc );\
className *g_##className##LinkerHack = NULL;
#define DECLARE_BUILD_FACTORY_CUSTOM_ALIAS( className, factoryName, createFunc ) \
static vgui::CBuildFactoryHelper g_##factoryName##_Helper( #factoryName, createFunc );\
className *g_##factoryName##LinkerHack = NULL;
} // namespace vgui
#endif // MESSAGEMAP_H

View File

@@ -0,0 +1,86 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PHANDLE_H
#define PHANDLE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
namespace vgui
{
class Panel;
//-----------------------------------------------------------------------------
// Purpose: Safe pointer class for handling Panel or derived panel classes
//-----------------------------------------------------------------------------
class PHandle
{
public:
PHandle() : m_iPanelID(INVALID_PANEL) {} //m_iSerialNumber(0), m_pListEntry(0) {}
Panel *Get();
Panel *Set( Panel *pPanel );
Panel *Set( HPanel hPanel );
operator Panel *() { return Get(); }
Panel * operator ->() { return Get(); }
Panel * operator = (Panel *pPanel) { return Set(pPanel); }
bool operator == (Panel *pPanel) { return (Get() == pPanel); }
operator bool () { return Get() != 0; }
private:
HPanel m_iPanelID;
};
//-----------------------------------------------------------------------------
// Purpose: Safe pointer class to just convert between VPANEL's and PHandle
//-----------------------------------------------------------------------------
class VPanelHandle
{
public:
VPanelHandle() : m_iPanelID(INVALID_PANEL) {}
VPANEL Get();
VPANEL Set( VPANEL pPanel );
operator VPANEL () { return Get(); }
VPANEL operator = (VPANEL pPanel) { return Set(pPanel); }
bool operator == (VPANEL pPanel) { return (Get() == pPanel); }
operator bool () { return Get() != 0; }
private:
HPanel m_iPanelID;
};
//-----------------------------------------------------------------------------
// Purpose: DHANDLE is a templated version of PHandle
//-----------------------------------------------------------------------------
template< class PanelType >
class DHANDLE : public PHandle
{
public:
PanelType *Get() { return (PanelType *)PHandle::Get(); }
PanelType *Set( PanelType *pPanel ) { return (PanelType *)PHandle::Set(pPanel); }
PanelType *Set( HPanel hPanel ) { return (PanelType *)PHandle::Set(hPanel); }
operator PanelType *() { return (PanelType *)PHandle::Get(); }
PanelType * operator ->() { return (PanelType *)PHandle::Get(); }
PanelType * operator = (PanelType *pPanel) { return (PanelType *)PHandle::Set(pPanel); }
bool operator == (Panel *pPanel) { return (PHandle::Get() == pPanel); }
operator bool () { return PHandle::Get() != NULL; }
};
};
#endif // PHANDLE_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,161 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef PANELANIMATIONVAR_H
#define PANELANIMATIONVAR_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlvector.h"
#include <vgui_controls/Panel.h>
#define DECLARE_PANELANIMATION( className ) \
static void AddToAnimationMap( char const *scriptname, char const *type, char const *var, \
char const *defaultvalue, bool array, PANELLOOKUPFUNC func ) \
{ \
PanelAnimationMap *map = FindOrAddPanelAnimationMap( GetPanelClassName() ); \
\
PanelAnimationMapEntry entry; \
entry.m_pszScriptName = scriptname; \
entry.m_pszVariable = var; \
entry.m_pszType = type; \
entry.m_pszDefaultValue = defaultvalue; \
entry.m_pfnLookup = func; \
entry.m_bArray = array; \
\
map->entries.AddToTail( entry ); \
} \
\
static void ChainToAnimationMap( void ) \
{ \
static bool chained = false; \
if ( chained ) \
return; \
chained = true; \
PanelAnimationMap *map = FindOrAddPanelAnimationMap( GetPanelClassName() ); \
map->pfnClassName = GetPanelClassName; \
if ( map && GetPanelBaseClassName() && GetPanelBaseClassName()[0] ) \
{ \
map->baseMap = FindOrAddPanelAnimationMap( GetPanelBaseClassName() ); \
} \
} \
\
class className##_Register; \
friend class className##_Register; \
class className##_Register \
{ \
public: \
className##_Register() \
{ \
className::ChainToAnimationMap(); \
} \
}; \
className##_Register m_RegisterAnimationClass; \
\
virtual PanelAnimationMap *GetAnimMap() \
{ \
return FindOrAddPanelAnimationMap( GetPanelClassName() ); \
}
typedef void *( *PANELLOOKUPFUNC )( vgui::Panel *panel );
// Use this macro to define a variable which hudanimations.txt and hudlayout.res scripts can access
#define CPanelAnimationVarAliasType( type, name, scriptname, defaultvalue, typealias ) \
class PanelAnimationVar_##name; \
friend class PanelAnimationVar_##name; \
static void *GetVar_##name( vgui::Panel *panel ) \
{ \
return &(( ThisClass *)panel)->name; \
} \
class PanelAnimationVar_##name \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
AddToAnimationMap( scriptname, typealias, #name, defaultvalue, false, ThisClass::GetVar_##name ); \
} \
} \
PanelAnimationVar_##name() \
{ \
PanelAnimationVar_##name::InitVar(); \
} \
}; \
PanelAnimationVar_##name m_##name##_register; \
type name;
#define CPanelAnimationVar( type, name, scriptname, defaultvalue ) \
CPanelAnimationVarAliasType( type, name, scriptname, defaultvalue, #type )
// Use this macro to define a variable which hudanimations.txt and hudlayout.res scripts can access
#define CPanelAnimationStringVarAliasType( count, name, scriptname, defaultvalue, typealias ) \
class PanelAnimationVar_##name; \
friend class PanelAnimationVar_##name; \
static void *GetVar_##name( vgui::Panel *panel ) \
{ \
return &(( ThisClass *)panel)->name; \
} \
class PanelAnimationVar_##name \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
AddToAnimationMap( scriptname, typealias, #name, defaultvalue, true, ThisClass::GetVar_##name ); \
} \
} \
PanelAnimationVar_##name() \
{ \
PanelAnimationVar_##name::InitVar(); \
} \
}; \
PanelAnimationVar_##name m_##name##_register; \
char name[ count ];
#define CPanelAnimationStringVar( count, name, scriptname, defaultvalue ) \
CPanelAnimationStringVarAliasType( count, name, scriptname, defaultvalue, "string" )
struct PanelAnimationMapEntry
{
char const *name() { return m_pszScriptName; }
char const *type() { return m_pszType; }
char const *defaultvalue() { return m_pszDefaultValue; }
bool isarray() { return m_bArray; }
char const *m_pszScriptName;
char const *m_pszVariable;
char const *m_pszType;
char const *m_pszDefaultValue;
bool m_bArray;
PANELLOOKUPFUNC m_pfnLookup;
};
struct PanelAnimationMap
{
PanelAnimationMap()
{
baseMap = NULL;
pfnClassName = NULL;
}
CUtlVector< PanelAnimationMapEntry > entries;
PanelAnimationMap *baseMap;
char const *(*pfnClassName)( void );
};
PanelAnimationMap *FindPanelAnimationMap( char const *className );
PanelAnimationMap *FindOrAddPanelAnimationMap( char const *className );
void PanelAnimationDumpVars( char const *className );
#endif // PANELANIMATIONVAR_H

View File

@@ -0,0 +1,126 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PANELLISTPANEL_H
#define PANELLISTPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <utllinkedlist.h>
#include <utlvector.h>
#include <vgui/VGUI.h>
#include <vgui_controls/EditablePanel.h>
class KeyValues;
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: A list of variable height child panels
// each list item consists of a label-panel pair. Height of the item is
// determined from the label.
//-----------------------------------------------------------------------------
class PanelListPanel : public EditablePanel
{
DECLARE_CLASS_SIMPLE( PanelListPanel, Panel );
public:
PanelListPanel( vgui::Panel *parent, char const *panelName );
~PanelListPanel();
// DATA & ROW HANDLING
// The list now owns the panel
virtual int AddItem( Panel *labelPanel, Panel *panel );
int GetItemCount() const;
int GetItemIDFromRow( int nRow ) const;
// Iteration. Use these until they return InvalidItemID to iterate all the items.
int FirstItem() const;
int NextItem( int nItemID ) const;
int InvalidItemID() const;
virtual Panel *GetItemLabel(int itemID);
virtual Panel *GetItemPanel(int itemID);
ScrollBar* GetScrollbar() { return m_vbar; }
virtual void RemoveItem(int itemID); // removes an item from the table (changing the indices of all following items)
virtual void DeleteAllItems(); // clears and deletes all the memory used by the data items
void RemoveAll();
// painting
virtual vgui::Panel *GetCellRenderer( int row );
// layout
void SetFirstColumnWidth( int width );
int GetFirstColumnWidth();
void SetNumColumns( int iNumColumns );
int GetNumColumns( void );
void MoveScrollBarToTop();
// selection
void SetSelectedPanel( Panel *panel );
Panel *GetSelectedPanel();
/*
On a panel being selected, a message gets sent to it
"PanelSelected" int "state"
where state is 1 on selection, 0 on deselection
*/
void SetVerticalBufferPixels( int buffer );
void ScrollToItem( int itemNumber );
CUtlVector< int > *GetSortedVector( void )
{
return &m_SortedItems;
}
int ComputeVPixelsNeeded();
protected:
// overrides
virtual void OnSizeChanged(int wide, int tall);
MESSAGE_FUNC_INT( OnSliderMoved, "ScrollBarSliderMoved", position );
virtual void PerformLayout();
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
virtual void OnMouseWheeled(int delta);
private:
enum { DEFAULT_HEIGHT = 24, PANELBUFFER = 5 };
typedef struct dataitem_s
{
// Always store a panel pointer
Panel *panel;
Panel *labelPanel;
} DATAITEM;
// list of the column headers
CUtlLinkedList<DATAITEM, int> m_DataItems;
CUtlVector<int> m_SortedItems;
ScrollBar *m_vbar;
Panel *m_pPanelEmbedded;
PHandle m_hSelectedItem;
int m_iFirstColumnWidth;
int m_iNumColumns;
int m_iDefaultHeight;
int m_iPanelBuffer;
CPanelAnimationVar( bool, m_bAutoHideScrollbar, "autohide_scrollbar", "0" );
};
}
#endif // PANELLISTPANEL_H

View File

@@ -0,0 +1,67 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Allows you to browse a directory structure, showing perforce files
//
// $NoKeywords: $
//===========================================================================//
#ifndef PERFORCEFILEEXPLORER_H
#define PERFORCEFILEEXPLORER_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlstring.h"
#include "vgui_controls/Frame.h"
namespace vgui
{
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class PerforceFileList;
class ComboBox;
class Button;
//-----------------------------------------------------------------------------
// Contains a list of files, determines their perforce status
//-----------------------------------------------------------------------------
class PerforceFileExplorer : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( PerforceFileExplorer, Frame );
public:
// The context keyvalues are added to all messages sent by this dialog if they are specified
PerforceFileExplorer( Panel *parent, const char *pPanelName );
~PerforceFileExplorer();
// Inherited from Frame
virtual void ApplySchemeSettings( IScheme *pScheme );
virtual void PerformLayout();
protected:
MESSAGE_FUNC_PARAMS( OnTextChanged, "TextChanged", kv );
MESSAGE_FUNC( OnItemDoubleClicked, "ItemDoubleClicked" );
MESSAGE_FUNC( OnFolderUp, "FolderUp" );
void PopulateFileList();
void PopulateDriveList();
// Returns the current directory
void SetCurrentDirectory( const char *pCurrentDirectory );
Button *m_pFolderUpButton;
ComboBox *m_pFullPathCombo;
PerforceFileList *m_pFileList;
CUtlString m_CurrentDirectory;
};
} // namespace vgui
#endif // PERFORCEFILEEXPLORER_H

View File

@@ -0,0 +1,114 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Contains a list of files, determines their perforce status
//
// $NoKeywords: $
//===========================================================================//
#ifndef PERFORCEFILELIST_H
#define PERFORCEFILELIST_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlstring.h"
#include "tier1/UtlStringMap.h"
#include "vgui_controls/ListPanel.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
struct P4File_t;
namespace vgui
{
class ListPanel;
}
namespace vgui
{
//-----------------------------------------------------------------------------
// Contains a list of files, determines their perforce status
//-----------------------------------------------------------------------------
class PerforceFileList : public vgui::ListPanel
{
DECLARE_CLASS_SIMPLE( PerforceFileList, ListPanel );
public:
// The context keyvalues are added to all messages sent by this dialog if they are specified
PerforceFileList( Panel *parent, const char *pPanelName );
~PerforceFileList();
// Add a file to the file list. Note that this file may exist on disk or not
// and it may exist in perforce or not. It's specified as a full path on disk though.
// In the case where a file doesn't exist on disk, but it does exist in perforce
// specify where that file would appear on disk.
// This function returns the itemID of the added file
// If you already know the file exists or is a directory (or not), specify that in the call.
// -1 means autodetect whether the file exists or is a directory
int AddFile( const char *pFullPath, int nFileExists = -1, int nIsDirectory = -1 );
// Is a file already in the list?
bool IsFileInList( const char *pFullPath );
// Find the item ID associated with a particular file
int FindFile( const char *pFullPath );
// Remove all files from the list
void RemoveAllFiles();
// Refresh perforce information
void Refresh();
// Refresh perforce information manually
void RefreshPerforceState( int nItemID, bool bFileExists, P4File_t *pFileInfo );
// Is a particular list item a directory?
bool IsDirectoryItem( int nItemID );
// Returns the file associated with a particular item ID
const char *GetFile( int nItemID );
// Toggle showing deleted files or not
void ShowDeletedFiles( bool bShowDeletedFiles );
// Inherited from vgui::EditablePanel
virtual void ApplySchemeSettings( IScheme *pScheme );
virtual void OnMouseDoublePressed( MouseCode code );
/*
messages sent:
"ItemDoubleClicked" // Called when an item is double-clicked
*/
protected:
struct DirectoryInfo_t
{
CUtlString m_ClientSpec;
CUtlVector< int > m_ItemIDs;
};
// Add a file to the file list.
int AddFileToFileList( const char *pFullPath, bool bExistsOnDisk );
// Add a directory to the file list.
int AddDirectoryToFileList( const char *pFullPath, bool bExistsOnDisk );
// Add a directory to the directory list, returns client spec
void AddItemToDirectoryList( const char *pFullPath, int nItemID, bool bIsDirectory );
// Used to look up directories -> client specs
CUtlStringMap< DirectoryInfo_t > m_Directories;
// Show deleted files?
bool m_bShowDeletedFiles;
};
} // namespace vgui
#endif // PERFORCEFILELIST_H

View File

@@ -0,0 +1,103 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PROGRESSBAR_H
#define PROGRESSBAR_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Status bar that visually displays discrete progress in the form
// of a segmented strip
//-----------------------------------------------------------------------------
class ProgressBar : public Panel
{
DECLARE_CLASS_SIMPLE( ProgressBar, Panel );
public:
ProgressBar(Panel *parent, const char *panelName);
~ProgressBar();
// 'progress' is in the range [0.0f, 1.0f]
MESSAGE_FUNC_FLOAT( SetProgress, "SetProgress", progress );
float GetProgress();
virtual void SetSegmentInfo( int gap, int width );
// utility function for calculating a time remaining string
static bool ConstructTimeRemainingString(OUT_Z_BYTECAP(outputBufferSizeInBytes) wchar_t *output, int outputBufferSizeInBytes, float startTime, float currentTime, float currentProgress, float lastProgressUpdateTime, bool addRemainingSuffix);
void SetBarInset( int pixels );
int GetBarInset( void );
void SetMargin( int pixels );
int GetMargin();
virtual void ApplySettings(KeyValues *inResourceData);
virtual void GetSettings(KeyValues *outResourceData);
virtual const char *GetDescription();
// returns the number of segment blocks drawn
int GetDrawnSegmentCount();
enum ProgressDir_e
{
PROGRESS_EAST,
PROGRESS_WEST,
PROGRESS_NORTH,
PROGRESS_SOUTH
};
int GetProgressDirection() const { return m_iProgressDirection; }
void SetProgressDirection( int val ) { m_iProgressDirection = val; }
protected:
virtual void Paint();
void PaintSegment( int &x, int &y, int tall, int wide );
virtual void PaintBackground();
virtual void ApplySchemeSettings(IScheme *pScheme);
MESSAGE_FUNC_PARAMS( OnDialogVariablesChanged, "DialogVariables", dialogVariables );
/* CUSTOM MESSAGE HANDLING
"SetProgress"
input: "progress" - float value of the progress to set
*/
protected:
int m_iProgressDirection;
float _progress;
private:
int _segmentCount;
int _segmentGap;
int _segmentWide;
int m_iBarInset;
int m_iBarMargin;
char *m_pszDialogVar;
};
//-----------------------------------------------------------------------------
// Purpose: Non-segmented progress bar
//-----------------------------------------------------------------------------
class ContinuousProgressBar : public ProgressBar
{
DECLARE_CLASS_SIMPLE( ContinuousProgressBar, ProgressBar );
public:
ContinuousProgressBar(Panel *parent, const char *panelName);
virtual void Paint();
};
} // namespace vgui
#endif // PROGRESSBAR_H

View File

@@ -0,0 +1,99 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PROGRESSBOX_H
#define PROGRESSBOX_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Frame.h>
// prevent windows macros from messing with the class
#ifdef ProgressBox
#undef ProgressBox
#endif
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Popup discardable message box
//-----------------------------------------------------------------------------
class ProgressBox : public Frame
{
DECLARE_CLASS_SIMPLE( ProgressBox, Frame );
public:
// title - Text to be displayed in the title bar of the window
// text - Text message in the message box
// parent - parent panel of the message box, by default it has no parent.
ProgressBox(const char *title, const char *text, const char *pszUnknownTimeString, Panel *parent = NULL);
ProgressBox(const wchar_t *wszTitle, const wchar_t *wszText, const wchar_t *wszUnknownTimeString, Panel *parent = NULL);
~ProgressBox();
// Put the message box into a modal state
virtual void DoModal(Frame *pFrameOver = NULL);
// make the message box appear and in a modeless state
virtual void ShowWindow(Frame *pFrameOver = NULL);
// updates progress bar, range [0, 1]
virtual void SetProgress(float progress);
// sets the info text
virtual void SetText(const char *text);
// toggles visibility of the close box.
virtual void SetCancelButtonVisible(bool state);
// toggles the enabled state of the cancel button (for if it needs to be disabled part way through a process)
virtual void SetCancelButtonEnabled(bool state);
/* custom messages:
"ProgressBoxCancelled"
sent if the user pressed the cancel button (must be enabled & visible for this to happen)
*/
protected:
virtual void PerformLayout();
virtual void OnClose();
virtual void OnCloseFrameButtonPressed();
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void OnThink();
virtual void OnCommand(const char *command);
virtual void OnTick();
// called when the update has been cancelled
virtual void OnCancel();
private:
MESSAGE_FUNC( OnShutdownRequest, "ShutdownRequest" );
void Init();
void UpdateTitle();
Label *m_pMessageLabel;
ProgressBar *m_pProgressBar;
Button *m_pCancelButton;
wchar_t m_wszTitleString[128];
wchar_t m_wcsInfoString[128];
wchar_t m_wszUnknownTimeString[128];
float m_flFirstProgressUpdate;
float m_flLastProgressUpdate;
float m_flCurrentProgress;
};
} // namespace vgui
#endif // PROGRESSBOX_H

View File

@@ -0,0 +1,84 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PROPERTYDIALOG_H
#define PROPERTYDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Frame.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Simple frame that holds a property sheet
//-----------------------------------------------------------------------------
class PropertyDialog : public Frame
{
DECLARE_CLASS_SIMPLE( PropertyDialog, Frame );
public:
PropertyDialog(Panel *parent, const char *panelName);
~PropertyDialog();
// returns a pointer to the PropertySheet this dialog encapsulates
virtual PropertySheet *GetPropertySheet();
// wrapper for PropertySheet interface
virtual void AddPage(Panel *page, const char *title);
virtual Panel *GetActivePage();
virtual void ResetAllData();
virtual void ApplyChanges();
// sets the text on the OK/Cancel buttons, overriding the default
void SetOKButtonText(const char *text);
void SetCancelButtonText(const char *text);
void SetApplyButtonText(const char *text);
// changes the visibility of the buttons
void SetOKButtonVisible(bool state);
void SetCancelButtonVisible(bool state);
void SetApplyButtonVisible(bool state);
/* MESSAGES SENT
"ResetData" - sent when page is loaded. Data should be reloaded from document into controls.
"ApplyChanges" - sent when the OK / Apply button is pressed. Changed data should be written into document.
*/
protected:
// Called when the OK button is pressed. Simply closes the dialog.
virtual bool OnOK(bool applyOnly);
// called when the Cancel button is pressed
virtual void OnCancel();
// vgui overrides
virtual void PerformLayout();
virtual void OnCommand(const char *command);
virtual void ActivateBuildMode();
virtual void OnKeyCodeTyped(KeyCode code);
virtual void RequestFocus(int direction = 0);
MESSAGE_FUNC( OnApplyButtonEnable, "ApplyButtonEnable" );
void EnableApplyButton(bool bEnable);
private:
PropertySheet *_propertySheet;
Button *_okButton;
Button *_cancelButton;
Button *_applyButton;
CPanelAnimationVar( int, m_iSheetInsetBottom, "sheetinset_bottom", "32" );
};
}; // vgui
#endif // PROPERTYDIALOG_H

View File

@@ -0,0 +1,58 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PROPERTYPAGE_H
#define PROPERTYPAGE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/EditablePanel.h>
#include <vgui_controls/PHandle.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Property page, as held by a set of property sheets
//-----------------------------------------------------------------------------
class PropertyPage : public EditablePanel
{
DECLARE_CLASS_SIMPLE( PropertyPage, EditablePanel );
public:
PropertyPage(Panel *parent, const char *panelName);
~PropertyPage();
// Called when page is loaded. Data should be reloaded from document into controls.
MESSAGE_FUNC( OnResetData, "ResetData" );
// Called when the OK / Apply button is pressed. Changed data should be written into document.
MESSAGE_FUNC( OnApplyChanges, "ApplyChanges" );
// called when the page is shown/hidden
MESSAGE_FUNC( OnPageShow, "PageShow" );
MESSAGE_FUNC( OnPageHide, "PageHide" );
virtual void OnKeyCodeTyped(KeyCode code);
virtual bool HasUserConfigSettings() { return true; }
virtual void SetVisible(bool state);
protected:
// called to be notified of the tab button used to Activate this page
// if overridden this must be chained back to
MESSAGE_FUNC_PTR( OnPageTabActivated, "PageTabActivated", panel );
private:
PHandle _pageTab;
};
} // namespace vgui
#endif // PROPERTYPAGE_H

View File

@@ -0,0 +1,209 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PROPERTYSHEET_H
#define PROPERTYSHEET_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui/VGUI.h"
#include "vgui_controls/EditablePanel.h"
#include "vgui_controls/PHandle.h"
#include "utlvector.h"
namespace vgui
{
class PageTab;
class ImagePanel;
//-----------------------------------------------------------------------------
// Purpose: Tabbed property sheet. Holds and displays a set of Panel's
//-----------------------------------------------------------------------------
class PropertySheet : public EditablePanel
{
DECLARE_CLASS_SIMPLE( PropertySheet, EditablePanel );
public:
PropertySheet(Panel *parent, const char *panelName, bool draggableTabs = false );
PropertySheet(Panel *parent, const char *panelName,ComboBox *combo);
~PropertySheet();
virtual bool IsDraggableTab() const;
void SetDraggableTabs( bool state );
// Adds a page to the sheet. The first page added becomes the active sheet.
virtual void AddPage(Panel *page, const char *title, char const *imageName = NULL, bool showContextMenu = false );
// sets the current page
virtual void SetActivePage(Panel *page);
// sets the width, in pixels, of the page tab buttons.
virtual void SetTabWidth(int pixels);
// Gets a pointer to the currently active page.
virtual Panel *GetActivePage();
// Removes (but doesn't delete) all pages
virtual void RemoveAllPages();
// Removes all the pages and marks all the pages for deletion.
virtual void DeleteAllPages();
// reloads the data in all the property page
virtual void ResetAllData();
// writes out any changed data to the doc
virtual void ApplyChanges();
// focus handling - passed on to current active page
virtual void RequestFocus(int direction = 0);
virtual bool RequestFocusPrev(VPANEL panel = NULL);
virtual bool RequestFocusNext(VPANEL panel = NULL);
// returns the ith panel
virtual Panel *GetPage(int i);
// deletes this panel from the sheet
virtual void DeletePage(Panel *panel);
// removes this panel from the sheet, sets its parent to NULL, but does not delete it
virtual void RemovePage(Panel *panel);
// returns the current activated tab
virtual Panel *GetActiveTab();
// returns the title text of the tab
virtual void GetActiveTabTitle( char *textOut, int bufferLen );
// returns the title of tab "i"
virtual bool GetTabTitle( int i, char *textOut, int bufferLen );
// sets the title of tab "i"
virtual bool SetTabTitle( int i, char *pchTitle );
// returns the index of the active page
virtual int GetActivePageNum();
// returns the number of pages in the sheet
virtual int GetNumPages();
// disable the page with title "title"
virtual void DisablePage(const char *title);
// enable the page with title "title"
virtual void EnablePage(const char *title);
virtual void SetSmallTabs( bool state );
virtual bool IsSmallTabs() const;
/* MESSAGES SENT TO PAGES
"PageShow" - sent when a page is shown
"PageHide" - sent when a page is hidden
"ResetData" - sent when the data should be reloaded from doc
"ApplyChanges" - sent when data should be written to doc
*/
virtual void OnPanelDropped( CUtlVector< KeyValues * >& msglist );
virtual bool IsDroppable( CUtlVector< KeyValues * >& msglist );
// Mouse is now over a droppable panel
virtual void OnDroppablePanelPaint( CUtlVector< KeyValues * >& msglist, CUtlVector< Panel * >& dragPanels );
void ShowContextButtons( bool state );
bool ShouldShowContextButtons() const;
int FindPage( Panel *page ) const;
bool PageHasContextMenu( Panel *page ) const;
void SetKBNavigationEnabled( bool state );
bool IsKBNavigationEnabled() const;
virtual bool HasUserConfigSettings() { return true; }
protected:
virtual void PaintBorder();
virtual void PerformLayout();
virtual Panel *HasHotkey(wchar_t key);
virtual void ChangeActiveTab(int index);
virtual void OnKeyCodePressed(KeyCode code);
virtual void OnCommand(const char *command);
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void ApplySettings(KeyValues *inResourceData);
// internal message handlers
MESSAGE_FUNC_PTR( OnTabPressed, "TabPressed", panel );
MESSAGE_FUNC_PTR_WCHARPTR( OnTextChanged, "TextChanged", panel, text );
MESSAGE_FUNC_PARAMS( OnOpenContextMenu, "OpenContextMenu", params );
MESSAGE_FUNC( OnApplyButtonEnable, "ApplyButtonEnable" );
// called when default button has been set
MESSAGE_FUNC_HANDLE( OnDefaultButtonSet, "DefaultButtonSet", button );
// called when the current default button has been set
MESSAGE_FUNC_HANDLE( OnCurrentDefaultButtonSet, "CurrentDefaultButtonSet", button);
MESSAGE_FUNC( OnFindDefaultButton, "FindDefaultButton" );
private:
// enable/disable the page with title "title"
virtual void SetPageEnabled(const char *title,bool state);
struct Page_t
{
Page_t() :
page( 0 ),
contextMenu( false )
{
}
Panel *page;
bool contextMenu;
};
CUtlVector<Page_t> m_Pages;
CUtlVector<PageTab *> m_PageTabs;
Panel *_activePage;
PageTab *_activeTab;
int _tabWidth;
int _activeTabIndex;
ComboBox *_combo;
bool _showTabs;
bool _tabFocus;
PHandle m_hPreviouslyActivePage;
float m_flPageTransitionEffectTime;
bool m_bSmallTabs;
HFont m_tabFont;
bool m_bDraggableTabs;
bool m_bContextButton;
bool m_bKBNavigationEnabled;
CPanelAnimationVarAliasType( int, m_iTabXIndent, "tabxindent", "0", "proportional_int" );
CPanelAnimationVarAliasType( int, m_iTabXDelta, "tabxdelta", "0", "proportional_int" );
CPanelAnimationVarAliasType( bool, m_bTabFitText, "tabxfittotext", "1", "bool" );
//=============================================================================
// HPE_BEGIN:
// [tj] These variables have been split into the initially specified size
// and the currently set size. This is so we can always recalculate the
// new value for resolution changes.
//=============================================================================
CPanelAnimationVarAliasType( int, m_iSpecifiedTabHeight, "tabheight", "28", "int" );
CPanelAnimationVarAliasType( int, m_iSpecifiedTabHeightSmall, "tabheight_small", "14", "int" );
int m_iTabHeight;
int m_iTabHeightSmall;
//=============================================================================
// HPE_END
//=============================================================================
KeyValues *m_pTabKV;
};
}; // namespace vgui
#endif // PROPERTYSHEET_H

View File

@@ -0,0 +1,62 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Creates a Message box with a question in it and yes/no buttons
//
// $NoKeywords: $
//=============================================================================//
#ifndef QUERYBOX_H
#define QUERYBOX_H
#ifdef _WIN32
#pragma once
#endif
#include <KeyValues.h>
#include <vgui_controls/MessageBox.h>
#include <vgui_controls/Button.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Creates A Message box with a question in it and yes/no buttons
//-----------------------------------------------------------------------------
class QueryBox : public MessageBox
{
DECLARE_CLASS_SIMPLE( QueryBox, MessageBox );
public:
QueryBox(const char *title, const char *queryText,vgui::Panel *parent = NULL );
QueryBox(const wchar_t *wszTitle, const wchar_t *wszQueryText,vgui::Panel *parent = NULL);
~QueryBox();
// Layout the window for drawing
virtual void PerformLayout();
// Set the keyvalues to send when ok button is hit
void SetOKCommand(KeyValues *keyValues);
// Set the keyvalues to send when the cancel button is hit
void SetCancelCommand(KeyValues *keyValues);
// Set the text on the Cancel button
void SetCancelButtonText(const char *buttonText);
void SetCancelButtonText(const wchar_t *wszButtonText);
// Set a value of the ok command
void SetOKCommandValue(const char *keyName, int value);
protected:
virtual void OnKeyCodeTyped( KeyCode code );
virtual void OnKeyCodePressed( KeyCode code );
virtual void OnCommand(const char *command);
Button *m_pCancelButton;
private:
KeyValues *m_pCancelCommand;
KeyValues *m_pOkCommand;
};
}
#endif // QUERYBOX_H

View File

@@ -0,0 +1,112 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef RADIOBUTTON_H
#define RADIOBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/ToggleButton.h>
#include <vgui_controls/TextImage.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Radio buton image
//-----------------------------------------------------------------------------
class RadioImage : public TextImage
{
public:
RadioImage(RadioButton *radioButton) : TextImage( "n" )
{
_radioButton = radioButton;
SetSize(20, 13);
}
virtual void Paint();
virtual void SetColor(Color color)
{
_borderColor1 = color;
_borderColor2 = color;
_checkColor = color;
}
Color _borderColor1;
Color _borderColor2;
Color _checkColor;
Color _bgColor;
private:
RadioButton *_radioButton;
};
//-----------------------------------------------------------------------------
// Purpose: Radio buttons are automatically selected into groups by who their
// parent is. At most one radio button is active at any time.
//-----------------------------------------------------------------------------
class RadioButton : public ToggleButton
{
DECLARE_CLASS_SIMPLE( RadioButton, ToggleButton );
public:
RadioButton(Panel *parent, const char *panelName, const char *text);
~RadioButton();
// Set the radio button checked. When a radio button is checked, a
// message is sent to all other radio buttons in the same group so
// they will become unchecked.
virtual void SetSelected(bool state);
// Get the tab position of the radio button with the set of radio buttons
// A group of RadioButtons must have the same TabPosition, with [1, n] subtabpositions
virtual int GetSubTabPosition();
virtual void SetSubTabPosition(int position);
// Return the RadioButton's real tab position (its Panel one changes)
virtual int GetRadioTabPosition();
// Set the selection state of the radio button, but don't fire
// any action signals or messages to other radio buttons
virtual void SilentSetSelected(bool state);
protected:
virtual void DoClick();
virtual void Paint();
virtual void ApplySchemeSettings(IScheme *pScheme);
MESSAGE_FUNC_INT( OnRadioButtonChecked, "RadioButtonChecked", tabposition);
virtual void OnKeyCodeTyped(KeyCode code);
virtual IBorder *GetBorder(bool depressed, bool armed, bool selected, bool keyfocus);
virtual void ApplySettings(KeyValues *inResourceData);
virtual void GetSettings(KeyValues *outResourceData);
virtual const char *GetDescription();
virtual void PerformLayout();
RadioButton *FindBestRadioButton(int direction);
private:
RadioImage *_radioBoxImage;
int _oldTabPosition;
Color _selectedFgColor;
int _subTabPosition; // tab position with the radio button list
void InternalSetSelected(bool state, bool bFireEvents);
};
}; // namespace vgui
#endif // RADIOBUTTON_H

View File

@@ -0,0 +1,297 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef RICHTEXT_H
#define RICHTEXT_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Panel.h>
#include <utlvector.h>
namespace vgui
{
class ClickPanel;
//-----------------------------------------------------------------------------
// Purpose: Non-editable display of a rich text control
//-----------------------------------------------------------------------------
class RichText : public Panel
{
DECLARE_CLASS_SIMPLE( RichText, Panel );
public:
RichText(Panel *parent, const char *panelName);
~RichText();
// text manipulation
virtual void SetText(const char *text);
virtual void SetText(const wchar_t *text);
void GetText(int offset, OUT_Z_BYTECAP(bufLenInBytes) wchar_t *buf, int bufLenInBytes);
void GetText(int offset, OUT_Z_BYTECAP(bufLenInBytes) char *pch, int bufLenInBytes);
// configuration
void SetFont(HFont font);
// inserts characters at the end of the stream
void InsertChar(wchar_t ch);
void InsertString(const char *text);
void InsertString(const wchar_t *wszText);
// selection
void SelectNone();
void SelectAllText();
void SelectNoText();
MESSAGE_FUNC( CutSelected, "DoCutSelected" );
MESSAGE_FUNC( CopySelected, "DoCopySelected" );
// sets the RichText control interactive or not (meaning you can select/copy text in the window)
void SetPanelInteractive( bool bInteractive ){ m_bInteractive = bInteractive; }
// sets the RichText scrollbar invisible if it's not going to be used
void SetUnusedScrollbarInvisible( bool bInvis ){ m_bUnusedScrollbarInvis = bInvis; }
// cursor movement
void GotoTextStart(); // go to start of text buffer
void GotoTextEnd(); // go to end of text buffer
// configuration
// sets visibility of scrollbar
void SetVerticalScrollbar(bool state);
// sets limit of number of characters insertable into field; set to -1 to remove maximum
// only works with if rich-edit is NOT enabled
void SetMaximumCharCount(int maxChars);
// rich edit commands
void InsertColorChange(Color col);
// IndentChange doesn't take effect until the next newline character
void InsertIndentChange(int pixelsIndent);
// clickable text
// notification that text was clicked is through "TextClicked" message
void InsertClickableTextStart( const char *pchClickAction = NULL );
void InsertClickableTextEnd();
// inserts a string that needs to be scanned for urls/mailto commands to be made clickable
void InsertPossibleURLString(const char *text, Color URLTextColor, Color normalTextColor);
void InsertFade( float flSustain, float flLength );
void ResetAllFades( bool bHold, bool bOnlyExpired = false, float flNewSustain = -1.0f );
// sets the height of the window so all text is visible.
// used by tooltips
void SetToFullHeight();
int GetNumLines();
/* CUSTOM MESSAGE HANDLING
"SetText"
input: "text" - text is set to be this string
*/
/* MESSAGE SENDING (to action signal targets)
"TextChanged" - sent when the text is edited by the user
"TextClicked" - sent when clickable text has been clicked on
"text" - the text that was clicked on
*/
virtual bool RequestInfo(KeyValues *outputData);
/* INFO HANDLING
"GetText"
returns:
"text" - text contained in the text box
*/
virtual void SetFgColor( Color color );
virtual void SetDrawOffsets( int ofsx, int ofsy );
bool IsScrollbarVisible();
// sets how URL's are handled
// if set, a "URLClicked" "url" "<data>" message will be sent to that panel
void SetURLClickedHandler( Panel *pPanelToHandleClickMsg );
void SetUnderlineFont( HFont font );
bool IsAllTextAlphaZero() const;
bool HasText() const;
void SetDrawTextOnly();
protected:
virtual void OnThink();
virtual void PerformLayout(); // layout the text in the window
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void Paint();
virtual void ApplySettings( KeyValues *inResourceData );
virtual void GetSettings( KeyValues *outResourceData );
virtual const char *GetDescription( void );
MESSAGE_FUNC_WCHARPTR( OnSetText, "SetText", text );
MESSAGE_FUNC( OnSliderMoved, "ScrollBarSliderMoved" ); // respond to scroll bar events
virtual void OnKillFocus();
virtual void OnMouseWheeled(int delta); // respond to mouse wheel events
virtual void OnKeyCodeTyped(KeyCode code); //respond to keyboard events
MESSAGE_FUNC_INT( OnClickPanel, "ClickPanel", index);
virtual void OnCursorMoved(int x, int y); // respond to moving the cursor with mouse button down
virtual void OnMousePressed(MouseCode code); // respond to mouse down events
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code); // respond to mouse up events
virtual void OnMouseFocusTicked(); // do while window has mouse focus
virtual void OnCursorEntered(); // handle cursor entering window
virtual void OnCursorExited(); // handle cursor exiting window
virtual void OnMouseCaptureLost();
virtual void OnSizeChanged(int newWide, int newTall);
virtual void OnSetFocus();
// clickable url handling
int ParseTextStringForUrls(const char *text, int startPos, char *pchURLText, int cchURLText, char *pchURL, int cchURL, bool &clickable);
virtual void OnTextClicked(const wchar_t *text);
#ifdef DBGFLAG_VALIDATE
virtual void Validate( CValidator &validator, char *pchName );
#endif // DBGFLAG_VALIDATE
protected:
ScrollBar *_vertScrollBar; // the scroll bar used in the window
private:
int GetLineHeight();
HFont GetDefaultFont();
const wchar_t *ResolveLocalizedTextAndVariables( char const *pchLookup, OUT_Z_BYTECAP(outbufsizeinbytes) wchar_t *outbuf, size_t outbufsizeinbytes );
void CheckRecalcLineBreaks();
void GotoWordRight(); // move cursor to start of next word
void GotoWordLeft(); // move cursor to start of prev word
void TruncateTextStream();
bool GetSelectedRange(int& cx0,int& cx1);
void CursorToPixelSpace(int cursorPos, int &cx, int &cy);
int PixelToCursorSpace(int cx, int cy);
void AddAnotherLine(int &cx, int &cy);
void RecalculateDefaultState(int startIndex);
void LayoutVerticalScrollBarSlider();
void OpenEditMenu();
void FinishingURL(int x, int y);
// Returns the character index the drawing should Start at
int GetStartDrawIndex(int &lineBreakIndexIndex);
int GetCursorLine();
int GetClickableTextIndexStart(int startIndex);
void CreateEditMenu(); // create copy/cut/paste menu
MESSAGE_FUNC_INT( MoveScrollBar, "MoveScrollBar", delta );
MESSAGE_FUNC_INT( MoveScrollBarDirect, "MoveScrollBarDirect", delta );
// linebreak stream functions
void InvalidateLineBreakStream();
void RecalculateLineBreaks();
struct TFade
{
float flFadeStartTime;
float flFadeLength;
float flFadeSustain;
int iOriginalAlpha;
};
// format stream - describes changes in formatting for the text stream
struct TFormatStream
{
// render state
Color color;
int pixelsIndent;
bool textClickable;
CUtlSymbol m_sClickableTextAction;
TFade fade;
// position in TextStream that these changes take effect
int textStreamIndex;
};
bool m_bResetFades;
bool m_bInteractive;
bool m_bUnusedScrollbarInvis;
bool m_bAllTextAlphaIsZero;
// data
CUtlVector<wchar_t> m_TextStream; // the text in the text window is stored in this buffer
CUtlVector<int> m_LineBreaks; // an array that holds the index in the buffer to wrap lines at
CUtlVector<TFormatStream> m_FormatStream; // list of format changes
bool m_bRecalcLineBreaks;
int _recalculateBreaksIndex; // tells next linebreakindex index to Start recalculating line breaks
bool _invalidateVerticalScrollbarSlider;
int _cursorPos; // the position in the text buffer of the blinking cursor
bool _mouseSelection; // whether we are highlighting text or not (selecting text)
bool _mouseDragSelection; // tells weather mouse is outside window and button is down so we select text
int _select[2]; // select[1] is the offset in the text to where the cursor is currently
// select[0] is the offset to where the cursor was dragged to. or -1 if no drag.
int _pixelsIndent;
int _maxCharCount; // max number of chars that can be in the text buffer
HFont _font; // font of chars in the text buffer
HFont m_hFontUnderline;
Color _selectionColor;
Color _selectionTextColor; // color of the highlighted text
bool _currentTextClickable;
CUtlVector<ClickPanel *> _clickableTextPanels;
int _clickableTextIndex;
Color _defaultTextColor;
int _drawOffsetX;
int _drawOffsetY;
Panel *m_pInterior;
PHandle m_hPanelToHandleClickingURLs;
// sub-controls
Menu *m_pEditMenu; // cut/copy/paste popup
char *m_pszInitialText; // initial text
// saved state
bool _recalcSavedRenderState;
struct TRenderState
{
// rendering positions
int x, y;
// basic state
Color textColor;
int pixelsIndent;
bool textClickable;
// index into our current position in the formatting stream
int formatStreamIndex;
};
TRenderState m_CachedRenderState; // cached render state for the beginning of painting
// updates a render state based on the formatting and color streams
// returns true if any state changed
bool UpdateRenderState(int textStreamPos, TRenderState &renderState);
void CalculateFade( TRenderState &renderState );
void GenerateRenderStateForTextStreamIndex(int textStreamIndex, TRenderState &renderState);
int FindFormatStreamIndexForTextStreamPos(int textStreamIndex);
// draws a string of characters with the same formatting using the current render state
int DrawString(int iFirst, int iLast, TRenderState &renderState, HFont font);
};
} // namespace vgui
#endif // RICHTEXT_H

View File

@@ -0,0 +1,67 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef ROTATINGPROGRESSBAR_H
#define ROTATINGPROGRESSBAR_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/ProgressBar.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Progress Bar that rotates an image around its center
//-----------------------------------------------------------------------------
class RotatingProgressBar : public ProgressBar
{
DECLARE_CLASS_SIMPLE( RotatingProgressBar, ProgressBar );
public:
RotatingProgressBar(Panel *parent, const char *panelName);
~RotatingProgressBar();
virtual void ApplySettings(KeyValues *inResourceData);
virtual void ApplySchemeSettings(IScheme *pScheme);
void SetImage( const char *imageName );
protected:
virtual void Paint();
virtual void PaintBackground();
virtual void OnTick();
private:
int m_nTextureId;
char *m_pszImageName;
float m_flStartRadians;
float m_flEndRadians;
float m_flLastAngle;
float m_flTickDelay;
float m_flApproachSpeed;
float m_flRotOriginX;
float m_flRotOriginY;
float m_flRotatingX;
float m_flRotatingY;
float m_flRotatingWide;
float m_flRotatingTall;
};
} // namespace vgui
#endif // ROTATINGPROGRESSBAR_H

View File

@@ -0,0 +1,59 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef SCALABLEIMAGEPANEL_H
#define SCALABLEIMAGEPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: 9-way Segmented background
//-----------------------------------------------------------------------------
class ScalableImagePanel : public Panel
{
DECLARE_CLASS_SIMPLE( ScalableImagePanel, Panel );
public:
ScalableImagePanel(Panel *parent, const char *name);
~ScalableImagePanel();
virtual void SetImage(const char *imageName);
void SetDrawColor( Color color ) { m_DrawColor = color; }
protected:
virtual void PaintBackground();
virtual void GetSettings(KeyValues *outResourceData);
virtual void ApplySettings(KeyValues *inResourceData);
virtual void PerformLayout( void );
virtual const char *GetDescription();
private:
int m_iSrcCornerHeight; // in pixels, how tall is the corner inside the image
int m_iSrcCornerWidth; // same for width
int m_iCornerHeight; // output size of the corner height in pixels
int m_iCornerWidth; // same for width
int m_iTextureID;
float m_flCornerWidthPercent; // corner width as percentage of image width
float m_flCornerHeightPercent; // same for height
char *m_pszImageName;
char *m_pszDrawColorName;
Color m_DrawColor;
};
} // namespace vgui
#endif // SCALABLEIMAGEPANEL_H

View File

@@ -0,0 +1,133 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef SCROLLBAR_H
#define SCROLLBAR_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
namespace vgui
{
class Button;
class ScrollBarSlider;
//-----------------------------------------------------------------------------
// Purpose: Generic scrollbar
// Uses Buttons & SliderBars for the main functionality
//-----------------------------------------------------------------------------
class ScrollBar : public Panel
{
DECLARE_CLASS_SIMPLE( ScrollBar, Panel );
public:
ScrollBar(Panel *parent, const char *panelName, bool vertical);
// Set the value of the scroll bar slider.
virtual void SetValue(int value);
// Get the value of the scroll bar slider.
virtual int GetValue();
// Set the rangeof numbers the slider can scroll through
virtual void SetRange(int min,int max);
virtual void GetRange(int &min, int &max);
// Set how many lines are displayed at one time
// in the window the scroll bar is attached to.
virtual void SetRangeWindow(int rangeWindow);
// Get how many lines are displayed at one time
// in the window the scroll bar is attached to.
virtual int GetRangeWindow();
// Check if the scrollbar is vertical or horizontal
virtual bool IsVertical();
// Purpose: Check if the slider can move through one or more pixels per
// unit of its range.
virtual bool HasFullRange();
// Setup the indexed scroll bar button with the input params.
virtual void SetButton(Button* button,int index);
// Return the indexed scroll bar button
virtual Button *GetButton(int index);
// Set up the slider.
virtual void SetSlider(ScrollBarSlider* slider);
// Return a pointer to the slider.
virtual ScrollBarSlider *GetSlider();
// Set how far the scroll bar slider moves
// when a scroll bar button is pressed
virtual void SetButtonPressedScrollValue(int value);
virtual void Validate();
// Update and look for clicks when mouse is in the scroll bar window.
virtual void OnMouseFocusTicked();
// Set the slider's Paint border enabled.
virtual void SetPaintBorderEnabled(bool state);
// Set the slider's Paint background enabled.
virtual void SetPaintBackgroundEnabled(bool state);
// Set the slider's Paint enabled.
virtual void SetPaintEnabled(bool state);
// Sets the scrollbar buttons visible or not
virtual void SetScrollbarButtonsVisible(bool visible);
void SetAutohideButtons( bool bAutohide ) { m_bAutoHideButtons = bAutohide; }
void UseImages( const char *pszUpArrow, const char *pszDownArrow, const char *pszLine, const char *pszBox );
/* MESSAGES SENT:
"ScrollBarSliderMoved"
"position" - new value of the slider
*/
void SetOverriddenButtons( Button *pB1, Button *pB2 ) { m_pOverriddenButtons[0] = pB1; m_pOverriddenButtons[1] = pB2; }
virtual void ApplySettings( KeyValues *pInResourceData );
protected:
virtual void PerformLayout();
virtual void SendSliderMoveMessage(int value);
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void OnSizeChanged(int wide, int tall);
MESSAGE_FUNC_INT( OnSliderMoved, "ScrollBarSliderMoved", position );
virtual void RespondToScrollArrow(int const direction);
virtual void UpdateButtonsForImages( void );
virtual void UpdateSliderImages( void );
Button *GetDepressedButton( int iIndex );
private:
Button* _button[2];
ScrollBarSlider* _slider;
int _buttonPressedScrollValue;
int _scrollDelay; // used to control delays in scrolling
bool _respond;
bool m_bNoButtons;
CPanelAnimationVar( bool, m_bAutoHideButtons, "autohide_buttons", "0" );
vgui::ImagePanel *m_pUpArrow;
vgui::ImagePanel *m_pLine;
vgui::ImagePanel *m_pDownArrow;
vgui::ImagePanel *m_pBox;
Button *m_pOverriddenButtons[2];
};
}
#endif // SCROLLBAR_H

View File

@@ -0,0 +1,94 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef SCROLLBARSLIDER_H
#define SCROLLBARSLIDER_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
namespace vgui
{
class IBorder;
//-----------------------------------------------------------------------------
// Purpose: ScrollBarSlider bar, as used in ScrollBar's
//-----------------------------------------------------------------------------
class ScrollBarSlider : public Panel
{
DECLARE_CLASS_SIMPLE( ScrollBarSlider, Panel );
public:
ScrollBarSlider(Panel *parent, const char *panelName, bool vertical);
// Set the ScrollBarSlider value of the nob.
virtual void SetValue(int value);
virtual int GetValue();
// Check whether the scroll bar is vertical or not
virtual bool IsVertical();
// Set max and min range of lines to display
virtual void SetRange(int min, int max);
virtual void GetRange(int &min, int &max);
// Set number of rows that can be displayed in window
virtual void SetRangeWindow(int rangeWindow);
// Get number of rows that can be displayed in window
virtual int GetRangeWindow();
// Set the size of the ScrollBarSlider nob
virtual void SetSize(int wide, int tall);
// Get current ScrollBarSlider bounds
virtual void GetNobPos(int &min, int &max);
virtual bool HasFullRange();
virtual void SetButtonOffset(int buttonOffset);
virtual void OnCursorMoved(int x, int y);
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code);
// Return true if this slider is actually drawing itself
virtual bool IsSliderVisible( void );
virtual void ApplySettings( KeyValues *pInResourceData );
protected:
virtual void Paint();
virtual void PaintBackground();
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme *pScheme);
private:
virtual void RecomputeNobPosFromValue();
virtual void RecomputeValueFromNobPos();
virtual void SendScrollBarSliderMovedMessage();
bool _vertical;
bool _dragging;
int _nobPos[2];
int _nobDragStartPos[2];
int _dragStartPos[2];
int _range[2];
int _value; // the position of the ScrollBarSlider, in coordinates as specified by SetRange/SetRangeWindow
int _rangeWindow;
int _buttonOffset;
IBorder *_ScrollBarSliderBorder;
};
} // namespace vgui
#endif // SCROLLBARSLIDER_H

View File

@@ -0,0 +1,55 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#ifndef SCROLLABLEEDITABLEPANEL_H
#define SCROLLABLEEDITABLEPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/EditablePanel.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
namespace vgui
{
class ScrollBar;
}
namespace vgui
{
//-----------------------------------------------------------------------------
// An editable panel that has a scrollbar
//-----------------------------------------------------------------------------
class ScrollableEditablePanel : public vgui::EditablePanel
{
DECLARE_CLASS_SIMPLE( ScrollableEditablePanel, vgui::EditablePanel );
public:
ScrollableEditablePanel( vgui::Panel *pParent, vgui::EditablePanel *pChild, const char *pName );
virtual ~ScrollableEditablePanel() {}
virtual void ApplySettings( KeyValues *pInResourceData );
virtual void PerformLayout();
vgui::ScrollBar *GetScrollbar( void ) { return m_pScrollBar; }
MESSAGE_FUNC( OnScrollBarSliderMoved, "ScrollBarSliderMoved" );
virtual void OnMouseWheeled(int delta); // respond to mouse wheel events
private:
vgui::ScrollBar *m_pScrollBar;
vgui::EditablePanel *m_pChild;
};
} // end namespace vgui
#endif // SCROLLABLEEDITABLEPANEL_H

View File

@@ -0,0 +1,317 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef SECTIONEDLISTPANEL_H
#define SECTIONEDLISTPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <utlvector.h>
#include <utllinkedlist.h>
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/PHandle.h>
#include <vgui_controls/Label.h>
namespace vgui
{
class SectionedListPanel;
class SectionedListPanelHeader;
class CItemButton;
// sorting function, should return true if itemID1 should be displayed before itemID2
typedef bool (*SectionSortFunc_t)(SectionedListPanel *list, int itemID1, int itemID2);
//-----------------------------------------------------------------------------
// Purpose: List panel control that is divided up into discrete sections
//-----------------------------------------------------------------------------
class SectionedListPanel : public Panel
{
DECLARE_CLASS_SIMPLE( SectionedListPanel, Panel );
public:
SectionedListPanel(vgui::Panel *parent, const char *name);
~SectionedListPanel();
// adds a new section; returns false if section already exists
virtual void AddSection(int sectionID, const char *name, SectionSortFunc_t sortFunc = NULL);
virtual void AddSection(int sectionID, const wchar_t *name, SectionSortFunc_t sortFunc = NULL);
virtual void AddSection(int sectionID, SectionedListPanelHeader *pHeader, SectionSortFunc_t sortFunc = NULL);
// clears all the sections - leaves the items in place
virtual void RemoveAllSections();
// modifies section info
virtual void SetSectionFgColor(int sectionID, Color color);
virtual void SetSectionDividerColor( int sectionID, Color color);
// forces a section to always be visible
virtual void SetSectionAlwaysVisible(int sectionID, bool visible = true);
virtual void SetSectionMinimumHeight(int sectionID, int iMinimumHeight);
// adds a new column to a section
enum ColumnFlags_e
{
HEADER_IMAGE = 0x01, // set if the header for the column is an image instead of text
COLUMN_IMAGE = 0x02, // set if the column contains an image instead of text (images are looked up by index from the ImageList) (see SetImageList below)
COLUMN_BRIGHT = 0x04, // set if the column text should be the bright color
COLUMN_CENTER = 0x08, // set to center the text/image in the column
COLUMN_RIGHT = 0x10, // set to right-align the text in the column
};
virtual bool AddColumnToSection(int sectionID, const char *columnName, const char *columnText, int columnFlags, int width, HFont fallbackFont = INVALID_FONT );
virtual bool AddColumnToSection(int sectionID, const char *columnName, const wchar_t *columnText, int columnFlags, int width, HFont fallbackFont = INVALID_FONT );
// modifies the text in an existing column
virtual bool ModifyColumn(int sectionID, const char *columnName, const wchar_t *columnText);
// adds an item to the list; returns the itemID of the new item
virtual int AddItem(int sectionID, const KeyValues *data);
// modifies an existing item; returns false if the item does not exist
virtual bool ModifyItem(int itemID, int sectionID, const KeyValues *data);
// removes an item from the list; returns false if the item does not exist or is already removed
virtual bool RemoveItem(int itemID);
// clears the list
virtual void RemoveAll() { DeleteAllItems(); }
// DeleteAllItems() is deprecated, use RemoveAll();
virtual void DeleteAllItems();
// set the text color of an item
virtual void SetItemFgColor(int itemID, Color color);
//=============================================================================
// HPE_BEGIN:
// [menglish] Getters and setters for several item and section objects
//=============================================================================
virtual void SetItemBgColor( int itemID, Color color );
virtual int GetColumnIndexByName(int sectionID, char* name);
virtual int GetLineSpacing() { return m_iLineSpacing; }
//=============================================================================
// HPE_END
//=============================================================================
virtual void SetItemFont( int itemID, HFont font );
virtual void SetItemEnabled( int itemID, bool bEnabled );
/* MESSAGES SENT:
"RowSelected"
"itemID" - the selected item id, -1 if nothing selected
// when an item has been clicked on
"RowContextMenu" "itemID"
"RowLeftClick" "itemID"
"RowDoubleLeftClick" "itemID"
*/
// returns the number of columns in a section
virtual int GetColumnCountBySection(int sectionID);
// returns the name of a column by section and column index; returns NULL if there are no more columns
// valid range of columnIndex is [0, GetColumnCountBySection)
virtual const char *GetColumnNameBySection(int sectionID, int columnIndex);
virtual const wchar_t *GetColumnTextBySection(int sectionID, int columnIndex);
virtual int GetColumnFlagsBySection(int sectionID, int columnIndex);
virtual int GetColumnWidthBySection(int sectionID, int columnIndex);
virtual HFont GetColumnFallbackFontBySection( int sectionID, int columnIndex );
// returns the id of the currently selected item, -1 if nothing is selected
virtual int GetSelectedItem();
// sets which item is currently selected
virtual void SetSelectedItem(int itemID);
// remove selection
virtual void ClearSelection( void );
// returns the data of a selected item
// InvalidateItem(itemID) needs to be called if the KeyValues are modified
virtual KeyValues *GetItemData(int itemID);
// returns what section an item is in
virtual int GetItemSection(int itemID);
// forces an item to redraw (use when keyvalues have been modified)
virtual void InvalidateItem(int itemID);
// returns true if the itemID is valid for use
virtual bool IsItemIDValid(int itemID);
virtual int GetHighestItemID();
// returns the number of items (ignoring section dividers)
virtual int GetItemCount();
// returns the item ID from the row, again ignoring section dividers - valid from [0, GetItemCount )
virtual int GetItemIDFromRow(int row);
// returns the row that this itemID occupies. -1 if the itemID is invalid
virtual int GetRowFromItemID(int itemID);
// gets the local coordinates of a cell
virtual bool GetCellBounds(int itemID, int column, int &x, int &y, int &wide, int &tall);
// Gets the coordinates of a section header
virtual bool GetSectionHeaderBounds(int sectionID, int &x, int &y, int &wide, int &tall);
//=============================================================================
// HPE_BEGIN:
// [menglish] Get the bounds of an item or column.
//=============================================================================
// gets the local coordinates of a cell using the max width for every column
virtual bool GetMaxCellBounds(int itemID, int column, int &x, int &y, int &wide, int &tall);
// gets the local coordinates of an item
virtual bool GetItemBounds(int itemID, int &x, int &y, int &wide, int &tall);
// [tj] Accessors for clickability
void SetClickable(bool clickable) { m_clickable = clickable; }
bool IsClickable() { return m_clickable; }
// [tj] Accessors for header drawing
void SetDrawHeaders(bool drawHeaders) { m_bDrawSectionHeaders = drawHeaders; }
bool GetDrawHeaders() { return m_bDrawSectionHeaders; }
//=============================================================================
// HPE_END
//=============================================================================
// set up a field for editing
virtual void EnterEditMode(int itemID, int column, vgui::Panel *editPanel);
// leaves editing mode
virtual void LeaveEditMode();
// returns true if we are currently in inline editing mode
virtual bool IsInEditMode();
// sets whether or not the vertical scrollbar should ever be displayed
virtual void SetVerticalScrollbar(bool state);
// returns the size required to fully draw the contents of the panel
virtual void GetContentSize(int &wide, int &tall);
// image handling
virtual void SetImageList(ImageList *imageList, bool deleteImageListWhenDone);
virtual void ScrollToItem(int iItem);
virtual void SetProportional(bool state);
HFont GetHeaderFont( void ) const;
void SetHeaderFont( HFont hFont );
HFont GetRowFont( void ) const;
void SetRowFont( HFont hFont );
void MoveSelectionDown( void );
void MoveSelectionUp( void );
protected:
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void ApplySettings(KeyValues *inResourceData);
virtual void OnSizeChanged(int wide, int tall);
virtual void OnMouseWheeled(int delta);
virtual void OnMousePressed( MouseCode code);
virtual void NavigateTo( void );
virtual void OnKeyCodePressed( KeyCode code );
virtual void OnSetFocus(); // called after the panel receives the keyboard focus
public:
virtual void SetFontSection(int sectionID, HFont font);
private:
MESSAGE_FUNC( OnSliderMoved, "ScrollBarSliderMoved" );
int GetSectionTall();
void LayoutPanels(int &contentTall);
// Returns the index of a new item button, reusing an existing item button if possible
int GetNewItemButton();
friend class CItemButton;
void SetSelectedItem(CItemButton *item);
DHANDLE<CItemButton> m_hSelectedItem;
struct column_t
{
char m_szColumnName[32];
wchar_t m_szColumnText[64];
int m_iColumnFlags;
int m_iWidth;
HFont m_hFallbackFont;
};
struct section_t
{
int m_iID;
bool m_bAlwaysVisible;
SectionedListPanelHeader *m_pHeader;
CUtlVector<column_t> m_Columns;
SectionSortFunc_t m_pSortFunc;
int m_iMinimumHeight;
};
CUtlVector<section_t> m_Sections;
CUtlLinkedList<CItemButton *, int> m_Items;
CUtlLinkedList<CItemButton *, int> m_FreeItems;
CUtlVector<CItemButton *> m_SortedItems;
PHandle m_hEditModePanel;
int m_iEditModeItemID;
int m_iEditModeColumn;
int m_iContentHeight;
int m_iLineSpacing;
int m_iSectionGap;
int FindSectionIndexByID(int sectionID);
void ReSortList();
ScrollBar *m_pScrollBar;
ImageList *m_pImageList;
bool m_bDeleteImageListWhenDone;
bool m_bSortNeeded;
bool m_bVerticalScrollbarEnabled;
HFont m_hHeaderFont;
HFont m_hRowFont;
//=============================================================================
// HPE_BEGIN:
//=============================================================================
// [tj] Whether or not this list should respond to the mouse
bool m_clickable;
// [tj] Whether or not this list should draw the headers for the sections
bool m_bDrawSectionHeaders;
//=============================================================================
// HPE_END
//=============================================================================
CPanelAnimationVar( bool, m_bShowColumns, "show_columns", "false" );
};
class SectionedListPanelHeader : public Label
{
DECLARE_CLASS_SIMPLE( SectionedListPanelHeader, Label );
public:
SectionedListPanelHeader(SectionedListPanel *parent, const char *name, int sectionID);
SectionedListPanelHeader(SectionedListPanel *parent, const wchar_t *name, int sectionID);
virtual void ApplySchemeSettings(IScheme *pScheme) OVERRIDE;
virtual void Paint() OVERRIDE;
virtual void PerformLayout() OVERRIDE;
void SetColor(Color col);
void SetDividerColor(Color col );
protected:
int m_iSectionID;
Color m_SectionDividerColor;
SectionedListPanel *m_pListPanel;
};
} // namespace vgui
#endif // SECTIONEDLISTPANEL_H

View File

@@ -0,0 +1,123 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef SLIDER_H
#define SLIDER_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Labeled horizontal slider
//-----------------------------------------------------------------------------
class Slider : public Panel
{
DECLARE_CLASS_SIMPLE( Slider, Panel );
public:
Slider(Panel *parent, const char *panelName);
// interface
virtual void SetValue(int value, bool bTriggerChangeMessage = true);
virtual int GetValue();
virtual void SetRange(int min, int max); // set to max and min range of rows to display
virtual void GetRange(int &min, int &max);
virtual void GetNobPos(int &min, int &max); // get current Slider position
virtual void SetButtonOffset(int buttonOffset);
virtual void OnCursorMoved(int x, int y);
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code);
virtual void SetTickCaptions(const wchar_t *left, const wchar_t *right);
virtual void SetTickCaptions(const char *left, const char *right);
virtual void SetNumTicks(int ticks);
virtual void SetThumbWidth( int width );
virtual int EstimateValueAtPos( int localMouseX, int localMouseY );
virtual void SetInverted( bool bInverted );
// If you click on the slider outside of the nob, the nob jumps
// to the click position, and if this setting is enabled, the nob
// is then draggable from the new position until the mouse is released
virtual void SetDragOnRepositionNob( bool state );
virtual bool IsDragOnRepositionNob() const;
// Get if the slider nob is being dragged by user, usually the application
// should refuse from forcefully setting slider value if it is being dragged
// by user since the next frame the nob will pop back to mouse position
virtual bool IsDragged( void ) const;
// This allows the slider to behave like it's larger than what's actually being drawn
virtual void SetSliderThumbSubRange( bool bEnable, int nMin = 0, int nMax = 100 );
protected:
virtual void OnSizeChanged(int wide, int tall);
virtual void Paint();
virtual void PaintBackground();
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void GetSettings(KeyValues *outResourceData);
virtual void ApplySettings(KeyValues *inResourceData);
virtual const char *GetDescription();
#ifdef _X360
virtual void OnKeyCodePressed(KeyCode code);
#endif
virtual void OnKeyCodeTyped(KeyCode code);
virtual void DrawNob();
virtual void DrawTicks();
virtual void DrawTickLabels();
virtual void GetTrackRect( int &x, int &y, int &w, int &h );
protected:
virtual void RecomputeNobPosFromValue();
virtual void RecomputeValueFromNobPos();
virtual void SendSliderMovedMessage();
virtual void SendSliderDragStartMessage();
virtual void SendSliderDragEndMessage();
void ClampRange();
bool _dragging;
int _nobPos[2];
int _nobDragStartPos[2];
int _dragStartPos[2];
int _range[2];
int _subrange[ 2 ];
int _value; // the position of the Slider, in coordinates as specified by SetRange/SetRangeWindow
int _buttonOffset;
IBorder *_sliderBorder;
IBorder *_insetBorder;
float _nobSize;
TextImage *_leftCaption;
TextImage *_rightCaption;
Color m_TickColor;
Color m_TrackColor;
Color m_DisabledTextColor1;
Color m_DisabledTextColor2;
#ifdef _X360
Color m_DepressedBgColor;
#endif
int m_nNumTicks;
bool m_bIsDragOnRepositionNob : 1;
bool m_bUseSubRange : 1;
bool m_bInverted : 1;
};
}
#endif // SLIDER_H

View File

@@ -0,0 +1,98 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef SPLITTER_H
#define SPLITTER_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/EditablePanel.h>
namespace vgui
{
enum SplitterMode_t
{
SPLITTER_MODE_HORIZONTAL = 0,
SPLITTER_MODE_VERTICAL
};
class SplitterHandle;
class SplitterChildPanel;
//-----------------------------------------------------------------------------
// Purpose: Thin line used to divide sections, can be moved dragged!
//-----------------------------------------------------------------------------
class Splitter : public EditablePanel
{
DECLARE_CLASS_SIMPLE( Splitter, EditablePanel );
public:
// nCount is the number of splitters to create.
// NOTE: The constructor here will create (nCount+1) EditablePanel children
// and name them child0...childN for .res file purposes.
Splitter( Panel *parent, const char *name, SplitterMode_t mode, int nCount );
~Splitter();
// Evenly respace all splitters
void EvenlyRespaceSplitters();
// respace splitters using given fractions (must sum to 1)
void RespaceSplitters( float *flFractions );
// Inherited from Panel
virtual void ApplySettings(KeyValues *inResourceData);
virtual void GetSettings( KeyValues *outResourceData );
virtual void PerformLayout();
virtual void OnSizeChanged(int newWide, int newTall);
virtual void ApplyUserConfigSettings(KeyValues *userConfig);
virtual void GetUserConfigSettings(KeyValues *userConfig);
virtual bool HasUserConfigSettings() { return true; }
// Sets the splitter color
void SetSplitterColor( Color c );
// Enables borders on the splitters
void EnableBorders( bool bEnable );
// Locks the size of a particular child in pixels.
void LockChildSize( int nChildIndex, int nSize );
void UnlockChildSize( int nChildIndex );
private:
void RecreateSplitters( int nCount );
struct SplitterInfo_t
{
SplitterChildPanel *m_pPanel; // This panel is to the left or above the handle
SplitterHandle *m_pHandle;
float m_flPos;
bool m_bLocked;
int m_nLockedSize;
};
int GetPosRange();
int GetSplitterCount() const;
int GetSplitterPosition( int nIndex );
void SetSplitterPosition( int nIndex, int nPos );
int GetSubPanelCount() const;
int ComputeLockedSize( int nStartingIndex );
CUtlVector< SplitterInfo_t > m_Splitters;
SplitterMode_t m_Mode;
friend class SplitterHandle;
};
} // namespace vgui
#endif // SPLITTER_H

View File

@@ -0,0 +1,390 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: A Class to create a window that you can type and edit text in.
// Window can hold single line or multiline text.
// If it is single it can scroll horizontally in response to
// key input and mouse selection.
//
// $NoKeywords: $
//=============================================================================//
#ifndef TEXTENTRY_H
#define TEXTENTRY_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <Color.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/ListPanel.h>
#include <utlvector.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Text-input handler
// Behaviour Specs:
// This class handles input from mouse and keyboard.
// TextEntry classes support several box styles, horizontal scrolling with no scrollbar
// vertical scrolling with or without a scrollbar, single line, multiline,
// editable and noneditable.
//
// Shared behaviour:
// URL's are a different text color and are clickable. Clicking them brings up a web browser.
// For vertical scroll bars, up and down arrows scroll one line at a time.
// Clicking and dragging the nob scrolls through text lines.
// Mouse wheel also moves the nob.
// User can select and highlight text in the window.
// Double clicking on a word selects it.
//
// Non editable:
// No blinking cursor in non editable windows.
// Right clicking mouse opens copy menu. Menu's top left corner is where mouse is.
// Ctrl-c will also copy the text.
// Editable:
// Blinking cursor is positioned where text will be inserted.
// Text keys type chars in the window.
// ctrl-c copy highlighted text
// ctrl-v paste highlighted text
// ctrl-x cut highlighted text
// ctrl-right arrow move cursor to the start of the next word
// ctrl-left arrow move cursor to the start of the prev word
// ctrl-enter delete the selected text (and inserts a newline if _catchEnterKey is true)
// insert delete selected text and pastes text from the clipboard
// delete delete the selected text
// ctrl-home move cursor to the start of the text
// ctrl-end move cursor to the end of the text.
// left arrow move cursor before prev char
// ctrl-shift left/right arrow selects text a word at a time
// right arrow move cursor before next char
// up arrow move cursor up one line.
// down arrow move cursor down one line.
// home move cursor to start of current line
// end move cursor to end of current line
// backspace delete prev char or selected text.
// Trying to move to the prev/next char/line/word when there is none moves the cursor to the
// start/end of the text.
// Horizontal scrolling:
// Trying to move to the prev/next char/line/word when there is none scrolls the text
// horizontally in the window so the new text displays at the correct side.
// When moving to prev chars scrolling is staggered. To next chars it is one char at a time.
// Cut/Copy/Paste Menu:
// Right clicking mouse brings up cut/copy/paste menu.
// If no text is highlighted the cut/copy options are dimmed. Cut is dimmed in non editable panels
// If there is no text in the clipboard or panel is not editable the paste option is dimmed.
// If the mouse is right clicked over selected text, the text stays selected.
// If the mouse is right clicked over unselected text, any selected text is deselected.
//
//
//-----------------------------------------------------------------------------
class TextEntry : public Panel
{
DECLARE_CLASS_SIMPLE( TextEntry, Panel );
public:
TextEntry(Panel *parent, const char *panelName);
virtual ~TextEntry();
virtual void SetText(const wchar_t *wszText);
virtual void SetText(const char *text);
virtual void GetText(OUT_Z_BYTECAP(bufLenInBytes) char *buf, int bufLenInBytes);
virtual void GetText(OUT_Z_BYTECAP(bufLenInBytes) wchar_t *buf, int bufLenInBytes);
virtual int GetTextLength() const;
virtual bool IsTextFullySelected() const;
// editing
virtual void GotoLeft(); // move cursor one char left
virtual void GotoRight(); // move cursor one char right
virtual void GotoUp(); // move cursor one line up
virtual void GotoDown(); // move cursor one line down
virtual void GotoWordRight(); // move cursor to Start of next word
virtual void GotoWordLeft(); // move cursor to Start of prev word
virtual void GotoFirstOfLine(); // go to Start of the current line
virtual void GotoEndOfLine(); // go to end of the current line
virtual void GotoTextStart(); // go to Start of text buffer
virtual void GotoTextEnd(); // go to end of text buffer
virtual void InsertChar(wchar_t ch);
virtual void InsertString(const char *text);
virtual void InsertString(const wchar_t *wszText);
virtual void Backspace();
virtual void Delete();
virtual void SelectNone();
virtual void OpenEditMenu();
MESSAGE_FUNC( CutSelected, "DoCutSelected" );
MESSAGE_FUNC( CopySelected, "DoCopySelected" );
MESSAGE_FUNC( Paste, "DoPaste" );
MESSAGE_FUNC_INT( LanguageChanged, "DoLanguageChanged", handle );
MESSAGE_FUNC_INT( ConversionModeChanged, "DoConversionModeChanged", handle );
MESSAGE_FUNC_INT( SentenceModeChanged, "DoSentenceModeChanged", handle );
MESSAGE_FUNC_WCHARPTR( CompositionString, "DoCompositionString", string );
MESSAGE_FUNC( ShowIMECandidates, "DoShowIMECandidates" );
MESSAGE_FUNC( HideIMECandidates, "DoHideIMECandidates" );
MESSAGE_FUNC( UpdateIMECandidates, "DoUpdateIMECandidates" );
virtual void DeleteSelected();
virtual void Undo();
virtual void SaveUndoState();
virtual void SetFont(HFont font);
virtual void SetTextHidden(bool bHideText);
virtual void SetEditable(bool state);
virtual bool IsEditable();
virtual void SetEnabled(bool state);
// move the cursor to line 'line', given how many pixels are in a line
virtual void MoveCursor(int line, int pixelsAcross);
// sets the color of the background when the control is disabled
virtual void SetDisabledBgColor(Color col);
// set whether the box handles more than one line of entry
virtual void SetMultiline(bool state);
virtual bool IsMultiline();
// sets visibility of scrollbar
virtual void SetVerticalScrollbar(bool state);
// sets whether or not the edit catches and stores ENTER key presses
virtual void SetCatchEnterKey(bool state);
// sets whether or not to send "TextNewLine" msgs when ENTER key is pressed
virtual void SendNewLine(bool send);
// sets limit of number of characters insertable into field; set to -1 to remove maximum
// only works with if rich-edit is NOT enabled
virtual void SetMaximumCharCount(int maxChars);
virtual int GetMaximumCharCount();
virtual void SetAutoProgressOnHittingCharLimit(bool state);
// sets whether to wrap text once maxChars is reached (on a line by line basis)
virtual void SetWrap(bool wrap);
virtual void RecalculateLineBreaks();
virtual void LayoutVerticalScrollBarSlider();
virtual bool RequestInfo(KeyValues *outputData);
// sets the height of the window so all text is visible.
// used by tooltips
void SetToFullHeight();
// sets the width of the window so all text is visible. (will create one line)
// used by tooltips
void SetToFullWidth();
int GetNumLines();
/* INFO HANDLING
"GetText"
returns:
"text" - text contained in the text box
*/
/* CUSTOM MESSAGE HANDLING
"SetText"
input: "text" - text is set to be this string
*/
/* MESSAGE SENDING (to action signal targets)
"TextChanged" - sent when the text is edited by the user
"TextNewLine" - sent when the end key is pressed in the text entry AND _sendNewLines is true
"TextKillFocus" - sent when focus leaves textentry field
*/
// Selects all the text in the text entry.
void SelectAllText(bool bResetCursorPos);
void SelectNoText();
void SelectAllOnFirstFocus( bool status );
void SetDrawWidth(int width); // width from right side of window we have to draw in
int GetDrawWidth();
void SetHorizontalScrolling(bool status); // turn horizontal scrolling on or off.
// sets whether non-asci characters (unicode chars > 127) are allowed in the control - defaults to OFF
void SetAllowNonAsciiCharacters(bool state);
// sets whether or not number input only is allowed
void SetAllowNumericInputOnly(bool state);
// By default, we draw the language shortname on the right hand side of the control
void SetDrawLanguageIDAtLeft( bool state );
virtual bool GetDropContextMenu( Menu *menu, CUtlVector< KeyValues * >& data );
virtual bool IsDroppable( CUtlVector< KeyValues * >& data );
virtual void OnPanelDropped( CUtlVector< KeyValues * >& data );
virtual Panel *GetDragPanel();
virtual void OnCreateDragData( KeyValues *msg );
void SelectAllOnFocusAlways( bool status );
void SetSelectionTextColor( const Color& clr );
void SetSelectionBgColor( const Color& clr );
void SetSelectionUnfocusedBgColor( const Color& clr );
void SetUseFallbackFont( bool bState, HFont hFallback );
protected:
virtual void ResetCursorBlink();
virtual void PerformLayout(); // layout the text in the window
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual void PaintBackground();
virtual int DrawChar(wchar_t ch, HFont font, int index, int x, int y);
virtual bool DrawCursor(int x, int y);
virtual void SetCharAt(wchar_t ch, int index); // set the value of a char in the text buffer
virtual void ApplySettings( KeyValues *inResourceData );
virtual void GetSettings( KeyValues *outResourceData );
virtual const char *GetDescription( void );
virtual void FireActionSignal();
virtual bool GetSelectedRange(int& cx0,int& cx1);
virtual void CursorToPixelSpace(int cursorPos, int &cx, int &cy);
virtual int PixelToCursorSpace(int cx, int cy);
virtual void AddAnotherLine(int &cx, int &cy);
virtual int GetYStart(); // works out ypixel position drawing started at
virtual bool SelectCheck( bool fromMouse = false ); // check if we are in text selection mode
MESSAGE_FUNC_WCHARPTR( OnSetText, "SetText", text );
MESSAGE_FUNC( OnSliderMoved, "ScrollBarSliderMoved" ); // respond to scroll bar events
virtual void OnKillFocus();
virtual void OnMouseWheeled(int delta); // respond to mouse wheel events
virtual void OnKeyCodePressed(KeyCode code); //respond to keyboard events
virtual void OnKeyCodeTyped(KeyCode code); //respond to keyboard events
virtual void OnKeyTyped(wchar_t unichar); //respond to keyboard events
virtual void OnCursorMoved(int x, int y); // respond to moving the cursor with mouse button down
virtual void OnMousePressed(MouseCode code); // respond to mouse down events
virtual void OnMouseDoublePressed( MouseCode code );
virtual void OnMouseTriplePressed( MouseCode code );
virtual void OnMouseReleased( MouseCode code ); // respond to mouse up events
virtual void OnKeyFocusTicked(); // do while window has keyboard focus
virtual void OnMouseFocusTicked(); // do while window has mouse focus
virtual void OnCursorEntered(); // handle cursor entering window
virtual void OnCursorExited(); // handle cursor exiting window
virtual void OnMouseCaptureLost();
virtual void OnSizeChanged(int newWide, int newTall);
// Returns the character index the drawing should Start at
virtual int GetStartDrawIndex(int &lineBreakIndexIndex);
public:
// helper accessors for common gets
virtual float GetValueAsFloat();
virtual int GetValueAsInt();
protected:
void ScrollRight(); // scroll to right until cursor is visible
void ScrollLeft(); // scroll to left
bool IsCursorOffRightSideOfWindow(int cursorPos); // check if cursor is off right side of window
bool IsCursorOffLeftSideOfWindow(int cursorPos); // check if cursor is off left side of window
void ScrollLeftForResize();
void OnSetFocus();
// Change keyboard layout type
void OnChangeIME( bool forward );
bool NeedsEllipses( HFont font, int *pIndex );
private:
MESSAGE_FUNC_INT( OnSetState, "SetState", state );
// get index in buffer of the Start of the current line we are on
int GetCurrentLineStart();
// get index in buffer of the end of the current line we are on
int GetCurrentLineEnd();
bool IsLineBreak(int index);
int GetCursorLine();
void MoveScrollBar(int delta);
void CalcBreakIndex(); // calculate _recalculateLineBreaksIndex
void CreateEditMenu(); // create copy/cut/paste menu
public:
Menu *GetEditMenu(); // retrieve copy/cut/paste menu
private:
void FlipToLastIME();
public:
virtual void GetTextRange( wchar_t *buf, int from, int numchars ); // copy a portion of the text to the buffer and add zero-termination
virtual void GetTextRange( char *buf, int from, int numchars ); // copy a portion of the text to the buffer and add zero-termination
private:
CUtlVector<wchar_t> m_TextStream; // the text in the text window is stored in this buffer
CUtlVector<wchar_t> m_UndoTextStream; // a copy of the text buffer to revert changes
CUtlVector<int> m_LineBreaks; // an array that holds the index in the buffer to wrap lines at
int _cursorPos; // the position in the text buffer of the blinking cursor
bool _cursorIsAtEnd;
bool _putCursorAtEnd;
int _undoCursorPos; // a copy of the cursor position to revert changes
bool _cursorBlink; // whether cursor is blinking or not
bool _hideText; // whether text is visible on screen or not
bool _editable; // whether text is editable or not
bool _mouseSelection; // whether we are highlighting text or not (selecting text)
bool _mouseDragSelection; // tells weather mouse is outside window and button is down so we select text
int _mouseSelectCursorStart; // where mouse button was pressed down in text window
long _cursorNextBlinkTime; // time of next cursor blink
int _cursorBlinkRate; // speed of cursor blinking
int _select[2]; // select[1] is the offset in the text to where the cursor is currently
// select[0] is the offset to where the cursor was dragged to. or -1 if no drag.
int _pixelsIndent;
int _charCount;
int _maxCharCount; // max number of chars that can be in the text buffer
HFont _font; // font of chars in the text buffer
HFont _smallfont;
bool _dataChanged; // whether anything in the window has changed.
bool _multiline; // whether buffer is multiline or just a single line
bool _verticalScrollbar; // whether window has a vertical scroll bar
ScrollBar *_vertScrollBar; // the scroll bar used in the window
Color _cursorColor; // color of the text cursor
Color _disabledFgColor;
Color _disabledBgColor;
Color _selectionColor;
Color _selectionTextColor; // color of the highlighted text
Color _defaultSelectionBG2Color;
int _currentStartLine; // use for checking vertical text scrolling (multiline)
int _currentStartIndex; // use for horizontal text scrolling (!multiline)
bool _horizScrollingAllowed; // use to disable horizontal text scrolling period.
Color _focusEdgeColor;
bool _catchEnterKey;
bool _wrap;
bool _sendNewLines;
int _drawWidth;
// selection data
Menu *m_pEditMenu; ///cut/copy/paste popup
int _recalculateBreaksIndex; // tells next linebreakindex index to Start recalculating line breaks
bool _selectAllOnFirstFocus : 1; // highlights all text in window when focus is gained.
bool _selectAllOnFocusAlways : 1;
bool _firstFocusStatus; // keep track if we've had that first focus or not
bool m_bAllowNumericInputOnly;
bool m_bAllowNonAsciiCharacters;
bool m_bAutoProgressOnHittingCharLimit;
enum
{
MAX_COMPOSITION_STRING = 256,
};
wchar_t m_szComposition[ MAX_COMPOSITION_STRING ];
Menu *m_pIMECandidates;
int m_hPreviousIME;
bool m_bDrawLanguageIDAtLeft;
int m_nLangInset;
bool m_bUseFallbackFont : 1;
HFont m_hFallbackFont;
};
}
#endif // TEXTENTRY_H

View File

@@ -0,0 +1,143 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef TEXTIMAGE_H
#define TEXTIMAGE_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui/ILocalize.h>
#include <vgui_controls/Image.h>
#include <utlvector.h>
#include <UtlSortVector.h>
class KeyValues;
namespace vgui
{
struct label_colorchange_t
{
Color color;
int textStreamIndex;
};
// Used to sort the color changes into sequential order.
class CColorChangeListLess
{
public:
bool Less( const label_colorchange_t &src1, const label_colorchange_t &src2, void *pCtx )
{
if ( src1.textStreamIndex < src2.textStreamIndex )
return true;
return false;
}
};
//-----------------------------------------------------------------------------
// Purpose: Image that handles drawing of a text string
//-----------------------------------------------------------------------------
class TextImage : public Image
{
public:
TextImage(const char *text);
TextImage(const wchar_t *wszText);
~TextImage();
public:
// takes the string and looks it up in the localization file to convert it to unicode
virtual void SetText(const char *text);
// sets unicode text directly
virtual void SetText(const wchar_t *text, bool bClearUnlocalizedSymbol = false);
// get the full text in the image
virtual void GetText(char *buffer, int bufferSize);
virtual void GetText(wchar_t *buffer, int bufferLength);
// get the text in it's unlocalized form
virtual void GetUnlocalizedText(char *buffer, int bufferSize);
virtual StringIndex_t GetUnlocalizedTextSymbol();
// set the font of the text
virtual void SetFont(vgui::HFont font);
// get the font of the text
virtual vgui::HFont GetFont();
// set the width of the text to be drawn
// use this function if the textImage is in another window to cause
// the text to be truncated to the width of the window (elipsis added)
void SetDrawWidth(int width);
// get the width of the text to be drawn
void GetDrawWidth(int &width);
void ResizeImageToContent();
void ResizeImageToContentMaxWidth( int nMaxWidth );
// set the size of the image
virtual void SetSize(int wide,int tall);
// get the full size of a text string
virtual void GetContentSize(int &wide, int &tall);
// draws the text
virtual void Paint();
void SetWrap( bool bWrap );
void RecalculateNewLinePositions();
void SetUseFallbackFont( bool bState, HFont hFallback );
void SetAllCaps( bool bAllCaps );
void SetCenterWrap( bool bWrap );
void RecalculateCenterWrapIndents();
const wchar_t *GetUText( void ) { return _utext; }
void AddColorChange( Color col, int iTextStreamIndex );
void SetColorChangeStream( CUtlSortVector<label_colorchange_t,CColorChangeListLess> *pUtlVecStream );
void ClearColorChangeStream( void ) { m_ColorChangeStream.Purge(); }
protected:
// truncate the _text string to fit into the draw width
void SizeText(wchar_t *tempText, int stringLength);
// gets the size of a specified piece of text
virtual void GetTextSize(int &wide, int &tall);
private:
void RecalculateEllipsesPosition();
wchar_t *_utext; // unicode version of the text
short _textBufferLen; // size of the text buffer
short _textLen; // length of the text string
vgui::HFont _font; // font of the text string
vgui::HFont _fallbackFont;
int _drawWidth; // this is the width of the window we are drawing into.
// if there is not enough room truncate the txt and add an elipsis
StringIndex_t _unlocalizedTextSymbol; // store off the unlocalized text index for build mode
wchar_t *m_pwszEllipsesPosition;
bool m_bRecalculateTruncation : 1;
bool m_bWrap : 1;
bool m_bUseFallbackFont : 1;
bool m_bRenderUsingFallbackFont : 1;
bool m_bAllCaps : 1;
CUtlVector<wchar_t *> m_LineBreaks; // an array that holds the index in the buffer to wrap lines at
bool m_bWrapCenter; // Separate from m_bWrap to ensure it doesn't break legacy code.
CUtlVector<int> m_LineXIndent; // For centered word wrap. The X indent for each line.
CUtlSortVector<label_colorchange_t,CColorChangeListLess> m_ColorChangeStream;
};
} // namespace vgui
#endif // TEXTIMAGE_H

View File

@@ -0,0 +1,54 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef TOGGLEBUTTON_H
#define TOGGLEBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Button.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Type of button that when pressed stays selected & depressed until pressed again
//-----------------------------------------------------------------------------
class ToggleButton : public Button
{
DECLARE_CLASS_SIMPLE( ToggleButton, Button );
public:
ToggleButton(Panel *parent, const char *panelName, const char *text);
virtual void DoClick();
/* messages sent (get via AddActionSignalTarget()):
"ButtonToggled"
int "state"
*/
protected:
// overrides
virtual void OnMouseDoublePressed(MouseCode code);
virtual Color GetButtonFgColor();
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual bool CanBeDefaultButton(void);
virtual void OnKeyCodePressed(KeyCode code);
private:
Color _selectedColor;
};
} // namespace vgui
#endif // TOGGLEBUTTON_H

View File

@@ -0,0 +1,78 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef TOOLWINDOW_H
#define TOOLWINDOW_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Frame.h>
namespace vgui
{
class ToolWindow;
// So that an app can have a "custom" tool window class created during window drag/drop operations on the property sheet
class IToolWindowFactory
{
public:
virtual ToolWindow *InstanceToolWindow( Panel *parent, bool contextLabel, Panel *firstPage, char const *title, bool contextMenu ) = 0;
};
//-----------------------------------------------------------------------------
// Purpose: Simple frame that holds a property sheet
//-----------------------------------------------------------------------------
class ToolWindow : public Frame
{
DECLARE_CLASS_SIMPLE( ToolWindow, Frame );
public:
ToolWindow(Panel *parent, bool contextLabel, IToolWindowFactory *factory = 0, Panel *page = NULL, char const *title = NULL, bool contextMenu = false, bool inGlobalList = true );
~ToolWindow();
virtual bool IsDraggableTabContainer() const;
// returns a pointer to the PropertySheet this dialog encapsulates
PropertySheet *GetPropertySheet();
// wrapper for PropertySheet interface
void AddPage(Panel *page, const char *title, bool contextMenu );
void RemovePage( Panel *page );
Panel *GetActivePage();
void SetActivePage( Panel *page );
void SetToolWindowFactory( IToolWindowFactory *factory );
IToolWindowFactory *GetToolWindowFactory();
static int GetToolWindowCount();
static ToolWindow *GetToolWindow( int index );
static CUtlVector< ToolWindow * > s_ToolWindows;
virtual void Grow( int edge = 0, int from_x = -1, int from_y = -1 );
virtual void GrowFromClick();
protected:
// vgui overrides
virtual void PerformLayout();
virtual void ActivateBuildMode();
virtual void RequestFocus(int direction = 0);
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
private:
PropertySheet *m_pPropertySheet;
IToolWindowFactory *m_pFactory;
};
}; // vgui
#endif // TOOLWINDOW_H

View File

@@ -0,0 +1,76 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Creates a Message box with a question in it and yes/no buttons
//
// $NoKeywords: $
//=============================================================================//
#ifndef TOOLTIP_H
#define TOOLTIP_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Controls.h>
#include <utlvector.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Tooltip for a panel - shows text when cursor hovers over a panel
//-----------------------------------------------------------------------------
class BaseTooltip
{
public:
BaseTooltip(Panel *parent, const char *text = NULL);
virtual void SetText(const char *text);
virtual const char *GetText();
virtual void ShowTooltip(Panel *currentPanel);
virtual void HideTooltip();
bool ShouldLayout( void );
virtual void PerformLayout() { return; }
virtual void PositionWindow( Panel *pTipPanel );
void ResetDelay();
void SetTooltipFormatToSingleLine();
void SetTooltipFormatToMultiLine();
void SetTooltipDelay(int tooltipDelayMilliseconds);
int GetTooltipDelay();
void SetEnabled( bool bState );
private:
Panel *m_pParent;
virtual void ApplySchemeSettings(IScheme *pScheme) {};
protected:
CUtlVector<char> m_Text;
int _delay; // delay that counts down
int _tooltipDelay; // delay before tooltip comes up.
bool _makeVisible : 1;
bool _displayOnOneLine : 1;
bool _isDirty : 1;
bool _enabled : 1;
};
class TextTooltip : public BaseTooltip
{
public:
TextTooltip(Panel *parent, const char *text = NULL);
~TextTooltip();
virtual void SetText(const char *text);
virtual void ShowTooltip(Panel *currentPanel);
virtual void HideTooltip();
virtual void SizeTextWindow();
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme *pScheme);
};
};
#endif // TOOLTIP_H

View File

@@ -0,0 +1,203 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef TREEVIEW_H
#define TREEVIEW_H
#ifdef _WIN32
#pragma once
#endif
#include <utllinkedlist.h>
#include <utlvector.h>
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
class KeyValues;
namespace vgui
{
class ExpandButton;
class TreeNode;
class TreeViewSubPanel;
// sorting function, should return true if node1 should be displayed before node2
typedef bool (*TreeViewSortFunc_t)(KeyValues *node1, KeyValues *node2);
class TreeView : public Panel
{
DECLARE_CLASS_SIMPLE( TreeView, Panel );
public:
TreeView(Panel *parent, const char *panelName);
~TreeView();
void SetSortFunc(TreeViewSortFunc_t pSortFunc);
virtual int AddItem(KeyValues *data, int parentItemIndex);
virtual int GetRootItemIndex();
virtual int GetNumChildren( int itemIndex );
virtual int GetChild( int iParentItemIndex, int iChild ); // between 0 and GetNumChildren( iParentItemIndex ).
virtual int GetItemCount(void);
virtual KeyValues *GetItemData(int itemIndex);
virtual void RemoveItem(int itemIndex, bool bPromoteChildren, bool bRecursivelyRemove = false );
virtual void RemoveAll();
virtual bool ModifyItem(int itemIndex, KeyValues *data);
virtual int GetItemParent(int itemIndex);
virtual void SetFont(HFont font);
virtual void SetImageList(ImageList *imageList, bool deleteImageListWhenDone);
void SetAllowMultipleSelections( bool state );
bool IsMultipleSelectionAllowed() const;
virtual void ClearSelection();
virtual void AddSelectedItem( int itemIndex, bool clearCurrentSelection, bool requestFocus = true, bool bMakeItemVisible = true );
virtual void RemoveSelectedItem( int itemIndex );
virtual void SelectAll();
virtual bool IsItemSelected( int itemIndex );
virtual void RangeSelectItems( int clickedItem );
virtual void FindNodesInRange( int startItem, int endItem, CUtlVector< int >& itemIndices );
// returns the id of the currently selected item, -1 if nothing is selected
virtual int GetSelectedItemCount() const;
virtual int GetFirstSelectedItem() const;
virtual void GetSelectedItems( CUtlVector< int >& list );
virtual void GetSelectedItemData( CUtlVector< KeyValues * >& list );
// set colors for individual elments
virtual void SetItemFgColor(int itemIndex, const Color& color);
virtual void SetItemBgColor(int itemIndex, const Color& color);
virtual void SetItemSelectionTextColor( int itemIndex, const Color& clr );
virtual void SetItemSelectionBgColor( int itemIndex, const Color& clr );
virtual void SetItemSelectionUnfocusedBgColor( int itemIndex, const Color& clr );
// returns true if the itemID is valid for use
virtual bool IsItemIDValid(int itemIndex);
// item iterators
// iterate from [0..GetHighestItemID()],
// and check each with IsItemIDValid() before using
virtual int GetHighestItemID();
virtual void ExpandItem(int itemIndex, bool bExpand);
virtual bool IsItemExpanded( int itemIndex );
virtual void MakeItemVisible(int itemIndex);
// This tells which of the visible items is the top one.
virtual void GetVBarInfo( int &top, int &nItemsVisible, bool& hbarVisible );
virtual HFont GetFont();
virtual void GenerateDragDataForItem( int itemIndex, KeyValues *msg );
virtual void SetDragEnabledItems( bool state );
virtual void OnLabelChanged( int itemIndex, char const *oldString, char const *newString );
virtual bool IsLabelEditingAllowed() const;
virtual bool IsLabelBeingEdited() const;
virtual void SetAllowLabelEditing( bool state );
/* message sent
"TreeViewItemSelected" int "itemIndex"
called when the selected item changes
"TreeViewItemDeselected" int "itemIndex"
called when item is deselected
*/
int GetRowHeight();
int GetVisibleMaxWidth();
virtual void OnMousePressed(MouseCode code);
// By default, the tree view expands nodes on left-click. This enables/disables that feature
void EnableExpandTreeOnLeftClick( bool bEnable );
virtual void SetLabelEditingAllowed( int itemIndex, bool state );
virtual void StartEditingLabel( int itemIndex );
virtual bool IsItemDroppable( int itemIndex, CUtlVector< KeyValues * >& msglist );
virtual void OnItemDropped( int itemIndex, CUtlVector< KeyValues * >& msglist );
virtual bool GetItemDropContextMenu( int itemIndex, Menu *menu, CUtlVector< KeyValues * >& msglist );
virtual HCursor GetItemDropCursor( int itemIndex, CUtlVector< KeyValues * >& msglist );
virtual int GetPrevChildItemIndex( int itemIndex );
virtual int GetNextChildItemIndex( int itemIndex );
virtual void PerformLayout();
// Makes the scrollbar parented to some other panel...
ScrollBar *SetScrollBarExternal( bool vertical, Panel *newParent );
void GetScrollBarSize( bool vertical, int& w, int& h );
void SetMultipleItemDragEnabled( bool state ); // if this is set, then clicking on one row and dragging will select a run or items, etc.
bool IsMultipleItemDragEnabled() const;
int FindItemUnderMouse( int mx, int my );
protected:
// functions to override
// called when a node, marked as "Expand", needs to generate it's child nodes when expanded
virtual void GenerateChildrenOfNode(int itemIndex) {}
// override to open a custom context menu on a node being selected and right-clicked
virtual void GenerateContextMenu( int itemIndex, int x, int y ) {}
// overrides
virtual void OnMouseWheeled(int delta);
virtual void OnSizeChanged(int wide, int tall);
virtual void ApplySchemeSettings(IScheme *pScheme);
MESSAGE_FUNC_INT( OnSliderMoved, "ScrollBarSliderMoved", position );
virtual void SetBgColor( Color color );
private:
friend class TreeNode;
friend class TreeNodeText;
TreeNode* GetItem( int itemIndex );
virtual void RemoveChildrenOfNode( int itemIndex );
void SetLabelBeingEdited( bool state );
// Clean up the image list
void CleanUpImageList( );
// to be accessed by TreeNodes
IImage* GetImage(int index);
// bools
bool m_bAllowLabelEditing : 1;
bool m_bDragEnabledItems : 1;
bool m_bDeleteImageListWhenDone : 1;
bool m_bLeftClickExpandsTree : 1;
bool m_bLabelBeingEdited : 1;
bool m_bMultipleItemDragging : 1;
bool m_bAllowMultipleSelections : 1;
// cross reference - no hierarchy ordering in this list
CUtlLinkedList<TreeNode *, int> m_NodeList;
ScrollBar *m_pHorzScrollBar, *m_pVertScrollBar;
int m_nRowHeight;
ImageList *m_pImageList;
TreeNode *m_pRootNode;
TreeViewSortFunc_t m_pSortFunc;
HFont m_Font;
CUtlVector< TreeNode * > m_SelectedItems;
TreeViewSubPanel *m_pSubPanel;
int m_nMostRecentlySelectedItem;
bool m_bScrollbarExternal[ 2 ]; // 0 = vert, 1 = horz
};
}
#endif // TREEVIEW_H

View File

@@ -0,0 +1,130 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef TREEVIEWLISTCONTROL_H
#define TREEVIEWLISTCONTROL_H
#ifdef _WIN32
#pragma once
#endif
#include <utllinkedlist.h>
#include <utlvector.h>
#include <vgui/VGUI.h>
#include <vgui_controls/Panel.h>
#include "utlsymbol.h"
namespace vgui
{
// --------------------------------------------------------------------------------- //
// CTreeViewListControl
//
// This control has N columns, with a tree view in the leftmost column.
// --------------------------------------------------------------------------------- //
class CTreeViewListControl : public vgui::Panel
{
DECLARE_CLASS_SIMPLE( CTreeViewListControl, Panel );
public:
CTreeViewListControl( vgui::Panel *pParent, const char *pName );
// Set the tree view to be displayed on the left. If this isn't set, then nothing displays in here.
virtual void SetTreeView( vgui::TreeView *pTree );
// Set the height of the title bar.
virtual void SetTitleBarInfo( vgui::HFont hFont, int titleBarHeight );
// Set the color to draw the border lines in.
virtual void SetBorderColor( Color clr );
// Initialize the column headers.. This info includes the tree view on the left, so this
virtual void SetNumColumns( int nColumns );
virtual int GetNumColumns() const;
// ciFlags is a combination of CI_ flags.
virtual void SetColumnInfo( int iColumn, const char *pTitle, int width, int ciFlags=0 );
// Use this to render your stuff. Iterate over the rows in the tree view and
virtual int GetNumRows();
virtual int GetTreeItemAtRow( int iRow ); // You can use m_pTree->GetItemData to get at the data for the row.
// Use this to find out the client area to render in for each grid element.
// The returned box is inclusive.
// The rule is that the the top and left pixels in each grid element are reserved for lines.
virtual void GetGridElementBounds( int iColumn, int iRow, int &left, int &top, int &right, int &bottom );
virtual vgui::TreeView *GetTree();
virtual int GetTitleBarHeight();
virtual int GetScrollBarSize();
// Overrides.
public:
// This is where it recalculates the row infos.
virtual void PerformLayout();
// Usually, you'll want to override paint. After calling the base, use GetNumRows() to
// iterate over the data in the tree control and fill in the other columns.
virtual void Paint();
virtual void PostChildPaint();
// You can override this to change the way the title bars are drawn.
virtual void DrawTitleBars();
public:
enum
{
// By default, column header text is centered.
CI_HEADER_LEFTALIGN =0x0001
};
protected:
void RecalculateRows();
void RecalculateRows_R( int index );
void RecalculateColumns();
private:
vgui::TreeView *m_pTree;
class CColumnInfo
{
public:
CColumnInfo()
{
m_Width = m_Left = m_Right = m_ciFlags = 0;
}
CUtlSymbol m_Title;
int m_Width;
int m_Left;
int m_Right;
int m_ciFlags; // Combination of CI_ flags.
};
CUtlVector<CColumnInfo> m_Columns;
vgui::HFont m_TitleBarFont;
int m_TitleBarHeight;
// These are indices into the tree view.
CUtlVector<int> m_Rows;
Color m_BorderColor;
};
} // namespace
#endif // TREEVIEWLISTCONTROL_H

View File

@@ -0,0 +1,49 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef URLLABEL_H
#define URLLABEL_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include <vgui_controls/Label.h>
namespace vgui
{
class URLLabel : public Label
{
DECLARE_CLASS_SIMPLE( URLLabel, Label );
public:
URLLabel(Panel *parent, const char *panelName, const char *text, const char *pszURL);
URLLabel(Panel *parent, const char *panelName, const wchar_t *wszText, const char *pszURL);
~URLLabel();
void SetURL(const char *pszURL);
protected:
virtual void OnMousePressed(MouseCode code);
virtual void ApplySettings( KeyValues *inResourceData );
virtual void GetSettings( KeyValues *outResourceData );
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual const char *GetDescription( void );
const char *GetURL( void ) { return m_pszURL; }
private:
char *m_pszURL;
int m_iURLSize;
bool m_bUnderline;
};
}
#endif // URLLABEL_H

View File

@@ -0,0 +1,127 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef WIZARDPANEL_H
#define WIZARDPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Frame.h>
namespace vgui
{
class WizardSubPanel;
//-----------------------------------------------------------------------------
// Purpose: Type of dialog that supports moving back and forth through a series
// of sub-dialogs, WizardSubPanels
//-----------------------------------------------------------------------------
class WizardPanel : public Frame
{
DECLARE_CLASS_SIMPLE( WizardPanel, Frame );
public:
WizardPanel(Panel *parent, const char *panelName);
~WizardPanel();
// Start the wizard, starting with the startPanel
virtual void Run(WizardSubPanel *startPanel);
// Called when the buttons are pressed
// WizardSubPanels can also call these functions to simulate a button being pressed
MESSAGE_FUNC( OnNextButton, "NextButton" );
MESSAGE_FUNC( OnPrevButton, "PrevButton" );
MESSAGE_FUNC( OnFinishButton, "FinishButton" );
MESSAGE_FUNC( OnCancelButton, "CancelButton" );
// sets whether or not a button is enabled
// this state is managed, and will be reset whenever going to a new page
virtual void SetNextButtonEnabled(bool state);
virtual void SetPrevButtonEnabled(bool state);
virtual void SetFinishButtonEnabled(bool state);
virtual void SetCancelButtonEnabled(bool state);
// sets whether or not a button is visible
// this state is unmanaged, the user needs to ensure that the buttons state
// is correct when going both back and prev through the wizard
virtual void SetNextButtonVisible(bool state);
virtual void SetPrevButtonVisible(bool state);
virtual void SetFinishButtonVisible(bool state);
virtual void SetCancelButtonVisible(bool state);
// sets the text for a button
// setting the text to be NULL resets the text to it's default state
// this state is unmanaged, the user needs to ensure that the buttons state
// is correct when going both back and prev through the wizard
virtual void SetNextButtonText(const char *text);
virtual void SetPrevButtonText(const char *text);
virtual void SetFinishButtonText(const char *text);
virtual void SetCancelButtonText(const char *text);
// general wizard state for all the subpanels to access
virtual KeyValues *GetWizardData();
// recalculates where the key focus should be in the wizard
virtual void ResetKeyFocus();
virtual void ResetDefaultButton();
// resets the sub panel history for the control
virtual void ResetHistory();
// returns a page by name
virtual WizardSubPanel *GetSubPanelByName(const char *pageName);
virtual void ShowButtons(bool state);
virtual void GetClientArea(int &x, int &y, int &wide, int &tall);
protected:
MESSAGE_FUNC_PTR( InternalActivateNextSubPanel, "ActivateNextSubPanel", panel )
{
ActivateNextSubPanel( (WizardSubPanel *)panel );
}
virtual void ActivateNextSubPanel(WizardSubPanel *subPanel);
virtual void ActivatePrevSubPanel();
virtual void CreateButtons();
virtual void RecalculateTabOrdering();
virtual vgui::WizardSubPanel *GetCurrentSubPanel() { return _currentSubPanel; }
// overrides
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme *pScheme);
// reroute build messages to the currently active sub panel
virtual void ActivateBuildMode();
// close maps to the cancel button
virtual void OnClose();
virtual void OnCommand(const char *command);
virtual void OnCloseFrameButtonPressed();
private:
WizardSubPanel *FindNextValidSubPanel(WizardSubPanel *currentPanel);
Button *_prevButton;
Button *_nextButton;
Button *_cancelButton;
Button *_finishButton;
WizardSubPanel *_currentSubPanel;
KeyValues *_currentData;
Dar<WizardSubPanel *> _subPanelStack; // contains a list of all the subpanels (not including the current one)
bool _showButtons;
};
} // namespace vgui
#endif // WIZARDPANEL_H

View File

@@ -0,0 +1,91 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef WIZARDSUBPANEL_H
#define WIZARDSUBPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/EditablePanel.h>
namespace vgui
{
//-----------------------------------------------------------------------------
// Purpose: Base panel for use in Wizards and in property sheets
//-----------------------------------------------------------------------------
class WizardSubPanel : public EditablePanel
{
DECLARE_CLASS_SIMPLE( WizardSubPanel, EditablePanel );
public:
// constructor
WizardSubPanel(Panel *parent, const char *panelName);
~WizardSubPanel();
// called when the subpanel is displayed
// All controls & data should be reinitialized at this time
virtual void OnDisplayAsNext() {}
// called anytime the panel is first displayed, whether the user is moving forward or back
// called immediately after OnDisplayAsNext/OnDisplayAsPrev
virtual void OnDisplay() {}
// called when displayed as previous
virtual void OnDisplayAsPrev() {}
// called when one of the wizard buttons are pressed
// returns true if the wizard should advance, false otherwise
virtual bool OnNextButton() { return true; }
virtual bool OnPrevButton() { return true; }
virtual bool OnFinishButton() { return true; }
virtual bool OnCancelButton() { return true; }
// returns true if this panel should be displayed, or if we should just skip over it
virtual bool ShouldDisplayPanel() { return true; }
// return true if this subpanel doesn't need the next/prev/finish/cancel buttons or will do it itself
virtual bool isNonWizardPanel() { return false; }
// returns a pointer to the next subpanel that should be displayed
virtual WizardSubPanel *GetNextSubPanel() = 0;
// returns a pointer to the panel to return to
// it must be a panel that is already in the wizards panel history
// returning NULL tells it to use the immediate previous panel in the history
virtual WizardSubPanel *GetPrevSubPanel() { return NULL; }
virtual WizardPanel *GetWizardPanel() { return _wizardPanel; }
virtual void SetWizardPanel(WizardPanel *wizardPanel) { _wizardPanel = wizardPanel; }
// returns a pointer to the wizard's doc
virtual KeyValues *GetWizardData();
// returns a pointer
virtual WizardSubPanel *GetSiblingSubPanelByName(const char *pageName);
// gets the size this subpanel would like the wizard to be
// returns true if it has a desired size
virtual bool GetDesiredSize(int &wide, int &tall);
protected:
virtual void ApplySettings(KeyValues *inResourceData);
virtual void GetSettings( KeyValues *outResourceData );
virtual void ApplySchemeSettings(IScheme *pScheme);
virtual const char *GetDescription();
private:
WizardPanel *_wizardPanel;
int m_iDesiredWide, m_iDesiredTall;
};
} // namespace vgui
#endif // WIZARDSUBPANEL_H

View File

@@ -0,0 +1,115 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PCH_VGUI_CONTROLS_H
#define PCH_VGUI_CONTROLS_H
#ifdef _WIN32
#pragma once
#endif
// general includes
#include <ctype.h>
#include <stdlib.h>
#include "tier0/dbg.h"
#include "tier0/valve_off.h"
#include "tier1/KeyValues.h"
#include "tier0/valve_on.h"
#include "tier0/memdbgon.h"
#include "filesystem.h"
#include "tier0/validator.h"
// vgui includes
#include "vgui/IBorder.h"
#include "vgui/IInput.h"
#include "vgui/ILocalize.h"
#include "vgui/IPanel.h"
#include "vgui/IScheme.h"
#include "vgui/ISurface.h"
#include "vgui/ISystem.h"
#include "vgui/IVGui.h"
#include "vgui/KeyCode.h"
#include "vgui/Cursor.h"
#include "vgui/MouseCode.h"
// vgui controls includes
#include "vgui_controls/Controls.h"
#include "vgui_controls/AnimatingImagePanel.h"
#include "vgui_controls/AnimationController.h"
#include "vgui_controls/BitmapImagePanel.h"
#include "vgui_controls/BuildGroup.h"
#include "vgui_controls/BuildModeDialog.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/CheckButton.h"
#include "vgui_controls/CheckButtonList.h"
#include "vgui_controls/ComboBox.h"
#include "vgui_controls/Controls.h"
#include "vgui_controls/DialogManager.h"
#include "vgui_controls/DirectorySelectDialog.h"
#include "vgui_controls/Divider.h"
#include "vgui_controls/EditablePanel.h"
#include "vgui_controls/FileOpenDialog.h"
#include "vgui_controls/FocusNavGroup.h"
#include "vgui_controls/Frame.h"
#include "vgui_controls/GraphPanel.h"
#include "vgui_controls/HTML.h"
#include "vgui_controls/Image.h"
#include "vgui_controls/ImageList.h"
#include "vgui_controls/ImagePanel.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/ListPanel.h"
#include "vgui_controls/ListViewPanel.h"
#include "vgui_controls/Menu.h"
#include "vgui_controls/MenuBar.h"
#include "vgui_controls/MenuButton.h"
#include "vgui_controls/MenuItem.h"
#include "vgui_controls/MessageBox.h"
#include "vgui_controls/Panel.h"
#ifndef HL1
#include "vgui_controls/PanelAnimationVar.h"
#endif
#include "vgui_controls/PanelListPanel.h"
#include "vgui_controls/PHandle.h"
#include "vgui_controls/ProgressBar.h"
#include "vgui_controls/ProgressBox.h"
#include "vgui_controls/PropertyDialog.h"
#include "vgui_controls/PropertyPage.h"
#include "vgui_controls/PropertySheet.h"
#include "vgui_controls/QueryBox.h"
#include "vgui_controls/RadioButton.h"
#include "vgui_controls/RichText.h"
#include "vgui_controls/ScrollBar.h"
#include "vgui_controls/ScrollBarSlider.h"
#include "vgui_controls/SectionedListPanel.h"
#include "vgui_controls/Slider.h"
#ifndef HL1
#include "vgui_controls/Splitter.h"
#endif
#include "vgui_controls/TextEntry.h"
#include "vgui_controls/TextImage.h"
#include "vgui_controls/ToggleButton.h"
#include "vgui_controls/Tooltip.h"
#ifndef HL1
#include "vgui_controls/ToolWindow.h"
#endif
#include "vgui_controls/TreeView.h"
#ifndef HL1
#include "vgui_controls/TreeViewListControl.h"
#endif
#include "vgui_controls/URLLabel.h"
#include "vgui_controls/WizardPanel.h"
#include "vgui_controls/WizardSubPanel.h"
#ifndef HL1
#include "vgui_controls/KeyBoardEditorDialog.h"
#include "vgui_controls/InputDialog.h"
#endif
#endif // PCH_VGUI_CONTROLS_H

View File

@@ -0,0 +1,151 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// List of perforce files and operations
//
//=============================================================================
#ifndef PERFORCEFILELISTFRAME_H
#define PERFORCEFILELISTFRAME_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
#include "tier1/utlvector.h"
#include "tier1/utlstring.h"
#include "p4lib/ip4.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Enumeration of operation dialog ids
//-----------------------------------------------------------------------------
enum
{
OPERATION_DIALOG_ID_PERFORCE = 0,
OPERATION_DIALOG_STANDARD_ID_COUNT,
OPERATION_DIALOG_STANDARD_ID_MAX = OPERATION_DIALOG_STANDARD_ID_COUNT - 1,
};
//-----------------------------------------------------------------------------
// Purpose: Modal dialog for a list of files + an operation to perform
//-----------------------------------------------------------------------------
class COperationFileListFrame : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( COperationFileListFrame, vgui::Frame );
public:
// NOTE: The dialog ID is used to allow dialogs to have different configurations saved
COperationFileListFrame( vgui::Panel *pParent, const char *pTitle, const char *pColumnHeader, bool bShowDescription, bool bShowOkOnly = false, int nDialogID = 1 );
virtual ~COperationFileListFrame();
// Command handler
virtual void OnCommand( const char *pCommand );
virtual void PerformLayout();
// Adds files to the frame
void ClearAllOperations();
void AddOperation( const char *pOperation, const char *pFileName );
void AddOperation( const char *pOperation, const char *pFileName, const Color& clr );
// Resizes the operation column to fit the operation text
void ResizeOperationColumnToContents();
// Sets the column header for the 'operation' column
void SetOperationColumnHeaderText( const char *pText );
// Shows the panel
void DoModal( KeyValues *pContextKeyValues = NULL, const char *pMessage = NULL );
// Retrieves the number of files, the file names, and operations
int GetOperationCount();
const char *GetFileName( int i );
const char *GetOperation( int i );
// Retreives the description (only if it was shown)
const char *GetDescription();
private:
virtual bool PerformOperation() { return true; }
const char *CompletionMessage();
void CleanUpMessage();
vgui::ListPanel *m_pFileBrowser;
vgui::Splitter *m_pSplitter;
vgui::TextEntry *m_pDescription;
vgui::Button *m_pYesButton;
vgui::Button *m_pNoButton;
KeyValues *m_pContextKeyValues;
CUtlString m_MessageName;
char *m_pText;
};
//-----------------------------------------------------------------------------
// Purpose: Modal dialog for picker
//-----------------------------------------------------------------------------
enum PerforceAction_t
{
PERFORCE_ACTION_NONE = -1,
PERFORCE_ACTION_FILE_ADD = 0,
PERFORCE_ACTION_FILE_EDIT,
PERFORCE_ACTION_FILE_DELETE,
PERFORCE_ACTION_FILE_REVERT,
PERFORCE_ACTION_FILE_SUBMIT,
};
//-----------------------------------------------------------------------------
// Purpose: Modal dialog for picker
//-----------------------------------------------------------------------------
class CPerforceFileListFrame : public COperationFileListFrame
{
DECLARE_CLASS_SIMPLE( CPerforceFileListFrame, COperationFileListFrame );
public:
CPerforceFileListFrame( vgui::Panel *pParent, const char *pTitle, const char *pColumnHeader, PerforceAction_t action );
virtual ~CPerforceFileListFrame();
// Adds files to the frame
void ClearAllFiles();
void AddFile( const char *pFullPath );
void AddFile( const char *pRelativePath, const char *pPathId );
void DoModal( KeyValues *pContextKeys = NULL, const char *pMessage = NULL );
private:
virtual bool PerformOperation();
// Adds files for open, submit
void AddFileForOpen( const char *pFullPath );
void AddFileForSubmit( const char *pFullPath, P4FileState_t state );
// Does the perforce operation
void PerformPerforceAction( );
PerforceAction_t m_Action;
CUtlVector< P4File_t > m_OpenedFiles;
CUtlString m_LastOpenedFilePathId;
};
//-----------------------------------------------------------------------------
// Show the perforce query dialog
// The specified keyvalues message will be sent either
// 1) If you open the file for add/edit
// 2) If you indicate to not add a file for add but don't hit cancel
// If a specific perforce action is specified, then the dialog will only
// be displayed if that action is appropriate
//-----------------------------------------------------------------------------
void ShowPerforceQuery( vgui::Panel *pParent, const char *pFileName, vgui::Panel *pActionSignalTarget, KeyValues *pKeyValues, PerforceAction_t actionFilter = PERFORCE_ACTION_NONE );
#endif // PERFORCEFILELISTFRAME_H

View File

@@ -0,0 +1,37 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// This dialog asks if you want to save your work
//
//=============================================================================
#ifndef SAVEDOCUMENTQUERY_H
#define SAVEDOCUMENTQUERY_H
#ifdef _WIN32
#pragma once
#endif
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class KeyValues;
namespace vgui
{
class Panel;
}
//-----------------------------------------------------------------------------
// Show the save document query dialog
// NOTE: The following commands will be posted to the action signal target:
// "OnExit" - when we want to quit
// "OnSave" - when we want to save the file
// "OnCloseNoSave" - when we want to close the file without saving it
// "commandname" - additional command send after saving (SAVEDOC_POSTCOMMAND_AFTER_SAVE)
// "OnMarkNotDirty" - when we want to mark the file not dirty
//-----------------------------------------------------------------------------
void ShowSaveDocumentQuery( vgui::Panel *pParent, const char *pFileName, const char *pFileType, int nContext, vgui::Panel *pActionSignalTarget, KeyValues *pPostSaveCommand );
#endif // SAVEDOCUMENTQUERY_H

View File

@@ -0,0 +1,51 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef SUBRECTIMAGE_H
#define SUBRECTIMAGE_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Image.h"
#include "vgui/VGUI.h"
//-----------------------------------------------------------------------------
// Purpose: Check box image
//-----------------------------------------------------------------------------
class CSubRectImage : public vgui::Image
{
public:
CSubRectImage( const char *filename, bool hardwareFiltered, int subx, int suby, int subw, int subh );
virtual ~CSubRectImage();
void GetSize( int &wide, int &tall );
void GetContentSize( int &wide, int &tall );
void SetSize( int x, int y );
void SetPos( int x, int y );
void SetColor( Color col );
const char *GetName();
void Paint();
void ForceUpload();
vgui::HTexture GetID();
bool IsValid();
private:
vgui::HTexture _id;
int sub[ 4 ];
char *_filename;
int _pos[2];
int _wide,_tall;
Color _color;
bool _uploaded;
bool _valid;
bool _filtered;
};
#endif // SUBRECTIMAGE_H

View File

@@ -0,0 +1,58 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "vgui/IVGui.h"
#include "vgui_controls/Controls.h"
#include "vgui_controls/AnimatingImagePanel.h"
#include "vgui_controls/BitmapImagePanel.h"
#include "vgui_controls/ExpandButton.h"
#include "vgui_controls/TreeViewListControl.h"
#include "vgui_controls/HTML.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
using namespace vgui;
USING_BUILD_FACTORY( Button );
USING_BUILD_FACTORY( EditablePanel );
USING_BUILD_FACTORY( ImagePanel );
USING_BUILD_FACTORY( Label );
USING_BUILD_FACTORY( Panel );
USING_BUILD_FACTORY( ToggleButton );
USING_BUILD_FACTORY( AnimatingImagePanel );
USING_BUILD_FACTORY( CBitmapImagePanel );
USING_BUILD_FACTORY( CheckButton );
USING_BUILD_FACTORY( ComboBox );
USING_BUILD_FACTORY_ALIAS( CvarToggleCheckButton<ConVarRef>, CvarToggleCheckButton );
USING_BUILD_FACTORY( Divider );
USING_BUILD_FACTORY( ExpandButton );
USING_BUILD_FACTORY( GraphPanel );
//USING_BUILD_FACTORY_ALIAS( HTML, HTML_NoJavascript );
//USING_BUILD_FACTORY_ALIAS( HTML, HTML_Javascript );
USING_BUILD_FACTORY( ListPanel );
USING_BUILD_FACTORY( ListViewPanel );
USING_BUILD_FACTORY( Menu );
USING_BUILD_FACTORY( MenuBar );
USING_BUILD_FACTORY( MenuButton );
USING_BUILD_FACTORY( MenuItem );
USING_BUILD_FACTORY( MessageBox );
USING_BUILD_FACTORY( ProgressBar );
USING_BUILD_FACTORY( CircularProgressBar );
USING_BUILD_FACTORY( RadioButton );
USING_BUILD_FACTORY( RichText );
USING_BUILD_FACTORY( ScalableImagePanel );
USING_BUILD_FACTORY_ALIAS( ScrollBar, ScrollBar_Vertical );
USING_BUILD_FACTORY_ALIAS( ScrollBar, ScrollBar_Horizontal );
USING_BUILD_FACTORY( ScrollBar );
USING_BUILD_FACTORY( Slider );
USING_BUILD_FACTORY( TextEntry );
USING_BUILD_FACTORY( TreeView );
USING_BUILD_FACTORY( CTreeViewListControl );
USING_BUILD_FACTORY( URLLabel );
int g_nYou_Must_Add_Public_Vgui_Controls_Vgui_ControlsCpp_To_Your_Project = 0;

View File

@@ -0,0 +1,549 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
//=============================================================================
#ifndef IVIDEOSERVICES_H
#define IVIDEOSERVICES_H
#if defined ( WIN32 )
#pragma once
#endif
#include <math.h>
#include "appframework/IAppSystem.h"
#include "tier0/platform.h"
#include <stdint.h>
#ifndef _STDINT_H
#define _STDINT_H
#endif
#ifndef _STDINT
#define _STDINT
#endif
#ifndef nullptr
#define nullptr ( 0 )
#endif
#ifndef INT32_MAX
#define INT32_MAX (0x7FFFFFFF)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (0xFFFFFFFFu)
#endif
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class IMaterial;
//-----------------------------------------------------------------------------
// Types used when dealing with video services
//-----------------------------------------------------------------------------
#define FILE_EXTENSION_ANY_MATCHING_VIDEO ".vid"
//#define ENABLE_EXTERNAL_ENCODER_LOGGING
//-----------------------------------------------------------------------------
// enums used when dealing with video services
//-----------------------------------------------------------------------------
// ==============================================
// various general video system enumerations
namespace VideoResult
{
enum EVideoResult_t
{
SUCCESS = 0,
SYSTEM_NOT_AVAILABLE,
CODEC_NOT_AVAILABLE,
FEATURE_NOT_AVAILABLE,
UNKNOWN_OPERATION,
ILLEGAL_OPERATION,
OPERATION_NOT_SUPPORTED,
BAD_INPUT_PARAMETERS,
OPERATION_ALREADY_PERFORMED,
OPERATION_OUT_OF_SEQUENCE,
VIDEO_ERROR_OCCURED,
FILE_ERROR_OCCURED,
AUDIO_ERROR_OCCURED,
SYSTEM_ERROR_OCCURED,
INITIALIZATION_ERROR_OCCURED,
SHUTDOWN_ERROR_OCCURED,
MATERIAL_NOT_FOUND,
RECORDER_NOT_FOUND,
VIDEO_FILE_NOT_FOUND,
VIDEO_SYSTEM_NOT_FOUND,
};
};
typedef VideoResult::EVideoResult_t VideoResult_t;
namespace VideoSystem
{
enum EVideoSystem_t
{
ALL_VIDEO_SYSTEMS = -2,
DETERMINE_FROM_FILE_EXTENSION = -1,
NONE = 0,
BINK,
AVI,
WMV,
QUICKTIME,
WEBM,
VIDEO_SYSTEM_COUNT,
VIDEO_SYSTEM_FIRST = 1,
};
};
typedef VideoSystem::EVideoSystem_t VideoSystem_t;
namespace VideoSystemStatus
{
enum EVideoSystemStatus_t
{
OK = 0,
NOT_INSTALLED,
NOT_CURRENT_VERSION,
NOT_INITIALIZED,
INITIALIZATION_ERROR,
};
};
typedef VideoSystemStatus::EVideoSystemStatus_t VideoSystemStatus_t;
namespace VideoSystemFeature
{
enum EVideoSystemFeature_t
{
NO_FEATURES = 0x00000000,
PLAY_VIDEO_FILE_FULL_SCREEN = 0x00000001,
PLAY_VIDEO_FILE_IN_MATERIAL = 0x00000002,
ENCODE_VIDEO_TO_FILE = 0x00000004,
ENCODE_AUDIO_TO_FILE = 0x00000008,
FULL_PLAYBACK = PLAY_VIDEO_FILE_FULL_SCREEN | PLAY_VIDEO_FILE_IN_MATERIAL,
FULL_ENCODE = ENCODE_VIDEO_TO_FILE | ENCODE_AUDIO_TO_FILE,
ALL_VALID_FEATURES = FULL_PLAYBACK | FULL_ENCODE,
ESF_FORCE_UINT32 = UINT32_MAX,
};
DEFINE_ENUM_BITWISE_OPERATORS( EVideoSystemFeature_t );
};
typedef VideoSystemFeature::EVideoSystemFeature_t VideoSystemFeature_t;
namespace VideoSoundDeviceOperation
{
enum EVideoSoundDeviceOperation_t
{
SET_DIRECT_SOUND_DEVICE = 0, // Windows option
SET_MILES_SOUND_DEVICE, // Supported by RAD
HOOK_X_AUDIO, // Xbox Option
SET_SOUND_MANAGER_DEVICE, // OSX Option
SET_LIB_AUDIO_DEVICE, // PS3 Option
SET_SDL_SOUND_DEVICE, // SDL Audio
SET_SDL_PARAMS, // SDL Audio params
SDLMIXER_CALLBACK, // SDLMixer callback
OPERATION_COUNT
};
};
typedef VideoSoundDeviceOperation::EVideoSoundDeviceOperation_t VideoSoundDeviceOperation_t;
// ==============================================
// Video Encoding related settings
namespace VideoEncodeCodec
{
//
// NOTE: NEW CODECS SHOULD BE ADDED TO THE END OF THIS LIST.
//
enum EVideoEncodeCodec_t
{
MPEG2_CODEC,
MPEG4_CODEC,
H261_CODEC,
H263_CODEC,
H264_CODEC,
MJPEG_A_CODEC,
MJPEG_B_CODEC,
SORENSON3_CODEC,
CINEPACK_CODEC,
WEBM_CODEC,
//
// NOTE: ADD NEW CODECS HERE.
//
CODEC_COUNT,
DEFAULT_CODEC = H264_CODEC,
};
};
typedef VideoEncodeCodec::EVideoEncodeCodec_t VideoEncodeCodec_t;
namespace VideoEncodeQuality
{
enum EVideoEncodeQuality_t
{
MIN_QUALITY = 0,
MAX_QUALITY = 100
};
};
typedef VideoEncodeQuality::EVideoEncodeQuality_t VideoEncodeQuality_t;
namespace VideoEncodeSourceFormat
{
enum EVideoEncodeSourceFormat_t // Image source format for frames to encoded
{
BGRA_32BIT = 0,
BGR_24BIT,
RGB_24BIT,
RGBA_32BIT,
VIDEO_FORMAT_COUNT,
VIDEO_FORMAT_FIRST = 0
};
};
typedef VideoEncodeSourceFormat::EVideoEncodeSourceFormat_t VideoEncodeSourceFormat_t;
namespace VideoEncodeGamma
{
enum EVideoEncodeGamma_t
{
NO_GAMMA_ADJUST = 0,
PLATFORM_STANDARD_GAMMA,
GAMMA_1_8,
GAMMA_2_2,
GAMMA_2_5,
GAMMA_COUNT
};
};
typedef VideoEncodeGamma::EVideoEncodeGamma_t VideoEncodeGamma_t;
namespace VideoPlaybackGamma
{
enum EVideoPlaybackGamma_t
{
USE_GAMMA_CONVAR = -1,
NO_GAMMA_ADJUST = 0,
PLATFORM_DEFAULT_GAMMMA,
GAMMA_1_8,
GAMMA_2_2,
GAMMA_2_5,
GAMMA_COUNT
};
};
typedef VideoPlaybackGamma::EVideoPlaybackGamma_t VideoPlaybackGamma_t;
// ==============================================
// Video Playback related settings
namespace VideoPlaybackFlags
{
enum EVideoPlaybackFlags_t // Options when playing a video file
{
NO_PLAYBACK_OPTIONS = 0x00000000,
// Full Screen Playback Options
FILL_WINDOW = 0x00000001, // force video fill entire window
LOCK_ASPECT_RATIO = 0x00000002, // preserve aspect ratio when scaling
INTEGRAL_SCALE = 0x00000004, // scale video only by integral amounts
CENTER_VIDEO_IN_WINDOW = 0x00000008, // center output video in window
FORCE_MIN_PLAY_TIME = 0x00000010, // play for a minimum amount of time before allowing skip or abort
ABORT_ON_SPACE = 0x00000100, // Keys to abort fullscreen playback on
ABORT_ON_ESC = 0x00000200,
ABORT_ON_RETURN = 0x00000400,
ABORT_ON_ANY_KEY = 0x00000700,
PAUSE_ON_SPACE = 0x00001000, // Keys to pause fullscreen playback on
PAUSE_ON_ESC = 0x00002000,
PAUSE_ON_RETURN = 0x00004000,
PAUSE_ON_ANY_KEY = 0x00007000,
LOOP_VIDEO = 0x00010000, // Full Screen and Video material
NO_AUDIO = 0x00020000,
PRELOAD_VIDEO = 0x00040000,
DONT_AUTO_START_VIDEO = 0x00100000, // Don't begin playing until told to do so.
TEXTURES_ACTUAL_SIZE = 0x00200000, // Try and use textures the same size as the video frame
VALID_FULLSCREEN_FLAGS = 0x0007771F, // Playback Flags that are valid for playing videos fullscreen
VALID_MATERIAL_FLAGS = 0x00370000, // Playback Flags that are valid for playing videos in a material
DEFAULT_MATERIAL_OPTIONS = NO_PLAYBACK_OPTIONS,
DEFAULT_FULLSCREEN_OPTIONS = CENTER_VIDEO_IN_WINDOW | LOCK_ASPECT_RATIO | ABORT_ON_ANY_KEY,
EVPF_FORCE_UINT32 = UINT32_MAX,
};
DEFINE_ENUM_BITWISE_OPERATORS( EVideoPlaybackFlags_t );
}
typedef VideoPlaybackFlags::EVideoPlaybackFlags_t VideoPlaybackFlags_t;
namespace AudioEncodeSourceFormat
{
enum EAudioEncodeSourceFormat_t // Audio source format to encode
{
AUDIO_NONE = 0,
AUDIO_16BIT_PCMStereo,
AUDIO_FORMAT_COUNT
};
};
typedef AudioEncodeSourceFormat::EAudioEncodeSourceFormat_t AudioEncodeSourceFormat_t;
namespace AudioEncodeOptions
{
enum EAudioEncodeOptions_t // Options to control audio encoding
{
NO_AUDIO_OPTIONS = 0x00000000,
USE_AUDIO_ENCODE_GROUP_SIZE = 0x00000001, // When adding to the video media, use fixed size sample groups
GROUP_SIZE_IS_VIDEO_FRAME = 0x00000002, // use a group size equal to one video frame in duration
LIMIT_AUDIO_TRACK_TO_VIDEO_DURATION = 0x00000004, // Don't let the Audio Track exceed the video track in duration
PAD_AUDIO_WITH_SILENCE = 0x00000008, // If Audio track duration is less than video track's, pad with silence
AEO_FORCE_UINT32 = UINT32_MAX,
};
DEFINE_ENUM_BITWISE_OPERATORS( EAudioEncodeOptions_t );
}
typedef AudioEncodeOptions::EAudioEncodeOptions_t AudioEncodeOptions_t;
//-----------------------------------------------------------------------------
// Frame Rate Class
//-----------------------------------------------------------------------------
class VideoFrameRate_t
{
public:
inline VideoFrameRate_t() : m_TimeUnitsPerSecond( 0 ), m_TimeUnitsPerFrame( 1000 ) {};
inline VideoFrameRate_t( int FPS, bool NTSC ) { SetFPS( FPS, NTSC); }
inline explicit VideoFrameRate_t( float FPS ) { SetFPS( FPS); };
inline VideoFrameRate_t& operator=( const VideoFrameRate_t& rhs ) { m_TimeUnitsPerSecond = rhs.m_TimeUnitsPerSecond; m_TimeUnitsPerFrame = rhs.m_TimeUnitsPerFrame; return *this; }
inline VideoFrameRate_t( const VideoFrameRate_t &rhs ) { *this = rhs; };
inline void SetRaw( int timeUnitsPerSecond, int TimeUnitsPerFrame ) { m_TimeUnitsPerSecond = timeUnitsPerSecond; m_TimeUnitsPerFrame = TimeUnitsPerFrame; }
inline float GetFPS() const { return (float) m_TimeUnitsPerSecond / (float) m_TimeUnitsPerFrame; }
inline int GetIntFPS() const { return (int) ( (float) m_TimeUnitsPerSecond / (float) m_TimeUnitsPerFrame + 0.5f ); }
inline bool IsNTSCRate() const { return ( m_TimeUnitsPerFrame == 1001 ); }
inline int GetUnitsPerSecond() const { return m_TimeUnitsPerSecond; }
inline int GetUnitsPerFrame() const { return m_TimeUnitsPerFrame; }
inline void SetFPS( int FPS, bool NTSC ) { m_TimeUnitsPerSecond = FPS * 1000; m_TimeUnitsPerFrame = 1000 + (uint) NTSC; }
inline void SetFPS( float FPS ) { m_TimeUnitsPerSecond = (uint) ( FPS * 1000.0f ); m_TimeUnitsPerFrame = 1000; }
static inline bool IsNTSC( float FPS ) { float diff = ceil(FPS) - FPS; return ( diff > 0.02f && diff < 0.05f); }
inline void Clear() { m_TimeUnitsPerSecond = 0; m_TimeUnitsPerFrame = 1000; }
inline bool IsValid() { return ( m_TimeUnitsPerSecond != 0); }
private:
uint32 m_TimeUnitsPerSecond;
uint32 m_TimeUnitsPerFrame;
};
//-----------------------------------------------------------------------------
// specific interfaces returned and managed by video services
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Video Material interface - manages the playing back of a video to a
// a material / texture combo
//-----------------------------------------------------------------------------
class IVideoMaterial : public IBaseInterface
{
public:
// Video information functions
virtual const char *GetVideoFileName() = 0; // Gets the file name of the video this material is playing
virtual VideoResult_t GetLastResult() = 0; // Gets detailed info on the last operation
virtual VideoFrameRate_t &GetVideoFrameRate() = 0; // Returns the frame rate of the associated video in FPS
// Audio Functions
virtual bool HasAudio() = 0; // Query if the video has an audio track
virtual bool SetVolume( float fVolume ) = 0; // Adjust the playback volume
virtual float GetVolume() = 0; // Query the current volume
virtual void SetMuted( bool bMuteState ) = 0; // Mute/UnMutes the audio playback
virtual bool IsMuted() = 0; // Query muted status
virtual VideoResult_t SoundDeviceCommand( VideoSoundDeviceOperation_t operation, void *pDevice = nullptr, void *pData = nullptr ) = 0; // Assign Sound Device for this Video Material
// Video playback state functions
virtual bool IsVideoReadyToPlay() = 0; // Queries if the video material was initialized successfully and is ready for playback, but not playing or finished
virtual bool IsVideoPlaying() = 0; // Is the video currently playing (and needs update calls, etc), or paused while playing?
virtual bool IsNewFrameReady() = 0; // Do we have a new frame to get & display?
virtual bool IsFinishedPlaying() = 0; // Have we reached the end of the movie
virtual bool StartVideo() = 0; // Starts the video playing
virtual bool StopVideo() = 0; // Terminates the video playing
virtual void SetLooping( bool bLoopVideo ) = 0; // Sets the video to loop (or not)
virtual bool IsLooping() = 0; // Queries if the video is looping
virtual void SetPaused( bool bPauseState ) = 0; // Pauses or Unpauses video playback
virtual bool IsPaused() = 0; // Queries if the video is paused
// Position in playback functions
virtual float GetVideoDuration() = 0; // Returns the duration of the associated video in seconds
virtual int GetFrameCount() = 0; // Returns the total number of (unique) frames in the video
virtual bool SetFrame( int FrameNum ) = 0; // Sets the current frame # in the video to play next
virtual int GetCurrentFrame() = 0; // Gets the current frame # for the video playback, 0 based
virtual bool SetTime( float flTime ) = 0; // Sets the video playback to specified time (in seconds)
virtual float GetCurrentVideoTime() = 0; // Gets the current time in the video playback
// Update function
virtual bool Update() = 0; // Updates the video frame to reflect the time passed, true = new frame available
// Material / Texture Info functions
virtual IMaterial *GetMaterial() = 0; // Gets the IMaterial associated with an video material
virtual void GetVideoTexCoordRange( float *pMaxU, float *pMaxV ) = 0; // Returns the max texture coordinate of the video portion of the material surface ( 0.0, 0.0 to U, V )
virtual void GetVideoImageSize( int *pWidth, int *pHeight ) = 0; // Returns the frame size of the Video Image Frame in pixels ( the stored in a subrect of the material itself)
};
//-----------------------------------------------------------------------------
// Video Recorder interface - manages the creation of a new video file
//-----------------------------------------------------------------------------
class IVideoRecorder : public IBaseInterface
{
public:
virtual bool EstimateMovieFileSize( size_t *pEstSize, int movieWidth, int movieHeight, VideoFrameRate_t movieFps, float movieDuration, VideoEncodeCodec_t theCodec, int videoQuality, AudioEncodeSourceFormat_t srcAudioFormat = AudioEncodeSourceFormat::AUDIO_NONE, int audioSampleRate = 0 ) = 0;
virtual bool CreateNewMovieFile( const char *pFilename, bool hasAudioTrack = false ) = 0;
virtual bool SetMovieVideoParameters( VideoEncodeCodec_t theCodec, int videoQuality, int movieFrameWidth, int movieFrameHeight, VideoFrameRate_t movieFPS, VideoEncodeGamma_t gamma = VideoEncodeGamma::NO_GAMMA_ADJUST ) = 0;
virtual bool SetMovieSourceImageParameters( VideoEncodeSourceFormat_t srcImageFormat, int imgWidth, int imgHeight ) = 0;
virtual bool SetMovieSourceAudioParameters( AudioEncodeSourceFormat_t srcAudioFormat = AudioEncodeSourceFormat::AUDIO_NONE, int audioSampleRate = 0, AudioEncodeOptions_t audioOptions = AudioEncodeOptions::NO_AUDIO_OPTIONS, int audioSampleGroupSize = 0) = 0;
virtual bool IsReadyToRecord() = 0;
virtual VideoResult_t GetLastResult() = 0;
virtual bool AppendVideoFrame( void *pFrameBuffer, int nStrideAdjustBytes = 0 ) = 0;
virtual bool AppendAudioSamples( void *pSampleBuffer, size_t sampleSize ) = 0;
virtual int GetFrameCount() = 0;
virtual int GetSampleCount() = 0;
virtual VideoFrameRate_t GetFPS() = 0;
virtual int GetSampleRate() = 0;
virtual bool AbortMovie() = 0;
virtual bool FinishMovie( bool SaveMovieToDisk = true ) = 0;
#ifdef ENABLE_EXTERNAL_ENCODER_LOGGING
virtual bool LogMessage( const char *msg ) = 0;
#endif
};
//-----------------------------------------------------------------------------
// Main VIDEO_SERVICES interface
//-----------------------------------------------------------------------------
#define VIDEO_SERVICES_INTERFACE_VERSION "IVideoServices002"
class IVideoServices : public IAppSystem
{
public:
// Query the available video systems
virtual int GetAvailableVideoSystemCount() = 0;
virtual VideoSystem_t GetAvailableVideoSystem( int n ) = 0;
virtual bool IsVideoSystemAvailable( VideoSystem_t videoSystem ) = 0;
virtual VideoSystemStatus_t GetVideoSystemStatus( VideoSystem_t videoSystem ) = 0;
virtual VideoSystemFeature_t GetVideoSystemFeatures( VideoSystem_t videoSystem ) = 0;
virtual const char *GetVideoSystemName( VideoSystem_t videoSystem ) = 0;
virtual VideoSystem_t FindNextSystemWithFeature( VideoSystemFeature_t features, VideoSystem_t startAfter = VideoSystem::NONE ) = 0;
virtual VideoResult_t GetLastResult() = 0;
// deal with video file extensions and video system mappings
virtual int GetSupportedFileExtensionCount( VideoSystem_t videoSystem ) = 0;
virtual const char *GetSupportedFileExtension( VideoSystem_t videoSystem, int extNum = 0 ) = 0;
virtual VideoSystemFeature_t GetSupportedFileExtensionFeatures( VideoSystem_t videoSystem, int extNum = 0 ) = 0;
virtual VideoSystem_t LocateVideoSystemForPlayingFile( const char *pFileName, VideoSystemFeature_t playMode = VideoSystemFeature::PLAY_VIDEO_FILE_IN_MATERIAL ) = 0;
virtual VideoResult_t LocatePlayableVideoFile( const char *pSearchFileName, const char *pPathID, VideoSystem_t *pPlaybackSystem, char *pPlaybackFileName, int fileNameMaxLen, VideoSystemFeature_t playMode = VideoSystemFeature::FULL_PLAYBACK ) = 0;
// Create/destroy a video material
virtual IVideoMaterial *CreateVideoMaterial( const char *pMaterialName, const char *pVideoFileName, const char *pPathID = nullptr,
VideoPlaybackFlags_t playbackFlags = VideoPlaybackFlags::DEFAULT_MATERIAL_OPTIONS,
VideoSystem_t videoSystem = VideoSystem::DETERMINE_FROM_FILE_EXTENSION, bool PlayAlternateIfNotAvailable = true ) = 0;
virtual VideoResult_t DestroyVideoMaterial( IVideoMaterial* pVideoMaterial ) = 0;
virtual int GetUniqueMaterialID() = 0;
// Create/destroy a video encoder
virtual VideoResult_t IsRecordCodecAvailable( VideoSystem_t videoSystem, VideoEncodeCodec_t codec ) = 0;
virtual IVideoRecorder *CreateVideoRecorder( VideoSystem_t videoSystem ) = 0;
virtual VideoResult_t DestroyVideoRecorder( IVideoRecorder *pVideoRecorder ) = 0;
// Plays a given video file until it completes or the user presses ESC, SPACE, or ENTER
virtual VideoResult_t PlayVideoFileFullScreen( const char *pFileName, const char *pPathID, void *mainWindow, int windowWidth, int windowHeight, int desktopWidth, int desktopHeight, bool windowed, float forcedMinTime,
VideoPlaybackFlags_t playbackFlags = VideoPlaybackFlags::DEFAULT_FULLSCREEN_OPTIONS,
VideoSystem_t videoSystem = VideoSystem::DETERMINE_FROM_FILE_EXTENSION, bool PlayAlternateIfNotAvailable = true ) = 0;
// Sets the sound devices that the video will decode to
virtual VideoResult_t SoundDeviceCommand( VideoSoundDeviceOperation_t operation, void *pDevice = nullptr, void *pData = nullptr, VideoSystem_t videoSystem = VideoSystem::ALL_VIDEO_SYSTEMS ) = 0;
// Get the (localized) name of a codec as a string
virtual const wchar_t *GetCodecName( VideoEncodeCodec_t nCodec ) = 0;
};
#endif // IVIDEOSERVICES_H

View File

@@ -0,0 +1,20 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// A set of collision rules
// NOTE: Defaults to all indices disabled
class IPhysicsCollisionSet
{
public:
~IPhysicsCollisionSet() {}
virtual void EnableCollisions( int index0, int index1 ) = 0;
virtual void DisableCollisions( int index0, int index1 ) = 0;
virtual bool ShouldCollide( int index0, int index1 ) = 0;
};

View File

@@ -0,0 +1,345 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CONSTRAINTS_H
#define CONSTRAINTS_H
#ifdef _WIN32
#pragma once
#endif
#include "vphysics_interface.h"
#include "mathlib/mathlib.h"
// constraint groups
struct constraint_groupparams_t
{
int additionalIterations; // additional solver iterations make the constraint system more stable
int minErrorTicks; // minimum number of ticks with an error before it's reported
float errorTolerance; // error tolerance in HL units
inline void Defaults()
{
additionalIterations = 0;
minErrorTicks = 15;
errorTolerance = 3.0f;
}
};
// Breakable constraints;
//
// forceLimit - kg * in / s limit (N * conversion(in/m))
// torqueLimit - kg * in^2 / s (Nm * conversion(in^2/m^2))
//
// strength 0 - 1
struct constraint_breakableparams_t
{
float strength; // strength of the constraint 0.0 - 1.0
float forceLimit; // constraint force limit to break (0 means never break)
float torqueLimit; // constraint torque limit to break (0 means never break)
float bodyMassScale[2]; // scale applied to mass of reference/attached object before solving constriant
bool isActive;
inline void Defaults()
{
forceLimit = 0.0f;
torqueLimit = 0.0f;
strength = 1.0f;
bodyMassScale[0] = 1.0f;
bodyMassScale[1] = 1.0f;
isActive = true;
}
};
//-----------------------------------------------------------------------------
// Purpose: constraint limit on a single rotation axis
//-----------------------------------------------------------------------------
struct constraint_axislimit_t
{
float minRotation;
float maxRotation;
float angularVelocity; // desired angular velocity around hinge
float torque; // torque to achieve angular velocity (use 0, torque for "friction")
inline void SetAxisFriction( float rmin, float rmax, float friction )
{
minRotation = rmin;
maxRotation = rmax;
angularVelocity = 0;
torque = friction;
}
inline void Defaults()
{
SetAxisFriction(0,0,0);
}
};
// Builds a transform which maps points in the input object's local space
// to the output object's local space
inline void BuildObjectRelativeXform( IPhysicsObject *pOutputSpace, IPhysicsObject *pInputSpace, matrix3x4_t &xformInToOut )
{
matrix3x4_t outInv, tmp, input;
pOutputSpace->GetPositionMatrix( &tmp );
MatrixInvert( tmp, outInv );
pInputSpace->GetPositionMatrix( &input );
ConcatTransforms( outInv, input, xformInToOut );
}
//-----------------------------------------------------------------------------
// Purpose: special limited ballsocket constraint for ragdolls.
// Has axis limits for all 3 axes.
//-----------------------------------------------------------------------------
struct constraint_ragdollparams_t
{
constraint_breakableparams_t constraint;
matrix3x4_t constraintToReference;// xform constraint space to refobject space
matrix3x4_t constraintToAttached; // xform constraint space to attached object space
int parentIndex; // NOTE: only used for parsing. NEED NOT BE SET for create
int childIndex; // NOTE: only used for parsing. NEED NOT BE SET for create
constraint_axislimit_t axes[3];
bool onlyAngularLimits; // only angular limits (not translation as well?)
bool isActive;
bool useClockwiseRotations; // HACKHACK: Did this wrong in version one. Fix in the future.
inline void Defaults()
{
constraint.Defaults();
isActive = true;
SetIdentityMatrix( constraintToReference );
SetIdentityMatrix( constraintToAttached );
parentIndex = -1;
childIndex = -1;
axes[0].Defaults();
axes[1].Defaults();
axes[2].Defaults();
onlyAngularLimits = false;
useClockwiseRotations = false;
}
};
//-----------------------------------------------------------------------------
// Purpose: Used to init a hinge restricting the relative position and orientation
// of two objects to rotation around a single axis
//-----------------------------------------------------------------------------
struct constraint_hingeparams_t
{
Vector worldPosition; // position in world space on the hinge axis
Vector worldAxisDirection; // unit direction vector of the hinge axis in world space
constraint_axislimit_t hingeAxis;
constraint_breakableparams_t constraint;
inline void Defaults()
{
worldPosition.Init();
worldAxisDirection.Init();
hingeAxis.Defaults();
constraint.Defaults();
}
};
struct constraint_limitedhingeparams_t : public constraint_hingeparams_t
{
Vector referencePerpAxisDirection; // unit direction vector vector perpendicular to the hinge axis in world space
Vector attachedPerpAxisDirection; // unit direction vector vector perpendicular to the hinge axis in world space
constraint_limitedhingeparams_t() {}
constraint_limitedhingeparams_t( const constraint_hingeparams_t &hinge )
{
static_cast<constraint_hingeparams_t &>(*this) = hinge;
referencePerpAxisDirection.Init();
attachedPerpAxisDirection.Init();
}
inline void Defaults()
{
this->constraint_hingeparams_t::Defaults();
referencePerpAxisDirection.Init();
attachedPerpAxisDirection.Init();
}
};
//-----------------------------------------------------------------------------
// Purpose: Used to init a constraint that fixes the position and orientation
// of two objects relative to each other (like glue)
//-----------------------------------------------------------------------------
struct constraint_fixedparams_t
{
matrix3x4_t attachedRefXform; // xform attached object space to ref object space
constraint_breakableparams_t constraint;
inline void InitWithCurrentObjectState( IPhysicsObject *pRef, IPhysicsObject *pAttached )
{
BuildObjectRelativeXform( pRef, pAttached, attachedRefXform );
}
inline void Defaults()
{
SetIdentityMatrix( attachedRefXform );
constraint.Defaults();
}
};
//-----------------------------------------------------------------------------
// Purpose: Same parameters as fixed constraint, but torqueLimit has no effect
//-----------------------------------------------------------------------------
struct constraint_ballsocketparams_t
{
Vector constraintPosition[2]; // position of the constraint in each object's space
constraint_breakableparams_t constraint;
inline void Defaults()
{
constraint.Defaults();
constraintPosition[0].Init();
constraintPosition[1].Init();
}
void InitWithCurrentObjectState( IPhysicsObject *pRef, IPhysicsObject *pAttached, const Vector &ballsocketOrigin )
{
pRef->WorldToLocal( &constraintPosition[0], ballsocketOrigin );
pAttached->WorldToLocal( &constraintPosition[1], ballsocketOrigin );
}
};
struct constraint_slidingparams_t
{
matrix3x4_t attachedRefXform; // xform attached object space to ref object space
Vector slideAxisRef; // unit direction vector of the slide axis in ref object space
constraint_breakableparams_t constraint;
// NOTE: if limitMin == limitMax there is NO limit set!
float limitMin; // minimum limit coordinate refAxisDirection space
float limitMax; // maximum limit coordinate refAxisDirection space
float friction; // friction on sliding
float velocity; // desired velocity
inline void Defaults()
{
SetIdentityMatrix( attachedRefXform );
slideAxisRef.Init();
limitMin = limitMax = 0;
friction = 0;
velocity = 0;
constraint.Defaults();
}
inline void SetFriction( float inputFriction )
{
friction = inputFriction;
velocity = 0;
}
inline void SetLinearMotor( float inputVelocity, float maxForce )
{
friction = maxForce;
velocity = inputVelocity;
}
inline void InitWithCurrentObjectState( IPhysicsObject *pRef, IPhysicsObject *pAttached, const Vector &slideDirWorldspace )
{
BuildObjectRelativeXform( pRef, pAttached, attachedRefXform );
matrix3x4_t tmp;
pRef->GetPositionMatrix( &tmp );
VectorIRotate( slideDirWorldspace, tmp, slideAxisRef );
}
};
struct constraint_pulleyparams_t
{
constraint_breakableparams_t constraint;
Vector pulleyPosition[2]; // These are the pulley positions for the reference and attached objects in world space
Vector objectPosition[2]; // local positions of attachments to the ref,att objects
float totalLength; // total rope length (include gearing!)
float gearRatio; // gearing affects attached object ALWAYS
bool isRigid;
inline void Defaults()
{
constraint.Defaults();
totalLength = 1.0;
gearRatio = 1.0;
pulleyPosition[0].Init();
pulleyPosition[1].Init();
objectPosition[0].Init();
objectPosition[1].Init();
isRigid = false;
}
};
struct constraint_lengthparams_t
{
constraint_breakableparams_t constraint;
Vector objectPosition[2]; // These are the positions for the reference and attached objects in local space
float totalLength; // Length of rope/spring/constraint. Distance to maintain
float minLength; // if rigid, objects are not allowed to move closer than totalLength either
void InitWorldspace( IPhysicsObject *pRef, IPhysicsObject *pAttached, const Vector &refPosition, const Vector &attachedPosition, bool rigid = false )
{
pRef->WorldToLocal( &objectPosition[0], refPosition );
pAttached->WorldToLocal( &objectPosition[1], attachedPosition );
totalLength = (refPosition - attachedPosition).Length();
minLength = rigid ? totalLength : 0;
}
inline void Defaults()
{
constraint.Defaults();
objectPosition[0].Init();
objectPosition[1].Init();
totalLength = 1;
minLength = 0;
}
};
class IPhysicsConstraint
{
public:
virtual ~IPhysicsConstraint( void ) {}
// NOTE: Constraints are active when created. You can temporarily enable/disable them with these functions
virtual void Activate( void ) = 0;
virtual void Deactivate( void ) = 0;
// set a pointer to the game object
virtual void SetGameData( void *gameData ) = 0;
// get a pointer to the game object
virtual void *GetGameData( void ) const = 0;
// Get the parent/referenced object
virtual IPhysicsObject *GetReferenceObject( void ) const = 0;
// Get the attached object
virtual IPhysicsObject *GetAttachedObject( void ) const = 0;
virtual void SetLinearMotor( float speed, float maxLinearImpulse ) = 0;
virtual void SetAngularMotor( float rotSpeed, float maxAngularImpulse ) = 0;
virtual void UpdateRagdollTransforms( const matrix3x4_t &constraintToReference, const matrix3x4_t &constraintToAttached ) = 0;
virtual bool GetConstraintTransform( matrix3x4_t *pConstraintToReference, matrix3x4_t *pConstraintToAttached ) const = 0;
virtual bool GetConstraintParams( constraint_breakableparams_t *pParams ) const = 0;
virtual void OutputDebugInfo() = 0;
};
class IPhysicsConstraintGroup
{
public:
virtual ~IPhysicsConstraintGroup( void ) {}
virtual void Activate() = 0;
virtual bool IsInErrorState() = 0;
virtual void ClearErrorState() = 0;
virtual void GetErrorParams( constraint_groupparams_t *pParams ) = 0;
virtual void SetErrorParams( const constraint_groupparams_t &params ) = 0;
virtual void SolvePenetration( IPhysicsObject *pObj0, IPhysicsObject *pObj1 ) = 0;
};
#endif // CONSTRAINTS_H

View File

@@ -0,0 +1,51 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef FRICTION_H
#define FRICTION_H
#ifdef _WIN32
#pragma once
#endif
// NOTE: This is an iterator for the contact points on an object
// NOTE: This should only be used temporarily. Holding one of these
// NOTE: across collision callbacks or calls into simulation will cause errors!
// NOTE: VPHYSICS may choose to make the data contained within this object invalid
// NOTE: any time simulation is run.
class IPhysicsFrictionSnapshot
{
public:
virtual ~IPhysicsFrictionSnapshot() {}
virtual bool IsValid() = 0;
// Object 0 is this object, Object 1 is the other object
virtual IPhysicsObject *GetObject( int index ) = 0;
virtual int GetMaterial( int index ) = 0;
virtual void GetContactPoint( Vector &out ) = 0;
// points away from source object
virtual void GetSurfaceNormal( Vector &out ) = 0;
virtual float GetNormalForce() = 0;
virtual float GetEnergyAbsorbed() = 0;
// recompute friction (useful if dynamically altering materials/mass)
virtual void RecomputeFriction() = 0;
// clear all friction force at this contact point
virtual void ClearFrictionForce() = 0;
virtual void MarkContactForDelete() = 0;
virtual void DeleteAllMarkedContacts( bool wakeObjects ) = 0;
// Move to the next friction data for this object
virtual void NextFrictionData() = 0;
virtual float GetFrictionCoefficient() = 0;
};
#endif // FRICTION_H

View File

@@ -0,0 +1,29 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef OBJECT_HASH_H
#define OBJECT_HASH_H
#ifdef _WIN32
#pragma once
#endif
class IPhysicsObjectPairHash
{
public:
virtual ~IPhysicsObjectPairHash() {}
virtual void AddObjectPair( void *pObject0, void *pObject1 ) = 0;
virtual void RemoveObjectPair( void *pObject0, void *pObject1 ) = 0;
virtual bool IsObjectPairInHash( void *pObject0, void *pObject1 ) = 0;
virtual void RemoveAllPairsForObject( void *pObject0 ) = 0;
virtual bool IsObjectInHash( void *pObject0 ) = 0;
// Used to iterate over all pairs an object is part of
virtual int GetPairCountForObject( void *pObject0 ) = 0;
virtual int GetPairListForObject( void *pObject0, int nMaxCount, void **ppObjectList ) = 0;
};
#endif // OBJECT_HASH_H

View File

@@ -0,0 +1,44 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef PERFORMANCE_H
#define PERFORMANCE_H
#ifdef _WIN32
#pragma once
#endif
// Don't ever change these values, or face all kinds of subtle gameplay changes
const float k_flMaxVelocity = 2000.0f;
const float k_flMaxAngularVelocity = 360.0f * 10.0f;
const float DEFAULT_MIN_FRICTION_MASS = 10.0f;
const float DEFAULT_MAX_FRICTION_MASS = 2500.0f;
struct physics_performanceparams_t
{
int maxCollisionsPerObjectPerTimestep; // object will be frozen after this many collisions (visual hitching vs. CPU cost)
int maxCollisionChecksPerTimestep; // objects may penetrate after this many collision checks (can be extended in AdditionalCollisionChecksThisTick)
float maxVelocity; // limit world space linear velocity to this (in / s)
float maxAngularVelocity; // limit world space angular velocity to this (degrees / s)
float lookAheadTimeObjectsVsWorld; // predict collisions this far (seconds) into the future
float lookAheadTimeObjectsVsObject; // predict collisions this far (seconds) into the future
float minFrictionMass; // min mass for friction solves (constrains dynamic range of mass to improve stability)
float maxFrictionMass; // mas mass for friction solves
void Defaults()
{
maxCollisionsPerObjectPerTimestep = 6;
maxCollisionChecksPerTimestep = 250;
maxVelocity = k_flMaxVelocity;
maxAngularVelocity = k_flMaxAngularVelocity;
lookAheadTimeObjectsVsWorld = 1.0f;
lookAheadTimeObjectsVsObject = 0.5f;
minFrictionMass = DEFAULT_MIN_FRICTION_MASS;
maxFrictionMass = DEFAULT_MAX_FRICTION_MASS;
}
};
#endif // PERFORMANCE_H

View File

@@ -0,0 +1,47 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef PLAYER_CONTROLLER_H
#define PLAYER_CONTROLLER_H
#ifdef _WIN32
#pragma once
#endif
class IPhysicsPlayerControllerEvent
{
public:
virtual int ShouldMoveTo( IPhysicsObject *pObject, const Vector &position ) = 0;
};
class IPhysicsPlayerController
{
public:
virtual ~IPhysicsPlayerController( void ) {}
virtual void Update( const Vector &position, const Vector &velocity, float secondsToArrival, bool onground, IPhysicsObject *ground ) = 0;
virtual void SetEventHandler( IPhysicsPlayerControllerEvent *handler ) = 0;
virtual bool IsInContact( void ) = 0;
virtual void MaxSpeed( const Vector &maxVelocity ) = 0;
// allows game code to change collision models
virtual void SetObject( IPhysicsObject *pObject ) = 0;
// UNDONE: Refactor this and shadow controllers into a single class/interface through IPhysicsObject
virtual int GetShadowPosition( Vector *position, QAngle *angles ) = 0;
virtual void StepUp( float height ) = 0;
virtual void Jump() = 0;
virtual void GetShadowVelocity( Vector *velocity ) = 0;
virtual IPhysicsObject *GetObject() = 0;
virtual void GetLastImpulse( Vector *pOut ) = 0;
virtual void SetPushMassLimit( float maxPushMass ) = 0;
virtual void SetPushSpeedLimit( float maxPushSpeed ) = 0;
virtual float GetPushMassLimit() = 0;
virtual float GetPushSpeedLimit() = 0;
virtual bool WasFrozen() = 0;
};
#endif // PLAYER_CONTROLLER_H

View File

@@ -0,0 +1,40 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef STATS_H
#define STATS_H
#ifdef _WIN32
#pragma once
#endif
// internal counters to measure cost of physics simulation
struct physics_stats_t
{
float maxRescueSpeed;
float maxSpeedGain;
int impactSysNum;
int impactCounter;
int impactSumSys;
int impactHardRescueCount;
int impactRescueAfterCount;
int impactDelayedCount;
int impactCollisionChecks;
int impactStaticCount;
double totalEnergyDestroyed;
int collisionPairsTotal;
int collisionPairsCreated;
int collisionPairsDestroyed;
int potentialCollisionsObjectVsObject;
int potentialCollisionsObjectVsWorld;
int frictionEventsProcessed;
};
#endif // STATS_H

View File

@@ -0,0 +1,250 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef VEHICLES_H
#define VEHICLES_H
#ifdef _WIN32
#pragma once
#endif
#include "datamap.h"
#define VEHICLE_TYPE_CAR_WHEELS (1<<0)
#define VEHICLE_TYPE_CAR_RAYCAST (1<<1)
#define VEHICLE_TYPE_JETSKI_RAYCAST (1<<2)
#define VEHICLE_TYPE_AIRBOAT_RAYCAST (1<<3)
#define VEHICLE_MAX_AXLE_COUNT 4
#define VEHICLE_MAX_GEAR_COUNT 6
#define VEHICLE_MAX_WHEEL_COUNT (2*VEHICLE_MAX_AXLE_COUNT)
#define VEHICLE_TIRE_NORMAL 0
#define VEHICLE_TIRE_BRAKING 1
#define VEHICLE_TIRE_POWERSLIDE 2
struct vehicle_controlparams_t
{
float throttle;
float steering;
float brake;
float boost;
bool handbrake;
bool handbrakeLeft;
bool handbrakeRight;
bool brakepedal;
bool bHasBrakePedal;
bool bAnalogSteering;
};
struct vehicle_operatingparams_t
{
DECLARE_SIMPLE_DATADESC();
float speed;
float engineRPM;
int gear;
float boostDelay;
int boostTimeLeft;
float skidSpeed;
int skidMaterial;
float steeringAngle;
int wheelsNotInContact;
int wheelsInContact;
bool isTorqueBoosting;
};
// Debug!
#define VEHICLE_DEBUGRENDERDATA_MAX_WHEELS 10
#define VEHICLE_DEBUGRENDERDATA_MAX_AXLES 3
struct vehicle_debugcarsystem_t
{
Vector vecAxlePos[VEHICLE_DEBUGRENDERDATA_MAX_AXLES];
Vector vecWheelPos[VEHICLE_DEBUGRENDERDATA_MAX_WHEELS];
Vector vecWheelRaycasts[VEHICLE_DEBUGRENDERDATA_MAX_WHEELS][2];
Vector vecWheelRaycastImpacts[VEHICLE_DEBUGRENDERDATA_MAX_WHEELS];
};
struct vehicleparams_t;
class IPhysicsVehicleController
{
public:
virtual ~IPhysicsVehicleController() {}
// call this from the game code with the control parameters
virtual void Update( float dt, vehicle_controlparams_t &controls ) = 0;
virtual const vehicle_operatingparams_t &GetOperatingParams() = 0;
virtual const vehicleparams_t &GetVehicleParams() = 0;
virtual vehicleparams_t &GetVehicleParamsForChange() = 0;
virtual float UpdateBooster(float dt) = 0;
virtual int GetWheelCount(void) = 0;
virtual IPhysicsObject *GetWheel(int index) = 0;
virtual bool GetWheelContactPoint( int index, Vector *pContactPoint, int *pSurfaceProps ) = 0;
virtual void SetSpringLength(int wheelIndex, float length) = 0;
virtual void SetWheelFriction(int wheelIndex, float friction) = 0;
virtual void OnVehicleEnter( void ) = 0;
virtual void OnVehicleExit( void ) = 0;
virtual void SetEngineDisabled( bool bDisable ) = 0;
virtual bool IsEngineDisabled( void ) = 0;
// Debug
virtual void GetCarSystemDebugData( vehicle_debugcarsystem_t &debugCarSystem ) = 0;
virtual void VehicleDataReload() = 0;
};
// parameters for the body object control of the vehicle
struct vehicle_bodyparams_t
{
DECLARE_SIMPLE_DATADESC();
Vector massCenterOverride; // leave at vec3_origin for no override
float massOverride; // leave at 0 for no override
float addGravity; // keeps car down
float tiltForce; // keeps car down when not on flat ground
float tiltForceHeight; // where the tilt force pulls relative to center of mass
float counterTorqueFactor;
float keepUprightTorque;
float maxAngularVelocity; // clamp the car angular velocity separately from other objects to keep stable
};
// wheel objects are created by vphysics, these are the parameters for those objects
// NOTE: They are paired, so only one set of parameters is necessary per axle
struct vehicle_wheelparams_t
{
DECLARE_SIMPLE_DATADESC();
float radius;
float mass;
float inertia;
float damping; // usually 0
float rotdamping; // usually 0
float frictionScale; // 1.5 front, 1.8 rear
int materialIndex;
int brakeMaterialIndex;
int skidMaterialIndex;
float springAdditionalLength; // 0 means the spring is at it's rest length
};
struct vehicle_suspensionparams_t
{
DECLARE_SIMPLE_DATADESC();
float springConstant;
float springDamping;
float stabilizerConstant;
float springDampingCompression;
float maxBodyForce;
};
// NOTE: both raytrace and wheel data here because jetski uses both.
struct vehicle_axleparams_t
{
DECLARE_SIMPLE_DATADESC();
Vector offset; // center of this axle in vehicle object space
Vector wheelOffset; // offset to wheel (assume other wheel is symmetric at -wheelOffset) from axle center
Vector raytraceCenterOffset; // offset to center of axle for the raytrace data.
Vector raytraceOffset; // offset to raytrace for non-wheel (some wheeled) vehicles
vehicle_wheelparams_t wheels;
vehicle_suspensionparams_t suspension;
float torqueFactor; // normalized to 1 across all axles
// e.g. 0,1 for rear wheel drive - 0.5,0.5 for 4 wheel drive
float brakeFactor; // normalized to 1 across all axles
};
struct vehicle_steeringparams_t
{
DECLARE_SIMPLE_DATADESC();
float degreesSlow; // angle in degrees of steering at slow speed
float degreesFast; // angle in degrees of steering at fast speed
float degreesBoost; // angle in degrees of steering at fast speed
float steeringRateSlow; // this is the speed the wheels are steered when the vehicle is slow
float steeringRateFast; // this is the speed the wheels are steered when the vehicle is "fast"
float steeringRestRateSlow; // this is the speed at which the wheels move toward their resting state (straight ahead) at slow speed
float steeringRestRateFast; // this is the speed at which the wheels move toward their resting state (straight ahead) at fast speed
float speedSlow; // this is the max speed of "slow"
float speedFast; // this is the min speed of "fast"
float turnThrottleReduceSlow; // this is the amount of throttle reduction to apply at the maximum steering angle
float turnThrottleReduceFast; // this is the amount of throttle reduction to apply at the maximum steering angle
float brakeSteeringRateFactor; // this scales the steering rate when the brake/handbrake is down
float throttleSteeringRestRateFactor; // this scales the steering rest rate when the throttle is down
float powerSlideAccel; // scale of speed to acceleration
float boostSteeringRestRateFactor; // this scales the steering rest rate when boosting
float boostSteeringRateFactor; // this scales the steering rest rate when boosting
float steeringExponent; // this makes the steering response non-linear. The steering function is linear, then raised to this power
bool isSkidAllowed; // true/false skid flag
bool dustCloud; // flag for creating a dustcloud behind vehicle
};
struct vehicle_engineparams_t
{
DECLARE_SIMPLE_DATADESC();
float horsepower;
float maxSpeed;
float maxRevSpeed;
float maxRPM; // redline RPM limit
float axleRatio; // ratio of engine rev to axle rev
float throttleTime; // time to reach full throttle in seconds
// transmission
int gearCount; // gear count - max 10
float gearRatio[VEHICLE_MAX_GEAR_COUNT]; // ratio for each gear
// automatic transmission (simple auto-shifter - switches at fixed RPM limits)
float shiftUpRPM; // max RPMs to switch to a higher gear
float shiftDownRPM; // min RPMs to switch to a lower gear
float boostForce;
float boostDuration;
float boostDelay;
float boostMaxSpeed;
float autobrakeSpeedGain;
float autobrakeSpeedFactor;
bool torqueBoost;
bool isAutoTransmission; // true for auto, false for manual
};
struct vehicleparams_t
{
DECLARE_SIMPLE_DATADESC();
int axleCount;
int wheelsPerAxle;
vehicle_bodyparams_t body;
vehicle_axleparams_t axles[VEHICLE_MAX_AXLE_COUNT];
vehicle_engineparams_t engine;
vehicle_steeringparams_t steering;
};
// Iterator for queries
class CPassengerSeatTransition;
typedef CUtlVector< CPassengerSeatTransition> PassengerSeatAnims_t;
// Seat query types
enum VehicleSeatQuery_e
{
VEHICLE_SEAT_ANY, // Any available seat for our role
VEHICLE_SEAT_NEAREST, // Seat closest to our starting point
};
// Seat anim types for return
enum PassengerSeatAnimType_t
{
PASSENGER_SEAT_ENTRY,
PASSENGER_SEAT_EXIT
};
#define VEHICLE_SEAT_INVALID -1 // An invalid seat
#endif // VEHICLES_H

View File

@@ -0,0 +1,46 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef VIRTUALMESH_H
#define VIRTUALMESH_H
#ifdef _WIN32
#pragma once
#endif
// NOTE: These are fixed length to make it easy to fill these out without memory allocation or storage
const int MAX_VIRTUAL_TRIANGLES = 1024;
struct virtualmeshlist_t
{
Vector *pVerts;
int indexCount;
int triangleCount;
int vertexCount;
int surfacePropsIndex;
byte *pHull;
unsigned short indices[MAX_VIRTUAL_TRIANGLES*3];
};
struct virtualmeshtrianglelist_t
{
int triangleCount;
unsigned short triangleIndices[MAX_VIRTUAL_TRIANGLES*3];
};
class IVirtualMeshEvent
{
public:
virtual void GetVirtualMesh( void *userData, virtualmeshlist_t *pList ) = 0;
virtual void GetWorldspaceBounds( void *userData, Vector *pMins, Vector *pMaxs ) = 0;
virtual void GetTrianglesInSphere( void *userData, const Vector &center, float radius, virtualmeshtrianglelist_t *pList ) = 0;
};
struct virtualmeshparams_t
{
IVirtualMeshEvent *pMeshEventHandler;
void *userData;
bool buildOuterHull;
};
#endif // VIRTUALMESH_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,414 @@
//========== Copyright <20> 2008, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef VSCRIPT_TEMPLATES_H
#define VSCRIPT_TEMPLATES_H
#include "tier0/basetypes.h"
#if defined( _WIN32 )
#pragma once
#endif
#define FUNC_APPEND_PARAMS_0
#define FUNC_APPEND_PARAMS_1 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 1 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) );
#define FUNC_APPEND_PARAMS_2 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 2 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) );
#define FUNC_APPEND_PARAMS_3 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 3 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) );
#define FUNC_APPEND_PARAMS_4 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 4 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) );
#define FUNC_APPEND_PARAMS_5 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 5 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) );
#define FUNC_APPEND_PARAMS_6 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 6 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) );
#define FUNC_APPEND_PARAMS_7 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 7 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_7 ) );
#define FUNC_APPEND_PARAMS_8 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 8 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_7 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_8 ) );
#define FUNC_APPEND_PARAMS_9 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 9 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_7 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_8 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_9 ) );
#define FUNC_APPEND_PARAMS_10 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 10 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_7 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_8 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_9 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_10 ) );
#define FUNC_APPEND_PARAMS_11 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 11 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_7 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_8 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_9 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_10 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_11 ) );
#define FUNC_APPEND_PARAMS_12 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 12 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_7 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_8 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_9 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_10 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_11 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_12 ) );
#define FUNC_APPEND_PARAMS_13 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 13 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_7 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_8 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_9 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_10 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_11 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_12 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_13 ) );
#define FUNC_APPEND_PARAMS_14 pDesc->m_Parameters.SetGrowSize( 1 ); pDesc->m_Parameters.EnsureCapacity( 14 ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_1 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_2 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_3 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_4 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_5 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_6 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_7 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_8 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_9 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_10 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_11 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_12 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_13 ) ); pDesc->m_Parameters.AddToTail( ScriptDeduceType( FUNC_ARG_TYPE_14 ) );
#define DEFINE_NONMEMBER_FUNC_TYPE_DEDUCER(N) \
template <typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
inline void ScriptDeduceFunctionSignature(ScriptFuncDescriptor_t *pDesc, FUNCTION_RETTYPE (*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) ) \
{ \
pDesc->m_ReturnType = ScriptDeduceType(FUNCTION_RETTYPE); \
FUNC_APPEND_PARAMS_##N \
}
FUNC_GENERATE_ALL( DEFINE_NONMEMBER_FUNC_TYPE_DEDUCER );
#define DEFINE_MEMBER_FUNC_TYPE_DEDUCER(N) \
template <typename OBJECT_TYPE_PTR, typename FUNCTION_CLASS, typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
inline void ScriptDeduceFunctionSignature(ScriptFuncDescriptor_t *pDesc, OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) ) \
{ \
pDesc->m_ReturnType = ScriptDeduceType(FUNCTION_RETTYPE); \
FUNC_APPEND_PARAMS_##N \
}
FUNC_GENERATE_ALL( DEFINE_MEMBER_FUNC_TYPE_DEDUCER );
//-------------------------------------
#define DEFINE_CONST_MEMBER_FUNC_TYPE_DEDUCER(N) \
template <typename OBJECT_TYPE_PTR, typename FUNCTION_CLASS, typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
inline void ScriptDeduceFunctionSignature(ScriptFuncDescriptor_t *pDesc, OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const ) \
{ \
pDesc->m_ReturnType = ScriptDeduceType(FUNCTION_RETTYPE); \
FUNC_APPEND_PARAMS_##N \
}
FUNC_GENERATE_ALL( DEFINE_CONST_MEMBER_FUNC_TYPE_DEDUCER );
#define ScriptInitMemberFuncDescriptor_( pDesc, class, func, scriptName ) if ( 0 ) {} else { (pDesc)->m_pszScriptName = scriptName; (pDesc)->m_pszFunction = #func; ScriptDeduceFunctionSignature( pDesc, (class *)(0), &class::func ); }
#define ScriptInitFuncDescriptorNamed( pDesc, func, scriptName ) if ( 0 ) {} else { (pDesc)->m_pszScriptName = scriptName; (pDesc)->m_pszFunction = #func; ScriptDeduceFunctionSignature( pDesc, &func ); }
#define ScriptInitFuncDescriptor( pDesc, func ) ScriptInitFuncDescriptorNamed( pDesc, func, #func )
#define ScriptInitMemberFuncDescriptorNamed( pDesc, class, func, scriptName ) ScriptInitMemberFuncDescriptor_( pDesc, class, func, scriptName )
#define ScriptInitMemberFuncDescriptor( pDesc, class, func ) ScriptInitMemberFuncDescriptorNamed( pDesc, class, func, #func )
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
template <typename FUNCPTR_TYPE>
inline void *ScriptConvertFuncPtrToVoid( FUNCPTR_TYPE pFunc )
{
if ( ( sizeof( FUNCPTR_TYPE ) == sizeof( void * ) ) )
{
union FuncPtrConvert
{
void *p;
FUNCPTR_TYPE pFunc;
};
FuncPtrConvert convert;
convert.pFunc = pFunc;
return convert.p;
}
#if defined( _MSC_VER )
else if ( ( sizeof( FUNCPTR_TYPE ) == sizeof( void * ) + sizeof( int ) ) )
{
struct MicrosoftUnknownMFP
{
void *p;
int m_delta;
};
union FuncPtrConvertMI
{
MicrosoftUnknownMFP mfp;
FUNCPTR_TYPE pFunc;
};
FuncPtrConvertMI convert;
convert.pFunc = pFunc;
if ( convert.mfp.m_delta == 0 )
{
return convert.mfp.p;
}
AssertMsg( 0, "Function pointer must be from primary vtable" );
}
else if ( ( sizeof( FUNCPTR_TYPE ) == sizeof( void * ) + ( sizeof( int ) * 3 ) ) )
{
struct MicrosoftUnknownMFP
{
void *p;
int m_delta;
int m_vtordisp;
int m_vtable_index;
};
union FuncPtrConvertMI
{
MicrosoftUnknownMFP mfp;
FUNCPTR_TYPE pFunc;
};
FuncPtrConvertMI convert;
convert.pFunc = pFunc;
if ( convert.mfp.m_delta == 0 )
{
return convert.mfp.p;
}
AssertMsg( 0, "Function pointer must be from primary vtable" );
}
#elif defined( GNUC )
else if ( ( sizeof( FUNCPTR_TYPE ) == sizeof( void * ) + sizeof( int ) ) )
{
AssertMsg( 0, "Note: This path has not been verified yet. See comments below in #else case." );
struct GnuMFP
{
union
{
void *funcadr; // If vtable_index_2 is even, then this is the function pointer.
int vtable_index_2; // If vtable_index_2 is odd, then this = vindex*2+1.
};
int delta;
};
GnuMFP *p = (GnuMFP*)&pFunc;
if ( p->vtable_index_2 & 1 )
{
char **delta = (char**)p->delta;
char *pCur = *delta + (p->vtable_index_2+1)/2;
return (void*)( pCur + 4 );
}
else
{
return p->funcadr;
}
}
#else
#error "Need to implement code to crack non-offset member function pointer case"
// For gcc, see: http://www.codeproject.com/KB/cpp/FastDelegate.aspx
//
// Current versions of the GNU compiler use a strange and tricky
// optimization. It observes that, for virtual inheritance, you have to look
// up the vtable in order to get the voffset required to calculate the this
// pointer. While you're doing that, you might as well store the function
// pointer in the vtable. By doing this, they combine the m_func_address and
// m_vtable_index fields into one, and they distinguish between them by
// ensuring that function pointers always point to even addresses but vtable
// indices are always odd:
//
// // GNU g++ uses a tricky space optimisation, also adopted by IBM's VisualAge and XLC.
// struct GnuMFP {
// union {
// CODEPTR funcadr; // always even
// int vtable_index_2; // = vindex*2+1, always odd
// };
// int delta;
// };
// adjustedthis = this + delta
// if (funcadr & 1) CALL (* ( *delta + (vindex+1)/2) + 4)
// else CALL funcadr
//
// The G++ method is well documented, so it has been adopted by many other
// vendors, including IBM's VisualAge and XLC compilers, recent versions of
// Open64, Pathscale EKO, and Metrowerks' 64-bit compilers. A simpler scheme
// used by earlier versions of GCC is also very common. SGI's now
// discontinued MIPSPro and Pro64 compilers, and Apple's ancient MrCpp
// compiler used this method. (Note that the Pro64 compiler has become the
// open source Open64 compiler).
#endif
else
AssertMsg( 0, "Member function pointer not supported. Why on earth are you using virtual inheritance!?" );
return NULL;
}
template <typename FUNCPTR_TYPE>
inline FUNCPTR_TYPE ScriptConvertFuncPtrFromVoid( void *p )
{
if ( ( sizeof( FUNCPTR_TYPE ) == sizeof( void * ) ) )
{
union FuncPtrConvert
{
void *p;
FUNCPTR_TYPE pFunc;
};
FuncPtrConvert convert;
convert.p = p;
return convert.pFunc;
}
#if defined( _MSC_VER )
if ( ( sizeof( FUNCPTR_TYPE ) == sizeof( void * ) + sizeof( int ) ) )
{
struct MicrosoftUnknownMFP
{
void *p;
int m_delta;
};
union FuncPtrConvertMI
{
MicrosoftUnknownMFP mfp;
FUNCPTR_TYPE pFunc;
};
FuncPtrConvertMI convert;
convert.mfp.p = p;
convert.mfp.m_delta = 0;
return convert.pFunc;
}
if ( ( sizeof( FUNCPTR_TYPE ) == sizeof( void * ) + ( sizeof( int ) * 3 ) ) )
{
struct MicrosoftUnknownMFP
{
void *p;
int m_delta;
int m_vtordisp;
int m_vtable_index;
};
union FuncPtrConvertMI
{
MicrosoftUnknownMFP mfp;
FUNCPTR_TYPE pFunc;
};
FuncPtrConvertMI convert;
convert.mfp.p = p;
convert.mfp.m_delta = 0;
return convert.pFunc;
}
#elif defined( POSIX )
AssertMsg( 0, "Note: This path has not been implemented yet." );
#else
#error "Need to implement code to crack non-offset member function pointer case"
#endif
Assert( 0 );
return NULL;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_0
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_1 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_1
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_2 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_2
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_3 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_3
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_4 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_4
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_5 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_5
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_6 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_6
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_7 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_7
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_8 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_8
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_9 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_9
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_10 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_10
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_11 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_11
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_12 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_12
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_13 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_13
#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_14 , FUNC_BASE_TEMPLATE_FUNC_PARAMS_14
#define SCRIPT_BINDING_ARGS_0
#define SCRIPT_BINDING_ARGS_1 pArguments[0]
#define SCRIPT_BINDING_ARGS_2 pArguments[0], pArguments[1]
#define SCRIPT_BINDING_ARGS_3 pArguments[0], pArguments[1], pArguments[2]
#define SCRIPT_BINDING_ARGS_4 pArguments[0], pArguments[1], pArguments[2], pArguments[3]
#define SCRIPT_BINDING_ARGS_5 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4]
#define SCRIPT_BINDING_ARGS_6 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5]
#define SCRIPT_BINDING_ARGS_7 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5], pArguments[6]
#define SCRIPT_BINDING_ARGS_8 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5], pArguments[6], pArguments[7]
#define SCRIPT_BINDING_ARGS_9 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5], pArguments[6], pArguments[7], pArguments[8]
#define SCRIPT_BINDING_ARGS_10 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5], pArguments[6], pArguments[7], pArguments[8], pArguments[9]
#define SCRIPT_BINDING_ARGS_11 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5], pArguments[6], pArguments[7], pArguments[8], pArguments[9], pArguments[10]
#define SCRIPT_BINDING_ARGS_12 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5], pArguments[6], pArguments[7], pArguments[8], pArguments[9], pArguments[10], pArguments[11]
#define SCRIPT_BINDING_ARGS_13 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5], pArguments[6], pArguments[7], pArguments[8], pArguments[9], pArguments[10], pArguments[11], pArguments[12]
#define SCRIPT_BINDING_ARGS_14 pArguments[0], pArguments[1], pArguments[2], pArguments[3], pArguments[4], pArguments[5], pArguments[6], pArguments[7], pArguments[8], pArguments[9], pArguments[10], pArguments[11], pArguments[12], pArguments[13]
#define DEFINE_SCRIPT_BINDINGS(N) \
template <typename FUNC_TYPE, typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
class CNonMemberScriptBinding##N \
{ \
public: \
static bool Call( void *pFunction, void *pContext, ScriptVariant_t *pArguments, int nArguments, ScriptVariant_t *pReturn ) \
{ \
Assert( nArguments == N ); \
Assert( pReturn ); \
Assert( !pContext ); \
\
if ( nArguments != N || !pReturn || pContext ) \
{ \
return false; \
} \
*pReturn = ((FUNC_TYPE)pFunction)( SCRIPT_BINDING_ARGS_##N ); \
if ( pReturn->m_type == FIELD_VECTOR ) \
pReturn->m_pVector = new Vector(*pReturn->m_pVector); \
return true; \
} \
}; \
\
template <typename FUNC_TYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
class CNonMemberScriptBinding##N<FUNC_TYPE, void FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_##N> \
{ \
public: \
static bool Call( void *pFunction, void *pContext, ScriptVariant_t *pArguments, int nArguments, ScriptVariant_t *pReturn ) \
{ \
Assert( nArguments == N ); \
Assert( !pReturn ); \
Assert( !pContext ); \
\
if ( nArguments != N || pReturn || pContext ) \
{ \
return false; \
} \
((FUNC_TYPE)pFunction)( SCRIPT_BINDING_ARGS_##N ); \
return true; \
} \
}; \
\
template <class OBJECT_TYPE_PTR, typename FUNC_TYPE, typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
class CMemberScriptBinding##N \
{ \
public: \
static bool Call( void *pFunction, void *pContext, ScriptVariant_t *pArguments, int nArguments, ScriptVariant_t *pReturn ) \
{ \
Assert( nArguments == N ); \
Assert( pReturn ); \
Assert( pContext ); \
\
if ( nArguments != N || !pReturn || !pContext ) \
{ \
return false; \
} \
*pReturn = (((OBJECT_TYPE_PTR)(pContext))->*ScriptConvertFuncPtrFromVoid<FUNC_TYPE>(pFunction))( SCRIPT_BINDING_ARGS_##N ); \
if ( pReturn->m_type == FIELD_VECTOR ) \
pReturn->m_pVector = new Vector(*pReturn->m_pVector); \
return true; \
} \
}; \
\
template <class OBJECT_TYPE_PTR, typename FUNC_TYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
class CMemberScriptBinding##N<OBJECT_TYPE_PTR, FUNC_TYPE, void FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_##N> \
{ \
public: \
static bool Call( void *pFunction, void *pContext, ScriptVariant_t *pArguments, int nArguments, ScriptVariant_t *pReturn ) \
{ \
Assert( nArguments == N ); \
Assert( !pReturn ); \
Assert( pContext ); \
\
if ( nArguments != N || pReturn || !pContext ) \
{ \
return false; \
} \
(((OBJECT_TYPE_PTR)(pContext))->*ScriptConvertFuncPtrFromVoid<FUNC_TYPE>(pFunction))( SCRIPT_BINDING_ARGS_##N ); \
return true; \
} \
}; \
\
template <typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
inline ScriptBindingFunc_t ScriptCreateBinding(FUNCTION_RETTYPE (*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) ) \
{ \
typedef FUNCTION_RETTYPE (*Func_t)(FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N); \
return &CNonMemberScriptBinding##N<Func_t, FUNCTION_RETTYPE FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_##N>::Call; \
} \
\
template <typename OBJECT_TYPE_PTR, typename FUNCTION_CLASS, typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
inline ScriptBindingFunc_t ScriptCreateBinding(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE (FUNCTION_CLASS::*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) ) \
{ \
typedef FUNCTION_RETTYPE (FUNCTION_CLASS::*Func_t)(FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N); \
return &CMemberScriptBinding##N<OBJECT_TYPE_PTR, Func_t, FUNCTION_RETTYPE FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_##N>::Call; \
} \
\
template <typename OBJECT_TYPE_PTR, typename FUNCTION_CLASS, typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N> \
inline ScriptBindingFunc_t ScriptCreateBinding(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE (FUNCTION_CLASS::*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const ) \
{ \
typedef FUNCTION_RETTYPE (FUNCTION_CLASS::*Func_t)(FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N); \
return &CMemberScriptBinding##N<OBJECT_TYPE_PTR, Func_t, FUNCTION_RETTYPE FUNC_BASE_TEMPLATE_FUNC_PARAMS_PASSTHRU_##N>::Call; \
}
FUNC_GENERATE_ALL( DEFINE_SCRIPT_BINDINGS );
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
#endif // VSCRIPT_TEMPLATES_H

View File

@@ -0,0 +1,48 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef VSTDLIB_IKEYVALUESSYSTEM_H
#define VSTDLIB_IKEYVALUESSYSTEM_H
#ifdef _WIN32
#pragma once
#endif
#include "vstdlib/vstdlib.h"
// handle to a KeyValues key name symbol
typedef int HKeySymbol;
#define INVALID_KEY_SYMBOL (-1)
//-----------------------------------------------------------------------------
// Purpose: Interface to shared data repository for KeyValues (included in vgui_controls.lib)
// allows for central data storage point of KeyValues symbol table
//-----------------------------------------------------------------------------
class IKeyValuesSystem
{
public:
// registers the size of the KeyValues in the specified instance
// so it can build a properly sized memory pool for the KeyValues objects
// the sizes will usually never differ but this is for versioning safety
virtual void RegisterSizeofKeyValues(int size) = 0;
// allocates/frees a KeyValues object from the shared mempool
virtual void *AllocKeyValuesMemory(int size) = 0;
virtual void FreeKeyValuesMemory(void *pMem) = 0;
// symbol table access (used for key names)
virtual HKeySymbol GetSymbolForString( const char *name, bool bCreate = true ) = 0;
virtual const char *GetStringForSymbol(HKeySymbol symbol) = 0;
// for debugging, adds KeyValues record into global list so we can track memory leaks
virtual void AddKeyValuesToMemoryLeakList(void *pMem, HKeySymbol name) = 0;
virtual void RemoveKeyValuesFromMemoryLeakList(void *pMem) = 0;
};
VSTDLIB_INTERFACE IKeyValuesSystem *KeyValuesSystem();
// #define KEYVALUESSYSTEM_INTERFACE_VERSION "KeyValuesSystem002"
#endif // VSTDLIB_IKEYVALUESSYSTEM_H

View File

@@ -0,0 +1,69 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: setjmp/longjmp based cooperative multitasking system
//
//=============================================================================
#ifndef COROUTINE_H
#define COROUTINE_H
#pragma once
#include "vstdlib/vstdlib.h"
// enable this to do coroutine tracing
// this will tell coroutine API users to set coroutine names
// #define COROUTINE_TRACE
//-----------------------------------------------------------------------------
// Purpose: handles running coroutines
// setjmp/longjmp based cooperative multitasking system
//-----------------------------------------------------------------------------
// coroutine callback
typedef void (__cdecl *CoroutineFunc_t )(void *);
// handle to a coroutine
typedef int32 HCoroutine;
// creates a new coroutine
// no coroutine code is executed until Coroutine_Continue() is called
VSTDLIB_INTERFACE HCoroutine Coroutine_Create( CoroutineFunc_t pFunc, void *pvParam );
// continues the specified coroutine
// returns true if the coroutine is still running, false otherwise
VSTDLIB_INTERFACE bool Coroutine_Continue( HCoroutine hCoroutine, const char *pchName = NULL );
// cancels a currently running coroutine
VSTDLIB_INTERFACE void Coroutine_Cancel( HCoroutine hCoroutine );
// 'load' a coroutine only to debug it - immediately breaks into debugger
// when continued, pops back to the prior coroutine
VSTDLIB_INTERFACE void Coroutine_DebugBreak( HCoroutine hCoroutine );
// Load a coroutine and generate an assert. Used to get a minidump of a job
VSTDLIB_INTERFACE void Coroutine_DebugAssert( HCoroutine hCoroutine, const char *pchMsg );
// called from the coroutine to return control to the main thread
VSTDLIB_INTERFACE void Coroutine_YieldToMain();
// returns true if the code is currently running inside of a coroutine
VSTDLIB_INTERFACE bool Coroutine_IsActive();
// returns a handle the currently active coroutine
VSTDLIB_INTERFACE HCoroutine Coroutine_GetCurrentlyActive();
// call when a thread is quiting to release any per-thread memory
VSTDLIB_INTERFACE void Coroutine_ReleaseThreadMemory();
// runs a self-test of the coroutine system
VSTDLIB_INTERFACE bool Coroutine_Test();
// memory validation
VSTDLIB_INTERFACE void Coroutine_ValidateGlobals( class CValidator &validator );
// for debugging purposes - returns stack depth of current coroutine
VSTDLIB_INTERFACE size_t Coroutine_GetStackDepth();
#endif // COROUTINE_H

View File

@@ -0,0 +1,25 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#if !defined( CVAR_H )
#define CVAR_H
#ifdef _WIN32
#pragma once
#endif
#include "vstdlib/vstdlib.h"
#include "icvar.h"
//-----------------------------------------------------------------------------
// Returns a CVar dictionary for tool usage
//-----------------------------------------------------------------------------
VSTDLIB_INTERFACE CreateInterfaceFn VStdLib_GetICVarFactory();
#endif // CVAR_H

View File

@@ -0,0 +1,64 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//===========================================================================//
#ifndef IPROCESSUTILS_H
#define IPROCESSUTILS_H
#ifdef _WIN32
#pragma once
#endif
#include "appframework/IAppSystem.h"
//-----------------------------------------------------------------------------
// Handle to a process
//-----------------------------------------------------------------------------
typedef int ProcessHandle_t;
enum
{
PROCESS_HANDLE_INVALID = 0,
};
//-----------------------------------------------------------------------------
// Interface version
//-----------------------------------------------------------------------------
#define PROCESS_UTILS_INTERFACE_VERSION "VProcessUtils001"
//-----------------------------------------------------------------------------
// Interface for makefiles to build differently depending on where they are run from
//-----------------------------------------------------------------------------
abstract_class IProcessUtils : public IAppSystem
{
public:
// Starts, stops a process
virtual ProcessHandle_t StartProcess( const char *pCommandLine, bool bConnectStdPipes ) = 0;
virtual ProcessHandle_t StartProcess( int argc, const char **argv, bool bConnectStdPipes ) = 0;
virtual void CloseProcess( ProcessHandle_t hProcess ) = 0;
virtual void AbortProcess( ProcessHandle_t hProcess ) = 0;
// Returns true if a process is complete
virtual bool IsProcessComplete( ProcessHandle_t hProcess ) = 0;
// Waits until a process is complete
virtual void WaitUntilProcessCompletes( ProcessHandle_t hProcess ) = 0;
// Methods used to write input into a process
virtual int SendProcessInput( ProcessHandle_t hProcess, char *pBuf, int nBufLen ) = 0;
// Methods used to read output back from a process
virtual int GetProcessOutputSize( ProcessHandle_t hProcess ) = 0;
virtual int GetProcessOutput( ProcessHandle_t hProcess, char *pBuf, int nBufLen ) = 0;
// Returns the exit code for the process. Doesn't work unless the process is complete
virtual int GetProcessExitCode( ProcessHandle_t hProcess ) = 0;
};
#endif // IPROCESSUTILS_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,60 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#ifndef OSVERSION_H
#define OSVERSION_H
#pragma once
#include "vstdlib/vstdlib.h"
// OS types we know about
// Must be in ascending capability order, we use this for min OS requirements
enum EOSType
{
k_eOSUnknown = -1,
k_eMacOSUnknown = -102,
k_eMacOS104 = -101,
k_eMacOS105 = -100,
k_eMacOS1058 = -99,
k_eMacOS106 = -95,
k_eMacOS1063 = -94,
k_eMacOS107 = -90,
// k_eMacOSMax = -1
k_eLinuxUnknown = -203,
k_eLinux22 = -202,
k_eLinux24 = -201,
k_eLinux26 = -200,
// k_eLinuxMax = -103
k_eWinUnknown = 0,
k_eWin311 = 1,
k_eWin95,
k_eWin98,
k_eWinME,
k_eWinNT,
k_eWin2000,
k_eWinXP,
k_eWin2003,
k_eWinVista,
k_eWindows7,
k_eWin2008,
k_eWinMAX,
k_eOSTypeMax = k_eWinMAX + 11 // win types + other ifdef'd types
};
VSTDLIB_INTERFACE const char *GetNameFromOSType( EOSType eOSType );
VSTDLIB_INTERFACE const char *GetOSDetailString( char *pchOutBuf, int cchOutBuf );
VSTDLIB_INTERFACE EOSType GetOSType();
VSTDLIB_INTERFACE bool OSTypesAreCompatible( EOSType eOSTypeDetected, EOSType eOSTypeRequired );
VSTDLIB_INTERFACE const char *GetPlatformName( bool *pbIs64Bit );
#endif // OSVERSION_H

View File

@@ -0,0 +1,51 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $Workfile: $
// $NoKeywords: $
//=============================================================================
#pragma warning(disable: 4514)
// First include standard libraries
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <malloc.h>
#include <memory.h>
#include <ctype.h>
// Next, include public
#include "tier0/basetypes.h"
#include "tier0/dbg.h"
#include "tier0/valobject.h"
// Next, include vstdlib
#include "vstdlib/vstdlib.h"
#include "tier1/strtools.h"
#include "vstdlib/random.h"
#include "tier1/KeyValues.h"
#include "tier1/utlmemory.h"
#include "tier1/utlrbtree.h"
#include "tier1/utlvector.h"
#include "tier1/utllinkedlist.h"
#include "tier1/utlmultilist.h"
#include "tier1/utlsymbol.h"
#include "tier0/icommandline.h"
#include "tier1/netadr.h"
#include "tier1/mempool.h"
#include "tier1/utlbuffer.h"
#include "tier1/utlstring.h"
#include "tier1/utlmap.h"
#include "tier0/memdbgon.h"

View File

@@ -0,0 +1,111 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Random number generator
//
// $Workfile: $
// $NoKeywords: $
//===========================================================================//
#ifndef VSTDLIB_RANDOM_H
#define VSTDLIB_RANDOM_H
#include "vstdlib/vstdlib.h"
#include "tier0/basetypes.h"
#include "tier0/threadtools.h"
#include "tier1/interface.h"
#define NTAB 32
#pragma warning(push)
#pragma warning( disable:4251 )
//-----------------------------------------------------------------------------
// A generator of uniformly distributed random numbers
//-----------------------------------------------------------------------------
class IUniformRandomStream
{
public:
// Sets the seed of the random number generator
virtual void SetSeed( int iSeed ) = 0;
// Generates random numbers
virtual float RandomFloat( float flMinVal = 0.0f, float flMaxVal = 1.0f ) = 0;
virtual int RandomInt( int iMinVal, int iMaxVal ) = 0;
virtual float RandomFloatExp( float flMinVal = 0.0f, float flMaxVal = 1.0f, float flExponent = 1.0f ) = 0;
};
//-----------------------------------------------------------------------------
// The standard generator of uniformly distributed random numbers
//-----------------------------------------------------------------------------
class VSTDLIB_CLASS CUniformRandomStream : public IUniformRandomStream
{
public:
CUniformRandomStream();
// Sets the seed of the random number generator
virtual void SetSeed( int iSeed );
// Generates random numbers
virtual float RandomFloat( float flMinVal = 0.0f, float flMaxVal = 1.0f );
virtual int RandomInt( int iMinVal, int iMaxVal );
virtual float RandomFloatExp( float flMinVal = 0.0f, float flMaxVal = 1.0f, float flExponent = 1.0f );
private:
int GenerateRandomNumber();
int m_idum;
int m_iy;
int m_iv[NTAB];
CThreadFastMutex m_mutex;
};
//-----------------------------------------------------------------------------
// A generator of gaussian distributed random numbers
//-----------------------------------------------------------------------------
class VSTDLIB_CLASS CGaussianRandomStream
{
public:
// Passing in NULL will cause the gaussian stream to use the
// installed global random number generator
CGaussianRandomStream( IUniformRandomStream *pUniformStream = NULL );
// Attaches to a random uniform stream
void AttachToStream( IUniformRandomStream *pUniformStream = NULL );
// Generates random numbers
float RandomFloat( float flMean = 0.0f, float flStdDev = 1.0f );
private:
IUniformRandomStream *m_pUniformStream;
bool m_bHaveValue;
float m_flRandomValue;
CThreadFastMutex m_mutex;
};
//-----------------------------------------------------------------------------
// A couple of convenience functions to access the library's global uniform stream
//-----------------------------------------------------------------------------
VSTDLIB_INTERFACE void RandomSeed( int iSeed );
VSTDLIB_INTERFACE float RandomFloat( float flMinVal = 0.0f, float flMaxVal = 1.0f );
VSTDLIB_INTERFACE float RandomFloatExp( float flMinVal = 0.0f, float flMaxVal = 1.0f, float flExponent = 1.0f );
VSTDLIB_INTERFACE int RandomInt( int iMinVal, int iMaxVal );
VSTDLIB_INTERFACE float RandomGaussianFloat( float flMean = 0.0f, float flStdDev = 1.0f );
//-----------------------------------------------------------------------------
// Installs a global random number generator, which will affect the Random functions above
//-----------------------------------------------------------------------------
VSTDLIB_INTERFACE void InstallUniformRandomStream( IUniformRandomStream *pStream );
#pragma warning(pop)
#endif // VSTDLIB_RANDOM_H

View File

@@ -0,0 +1,125 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: A simple tool for coverage tests
//
//=============================================================================
#ifndef VCOVER_H
#define VCOVER_H
#include "tier1/utlrbtree.h"
#include "vstdlib.h"
#if defined( _WIN32 )
#pragma once
#endif
class CVCoverage
{
public:
CVCoverage() :
m_bActive( false ),
m_depth( 0 ),
m_token( 1 )
{
}
bool IsActive() const
{
return m_bActive;
}
void SetActive( bool bActive )
{
Assert( bActive != m_bActive );
m_bActive = bActive;
if ( bActive )
++m_token;
}
void Begin()
{
++m_depth;
}
void End()
{
--m_depth;
}
void Reset()
{
m_locations.RemoveAll();
}
bool ShouldCover( unsigned token ) const
{
return ( m_bActive && m_depth > 0 && token != m_token );
}
unsigned Cover( const char *pszFile, int line )
{
Location_t location = { pszFile, line };
m_locations.Insert( location );
return m_token;
}
void Report()
{
for ( int i = m_locations.FirstInorder(); i != m_locations.InvalidIndex(); i = m_locations.NextInorder( i ) )
{
Msg( "%s(%d) :\n", m_locations[i].pszFile, m_locations[i].line );
}
}
private:
struct Location_t
{
const char *pszFile;
int line;
};
class CLocationLess
{
public:
CLocationLess( int ignored ) {}
bool operator!() { return false; }
bool operator()( const Location_t &lhs, const Location_t &rhs ) const
{
if ( lhs.line < rhs.line )
{
return true;
}
return CaselessStringLessThan( lhs.pszFile, rhs.pszFile );
}
};
bool m_bActive;
int m_depth;
unsigned m_token;
CUtlRBTree< Location_t, unsigned short, CLocationLess > m_locations;
};
VSTDLIB_INTERFACE CVCoverage g_VCoverage;
#ifdef VCOVER_ENABLED
#define VCOVER() \
do \
{ \
static token; \
if ( g_VCoverage.ShouldCover( token ) ) \
{ \
token = g_VCoverage.Cover( __FILE__, __LINE__ ); \
} \
} while( 0 )
#else
#define VCOVER() ((void)0)
#endif
#endif // VCOVER_H

View File

@@ -0,0 +1,33 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef VSTDLIB_H
#define VSTDLIB_H
#ifdef _WIN32
#pragma once
#endif
#include "tier0/platform.h"
//-----------------------------------------------------------------------------
// dll export stuff
//-----------------------------------------------------------------------------
#ifdef VSTDLIB_DLL_EXPORT
#define VSTDLIB_INTERFACE DLL_EXPORT
#define VSTDLIB_OVERLOAD DLL_GLOBAL_EXPORT
#define VSTDLIB_CLASS DLL_CLASS_EXPORT
#define VSTDLIB_GLOBAL DLL_GLOBAL_EXPORT
#else
#define VSTDLIB_INTERFACE DLL_IMPORT
#define VSTDLIB_OVERLOAD DLL_GLOBAL_IMPORT
#define VSTDLIB_CLASS DLL_CLASS_IMPORT
#define VSTDLIB_GLOBAL DLL_GLOBAL_IMPORT
#endif
#endif // VSTDLIB_H

608
sp/src/public/vtf/vtf.h Normal file
View File

@@ -0,0 +1,608 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef VTF_H
#define VTF_H
#ifdef _WIN32
#pragma once
#endif
#include "bitmap/imageformat.h"
#include "tier0/platform.h"
// #define VTF_FILE_FORMAT_ONLY to just include the vtf header and none of the code declaration
#ifndef VTF_FILE_FORMAT_ONLY
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class CUtlBuffer;
class Vector;
struct Rect_t;
class IFileSystem;
//-----------------------------------------------------------------------------
// Texture flags
//-----------------------------------------------------------------------------
enum CompiledVtfFlags
{
// flags from the *.txt config file
TEXTUREFLAGS_POINTSAMPLE = 0x00000001,
TEXTUREFLAGS_TRILINEAR = 0x00000002,
TEXTUREFLAGS_CLAMPS = 0x00000004,
TEXTUREFLAGS_CLAMPT = 0x00000008,
TEXTUREFLAGS_ANISOTROPIC = 0x00000010,
TEXTUREFLAGS_HINT_DXT5 = 0x00000020,
TEXTUREFLAGS_SRGB = 0x00000040,
TEXTUREFLAGS_NORMAL = 0x00000080,
TEXTUREFLAGS_NOMIP = 0x00000100,
TEXTUREFLAGS_NOLOD = 0x00000200,
TEXTUREFLAGS_ALL_MIPS = 0x00000400,
TEXTUREFLAGS_PROCEDURAL = 0x00000800,
// These are automatically generated by vtex from the texture data.
TEXTUREFLAGS_ONEBITALPHA = 0x00001000,
TEXTUREFLAGS_EIGHTBITALPHA = 0x00002000,
// newer flags from the *.txt config file
TEXTUREFLAGS_ENVMAP = 0x00004000,
TEXTUREFLAGS_RENDERTARGET = 0x00008000,
TEXTUREFLAGS_DEPTHRENDERTARGET = 0x00010000,
TEXTUREFLAGS_NODEBUGOVERRIDE = 0x00020000,
TEXTUREFLAGS_SINGLECOPY = 0x00040000,
TEXTUREFLAGS_UNUSED_00080000 = 0x00080000,
TEXTUREFLAGS_UNUSED_00100000 = 0x00100000,
TEXTUREFLAGS_UNUSED_00200000 = 0x00200000,
TEXTUREFLAGS_UNUSED_00400000 = 0x00400000,
TEXTUREFLAGS_NODEPTHBUFFER = 0x00800000,
TEXTUREFLAGS_UNUSED_01000000 = 0x01000000,
TEXTUREFLAGS_CLAMPU = 0x02000000,
TEXTUREFLAGS_VERTEXTEXTURE = 0x04000000, // Useable as a vertex texture
TEXTUREFLAGS_SSBUMP = 0x08000000,
TEXTUREFLAGS_UNUSED_10000000 = 0x10000000,
// Clamp to border color on all texture coordinates
TEXTUREFLAGS_BORDER = 0x20000000,
TEXTUREFLAGS_UNUSED_40000000 = 0x40000000,
TEXTUREFLAGS_UNUSED_80000000 = 0x80000000,
};
enum VersionedVtfFlags
{
VERSIONED_VTF_FLAGS_MASK_7_3 = ~0xD1780400, // For a ver 7.3 or earlier only these flags are valid
};
struct VtfProcessingOptions
{
uint32 cbSize; // Set to sizeof( VtfProcessingOptions )
//
// Flags0
//
enum Flags0
{
// Have a channel decaying to a given decay goal for the given last number of mips
OPT_DECAY_R = 0x00000001, // Red decays
OPT_DECAY_G = 0x00000002, // Green decays
OPT_DECAY_B = 0x00000004, // Blue decays
OPT_DECAY_A = 0x00000008, // Alpha decays
OPT_DECAY_EXP_R = 0x00000010, // Channel R decays exponentially (otherwise linearly)
OPT_DECAY_EXP_G = 0x00000020, // Channel G decays exponentially (otherwise linearly)
OPT_DECAY_EXP_B = 0x00000040, // Channel B decays exponentially (otherwise linearly)
OPT_DECAY_EXP_A = 0x00000080, // Channel A decays exponentially (otherwise linearly)
OPT_NOCOMPRESS = 0x00000100, // Use uncompressed image format
OPT_NORMAL_DUDV = 0x00000200, // dU dV normal map
OPT_FILTER_NICE = 0x00000400, // Use nice filtering
OPT_SET_ALPHA_ONEOVERMIP = 0x00001000, // Alpha = 1/miplevel
OPT_PREMULT_COLOR_ONEOVERMIP = 0x00002000, // Color *= 1/miplevel
OPT_MIP_ALPHATEST = 0x00004000, // Alpha-tested mip generation
};
uint32 flags0; // A combination of "Flags0"
//
// Decay settings
//
uint8 clrDecayGoal[4]; // Goal colors for R G B A
uint8 numNotDecayMips[4]; // Number of first mips unaffected by decay (0 means all below mip0)
float fDecayExponentBase[4]; // For exponential decay the base number (e.g. 0.75)
};
//-----------------------------------------------------------------------------
// Cubemap face indices
//-----------------------------------------------------------------------------
enum CubeMapFaceIndex_t
{
CUBEMAP_FACE_RIGHT = 0,
CUBEMAP_FACE_LEFT,
CUBEMAP_FACE_BACK, // NOTE: This face is in the +y direction?!?!?
CUBEMAP_FACE_FRONT, // NOTE: This face is in the -y direction!?!?
CUBEMAP_FACE_UP,
CUBEMAP_FACE_DOWN,
// This is the fallback for low-end
CUBEMAP_FACE_SPHEREMAP,
// NOTE: Cubemaps have *7* faces; the 7th is the fallback spheremap
CUBEMAP_FACE_COUNT
};
//-----------------------------------------------------------------------------
// Enumeration used for spheremap generation
//-----------------------------------------------------------------------------
enum LookDir_t
{
LOOK_DOWN_X = 0,
LOOK_DOWN_NEGX,
LOOK_DOWN_Y,
LOOK_DOWN_NEGY,
LOOK_DOWN_Z,
LOOK_DOWN_NEGZ,
};
//-----------------------------------------------------------------------------
// Use this image format if you want to perform tool operations on the texture
//-----------------------------------------------------------------------------
#define IMAGE_FORMAT_DEFAULT ((ImageFormat)-2)
//-----------------------------------------------------------------------------
// Interface to get at various bits of a VTF texture
//-----------------------------------------------------------------------------
class IVTFTexture
{
public:
virtual ~IVTFTexture() {}
// Initializes the texture and allocates space for the bits
// In most cases, you shouldn't force the mip count.
virtual bool Init( int nWidth, int nHeight, int nDepth, ImageFormat fmt, int nFlags, int iFrameCount, int nForceMipCount = -1 ) = 0;
// Methods to set other texture fields
virtual void SetBumpScale( float flScale ) = 0;
virtual void SetReflectivity( const Vector &vecReflectivity ) = 0;
// Methods to initialize the low-res image
virtual void InitLowResImage( int nWidth, int nHeight, ImageFormat fmt ) = 0;
// set the resource data (for writers). pass size=0 to delete data. if pdata is not null,
// the resource data will be copied from *pData
virtual void *SetResourceData( uint32 eType, void const *pData, size_t nDataSize ) = 0;
// find the resource data and return a pointer to it. The data pointed to by this pointer will
// go away when the ivtftexture does. retruns null if resource not present
virtual void *GetResourceData( uint32 eType, size_t *pDataSize ) const = 0;
// Locates the resource entry info if it's present, easier than crawling array types
virtual bool HasResourceEntry( uint32 eType ) const = 0;
// Retrieve available resource types of this IVTFTextures
// arrTypesBuffer buffer to be filled with resource types available.
// numTypesBufferElems how many resource types the buffer can accomodate.
// Returns:
// number of resource types available (can be greater than "numTypesBufferElems"
// in which case only first "numTypesBufferElems" are copied to "arrTypesBuffer")
virtual unsigned int GetResourceTypes( uint32 *arrTypesBuffer, int numTypesBufferElems ) const = 0;
// When unserializing, we can skip a certain number of mip levels,
// and we also can just load everything but the image data
// NOTE: If you load only the buffer header, you'll need to use the
// VTFBufferHeaderSize() method below to only read that much from the file
// NOTE: If you skip mip levels, the height + width of the texture will
// change to reflect the size of the largest read in mip level
virtual bool Unserialize( CUtlBuffer &buf, bool bHeaderOnly = false, int nSkipMipLevels = 0 ) = 0;
virtual bool Serialize( CUtlBuffer &buf ) = 0;
// These are methods to help with optimization:
// Once the header is read in, they indicate where to start reading
// other data (measured from file start), and how many bytes to read....
virtual void LowResFileInfo( int *pStartLocation, int *pSizeInBytes) const = 0;
virtual void ImageFileInfo( int nFrame, int nFace, int nMip, int *pStartLocation, int *pSizeInBytes) const = 0;
virtual int FileSize( int nMipSkipCount = 0 ) const = 0;
// Attributes...
virtual int Width() const = 0;
virtual int Height() const = 0;
virtual int Depth() const = 0;
virtual int MipCount() const = 0;
// returns the size of one row of a particular mip level
virtual int RowSizeInBytes( int nMipLevel ) const = 0;
// returns the size of one face of a particular mip level
virtual int FaceSizeInBytes( int nMipLevel ) const = 0;
virtual ImageFormat Format() const = 0;
virtual int FaceCount() const = 0;
virtual int FrameCount() const = 0;
virtual int Flags() const = 0;
virtual float BumpScale() const = 0;
virtual int LowResWidth() const = 0;
virtual int LowResHeight() const = 0;
virtual ImageFormat LowResFormat() const = 0;
// NOTE: reflectivity[0] = blue, [1] = greem, [2] = red
virtual const Vector &Reflectivity() const = 0;
virtual bool IsCubeMap() const = 0;
virtual bool IsNormalMap() const = 0;
virtual bool IsVolumeTexture() const = 0;
// Computes the dimensions of a particular mip level
virtual void ComputeMipLevelDimensions( int iMipLevel, int *pMipWidth, int *pMipHeight, int *pMipDepth ) const = 0;
// Computes the size (in bytes) of a single mipmap of a single face of a single frame
virtual int ComputeMipSize( int iMipLevel ) const = 0;
// Computes the size of a subrect (specified at the top mip level) at a particular lower mip level
virtual void ComputeMipLevelSubRect( Rect_t* pSrcRect, int nMipLevel, Rect_t *pSubRect ) const = 0;
// Computes the size (in bytes) of a single face of a single frame
// All mip levels starting at the specified mip level are included
virtual int ComputeFaceSize( int iStartingMipLevel = 0 ) const = 0;
// Computes the total size (in bytes) of all faces, all frames
virtual int ComputeTotalSize() const = 0;
// Returns the base address of the image data
virtual unsigned char *ImageData() = 0;
// Returns a pointer to the data associated with a particular frame, face, and mip level
virtual unsigned char *ImageData( int iFrame, int iFace, int iMipLevel ) = 0;
// Returns a pointer to the data associated with a particular frame, face, mip level, and offset
virtual unsigned char *ImageData( int iFrame, int iFace, int iMipLevel, int x, int y, int z = 0 ) = 0;
// Returns the base address of the low-res image data
virtual unsigned char *LowResImageData() = 0;
// Converts the textures image format. Use IMAGE_FORMAT_DEFAULT
// if you want to be able to use various tool functions below
virtual void ConvertImageFormat( ImageFormat fmt, bool bNormalToDUDV ) = 0;
// NOTE: The following methods only work on textures using the
// IMAGE_FORMAT_DEFAULT!
// Generate spheremap based on the current cube faces (only works for cubemaps)
// The look dir indicates the direction of the center of the sphere
// NOTE: Only call this *after* cube faces have been correctly
// oriented (using FixCubemapFaceOrientation)
virtual void GenerateSpheremap( LookDir_t lookDir = LOOK_DOWN_Z ) = 0;
// Generate spheremap based on the current cube faces (only works for cubemaps)
// The look dir indicates the direction of the center of the sphere
// NOTE: Only call this *after* cube faces have been correctly
// oriented (using FixCubemapFaceOrientation)
virtual void GenerateHemisphereMap( unsigned char *pSphereMapBitsRGBA, int targetWidth,
int targetHeight, LookDir_t lookDir, int iFrame ) = 0;
// Fixes the cubemap faces orientation from our standard to the
// standard the material system needs.
virtual void FixCubemapFaceOrientation( ) = 0;
// Generates mipmaps from the base mip levels
virtual void GenerateMipmaps() = 0;
// Put 1/miplevel (1..n) into alpha.
virtual void PutOneOverMipLevelInAlpha() = 0;
// Computes the reflectivity
virtual void ComputeReflectivity( ) = 0;
// Computes the alpha flags
virtual void ComputeAlphaFlags() = 0;
// Generate the low-res image bits
virtual bool ConstructLowResImage() = 0;
// Gets the texture all internally consistent assuming you've loaded
// mip 0 of all faces of all frames
virtual void PostProcess(bool bGenerateSpheremap, LookDir_t lookDir = LOOK_DOWN_Z, bool bAllowFixCubemapOrientation = true) = 0;
// Blends adjacent pixels on cubemap borders, since the card doesn't do it. If the texture
// is S3TC compressed, then it has to do it AFTER the texture has been compressed to prevent
// artifacts along the edges.
//
// If bSkybox is true, it assumes the faces are oriented in the way the engine draws the skybox
// (which happens to be different from the way cubemaps have their faces).
virtual void MatchCubeMapBorders( int iStage, ImageFormat finalFormat, bool bSkybox ) = 0;
// Sets threshhold values for alphatest mipmapping
virtual void SetAlphaTestThreshholds( float flBase, float flHighFreq ) = 0;
#if defined( _X360 )
virtual int UpdateOrCreate( const char *pFilename, const char *pPathID = NULL, bool bForce = false ) = 0;
virtual bool UnserializeFromBuffer( CUtlBuffer &buf, bool bBufferIsVolatile, bool bHeaderOnly, bool bPreloadOnly, int nMipSkipCount ) = 0;
virtual int FileSize( bool bPreloadOnly, int nMipSkipCount ) const = 0;
virtual int MappingWidth() const = 0;
virtual int MappingHeight() const = 0;
virtual int MappingDepth() const = 0;
virtual int MipSkipCount() const = 0;
virtual bool IsPreTiled() const = 0;
virtual unsigned char *LowResImageSample() = 0;
virtual void ReleaseImageMemory() = 0;
#endif
// Sets post-processing flags (settings are copied, pointer passed to distinguish between structure versions)
virtual void SetPostProcessingSettings( VtfProcessingOptions const *pOptions ) = 0;
};
//-----------------------------------------------------------------------------
// Class factory
//-----------------------------------------------------------------------------
IVTFTexture *CreateVTFTexture();
void DestroyVTFTexture( IVTFTexture *pTexture );
//-----------------------------------------------------------------------------
// Allows us to only load in the first little bit of the VTF file to get info
// Clients should read this much into a UtlBuffer and then pass it in to
// Unserialize
//-----------------------------------------------------------------------------
int VTFFileHeaderSize( int nMajorVersion = -1, int nMinorVersion = -1 );
//-----------------------------------------------------------------------------
// 360 Conversion
//-----------------------------------------------------------------------------
typedef bool (*CompressFunc_t)( CUtlBuffer &inputBuffer, CUtlBuffer &outputBuffer );
bool ConvertVTFTo360Format( const char *pDebugName, CUtlBuffer &sourceBuf, CUtlBuffer &targetBuf, CompressFunc_t pCompressFunc );
//-----------------------------------------------------------------------------
// 360 Preload
//-----------------------------------------------------------------------------
bool GetVTFPreload360Data( const char *pDebugName, CUtlBuffer &fileBufferIn, CUtlBuffer &preloadBufferOut );
#include "mathlib/vector.h"
#endif // VTF_FILE_FORMAT_ONLY
//-----------------------------------------------------------------------------
// Disk format for VTF files ver. 7.2 and earlier
//
// NOTE: After the header is the low-res image data
// Then follows image data, which is sorted in the following manner
//
// for each mip level (starting with 1x1, and getting larger)
// for each animation frame
// for each face
// store the image data for the face
//
// NOTE: In memory, we store the data in the following manner:
// for each animation frame
// for each face
// for each mip level (starting with the largest, and getting smaller)
// store the image data for the face
//
// This is done because the various image manipulation function we have
// expect this format
//-----------------------------------------------------------------------------
// Disk format for VTF files ver. 7.3
//
// NOTE: After the header is the array of ResourceEntryInfo structures,
// number of elements in the array is defined by "numResources".
// there are entries for:
// eRsrcLowResImage = low-res image data
// eRsrcSheet = sheet data
// eRsrcImage = image data
// {
// for each mip level (starting with 1x1, and getting larger)
// for each animation frame
// for each face
// store the image data for the face
//
// NOTE: In memory, we store the data in the following manner:
// for each animation frame
// for each face
// for each mip level (starting with the largest, and getting smaller)
// store the image data for the face
// }
//
//-----------------------------------------------------------------------------
#include "datamap.h"
#pragma pack(1)
// version number for the disk texture cache
#define VTF_MAJOR_VERSION 7
#define VTF_MINOR_VERSION 4
//-----------------------------------------------------------------------------
// !!!!CRITICAL!!!! BEFORE YOU CHANGE THE FORMAT
//
// The structure sizes ARE NOT what they appear, regardless of Pack(1).
// The "VectorAligned" causes invisible padding in the FINAL derived structure.
//
// Each VTF format has been silently plagued by this.
//
// LOOK AT A 7.3 FILE. The 7.3 structure ends at 0x48 as you would expect by
// counting structure bytes. But, the "Infos" start at 0x50! because the PC
// compiler pads, the 360 compiler does NOT.
//-----------------------------------------------------------------------------
struct VTFFileBaseHeader_t
{
DECLARE_BYTESWAP_DATADESC();
char fileTypeString[4]; // "VTF" Valve texture file
int version[2]; // version[0].version[1]
int headerSize;
};
struct VTFFileHeaderV7_1_t : public VTFFileBaseHeader_t
{
DECLARE_BYTESWAP_DATADESC();
unsigned short width;
unsigned short height;
unsigned int flags;
unsigned short numFrames;
unsigned short startFrame;
#if !defined( POSIX ) && !defined( _X360 )
VectorAligned reflectivity;
#else
// must manually align in order to maintain pack(1) expected layout with existing binaries
char pad1[4];
Vector reflectivity;
char pad2[4];
#endif
float bumpScale;
ImageFormat imageFormat;
unsigned char numMipLevels;
ImageFormat lowResImageFormat;
unsigned char lowResImageWidth;
unsigned char lowResImageHeight;
};
struct VTFFileHeaderV7_2_t : public VTFFileHeaderV7_1_t
{
DECLARE_BYTESWAP_DATADESC();
unsigned short depth;
};
#define BYTE_POS( byteVal, shft ) uint32( uint32(uint8(byteVal)) << uint8(shft * 8) )
#if !defined( _X360 )
#define MK_VTF_RSRC_ID(a, b, c) uint32( BYTE_POS(a, 0) | BYTE_POS(b, 1) | BYTE_POS(c, 2) )
#define MK_VTF_RSRCF(d) BYTE_POS(d, 3)
#else
#define MK_VTF_RSRC_ID(a, b, c) uint32( BYTE_POS(a, 3) | BYTE_POS(b, 2) | BYTE_POS(c, 1) )
#define MK_VTF_RSRCF(d) BYTE_POS(d, 0)
#endif
// Special section for stock resources types
enum ResourceEntryType
{
// Legacy stock resources, readin/writing are handled differently (i.e. they do not have the length tag word!)
VTF_LEGACY_RSRC_LOW_RES_IMAGE = MK_VTF_RSRC_ID( 0x01, 0, 0 ), // Low-res image data
VTF_LEGACY_RSRC_IMAGE = MK_VTF_RSRC_ID( 0x30, 0, 0 ), // Image data
// New extended resource
VTF_RSRC_SHEET = MK_VTF_RSRC_ID( 0x10, 0, 0 ), // Sheet data
};
// Bytes with special meaning when set in a resource type
enum ResourceEntryTypeFlag
{
RSRCF_HAS_NO_DATA_CHUNK = MK_VTF_RSRCF( 0x02 ), // Resource doesn't have a corresponding data chunk
RSRCF_MASK = MK_VTF_RSRCF( 0xFF ) // Mask for all the flags
};
// Header details constants
enum HeaderDetails
{
MAX_RSRC_DICTIONARY_ENTRIES = 32, // Max number of resources in dictionary
MAX_X360_RSRC_DICTIONARY_ENTRIES = 4, // 360 needs this to be slim, otherwise preload size suffers
};
struct ResourceEntryInfo
{
union
{
unsigned int eType; // Use MK_VTF_??? macros to be endian compliant with the type
unsigned char chTypeBytes[4];
};
unsigned int resData; // Resource data or offset from the beginning of the file
};
struct VTFFileHeaderV7_3_t : public VTFFileHeaderV7_2_t
{
DECLARE_BYTESWAP_DATADESC();
char pad4[3];
unsigned int numResources;
#if defined( _X360 ) || defined( POSIX )
// must manually align in order to maintain pack(1) expected layout with existing binaries
char pad5[8];
#endif
// AFTER THE IMPLICIT PADDING CAUSED BY THE COMPILER....
// *** followed by *** ResourceEntryInfo resources[0];
// Array of resource entry infos sorted ascending by type
};
struct VTFFileHeader_t : public VTFFileHeaderV7_3_t
{
DECLARE_BYTESWAP_DATADESC();
};
#define VTF_X360_MAJOR_VERSION 0x0360
#define VTF_X360_MINOR_VERSION 8
struct VTFFileHeaderX360_t : public VTFFileBaseHeader_t
{
DECLARE_BYTESWAP_DATADESC();
unsigned int flags;
unsigned short width; // actual width of data in file
unsigned short height; // actual height of data in file
unsigned short depth; // actual depth of data in file
unsigned short numFrames;
unsigned short preloadDataSize; // exact size of preload data (may extend into image!)
unsigned char mipSkipCount; // used to resconstruct mapping dimensions
unsigned char numResources;
Vector reflectivity; // Resides on 16 byte boundary!
float bumpScale;
ImageFormat imageFormat;
unsigned char lowResImageSample[4];
unsigned int compressedSize;
// *** followed by *** ResourceEntryInfo resources[0];
};
///////////////////////////
// Resource Extensions //
///////////////////////////
// extended texture lod control:
#define VTF_RSRC_TEXTURE_LOD_SETTINGS ( MK_VTF_RSRC_ID( 'L','O','D' ) )
struct TextureLODControlSettings_t
{
// What to clamp the dimenstions to, mip-map wise, when at picmip 0. keeps texture from
// exceeding (1<<m_ResolutionClamp) at picmip 0. at picmip 1, it won't exceed
// (1<<(m_ResolutionClamp-1)), etc.
uint8 m_ResolutionClampX;
uint8 m_ResolutionClampY;
uint8 m_ResolutionClampX_360;
uint8 m_ResolutionClampY_360;
};
// Extended flags and settings:
#define VTF_RSRC_TEXTURE_SETTINGS_EX ( MK_VTF_RSRC_ID( 'T','S','0' ) )
struct TextureSettingsEx_t
{
enum Flags0 // flags0 byte mask
{
UNUSED = 0x01,
};
uint8 m_flags0; // a bitwise combination of Flags0
uint8 m_flags1; // set to zero. for future expansion.
uint8 m_flags2; // set to zero. for future expansion.
uint8 m_flags3; // set to zero. for future expansion.
};
#define VTF_RSRC_TEXTURE_CRC ( MK_VTF_RSRC_ID( 'C','R','C' ) )
#pragma pack()
#endif // VTF_H

424
sp/src/public/zip/XUnzip.h Normal file
View File

@@ -0,0 +1,424 @@
// XUnzip.h Version 1.1
//
// Authors: Mark Adler et al. (see below)
//
// Modified by: Lucian Wischik
// lu@wischik.com
//
// Version 1.0 - Turned C files into just a single CPP file
// - Made them compile cleanly as C++ files
// - Gave them simpler APIs
// - Added the ability to zip/unzip directly in memory without
// any intermediate files
//
// Modified by: Hans Dietrich
// hdietrich2@hotmail.com
//
// Version 1.1: - Added Unicode support to CreateZip() and ZipAdd()
// - Changed file names to avoid conflicts with Lucian's files
//
///////////////////////////////////////////////////////////////////////////////
//
// Lucian Wischik's comments:
// --------------------------
// THIS FILE is almost entirely based upon code by info-zip.
// It has been modified by Lucian Wischik.
// The original code may be found at http://www.info-zip.org
// The original copyright text follows.
//
///////////////////////////////////////////////////////////////////////////////
//
// Original authors' comments:
// ---------------------------
// This is version 2002-Feb-16 of the Info-ZIP copyright and license. The
// definitive version of this document should be available at
// ftp://ftp.info-zip.org/pub/infozip/license.html indefinitely.
//
// Copyright (c) 1990-2002 Info-ZIP. All rights reserved.
//
// For the purposes of this copyright and license, "Info-ZIP" is defined as
// the following set of individuals:
//
// Mark Adler, John Bush, Karl Davis, Harald Denker, Jean-Michel Dubois,
// Jean-loup Gailly, Hunter Goatley, Ian Gorman, Chris Herborth, Dirk Haase,
// Greg Hartwig, Robert Heath, Jonathan Hudson, Paul Kienitz,
// David Kirschbaum, Johnny Lee, Onno van der Linden, Igor Mandrichenko,
// Steve P. Miller, Sergio Monesi, Keith Owens, George Petrov, Greg Roelofs,
// Kai Uwe Rommel, Steve Salisbury, Dave Smith, Christian Spieler,
// Antoine Verheijen, Paul von Behren, Rich Wales, Mike White
//
// This software is provided "as is", without warranty of any kind, express
// or implied. In no event shall Info-ZIP or its contributors be held liable
// for any direct, indirect, incidental, special or consequential damages
// arising out of the use of or inability to use this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. Redistributions of source code must retain the above copyright notice,
// definition, disclaimer, and this list of conditions.
//
// 2. Redistributions in binary form (compiled executables) must reproduce
// the above copyright notice, definition, disclaimer, and this list of
// conditions in documentation and/or other materials provided with the
// distribution. The sole exception to this condition is redistribution
// of a standard UnZipSFX binary as part of a self-extracting archive;
// that is permitted without inclusion of this license, as long as the
// normal UnZipSFX banner has not been removed from the binary or disabled.
//
// 3. Altered versions--including, but not limited to, ports to new
// operating systems, existing ports with new graphical interfaces, and
// dynamic, shared, or static library versions--must be plainly marked
// as such and must not be misrepresented as being the original source.
// Such altered versions also must not be misrepresented as being
// Info-ZIP releases--including, but not limited to, labeling of the
// altered versions with the names "Info-ZIP" (or any variation thereof,
// including, but not limited to, different capitalizations),
// "Pocket UnZip", "WiZ" or "MacZip" without the explicit permission of
// Info-ZIP. Such altered versions are further prohibited from
// misrepresentative use of the Zip-Bugs or Info-ZIP e-mail addresses or
// of the Info-ZIP URL(s).
//
// 4. Info-ZIP retains the right to use the names "Info-ZIP", "Zip", "UnZip",
// "UnZipSFX", "WiZ", "Pocket UnZip", "Pocket Zip", and "MacZip" for its
// own source and binary releases.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef XUNZIP_H
#define XUNZIP_H
#if !defined( DWORD )
#ifdef _WIN32
typedef unsigned long DWORD;
#else
typedef unsigned int DWORD;
#endif
#endif
#if !defined( TCHAR )
typedef char TCHAR;
#endif
#if defined(POSIX) && !defined(MAX_PATH)
#include <limits.h>
#define MAX_PATH PATH_MAX
typedef bool BOOL;
#endif
#ifndef XZIP_H
#if !defined(DECLARE_HANDLE)
#if !defined(HANDLE)
typedef void *HANDLE;
#endif
#define DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name
#endif
DECLARE_HANDLE(HZIP); // An HZIP identifies a zip file that is being created
#endif
#if defined(_WIN32) && !defined(_WINBASE_) && !defined(_FILETIME_)
#define _FILETIME_
typedef struct _FILETIME
{
DWORD dwLowDateTime;
DWORD dwHighDateTime;
} FILETIME, * LPFILETIME, *PFILETIME;
#endif
#if defined(POSIX)
typedef time_t FILETIME;
#endif
typedef DWORD ZRESULT;
// return codes from any of the zip functions. Listed later.
#define ZIP_HANDLE 1
#define ZIP_FILENAME 2
#define ZIP_MEMORY 3
typedef struct
{ int index; // index of this file within the zip
char name[MAX_PATH]; // filename within the zip
DWORD attr; // attributes, as in GetFileAttributes.
FILETIME atime,ctime,mtime;// access, create, modify filetimes
long comp_size; // sizes of item, compressed and uncompressed. These
long unc_size; // may be -1 if not yet known (e.g. being streamed in)
} ZIPENTRY;
typedef struct
{ int index; // index of this file within the zip
TCHAR name[MAX_PATH]; // filename within the zip
DWORD attr; // attributes, as in GetFileAttributes.
FILETIME atime,ctime,mtime;// access, create, modify filetimes
long comp_size; // sizes of item, compressed and uncompressed. These
long unc_size; // may be -1 if not yet known (e.g. being streamed in)
} ZIPENTRYW;
///////////////////////////////////////////////////////////////////////////////
//
// OpenZip()
//
// Purpose: Open an existing zip archive file
//
// Parameters: z - archive file name if flags is ZIP_FILENAME; for other
// uses see below
// len - for memory (ZIP_MEMORY) should be the buffer size;
// for other uses, should be 0
// flags - indicates usage, see below; for files, this will be
// ZIP_FILENAME
//
// Returns: HZIP - non-zero if zip archive opened ok, otherwise 0
//
HZIP OpenZip(void *z, unsigned int len, DWORD flags);
// OpenZip - opens a zip file and returns a handle with which you can
// subsequently examine its contents. You can open a zip file from:
// from a pipe: OpenZip(hpipe_read,0, ZIP_HANDLE);
// from a file (by handle): OpenZip(hfile,0, ZIP_HANDLE);
// from a file (by name): OpenZip("c:\\test.zip",0, ZIP_FILENAME);
// from a memory block: OpenZip(bufstart, buflen, ZIP_MEMORY);
// If the file is opened through a pipe, then items may only be
// accessed in increasing order, and an item may only be unzipped once,
// although GetZipItem can be called immediately before and after unzipping
// it. If it's opened i n any other way, then full random access is possible.
// Note: pipe input is not yet implemented.
///////////////////////////////////////////////////////////////////////////////
//
// GetZipItem()
//
// Purpose: Get information about an item in an open zip archive
//
// Parameters: hz - handle of open zip archive
// index - index number (0 based) of item in zip
// ze - pointer to a ZIPENTRY (if ANSI) or ZIPENTRYW struct
// (if Unicode)
//
// Returns: ZRESULT - ZR_OK if success, otherwise some other value
//
#ifdef _UNICODE
#define GetZipItem GetZipItemW
#else
#define GetZipItem GetZipItemA
#endif
ZRESULT GetZipItemA(HZIP hz, int index, ZIPENTRY *ze);
ZRESULT GetZipItemW(HZIP hz, int index, ZIPENTRYW *ze);
// GetZipItem - call this to get information about an item in the zip.
// If index is -1 and the file wasn't opened through a pipe,
// then it returns information about the whole zipfile
// (and in particular ze.index returns the number of index items).
// Note: the item might be a directory (ze.attr & FILE_ATTRIBUTE_DIRECTORY)
// See below for notes on what happens when you unzip such an item.
// Note: if you are opening the zip through a pipe, then random access
// is not possible and GetZipItem(-1) fails and you can't discover the number
// of items except by calling GetZipItem on each one of them in turn,
// starting at 0, until eventually the call fails. Also, in the event that
// you are opening through a pipe and the zip was itself created into a pipe,
// then then comp_size and sometimes unc_size as well may not be known until
// after the item has been unzipped.
///////////////////////////////////////////////////////////////////////////////
//
// FindZipItem()
//
// Purpose: Find item by name and return information about it
//
// Parameters: hz - handle of open zip archive
// name - name of file to look for inside zip archive
// ic - TRUE = case insensitive
// index - pointer to index number returned, or -1
// ze - pointer to a ZIPENTRY (if ANSI) or ZIPENTRYW struct
// (if Unicode)
//
// Returns: ZRESULT - ZR_OK if success, otherwise some other value
//
#ifdef _UNICODE
#define FindZipItem FindZipItemW
#else
#define FindZipItem FindZipItemA
#endif
ZRESULT FindZipItemA(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze);
ZRESULT FindZipItemW(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRYW *ze);
// FindZipItem - finds an item by name. ic means 'insensitive to case'.
// It returns the index of the item, and returns information about it.
// If nothing was found, then index is set to -1 and the function returns
// an error code.
///////////////////////////////////////////////////////////////////////////////
//
// UnzipItem()
//
// Purpose: Find item by index and unzip it
//
// Parameters: hz - handle of open zip archive
// index - index number of file to unzip
// dst - target file name of unzipped file
// len - for memory (ZIP_MEMORY. length of buffer;
// otherwise 0
// flags - indicates usage, see below; for files, this will be
// ZIP_FILENAME
//
// Returns: ZRESULT - ZR_OK if success, otherwise some other value
//
ZRESULT UnzipItem(HZIP hz, int index, void *dst, unsigned int len, DWORD flags);
// UnzipItem - given an index to an item, unzips it. You can unzip to:
// to a pipe: UnzipItem(hz,i, hpipe_write,0,ZIP_HANDLE);
// to a file (by handle): UnzipItem(hz,i, hfile,0,ZIP_HANDLE);
// to a file (by name): UnzipItem(hz,i, ze.name,0,ZIP_FILENAME);
// to a memory block: UnzipItem(hz,i, buf,buflen,ZIP_MEMORY);
// In the final case, if the buffer isn't large enough to hold it all,
// then the return code indicates that more is yet to come. If it was
// large enough, and you want to know precisely how big, GetZipItem.
// Note: zip files are normally stored with relative pathnames. If you
// unzip with ZIP_FILENAME a relative pathname then the item gets created
// relative to the current directory - it first ensures that all necessary
// subdirectories have been created. Also, the item may itself be a directory.
// If you unzip a directory with ZIP_FILENAME, then the directory gets created.
// If you unzip it to a handle or a memory block, then nothing gets created
// and it emits 0 bytes.
///////////////////////////////////////////////////////////////////////////////
//
// CloseZip()
//
// Purpose: Close an open zip archive
//
// Parameters: hz - handle to an open zip archive
//
// Returns: ZRESULT - ZR_OK if success, otherwise some other value
//
ZRESULT CloseZip(HZIP hz);
// CloseZip - the zip handle must be closed with this function.
unsigned int FormatZipMessage(ZRESULT code, char *buf,unsigned int len);
// FormatZipMessage - given an error code, formats it as a string.
// It returns the length of the error message. If buf/len points
// to a real buffer, then it also writes as much as possible into there.
// These are the result codes:
#define ZR_OK 0x00000000 // nb. the pseudo-code zr-recent is never returned,
#define ZR_RECENT 0x00000001 // but can be passed to FormatZipMessage.
// The following come from general system stuff (e.g. files not openable)
#define ZR_GENMASK 0x0000FF00
#define ZR_NODUPH 0x00000100 // couldn't duplicate the handle
#define ZR_NOFILE 0x00000200 // couldn't create/open the file
#define ZR_NOALLOC 0x00000300 // failed to allocate some resource
#define ZR_WRITE 0x00000400 // a general error writing to the file
#define ZR_NOTFOUND 0x00000500 // couldn't find that file in the zip
#define ZR_MORE 0x00000600 // there's still more data to be unzipped
#define ZR_CORRUPT 0x00000700 // the zipfile is corrupt or not a zipfile
#define ZR_READ 0x00000800 // a general error reading the file
// The following come from mistakes on the part of the caller
#define ZR_CALLERMASK 0x00FF0000
#define ZR_ARGS 0x00010000 // general mistake with the arguments
#define ZR_NOTMMAP 0x00020000 // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't
#define ZR_MEMSIZE 0x00030000 // the memory size is too small
#define ZR_FAILED 0x00040000 // the thing was already failed when you called this function
#define ZR_ENDED 0x00050000 // the zip creation has already been closed
#define ZR_MISSIZE 0x00060000 // the indicated input file size turned out mistaken
#define ZR_PARTIALUNZ 0x00070000 // the file had already been partially unzipped
#define ZR_ZMODE 0x00080000 // tried to mix creating/opening a zip
// The following come from bugs within the zip library itself
#define ZR_BUGMASK 0xFF000000
#define ZR_NOTINITED 0x01000000 // initialisation didn't work
#define ZR_SEEK 0x02000000 // trying to seek in an unseekable file
#define ZR_NOCHANGE 0x04000000 // changed its mind on storage, but not allowed
#define ZR_FLATE 0x05000000 // an internal error in the de/inflation code
// e.g.
//
// SetCurrentDirectory("c:\\docs\\stuff");
// HZIP hz = OpenZip("c:\\stuff.zip",0,ZIP_FILENAME);
// ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numitems=ze.index;
// for (int i=0; i<numitems; i++)
// { GetZipItem(hz,i,&ze);
// UnzipItem(hz,i,ze.name,0,ZIP_FILENAME);
// }
// CloseZip(hz);
//
//
// HRSRC hrsrc = FindResource(hInstance,MAKEINTRESOURCE(1),RT_RCDATA);
// HANDLE hglob = LoadResource(hInstance,hrsrc);
// void *zipbuf=LockResource(hglob);
// unsigned int ziplen=SizeofResource(hInstance,hrsrc);
// HZIP hz = OpenZip(zipbuf, ziplen, ZIP_MEMORY);
// - unzip to a membuffer -
// ZIPENTRY ze; int i; FindZipItem(hz,"file.dat",&i,&ze);
// char *ibuf = new char[ze.unc_size];
// UnzipItem(hz,i, ibuf, ze.unc_size,ZIP_MEMORY);
// delete[] buf;
// - unzip to a fixed membuff -
// ZIPENTRY ze; int i; FindZipItem(hz,"file.dat",&i,&ze);
// char ibuf[1024]; ZIPRESULT zr=ZR_MORE; unsigned long totsize=0;
// while (zr==ZR_MORE)
// { zr = UnzipItem(hz,i, ibuf,1024,ZIP_MEMORY);
// unsigned long bufsize=1024; if (zr==ZR_OK) bufsize=ze.unc_size-totsize;
// totsize+=bufsize;
// }
// - unzip to a pipe -
// HANDLE hthread=CreateWavReaderThread(&hread,&hwrite);
// FindZipItem(hz,"sound.wav",&i,&ze);
// UnzipItem(hz,i, hwrite,0,ZIP_HANDLE);
// CloseHandle(hwrite);
// WaitForSingleObject(hthread,INFINITE);
// CloseHandle(hread); CloseHandle(hthread);
// - finished -
// CloseZip(hz);
// // note: no need to free resources obtained through Find/Load/LockResource
//
//
// SetCurrentDirectory("c:\\docs\\pipedzipstuff");
// HANDLE hread,hwrite; CreatePipe(&hread,&hwrite);
// CreateZipWriterThread(hwrite);
// HZIP hz = OpenZip(hread,0,ZIP_HANDLE);
// for (int i=0; ; i++)
// { ZIPENTRY ze; ZRESULT res = GetZipItem(hz,i,&ze);
// if (res!=ZE_OK) break; // no more
// UnzipItem(hz,i, ze.name,0,ZIP_FILENAME);
// }
// CloseZip(hz);
//
// Now we indulge in a little skullduggery so that the code works whether
// the user has included just zip or both zip and unzip.
// Idea: if header files for both zip and unzip are present, then presumably
// the cpp files for zip and unzip are both present, so we will call
// one or the other of them based on a dynamic choice. If the header file
// for only one is present, then we will bind to that particular one.
HZIP OpenZipU(void *z,unsigned int len,DWORD flags);
ZRESULT CloseZipU(HZIP hz);
unsigned int FormatZipMessageU(ZRESULT code, char *buf,unsigned int len);
bool IsZipHandleU(HZIP hz);
#define OpenZip OpenZipU
#ifdef XZIP_H
#undef CloseZip
#define CloseZip(hz) (IsZipHandleU(hz)?CloseZipU(hz):CloseZipZ(hz))
#else
#define CloseZip CloseZipU
#define FormatZipMessage FormatZipMessageU
#endif
// safe defintion of unzip, catches exceptions
bool SafeUnzipMemory( const void *pvZipped, int cubZipped, void *pvDest, int cubDest /* should be the exact expected unzipped size */ );
#endif //XUNZIP_H

342
sp/src/public/zip/XZip.h Normal file
View File

@@ -0,0 +1,342 @@
// XZip.h Version 1.1
//
// Authors: Mark Adler et al. (see below)
//
// Modified by: Lucian Wischik
// lu@wischik.com
//
// Version 1.0 - Turned C files into just a single CPP file
// - Made them compile cleanly as C++ files
// - Gave them simpler APIs
// - Added the ability to zip/unzip directly in memory without
// any intermediate files
//
// Modified by: Hans Dietrich
// hdietrich2@hotmail.com
//
// Version 1.1: - Added Unicode support to CreateZip() and ZipAdd()
// - Changed file names to avoid conflicts with Lucian's files
//
///////////////////////////////////////////////////////////////////////////////
//
// Lucian Wischik's comments:
// --------------------------
// THIS FILE is almost entirely based upon code by info-zip.
// It has been modified by Lucian Wischik.
// The original code may be found at http://www.info-zip.org
// The original copyright text follows.
//
///////////////////////////////////////////////////////////////////////////////
//
// Original authors' comments:
// ---------------------------
// This is version 2002-Feb-16 of the Info-ZIP copyright and license. The
// definitive version of this document should be available at
// ftp://ftp.info-zip.org/pub/infozip/license.html indefinitely.
//
// Copyright (c) 1990-2002 Info-ZIP. All rights reserved.
//
// For the purposes of this copyright and license, "Info-ZIP" is defined as
// the following set of individuals:
//
// Mark Adler, John Bush, Karl Davis, Harald Denker, Jean-Michel Dubois,
// Jean-loup Gailly, Hunter Goatley, Ian Gorman, Chris Herborth, Dirk Haase,
// Greg Hartwig, Robert Heath, Jonathan Hudson, Paul Kienitz,
// David Kirschbaum, Johnny Lee, Onno van der Linden, Igor Mandrichenko,
// Steve P. Miller, Sergio Monesi, Keith Owens, George Petrov, Greg Roelofs,
// Kai Uwe Rommel, Steve Salisbury, Dave Smith, Christian Spieler,
// Antoine Verheijen, Paul von Behren, Rich Wales, Mike White
//
// This software is provided "as is", without warranty of any kind, express
// or implied. In no event shall Info-ZIP or its contributors be held liable
// for any direct, indirect, incidental, special or consequential damages
// arising out of the use of or inability to use this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. Redistributions of source code must retain the above copyright notice,
// definition, disclaimer, and this list of conditions.
//
// 2. Redistributions in binary form (compiled executables) must reproduce
// the above copyright notice, definition, disclaimer, and this list of
// conditions in documentation and/or other materials provided with the
// distribution. The sole exception to this condition is redistribution
// of a standard UnZipSFX binary as part of a self-extracting archive;
// that is permitted without inclusion of this license, as long as the
// normal UnZipSFX banner has not been removed from the binary or disabled.
//
// 3. Altered versions--including, but not limited to, ports to new
// operating systems, existing ports with new graphical interfaces, and
// dynamic, shared, or static library versions--must be plainly marked
// as such and must not be misrepresented as being the original source.
// Such altered versions also must not be misrepresented as being
// Info-ZIP releases--including, but not limited to, labeling of the
// altered versions with the names "Info-ZIP" (or any variation thereof,
// including, but not limited to, different capitalizations),
// "Pocket UnZip", "WiZ" or "MacZip" without the explicit permission of
// Info-ZIP. Such altered versions are further prohibited from
// misrepresentative use of the Zip-Bugs or Info-ZIP e-mail addresses or
// of the Info-ZIP URL(s).
//
// 4. Info-ZIP retains the right to use the names "Info-ZIP", "Zip", "UnZip",
// "UnZipSFX", "WiZ", "Pocket UnZip", "Pocket Zip", and "MacZip" for its
// own source and binary releases.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef XZIP_H
#define XZIP_H
// ZIP functions -- for creating zip files
// This file is a repackaged form of the Info-Zip source code available
// at www.info-zip.org. The original copyright notice may be found in
// zip.cpp. The repackaging was done by Lucian Wischik to simplify its
// use in Windows/C++.
#if !defined( DWORD )
#ifdef _WIN32
typedef unsigned long DWORD;
#else
typedef unsigned int DWORD;
#endif
#endif
#if !defined( TCHAR )
typedef char TCHAR;
#endif
#ifndef XUNZIP_H
#if !defined(DECLARE_HANDLE)
#if !defined(HANDLE)
typedef void * HANDLE;
#endif
#define DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name
#endif
DECLARE_HANDLE(HZIP); // An HZIP identifies a zip file that is being created
#endif
typedef DWORD ZRESULT; // result codes from any of the zip functions. Listed later.
// flag values passed to some functions
#define ZIP_HANDLE 1
#define ZIP_FILENAME 2
#define ZIP_MEMORY 3
#define ZIP_FOLDER 4
///////////////////////////////////////////////////////////////////////////////
//
// CreateZip()
//
// Purpose: Create a zip archive file
//
// Parameters: z - archive file name if flags is ZIP_FILENAME; for other
// uses see below
// len - for memory (ZIP_MEMORY) should be the buffer size;
// for other uses, should be 0
// flags - indicates usage, see below; for files, this will be
// ZIP_FILENAME
//
// Returns: HZIP - non-zero if zip archive created ok, otherwise 0
//
HZIP CreateZip(void *z, unsigned int len, DWORD flags);
// CreateZip - call this to start the creation of a zip file.
// As the zip is being created, it will be stored somewhere:
// to a pipe: CreateZip(hpipe_write, 0,ZIP_HANDLE);
// in a file (by handle): CreateZip(hfile, 0,ZIP_HANDLE);
// in a file (by name): CreateZip("c:\\test.zip", 0,ZIP_FILENAME);
// in memory: CreateZip(buf, len,ZIP_MEMORY);
// or in pagefile memory: CreateZip(0, len,ZIP_MEMORY);
// The final case stores it in memory backed by the system paging file,
// where the zip may not exceed len bytes. This is a bit friendlier than
// allocating memory with new[]: it won't lead to fragmentation, and the
// memory won't be touched unless needed.
// Note: because pipes don't allow random access, the structure of a zipfile
// created into a pipe is slightly different from that created into a file
// or memory. In particular, the compressed-size of the item cannot be
// stored in the zipfile until after the item itself. (Also, for an item added
// itself via a pipe, the uncompressed-size might not either be known until
// after.) This is not normally a problem. But if you try to unzip via a pipe
// as well, then the unzipper will not know these things about the item until
// after it has been unzipped. Therefore: for unzippers which don't just write
// each item to disk or to a pipe, but instead pre-allocate memory space into
// which to unzip them, then either you have to create the zip not to a pipe,
// or you have to add items not from a pipe, or at least when adding items
// from a pipe you have to specify the length.
///////////////////////////////////////////////////////////////////////////////
//
// ZipAdd()
//
// Purpose: Add a file to a zip archive
//
// Parameters: hz - handle to an open zip archive
// dstzn - name used inside the zip archive to identify the file
// src - for a file (ZIP_FILENAME) this specifies the filename
// to be added to the archive; for other uses, see below
// len - for memory (ZIP_MEMORY) this specifies the buffer
// length; for other uses, this should be 0
// flags - indicates usage, see below; for files, this will be
// ZIP_FILENAME
//
// Returns: ZRESULT - ZR_OK if success, otherwise some other value
//
ZRESULT ZipAdd(HZIP hz, const TCHAR *dstzn, void *src, unsigned int len, DWORD flags);
// ZipAdd - call this for each file to be added to the zip.
// dstzn is the name that the file will be stored as in the zip file.
// The file to be added to the zip can come
// from a pipe: ZipAdd(hz,"file.dat", hpipe_read,0,ZIP_HANDLE);
// from a file: ZipAdd(hz,"file.dat", hfile,0,ZIP_HANDLE);
// from a fname: ZipAdd(hz,"file.dat", "c:\\docs\\origfile.dat",0,ZIP_FILENAME);
// from memory: ZipAdd(hz,"subdir\\file.dat", buf,len,ZIP_MEMORY);
// (folder): ZipAdd(hz,"subdir", 0,0,ZIP_FOLDER);
// Note: if adding an item from a pipe, and if also creating the zip file itself
// to a pipe, then you might wish to pass a non-zero length to the ZipAdd
// function. This will let the zipfile store the items size ahead of the
// compressed item itself, which in turn makes it easier when unzipping the
// zipfile into a pipe.
///////////////////////////////////////////////////////////////////////////////
//
// CloseZip()
//
// Purpose: Close an open zip archive
//
// Parameters: hz - handle to an open zip archive
//
// Returns: ZRESULT - ZR_OK if success, otherwise some other value
//
ZRESULT CloseZip(HZIP hz);
// CloseZip - the zip handle must be closed with this function.
ZRESULT ZipGetMemory(HZIP hz, void **buf, unsigned long *len);
// ZipGetMemory - If the zip was created in memory, via ZipCreate(0,ZIP_MEMORY),
// then this function will return information about that memory block.
// buf will receive a pointer to its start, and len its length.
// Note: you can't add any more after calling this.
unsigned int FormatZipMessage(ZRESULT code, char *buf,unsigned int len);
// FormatZipMessage - given an error code, formats it as a string.
// It returns the length of the error message. If buf/len points
// to a real buffer, then it also writes as much as possible into there.
// These are the result codes:
#define ZR_OK 0x00000000 // nb. the pseudo-code zr-recent is never returned,
#define ZR_RECENT 0x00000001 // but can be passed to FormatZipMessage.
// The following come from general system stuff (e.g. files not openable)
#define ZR_GENMASK 0x0000FF00
#define ZR_NODUPH 0x00000100 // couldn't duplicate the handle
#define ZR_NOFILE 0x00000200 // couldn't create/open the file
#define ZR_NOALLOC 0x00000300 // failed to allocate some resource
#define ZR_WRITE 0x00000400 // a general error writing to the file
#define ZR_NOTFOUND 0x00000500 // couldn't find that file in the zip
#define ZR_MORE 0x00000600 // there's still more data to be unzipped
#define ZR_CORRUPT 0x00000700 // the zipfile is corrupt or not a zipfile
#define ZR_READ 0x00000800 // a general error reading the file
// The following come from mistakes on the part of the caller
#define ZR_CALLERMASK 0x00FF0000
#define ZR_ARGS 0x00010000 // general mistake with the arguments
#define ZR_NOTMMAP 0x00020000 // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't
#define ZR_MEMSIZE 0x00030000 // the memory size is too small
#define ZR_FAILED 0x00040000 // the thing was already failed when you called this function
#define ZR_ENDED 0x00050000 // the zip creation has already been closed
#define ZR_MISSIZE 0x00060000 // the indicated input file size turned out mistaken
#define ZR_PARTIALUNZ 0x00070000 // the file had already been partially unzipped
#define ZR_ZMODE 0x00080000 // tried to mix creating/opening a zip
// The following come from bugs within the zip library itself
#define ZR_BUGMASK 0xFF000000
#define ZR_NOTINITED 0x01000000 // initialisation didn't work
#define ZR_SEEK 0x02000000 // trying to seek in an unseekable file
#define ZR_NOCHANGE 0x04000000 // changed its mind on storage, but not allowed
#define ZR_FLATE 0x05000000 // an internal error in the de/inflation code
// e.g.
//
// (1) Traditional use, creating a zipfile from existing files
// HZIP hz = CreateZip("c:\\temp.zip",0,ZIP_FILENAME);
// ZipAdd(hz,"src1.txt", "c:\\src1.txt",0,ZIP_FILENAME);
// ZipAdd(hz,"src2.bmp", "c:\\src2_origfn.bmp",0,ZIP_FILENAME);
// CloseZip(hz);
//
// (2) Memory use, creating an auto-allocated mem-based zip file from various sources
// HZIP hz = CreateZip(0,100000,ZIP_MEMORY);
// // adding a conventional file...
// ZipAdd(hz,"src1.txt", "c:\\src1.txt",0,ZIP_FILENAME);
// // adding something from memory...
// char buf[1000]; for (int i=0; i<1000; i++) buf[i]=(char)(i&0x7F);
// ZipAdd(hz,"file.dat", buf,1000,ZIP_MEMORY);
// // adding something from a pipe...
// HANDLE hread,hwrite; CreatePipe(&hread,&write,NULL,0);
// HANDLE hthread = CreateThread(ThreadFunc,(void*)hwrite);
// ZipAdd(hz,"unz3.dat", hread,0,ZIP_HANDLE);
// WaitForSingleObject(hthread,INFINITE);
// CloseHandle(hthread); CloseHandle(hread);
// ... meanwhile DWORD CALLBACK ThreadFunc(void *dat)
// { HANDLE hwrite = (HANDLE)dat;
// char buf[1000]={17};
// DWORD writ; WriteFile(hwrite,buf,1000,&writ,NULL);
// CloseHandle(hwrite);
// return 0;
// }
// // and now that the zip is created, let's do something with it:
// void *zbuf; unsigned long zlen; ZipGetMemory(hz,&zbuf,&zlen);
// HANDLE hfz = CreateFile("test2.zip",GENERIC_WRITE,CREATE_ALWAYS);
// DWORD writ; WriteFile(hfz,zbuf,zlen,&writ,NULL);
// CloseHandle(hfz);
// CloseZip(hz);
//
// (3) Handle use, for file handles and pipes
// HANDLE hzread,hzwrite; CreatePipe(&hzread,&hzwrite);
// HANDLE hthread = CreateThread(ZipReceiverThread,(void*)hread);
// HZIP hz = ZipCreate(hzwrite,ZIP_HANDLE);
// // ... add to it
// CloseZip(hz);
// CloseHandle(hzwrite);
// WaitForSingleObject(hthread,INFINITE);
// CloseHandle(hthread);
// ... meanwhile DWORD CALLBACK ThreadFunc(void *dat)
// { HANDLE hread = (HANDLE)dat;
// char buf[1000];
// while (true)
// { DWORD red; ReadFile(hread,buf,1000,&red,NULL);
// // ... and do something with this zip data we're receiving
// if (red==0) break;
// }
// CloseHandle(hread);
// return 0;
// }
//
// Now we indulge in a little skullduggery so that the code works whether
// the user has included just zip or both zip and unzip.
// Idea: if header files for both zip and unzip are present, then presumably
// the cpp files for zip and unzip are both present, so we will call
// one or the other of them based on a dynamic choice. If the header file
// for only one is present, then we will bind to that particular one.
HZIP CreateZipZ(void *z,unsigned int len,DWORD flags);
ZRESULT CloseZipZ(HZIP hz);
unsigned int FormatZipMessageZ(ZRESULT code, char *buf,unsigned int len);
bool IsZipHandleZ(HZIP hz);
#define CreateZip CreateZipZ
#ifdef XUNZIP_H
#undef CloseZip
#define CloseZip(hz) (IsZipHandleZ(hz)?CloseZipZ(hz):CloseZipU(hz))
#else
#define CloseZip CloseZipZ
#define FormatZipMessage FormatZipMessageZ
#endif
#endif //XZIP_H

View File

@@ -0,0 +1,905 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
// $Id$
#include "raytrace.h"
#include <filesystem_tools.h>
#include <cmdlib.h>
#include <stdio.h>
static bool SameSign(float a, float b)
{
int32 aa=*((int *) &a);
int32 bb=*((int *) &b);
return ((aa^bb)&0x80000000)==0;
}
int FourRays::CalculateDirectionSignMask(void) const
{
// this code treats the floats as integers since all it cares about is the sign bit and
// floating point compares suck.
int ret;
int ormask;
int andmask;
int32 const *treat_as_int=((int32 const *) (&direction));
ormask=andmask=*(treat_as_int++);
ormask|=*treat_as_int;
andmask&=*(treat_as_int++);
ormask|=*(treat_as_int);
andmask&=*(treat_as_int++);
ormask|=*(treat_as_int);
andmask&=*(treat_as_int++);
if (ormask>=0)
ret=0;
else
{
if (andmask<0)
ret=1;
else return -1;
}
ormask=andmask=*(treat_as_int++);
ormask|=*treat_as_int;
andmask&=*(treat_as_int++);
ormask|=*(treat_as_int);
andmask&=*(treat_as_int++);
ormask|=*(treat_as_int);
andmask&=*(treat_as_int++);
if (ormask<0)
{
if (andmask<0)
ret|=2;
else return -1;
}
ormask=andmask=*(treat_as_int++);
ormask|=*treat_as_int;
andmask&=*(treat_as_int++);
ormask|=*(treat_as_int);
andmask&=*(treat_as_int++);
ormask|=*(treat_as_int);
andmask&=*(treat_as_int++);
if (ormask<0)
{
if (andmask<0)
ret|=4;
else return -1;
}
return ret;
}
void RayTracingEnvironment::MakeRoomForTriangles( int ntris )
{
//OptimizedTriangleList.EnsureCapacity( ntris );
if (! (Flags & RTE_FLAGS_DONT_STORE_TRIANGLE_COLORS))
TriangleColors.EnsureCapacity( ntris );
}
void RayTracingEnvironment::AddTriangle(int32 id, const Vector &v1,
const Vector &v2, const Vector &v3,
const Vector &color)
{
AddTriangle( id, v1, v2, v3, color, 0, 0 );
}
void RayTracingEnvironment::AddTriangle(int32 id, const Vector &v1,
const Vector &v2, const Vector &v3,
const Vector &color, uint16 flags, int32 materialIndex)
{
CacheOptimizedTriangle tmptri;
tmptri.m_Data.m_GeometryData.m_nTriangleID = id;
tmptri.Vertex( 0 ) = v1;
tmptri.Vertex( 1 ) = v2;
tmptri.Vertex( 2 ) = v3;
tmptri.m_Data.m_GeometryData.m_nFlags = flags;
OptimizedTriangleList.AddToTail(tmptri);
if (! ( Flags & RTE_FLAGS_DONT_STORE_TRIANGLE_COLORS) )
TriangleColors.AddToTail(color);
if ( !( Flags & RTE_FLAGS_DONT_STORE_TRIANGLE_MATERIALS) )
TriangleMaterials.AddToTail(materialIndex);
// printf("add triange from (%f %f %f),(%f %f %f),(%f %f %f) id %d\n",
// XYZ(v1),XYZ(v2),XYZ(v3),id);
}
void RayTracingEnvironment::AddQuad(
int32 id, const Vector &v1, const Vector &v2, const Vector &v3,
const Vector &v4, // specify vertices in cw or ccw order
const Vector &color)
{
AddTriangle(id,v1,v2,v3,color);
AddTriangle(id+1,v1,v3,v4,color);
}
void RayTracingEnvironment::AddAxisAlignedRectangularSolid(int id,Vector minc, Vector maxc,
const Vector &color)
{
// "far" face
AddQuad(id,
Vector(minc.x,maxc.y,maxc.z),
Vector(maxc.x,maxc.y,maxc.z),Vector(maxc.x,minc.y,maxc.z),
Vector(minc.x,minc.y,maxc.z),color);
// "near" face
AddQuad(id,
Vector(minc.x,maxc.y,minc.z),
Vector(maxc.x,maxc.y,minc.z),Vector(maxc.x,minc.y,minc.z),
Vector(minc.x,minc.y,minc.z),color);
// "left" face
AddQuad(id,
Vector(minc.x,maxc.y,maxc.z),
Vector(minc.x,maxc.y,minc.z),
Vector(minc.x,minc.y,minc.z),
Vector(minc.x,minc.y,maxc.z),color);
// "right" face
AddQuad(id,
Vector(maxc.x,maxc.y,maxc.z),
Vector(maxc.x,maxc.y,minc.z),
Vector(maxc.x,minc.y,minc.z),
Vector(maxc.x,minc.y,maxc.z),color);
// "top" face
AddQuad(id,
Vector(minc.x,maxc.y,maxc.z),
Vector(maxc.x,maxc.y,maxc.z),
Vector(maxc.x,maxc.y,minc.z),
Vector(minc.x,maxc.y,minc.z),color);
// "bot" face
AddQuad(id,
Vector(minc.x,minc.y,maxc.z),
Vector(maxc.x,minc.y,maxc.z),
Vector(maxc.x,minc.y,minc.z),
Vector(minc.x,minc.y,minc.z),color);
}
static Vector GetEdgeEquation(Vector p1, Vector p2, int c1, int c2, Vector InsidePoint)
{
float nx=p1[c2]-p2[c2];
float ny=p2[c1]-p1[c1];
float d=-(nx*p1[c1]+ny*p1[c2]);
// assert(fabs(nx*p1[c1]+ny*p1[c2]+d)<0.01);
// assert(fabs(nx*p2[c1]+ny*p2[c2]+d)<0.01);
// use the convention that negative is "outside"
float trial_dist=InsidePoint[c1]*nx+InsidePoint[c2]*ny+d;
if (trial_dist<0)
{
nx = -nx;
ny = -ny;
d = -d;
trial_dist = -trial_dist;
}
nx /= trial_dist; // scale so that it will be =1.0 at the oppositve vertex
ny /= trial_dist;
d /= trial_dist;
return Vector(nx,ny,d);
}
void CacheOptimizedTriangle::ChangeIntoIntersectionFormat(void)
{
// lose the vertices and use edge equations instead
// grab the whole original triangle to we don't overwrite it
TriGeometryData_t srcTri = m_Data.m_GeometryData;
m_Data.m_IntersectData.m_nFlags = srcTri.m_nFlags;
m_Data.m_IntersectData.m_nTriangleID = srcTri.m_nTriangleID;
Vector p1 = srcTri.Vertex( 0 );
Vector p2 = srcTri.Vertex( 1 );
Vector p3 = srcTri.Vertex( 2 );
Vector e1 = p2 - p1;
Vector e2 = p3 - p1;
Vector N = e1.Cross( e2 );
N.NormalizeInPlace();
// now, determine which axis to drop
int drop_axis = 0;
for(int c=1 ; c<3 ; c++)
if ( fabs(N[c]) > fabs( N[drop_axis] ) )
drop_axis = c;
m_Data.m_IntersectData.m_flD = N.Dot( p1 );
m_Data.m_IntersectData.m_flNx = N.x;
m_Data.m_IntersectData.m_flNy = N.y;
m_Data.m_IntersectData.m_flNz = N.z;
// decide which axes to keep
int nCoordSelect0 = ( drop_axis + 1 ) % 3;
int nCoordSelect1 = ( drop_axis + 2 ) % 3;
m_Data.m_IntersectData.m_nCoordSelect0 = nCoordSelect0;
m_Data.m_IntersectData.m_nCoordSelect1 = nCoordSelect1;
Vector edge1 = GetEdgeEquation( p1, p2, nCoordSelect0, nCoordSelect1, p3 );
m_Data.m_IntersectData.m_ProjectedEdgeEquations[0] = edge1.x;
m_Data.m_IntersectData.m_ProjectedEdgeEquations[1] = edge1.y;
m_Data.m_IntersectData.m_ProjectedEdgeEquations[2] = edge1.z;
Vector edge2 = GetEdgeEquation( p2, p3, nCoordSelect0, nCoordSelect1, p1 );
m_Data.m_IntersectData.m_ProjectedEdgeEquations[3] = edge2.x;
m_Data.m_IntersectData.m_ProjectedEdgeEquations[4] = edge2.y;
m_Data.m_IntersectData.m_ProjectedEdgeEquations[5] = edge2.z;
}
#ifndef MAPBASE
int n_intersection_calculations=0;
#endif
int CacheOptimizedTriangle::ClassifyAgainstAxisSplit(int split_plane, float split_value)
{
// classify a triangle against an axis-aligned plane
float minc=Vertex(0)[split_plane];
float maxc=minc;
for(int v=1;v<3;v++)
{
minc=min(minc,Vertex(v)[split_plane]);
maxc=max(maxc,Vertex(v)[split_plane]);
}
if (minc>=split_value)
return PLANECHECK_POSITIVE;
if (maxc<=split_value)
return PLANECHECK_NEGATIVE;
if (minc==maxc)
return PLANECHECK_POSITIVE;
return PLANECHECK_STRADDLING;
}
#define MAILBOX_HASH_SIZE 256
#define MAX_TREE_DEPTH 21
#define MAX_NODE_STACK_LEN (40*MAX_TREE_DEPTH)
struct NodeToVisit {
CacheOptimizedKDNode const *node;
fltx4 TMin;
fltx4 TMax;
};
static fltx4 FourEpsilons={1.0e-10,1.0e-10,1.0e-10,1.0e-10};
static fltx4 FourZeros={1.0e-10,1.0e-10,1.0e-10,1.0e-10};
static fltx4 FourNegativeEpsilons={-1.0e-10,-1.0e-10,-1.0e-10,-1.0e-10};
static float BoxSurfaceArea(Vector const &boxmin, Vector const &boxmax)
{
Vector boxdim=boxmax-boxmin;
return 2.0*((boxdim[0]*boxdim[2])+(boxdim[0]*boxdim[1])+(boxdim[1]*boxdim[2]));
}
void RayTracingEnvironment::Trace4Rays(const FourRays &rays, fltx4 TMin, fltx4 TMax,
RayTracingResult *rslt_out,
int32 skip_id, ITransparentTriangleCallback *pCallback)
{
int msk=rays.CalculateDirectionSignMask();
if (msk!=-1)
Trace4Rays(rays,TMin,TMax,msk,rslt_out,skip_id, pCallback);
else
{
// sucky case - can't trace 4 rays at once. in the worst case, need to trace all 4
// separately, but usually we will still get 2x, Since our tracer only does 4 at a
// time, we will have to cover up the undesired rays with the desired ray
//!! speed!! there is room for some sse-ization here
FourRays tmprays;
tmprays.origin=rays.origin;
uint8 need_trace[4]={1,1,1,1};
for(int try_trace=0;try_trace<4;try_trace++)
{
if (need_trace[try_trace])
{
need_trace[try_trace]=2; // going to trace it
// replicate the ray being traced into all 4 rays
tmprays.direction.x=ReplicateX4(rays.direction.X(try_trace));
tmprays.direction.y=ReplicateX4(rays.direction.Y(try_trace));
tmprays.direction.z=ReplicateX4(rays.direction.Z(try_trace));
// now, see if any of the other remaining rays can be handled at the same time.
for(int try2=try_trace+1;try2<4;try2++)
if (need_trace[try2])
{
if (
SameSign(rays.direction.X(try2),
rays.direction.X(try_trace)) &&
SameSign(rays.direction.Y(try2),
rays.direction.Y(try_trace)) &&
SameSign(rays.direction.Z(try2),
rays.direction.Z(try_trace)))
{
need_trace[try2]=2;
tmprays.direction.X(try2) = rays.direction.X(try2);
tmprays.direction.Y(try2) = rays.direction.Y(try2);
tmprays.direction.Z(try2) = rays.direction.Z(try2);
}
}
// ok, now trace between 1 and 3 rays, and output the results
RayTracingResult tmpresults;
msk=tmprays.CalculateDirectionSignMask();
assert(msk!=-1);
Trace4Rays(tmprays,TMin,TMax,msk,&tmpresults,skip_id, pCallback);
// now, move results to proper place
for(int i=0;i<4;i++)
if (need_trace[i]==2)
{
need_trace[i]=0;
rslt_out->HitIds[i]=tmpresults.HitIds[i];
SubFloat(rslt_out->HitDistance, i) = SubFloat(tmpresults.HitDistance, i);
rslt_out->surface_normal.X(i) = tmpresults.surface_normal.X(i);
rslt_out->surface_normal.Y(i) = tmpresults.surface_normal.Y(i);
rslt_out->surface_normal.Z(i) = tmpresults.surface_normal.Z(i);
}
}
}
}
}
void RayTracingEnvironment::Trace4Rays(const FourRays &rays, fltx4 TMin, fltx4 TMax,
int DirectionSignMask, RayTracingResult *rslt_out,
int32 skip_id, ITransparentTriangleCallback *pCallback)
{
rays.Check();
memset(rslt_out->HitIds,0xff,sizeof(rslt_out->HitIds));
rslt_out->HitDistance=ReplicateX4(1.0e23);
rslt_out->surface_normal.DuplicateVector(Vector(0.,0.,0.));
FourVectors OneOverRayDir=rays.direction;
OneOverRayDir.MakeReciprocalSaturate();
// now, clip rays against bounding box
for(int c=0;c<3;c++)
{
fltx4 isect_min_t=
MulSIMD(SubSIMD(ReplicateX4(m_MinBound[c]),rays.origin[c]),OneOverRayDir[c]);
fltx4 isect_max_t=
MulSIMD(SubSIMD(ReplicateX4(m_MaxBound[c]),rays.origin[c]),OneOverRayDir[c]);
TMin=MaxSIMD(TMin,MinSIMD(isect_min_t,isect_max_t));
TMax=MinSIMD(TMax,MaxSIMD(isect_min_t,isect_max_t));
}
fltx4 active=CmpLeSIMD(TMin,TMax); // mask of which rays are active
if (! IsAnyNegative(active) )
return; // missed bounding box
int32 mailboxids[MAILBOX_HASH_SIZE]; // used to avoid redundant triangle tests
memset(mailboxids,0xff,sizeof(mailboxids)); // !!speed!! keep around?
int front_idx[3],back_idx[3]; // based on ray direction, whether to
// visit left or right node first
if (DirectionSignMask & 1)
{
back_idx[0]=0;
front_idx[0]=1;
}
else
{
back_idx[0]=1;
front_idx[0]=0;
}
if (DirectionSignMask & 2)
{
back_idx[1]=0;
front_idx[1]=1;
}
else
{
back_idx[1]=1;
front_idx[1]=0;
}
if (DirectionSignMask & 4)
{
back_idx[2]=0;
front_idx[2]=1;
}
else
{
back_idx[2]=1;
front_idx[2]=0;
}
NodeToVisit NodeQueue[MAX_NODE_STACK_LEN];
CacheOptimizedKDNode const *CurNode=&(OptimizedKDTree[0]);
NodeToVisit *stack_ptr=&NodeQueue[MAX_NODE_STACK_LEN];
while(1)
{
while (CurNode->NodeType() != KDNODE_STATE_LEAF) // traverse until next leaf
{
int split_plane_number=CurNode->NodeType();
CacheOptimizedKDNode const *FrontChild=&(OptimizedKDTree[CurNode->LeftChild()]);
fltx4 dist_to_sep_plane= // dist=(split-org)/dir
MulSIMD(
SubSIMD(ReplicateX4(CurNode->SplittingPlaneValue),
rays.origin[split_plane_number]),OneOverRayDir[split_plane_number]);
fltx4 active=CmpLeSIMD(TMin,TMax); // mask of which rays are active
// now, decide how to traverse children. can either do front,back, or do front and push
// back.
fltx4 hits_front=AndSIMD(active,CmpGeSIMD(dist_to_sep_plane,TMin));
if (! IsAnyNegative(hits_front))
{
// missed the front. only traverse back
//printf("only visit back %d\n",CurNode->LeftChild()+back_idx[split_plane_number]);
CurNode=FrontChild+back_idx[split_plane_number];
TMin=MaxSIMD(TMin, dist_to_sep_plane);
}
else
{
fltx4 hits_back=AndSIMD(active,CmpLeSIMD(dist_to_sep_plane,TMax));
if (! IsAnyNegative(hits_back) )
{
// missed the back - only need to traverse front node
//printf("only visit front %d\n",CurNode->LeftChild()+front_idx[split_plane_number]);
CurNode=FrontChild+front_idx[split_plane_number];
TMax=MinSIMD(TMax, dist_to_sep_plane);
}
else
{
// at least some rays hit both nodes.
// must push far, traverse near
//printf("visit %d,%d\n",CurNode->LeftChild()+front_idx[split_plane_number],
// CurNode->LeftChild()+back_idx[split_plane_number]);
assert(stack_ptr>NodeQueue);
--stack_ptr;
stack_ptr->node=FrontChild+back_idx[split_plane_number];
stack_ptr->TMin=MaxSIMD(TMin,dist_to_sep_plane);
stack_ptr->TMax=TMax;
CurNode=FrontChild+front_idx[split_plane_number];
TMax=MinSIMD(TMax,dist_to_sep_plane);
}
}
}
// hit a leaf! must do intersection check
int ntris=CurNode->NumberOfTrianglesInLeaf();
if (ntris)
{
int32 const *tlist=&(TriangleIndexList[CurNode->TriangleIndexStart()]);
do
{
int tnum=*(tlist++);
//printf("try tri %d\n",tnum);
// check mailbox
int mbox_slot=tnum & (MAILBOX_HASH_SIZE-1);
TriIntersectData_t const *tri = &( OptimizedTriangleList[tnum].m_Data.m_IntersectData );
if ( ( mailboxids[mbox_slot] != tnum ) && ( tri->m_nTriangleID != skip_id ) )
{
#ifndef MAPBASE
n_intersection_calculations++;
#endif
mailboxids[mbox_slot] = tnum;
// compute plane intersection
FourVectors N;
N.x = ReplicateX4( tri->m_flNx );
N.y = ReplicateX4( tri->m_flNy );
N.z = ReplicateX4( tri->m_flNz );
fltx4 DDotN = rays.direction * N;
// mask off zero or near zero (ray parallel to surface)
fltx4 did_hit = OrSIMD( CmpGtSIMD( DDotN,FourEpsilons ),
CmpLtSIMD( DDotN, FourNegativeEpsilons ) );
fltx4 numerator=SubSIMD( ReplicateX4( tri->m_flD ), rays.origin * N );
fltx4 isect_t=DivSIMD( numerator,DDotN );
// now, we have the distance to the plane. lets update our mask
did_hit = AndSIMD( did_hit, CmpGtSIMD( isect_t, FourZeros ) );
//did_hit=AndSIMD(did_hit,CmpLtSIMD(isect_t,TMax));
did_hit = AndSIMD( did_hit, CmpLtSIMD( isect_t, rslt_out->HitDistance ) );
if ( ! IsAnyNegative( did_hit ) )
continue;
// now, check 3 edges
fltx4 hitc1 = AddSIMD( rays.origin[tri->m_nCoordSelect0],
MulSIMD( isect_t, rays.direction[ tri->m_nCoordSelect0] ) );
fltx4 hitc2 = AddSIMD( rays.origin[tri->m_nCoordSelect1],
MulSIMD( isect_t, rays.direction[tri->m_nCoordSelect1] ) );
// do barycentric coordinate check
fltx4 B0 = MulSIMD( ReplicateX4( tri->m_ProjectedEdgeEquations[0] ), hitc1 );
B0 = AddSIMD(
B0,
MulSIMD( ReplicateX4( tri->m_ProjectedEdgeEquations[1] ), hitc2 ) );
B0 = AddSIMD(
B0, ReplicateX4( tri->m_ProjectedEdgeEquations[2] ) );
did_hit = AndSIMD( did_hit, CmpGeSIMD( B0, FourZeros ) );
fltx4 B1 = MulSIMD( ReplicateX4( tri->m_ProjectedEdgeEquations[3] ), hitc1 );
B1 = AddSIMD(
B1,
MulSIMD( ReplicateX4( tri->m_ProjectedEdgeEquations[4]), hitc2 ) );
B1 = AddSIMD(
B1, ReplicateX4( tri->m_ProjectedEdgeEquations[5] ) );
did_hit = AndSIMD( did_hit, CmpGeSIMD( B1, FourZeros ) );
fltx4 B2 = AddSIMD( B1, B0 );
did_hit = AndSIMD( did_hit, CmpLeSIMD( B2, Four_Ones ) );
if ( ! IsAnyNegative( did_hit ) )
continue;
// if the triangle is transparent
if ( tri->m_nFlags & FCACHETRI_TRANSPARENT )
{
if ( pCallback )
{
// assuming a triangle indexed as v0, v1, v2
// the projected edge equations are set up such that the vert opposite the first
// equation is v2, and the vert opposite the second equation is v0
// Therefore we pass them back in 1, 2, 0 order
// Also B2 is currently B1 + B0 and needs to be 1 - (B1+B0) in order to be a real
// barycentric coordinate. Compute that now and pass it to the callback
fltx4 b2 = SubSIMD( Four_Ones, B2 );
if ( pCallback->VisitTriangle_ShouldContinue( *tri, rays, &did_hit, &B1, &b2, &B0, tnum ) )
{
did_hit = Four_Zeros;
}
}
}
// now, set the hit_id and closest_hit fields for any enabled rays
fltx4 replicated_n = ReplicateIX4(tnum);
StoreAlignedSIMD((float *) rslt_out->HitIds,
OrSIMD(AndSIMD(replicated_n,did_hit),
AndNotSIMD(did_hit,LoadAlignedSIMD(
(float *) rslt_out->HitIds))));
rslt_out->HitDistance=OrSIMD(AndSIMD(isect_t,did_hit),
AndNotSIMD(did_hit,rslt_out->HitDistance));
rslt_out->surface_normal.x=OrSIMD(
AndSIMD(N.x,did_hit),
AndNotSIMD(did_hit,rslt_out->surface_normal.x));
rslt_out->surface_normal.y=OrSIMD(
AndSIMD(N.y,did_hit),
AndNotSIMD(did_hit,rslt_out->surface_normal.y));
rslt_out->surface_normal.z=OrSIMD(
AndSIMD(N.z,did_hit),
AndNotSIMD(did_hit,rslt_out->surface_normal.z));
}
} while (--ntris);
// now, check if all rays have terminated
fltx4 raydone=CmpLeSIMD(TMax,rslt_out->HitDistance);
if (! IsAnyNegative(raydone))
{
return;
}
}
if (stack_ptr==&NodeQueue[MAX_NODE_STACK_LEN])
{
return;
}
// pop stack!
CurNode=stack_ptr->node;
TMin=stack_ptr->TMin;
TMax=stack_ptr->TMax;
stack_ptr++;
}
}
int RayTracingEnvironment::MakeLeafNode(int first_tri, int last_tri)
{
CacheOptimizedKDNode ret;
ret.Children=KDNODE_STATE_LEAF+(TriangleIndexList.Count()<<2);
ret.SetNumberOfTrianglesInLeafNode(1+(last_tri-first_tri));
for(int tnum=first_tri;tnum<=last_tri;tnum++)
TriangleIndexList.AddToTail(tnum);
OptimizedKDTree.AddToTail(ret);
return OptimizedKDTree.Count()-1;
}
void RayTracingEnvironment::CalculateTriangleListBounds(int32 const *tris,int ntris,
Vector &minout, Vector &maxout)
{
minout = Vector( 1.0e23, 1.0e23, 1.0e23);
maxout = Vector( -1.0e23, -1.0e23, -1.0e23);
for(int i=0; i<ntris; i++)
{
CacheOptimizedTriangle const &tri=OptimizedTriangleList[tris[i]];
for(int v=0; v<3; v++)
for(int c=0; c<3; c++)
{
minout[c]=min(minout[c],tri.Vertex(v)[c]);
maxout[c]=max(maxout[c],tri.Vertex(v)[c]);
}
}
}
// Both the "quick" and regular kd tree building algorithms here use the "surface area heuristic":
// the relative probability of hitting the "left" subvolume (Vl) from a split is equal to that
// subvolume's surface area divided by its parent's surface area (Vp) : P(Vl | V)=SA(Vl)/SA(Vp).
// The same holds for the right subvolume, Vp. Nl is the number of triangles in the left volume,
// and Nr in the right volume. if Ct is the cost of traversing one tree node, and Ci is the cost of
// intersection with the primitive, than the cost of splitting is estimated as:
//
// Ct+Ci*((SA(Vl)/SA(V))*Nl+(SA(Vr)/SA(V)*Nr)).
// and the cost of not splitting is
// Ci*N
//
// This both provides a metric to minimize when computing how and where to split, and also a
// termination criterion.
//
// the "quick" method just splits down the middle, while the slow method splits at the best
// discontinuity of the cost formula. The quick method splits along the longest axis ; the
// regular algorithm tries all 3 to find which one results in the minimum cost
//
// both methods use the additional optimization of "growing" empty nodes - if the split results in
// one side being devoid of triangles, the empty side is "grown" as much as possible.
//
#define COST_OF_TRAVERSAL 75 // approximate #operations
#define COST_OF_INTERSECTION 167 // approximate #operations
float RayTracingEnvironment::CalculateCostsOfSplit(
int split_plane,int32 const *tri_list,int ntris,
Vector MinBound,Vector MaxBound, float &split_value,
int &nleft, int &nright, int &nboth)
{
// determine the costs of splitting on a given axis, and label triangles with respect to
// that axis by storing the value in coordselect0. It will also return the number of
// tris in the left, right, and nboth groups, in order to facilitate memory
nleft=nboth=nright=0;
// now, label each triangle. Since we have not converted the triangles into
// intersection fromat yet, we can use the CoordSelect0 field of each as a temp.
nleft=0;
nright=0;
nboth=0;
float min_coord=1.0e23,max_coord=-1.0e23;
for(int t=0;t<ntris;t++)
{
CacheOptimizedTriangle &tri=OptimizedTriangleList[tri_list[t]];
// determine max and min coordinate values for later optimization
for(int v=0;v<3;v++)
{
min_coord = min( min_coord, tri.Vertex(v)[split_plane] );
max_coord = max( max_coord, tri.Vertex(v)[split_plane] );
}
switch(tri.ClassifyAgainstAxisSplit(split_plane,split_value))
{
case PLANECHECK_NEGATIVE:
nleft++;
tri.m_Data.m_GeometryData.m_nTmpData0 = PLANECHECK_NEGATIVE;
break;
case PLANECHECK_POSITIVE:
nright++;
tri.m_Data.m_GeometryData.m_nTmpData0 = PLANECHECK_POSITIVE;
break;
case PLANECHECK_STRADDLING:
nboth++;
tri.m_Data.m_GeometryData.m_nTmpData0 = PLANECHECK_STRADDLING;
break;
}
}
// now, if the split resulted in one half being empty, "grow" the empty half
if (nleft && (nboth==0) && (nright==0))
split_value=max_coord;
if (nright && (nboth==0) && (nleft==0))
split_value=min_coord;
// now, perform surface area/cost check to determine whether this split was worth it
Vector LeftMins=MinBound;
Vector LeftMaxes=MaxBound;
Vector RightMins=MinBound;
Vector RightMaxes=MaxBound;
LeftMaxes[split_plane]=split_value;
RightMins[split_plane]=split_value;
float SA_L=BoxSurfaceArea(LeftMins,LeftMaxes);
float SA_R=BoxSurfaceArea(RightMins,RightMaxes);
float ISA=1.0/BoxSurfaceArea(MinBound,MaxBound);
float cost_of_split=COST_OF_TRAVERSAL+COST_OF_INTERSECTION*(nboth+
(SA_L*ISA*(nleft))+(SA_R*ISA*(nright)));
return cost_of_split;
}
#define NEVER_SPLIT 0
void RayTracingEnvironment::RefineNode(int node_number,int32 const *tri_list,int ntris,
Vector MinBound,Vector MaxBound, int depth)
{
if (ntris<3) // never split empty lists
{
// no point in continuing
OptimizedKDTree[node_number].Children=KDNODE_STATE_LEAF+(TriangleIndexList.Count()<<2);
OptimizedKDTree[node_number].SetNumberOfTrianglesInLeafNode(ntris);
#ifdef DEBUG_RAYTRACE
OptimizedKDTree[node_number].vecMins = MinBound;
OptimizedKDTree[node_number].vecMaxs = MaxBound;
#endif
for(int t=0;t<ntris;t++)
TriangleIndexList.AddToTail(tri_list[t]);
return;
}
float best_cost=1.0e23;
int best_nleft=0,best_nright=0,best_nboth=0;
float best_splitvalue=0;
int split_plane=0;
int tri_skip=1+(ntris/10); // don't try all trinagles as split
// points when there are a lot of them
for(int axis=0;axis<3;axis++)
{
for(int ts=-1;ts<ntris;ts+=tri_skip)
{
for(int tv=0;tv<3;tv++)
{
int trial_nleft,trial_nright,trial_nboth;
float trial_splitvalue;
if (ts==-1)
trial_splitvalue=0.5*(MinBound[axis]+MaxBound[axis]);
else
{
// else, split at the triangle vertex if possible
CacheOptimizedTriangle &tri=OptimizedTriangleList[tri_list[ts]];
trial_splitvalue = tri.Vertex(tv)[axis];
if ((trial_splitvalue>MaxBound[axis]) || (trial_splitvalue<MinBound[axis]))
continue; // don't try this vertex - not inside
}
// printf("ts=%d tv=%d tp=%f\n",ts,tv,trial_splitvalue);
float trial_cost=
CalculateCostsOfSplit(axis,tri_list,ntris,MinBound,MaxBound,trial_splitvalue,
trial_nleft,trial_nright, trial_nboth);
// printf("try %d cost=%f nl=%d nr=%d nb=%d sp=%f\n",axis,trial_cost,trial_nleft,trial_nright, trial_nboth,
// trial_splitvalue);
if (trial_cost<best_cost)
{
split_plane=axis;
best_cost=trial_cost;
best_nleft=trial_nleft;
best_nright=trial_nright;
best_nboth=trial_nboth;
best_splitvalue=trial_splitvalue;
// save away the axis classification of each triangle
for(int t=0 ; t < ntris; t++)
{
CacheOptimizedTriangle &tri=OptimizedTriangleList[tri_list[t]];
tri.m_Data.m_GeometryData.m_nTmpData1 = tri.m_Data.m_GeometryData.m_nTmpData0;
}
}
if (ts==-1)
break;
}
}
}
float cost_of_no_split=COST_OF_INTERSECTION*ntris;
if ( (cost_of_no_split<=best_cost) || NEVER_SPLIT || (depth>MAX_TREE_DEPTH))
{
// no benefit to splitting. just make this a leaf node
OptimizedKDTree[node_number].Children=KDNODE_STATE_LEAF+(TriangleIndexList.Count()<<2);
OptimizedKDTree[node_number].SetNumberOfTrianglesInLeafNode(ntris);
#ifdef DEBUG_RAYTRACE
OptimizedKDTree[node_number].vecMins = MinBound;
OptimizedKDTree[node_number].vecMaxs = MaxBound;
#endif
for(int t=0;t<ntris;t++)
TriangleIndexList.AddToTail(tri_list[t]);
}
else
{
// printf("best split was %d at %f (mid=%f,n=%d, sk=%d)\n",split_plane,best_splitvalue,
// 0.5*(MinBound[split_plane]+MaxBound[split_plane]),ntris,tri_skip);
// its worth splitting!
// we will achieve the splitting without sorting by using a selection algorithm.
int32 *new_triangle_list;
new_triangle_list=new int32[ntris];
// now, perform surface area/cost check to determine whether this split was worth it
Vector LeftMins=MinBound;
Vector LeftMaxes=MaxBound;
Vector RightMins=MinBound;
Vector RightMaxes=MaxBound;
LeftMaxes[split_plane]=best_splitvalue;
RightMins[split_plane]=best_splitvalue;
int n_left_output=0;
int n_both_output=0;
int n_right_output=0;
for(int t=0;t<ntris;t++)
{
CacheOptimizedTriangle &tri=OptimizedTriangleList[tri_list[t]];
switch( tri.m_Data.m_GeometryData.m_nTmpData1 )
{
case PLANECHECK_NEGATIVE:
// printf("%d goes left\n",t);
new_triangle_list[n_left_output++]=tri_list[t];
break;
case PLANECHECK_POSITIVE:
n_right_output++;
// printf("%d goes right\n",t);
new_triangle_list[ntris-n_right_output]=tri_list[t];
break;
case PLANECHECK_STRADDLING:
// printf("%d goes both\n",t);
new_triangle_list[best_nleft+n_both_output]=tri_list[t];
n_both_output++;
break;
}
}
int left_child=OptimizedKDTree.Count();
int right_child=left_child+1;
// printf("node %d split on axis %d at %f, nl=%d nr=%d nb=%d lc=%d rc=%d\n",node_number,
// split_plane,best_splitvalue,best_nleft,best_nright,best_nboth,
// left_child,right_child);
OptimizedKDTree[node_number].Children=split_plane+(left_child<<2);
OptimizedKDTree[node_number].SplittingPlaneValue=best_splitvalue;
#ifdef DEBUG_RAYTRACE
OptimizedKDTree[node_number].vecMins = MinBound;
OptimizedKDTree[node_number].vecMaxs = MaxBound;
#endif
CacheOptimizedKDNode newnode;
OptimizedKDTree.AddToTail(newnode);
OptimizedKDTree.AddToTail(newnode);
// now, recurse!
if ( (ntris<20) && ((best_nleft==0) || (best_nright==0)) )
depth+=100;
RefineNode(left_child,new_triangle_list,best_nleft+best_nboth,LeftMins,LeftMaxes,depth+1);
RefineNode(right_child,new_triangle_list+best_nleft,best_nright+best_nboth,
RightMins,RightMaxes,depth+1);
delete[] new_triangle_list;
}
}
void RayTracingEnvironment::SetupAccelerationStructure(void)
{
CacheOptimizedKDNode root;
OptimizedKDTree.AddToTail(root);
int32 *root_triangle_list=new int32[OptimizedTriangleList.Count()];
for(int t=0;t<OptimizedTriangleList.Count();t++)
root_triangle_list[t]=t;
CalculateTriangleListBounds(root_triangle_list,OptimizedTriangleList.Count(),m_MinBound,
m_MaxBound);
RefineNode(0,root_triangle_list,OptimizedTriangleList.Count(),m_MinBound,m_MaxBound,0);
delete[] root_triangle_list;
// now, convert all triangles to "intersection format"
for(int i=0;i<OptimizedTriangleList.Count();i++)
OptimizedTriangleList[i].ChangeIntoIntersectionFormat();
}
void RayTracingEnvironment::AddInfinitePointLight(Vector position, Vector intensity)
{
LightDesc_t mylight(position,intensity);
LightList.AddToTail(mylight);
}

View File

@@ -0,0 +1,26 @@
//-----------------------------------------------------------------------------
// RAYTRACE.VPC
//
// Project Script
//-----------------------------------------------------------------------------
$Macro SRCDIR ".."
$Include "$SRCDIR\vpc_scripts\source_lib_base.vpc"
$Configuration
{
$Compiler
{
$AdditionalIncludeDirectories "$BASE,$SRCDIR\utils\common"
}
}
$Project "Raytrace"
{
$Folder "Source Files"
{
$File "raytrace.cpp"
$File "trace2.cpp"
$File "trace3.cpp"
}
}

376
sp/src/raytrace/trace2.cpp Normal file
View File

@@ -0,0 +1,376 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
// $Id$
#include "raytrace.h"
#include <mathlib/halton.h>
static uint32 MapDistanceToPixel(float t)
{
if (t<0) return 0xffff0000;
if (t>100) return 0xff000000;
int a=t*1000; a&=0xff;
int b=t*10; b &=0xff;
int c=t*.01; c &=0xff;
return 0xff000000+(a<<16)+(b<<8)+c;
}
#define IGAMMA (1.0/2.2)
#define MAGIC_NUMBER (1<<23)
static fltx4 Four_MagicNumbers={ MAGIC_NUMBER, MAGIC_NUMBER, MAGIC_NUMBER, MAGIC_NUMBER };
static ALIGN16 int32 Four_255s[4]= {0xff,0xff,0xff,0xff};
#define PIXMASK ( * ( reinterpret_cast< fltx4 *>( &Four_255s ) ) )
void MapLinearIntensities(FourVectors const &intens,uint32 *p1, uint32 *p2, uint32 *p3, uint32 *p4)
{
// convert four pixels worth of sse-style rgb into argb lwords
// NOTE the _mm_empty macro is voodoo. do not mess with this routine casually - simply throwing
// anything that ends up generating a fpu stack references in here would be bad news.
static fltx4 pixscale={255.0,255.0,255.0,255.0};
fltx4 r,g,b;
r=MinSIMD(pixscale,MulSIMD(pixscale,PowSIMD(intens.x,IGAMMA)));
g=MinSIMD(pixscale,MulSIMD(pixscale,PowSIMD(intens.y,IGAMMA)));
b=MinSIMD(pixscale,MulSIMD(pixscale,PowSIMD(intens.z,IGAMMA)));
// now, convert to integer
r=AndSIMD( AddSIMD( r, Four_MagicNumbers ), PIXMASK );
g=AndSIMD( AddSIMD( g, Four_MagicNumbers ), PIXMASK );
b=AndSIMD( AddSIMD( b, Four_MagicNumbers ), PIXMASK );
*(p1)=(SubInt(r, 0))|(SubInt(g, 0)<<8)|(SubInt(b, 0)<<16);
*(p2)=(SubInt(r, 1))|(SubInt(g, 1)<<8)|(SubInt(b, 1)<<16);
*(p3)=(SubInt(r, 2))|(SubInt(g, 2)<<8)|(SubInt(b, 2)<<16);
*(p4)=(SubInt(r, 3))|(SubInt(g, 3)<<8)|(SubInt(b, 3)<<16);
}
static ALIGN16 int32 signmask[4]={0x80000000,0x80000000,0x80000000,0x80000000};
static ALIGN16 int32 all_ones[4]={-1,-1,-1,-1};
static fltx4 all_zeros={0,0,0,0};
static fltx4 TraceLimit={1.0e20,1.0e20,1.0e20,1.0e20};
void RayTracingEnvironment::RenderScene(
int width, int height, // width and height of desired rendering
int stride, // actual width in pixels of target buffer
uint32 *output_buffer, // pointer to destination
Vector CameraOrigin, // eye position
Vector ULCorner, // word space coordinates of upper left
// monitor corner
Vector URCorner, // top right corner
Vector LLCorner, // lower left
Vector LRCorner, // lower right
RayTraceLightingMode_t lmode)
{
// first, compute deltas
Vector dxvector=URCorner;
dxvector-=ULCorner;
dxvector*=(1.0/width);
Vector dxvectortimes2=dxvector;
dxvectortimes2+=dxvector;
Vector dyvector=LLCorner;
dyvector-=ULCorner;
dyvector*=(1.0/height);
// block_offsets-relative offsets for eahc of the 4 pixels in the block, in sse format
FourVectors block_offsets;
block_offsets.LoadAndSwizzle(Vector(0,0,0),dxvector,dyvector,dxvector+dyvector);
FourRays myrays;
myrays.origin.DuplicateVector(CameraOrigin);
// tmprays is used fo rthe case when we cannot trace 4 rays at once.
FourRays tmprays;
tmprays.origin.DuplicateVector(CameraOrigin);
// now, we will ray trace pixels. we will do the rays in a 2x2 pattern
for(int y=0;y<height;y+=2)
{
Vector SLoc=dyvector;
SLoc*=((float) y);
SLoc+=ULCorner;
uint32 *dest=output_buffer+y*stride;
for(int x=0;x<width;x+=2)
{
myrays.direction.DuplicateVector(SLoc);
myrays.direction+=block_offsets;
myrays.direction.VectorNormalize();
RayTracingResult rslt;
Trace4Rays(myrays,all_zeros,TraceLimit, &rslt);
if ((rslt.HitIds[0]==-1) && (rslt.HitIds[1]==-1) &&
(rslt.HitIds[2]==-1) && (rslt.HitIds[3]==-1))
MapLinearIntensities(BackgroundColor,dest,dest+1,dest+stride,dest+stride+1);
else
{
// make sure normal points back towards ray origin
fltx4 ndoti=rslt.surface_normal*myrays.direction;
fltx4 bad_dirs=AndSIMD(CmpGtSIMD(ndoti,Four_Zeros),
LoadAlignedSIMD((float *) signmask));
// flip signs of all "wrong" normals
rslt.surface_normal.x=XorSIMD(bad_dirs,rslt.surface_normal.x);
rslt.surface_normal.y=XorSIMD(bad_dirs,rslt.surface_normal.y);
rslt.surface_normal.z=XorSIMD(bad_dirs,rslt.surface_normal.z);
FourVectors intens;
intens.DuplicateVector(Vector(0,0,0));
// set up colors
FourVectors surf_colors;
surf_colors.DuplicateVector(Vector(0,0,0));
for(int i=0;i<4;i++)
{
if (rslt.HitIds[i]>=0)
{
surf_colors.X(i)=TriangleColors[rslt.HitIds[i]].x;
surf_colors.Y(i)=TriangleColors[rslt.HitIds[i]].y;
surf_colors.Z(i)=TriangleColors[rslt.HitIds[i]].z;
}
}
FourVectors surface_pos=myrays.direction;
surface_pos*=rslt.HitDistance;
surface_pos+=myrays.origin;
switch(lmode)
{
case DIRECT_LIGHTING:
{
// light all points
for(int l=0;l<LightList.Count();l++)
{
LightList[l].ComputeLightAtPoints(surface_pos,rslt.surface_normal,
intens);
}
}
break;
case DIRECT_LIGHTING_WITH_SHADOWS:
{
// light all points
for(int l=0;l<LightList.Count();l++)
{
FourVectors ldir;
ldir.DuplicateVector(LightList[l].m_Position);
ldir-=surface_pos;
fltx4 MaxT=ldir.length();
ldir.VectorNormalizeFast();
// now, compute shadow flag
FourRays myrays;
myrays.origin=surface_pos;
FourVectors epsilon=ldir;
epsilon*=0.01;
myrays.origin+=epsilon;
myrays.direction=ldir;
RayTracingResult shadowtest;
Trace4Rays(myrays,Four_Zeros,MaxT, &shadowtest);
fltx4 unshadowed=CmpGtSIMD(shadowtest.HitDistance,MaxT);
if (! (IsAllZeros(unshadowed)))
{
FourVectors tmp;
tmp.DuplicateVector(Vector(0,0,0));
LightList[l].ComputeLightAtPoints(surface_pos,rslt.surface_normal,
tmp);
intens.x=AddSIMD(intens.x,AndSIMD(tmp.x,unshadowed));
intens.y=AddSIMD(intens.y,AndSIMD(tmp.y,unshadowed));
intens.z=AddSIMD(intens.z,AndSIMD(tmp.z,unshadowed));
}
}
}
break;
}
// now, mask off non-hitting pixels
intens.VProduct(surf_colors);
fltx4 no_hit_mask=CmpGtSIMD(rslt.HitDistance,TraceLimit);
intens.x=OrSIMD(AndSIMD(BackgroundColor.x,no_hit_mask),
AndNotSIMD(no_hit_mask,intens.x));
intens.y=OrSIMD(AndSIMD(BackgroundColor.y,no_hit_mask),
AndNotSIMD(no_hit_mask,intens.y));
intens.z=OrSIMD(AndSIMD(BackgroundColor.z,no_hit_mask),
AndNotSIMD(no_hit_mask,intens.z));
MapLinearIntensities(intens,dest,dest+1,dest+stride,dest+stride+1);
}
dest+=2;
SLoc+=dxvectortimes2;
}
}
}
#define SQ(x) ((x)*(x))
void RayTracingEnvironment::ComputeVirtualLightSources(void)
{
int start_pos=0;
for(int b=0;b<3;b++)
{
int nl=LightList.Count();
int where_to_start=start_pos;
start_pos=nl;
for(int l=where_to_start;l<nl;l++)
{
DirectionalSampler_t sample_generator;
int n_desired=1*LightList[l].m_Color.Length();
if (LightList[l].m_Type==MATERIAL_LIGHT_SPOT)
n_desired*=LightList[l].m_Phi/2;
for(int try1=0;try1<n_desired;try1++)
{
LightDesc_t const &li=LightList[l];
FourRays myrays;
myrays.origin.DuplicateVector(li.m_Position);
RayTracingResult rslt;
Vector trial_dir=sample_generator.NextValue();
if (li.IsDirectionWithinLightCone(trial_dir))
{
myrays.direction.DuplicateVector(trial_dir);
Trace4Rays(myrays,all_zeros,ReplicateX4(1000.0), &rslt);
if ((rslt.HitIds[0]!=-1))
{
// make sure normal points back towards ray origin
fltx4 ndoti=rslt.surface_normal*myrays.direction;
fltx4 bad_dirs=AndSIMD(CmpGtSIMD(ndoti,Four_Zeros),
LoadAlignedSIMD((float *) signmask));
// flip signs of all "wrong" normals
rslt.surface_normal.x=XorSIMD(bad_dirs,rslt.surface_normal.x);
rslt.surface_normal.y=XorSIMD(bad_dirs,rslt.surface_normal.y);
rslt.surface_normal.z=XorSIMD(bad_dirs,rslt.surface_normal.z);
// a hit! let's make a virtual light source
// treat the virtual light as a disk with its center at the hit position
// and its radius scaled by the amount of the solid angle this probe
// represents.
float area_of_virtual_light=
4.0*M_PI*SQ( SubFloat( rslt.HitDistance, 0 ) )*(1.0/n_desired);
FourVectors intens;
intens.DuplicateVector(Vector(0,0,0));
FourVectors surface_pos=myrays.direction;
surface_pos*=rslt.HitDistance;
surface_pos+=myrays.origin;
FourVectors delta=rslt.surface_normal;
delta*=0.1;
surface_pos+=delta;
LightList[l].ComputeLightAtPoints(surface_pos,rslt.surface_normal,
intens);
FourVectors surf_colors;
surf_colors.DuplicateVector(TriangleColors[rslt.HitIds[0]]);
intens*=surf_colors;
// see if significant
LightDesc_t l1;
l1.m_Type=MATERIAL_LIGHT_SPOT;
l1.m_Position=Vector(surface_pos.X(0),surface_pos.Y(0),surface_pos.Z(0));
l1.m_Direction=Vector(rslt.surface_normal.X(0),rslt.surface_normal.Y(0),
rslt.surface_normal.Z(0));
l1.m_Color=Vector(intens.X(0),intens.Y(0),intens.Z(0));
if (l1.m_Color.Length()>0)
{
l1.m_Color*=area_of_virtual_light/M_PI;
l1.m_Range=0.0;
l1.m_Falloff=1.0;
l1.m_Attenuation0=1.0;
l1.m_Attenuation1=0.0;
l1.m_Attenuation2=1.0; // intens falls off as 1/r^2
l1.m_Theta=0;
l1.m_Phi=M_PI;
l1.RecalculateDerivedValues();
LightList.AddToTail(l1);
}
}
}
}
}
}
}
static unsigned int GetSignMask(Vector const &v)
{
unsigned int ret=0;
if (v.x<0.0)
ret++;
if (v.y<0)
ret+=2;
if (v.z<0)
ret+=4;
return ret;
}
inline void RayTracingEnvironment::FlushStreamEntry(RayStream &s,int msk)
{
assert(msk>=0);
assert(msk<8);
fltx4 tmax=s.PendingRays[msk].direction.length();
fltx4 scl=ReciprocalSaturateSIMD(tmax);
s.PendingRays[msk].direction*=scl; // normalize
RayTracingResult tmpresult;
Trace4Rays(s.PendingRays[msk],Four_Zeros,tmax,msk,&tmpresult);
// now, write out results
for(int r=0;r<4;r++)
{
RayTracingSingleResult *out=s.PendingStreamOutputs[msk][r];
out->ray_length=SubFloat( tmax, r );
out->surface_normal.x=tmpresult.surface_normal.X(r);
out->surface_normal.y=tmpresult.surface_normal.Y(r);
out->surface_normal.z=tmpresult.surface_normal.Z(r);
out->HitID=tmpresult.HitIds[r];
out->HitDistance=SubFloat( tmpresult.HitDistance, r );
}
s.n_in_stream[msk]=0;
}
void RayTracingEnvironment::AddToRayStream(RayStream &s,
Vector const &start,Vector const &end,
RayTracingSingleResult *rslt_out)
{
Vector delta=end;
delta-=start;
int msk=GetSignMask(delta);
assert(msk>=0);
assert(msk<8);
int pos=s.n_in_stream[msk];
assert(pos<4);
s.PendingRays[msk].origin.X(pos)=start.x;
s.PendingRays[msk].origin.Y(pos)=start.y;
s.PendingRays[msk].origin.Z(pos)=start.z;
s.PendingRays[msk].direction.X(pos)=delta.x;
s.PendingRays[msk].direction.Y(pos)=delta.y;
s.PendingRays[msk].direction.Z(pos)=delta.z;
s.PendingStreamOutputs[msk][pos]=rslt_out;
if (pos==3)
{
FlushStreamEntry(s,msk);
}
else
s.n_in_stream[msk]++;
}
void RayTracingEnvironment::FinishRayStream(RayStream &s)
{
for(int msk=0;msk<8;msk++)
{
int cnt=s.n_in_stream[msk];
if (cnt)
{
// fill in unfilled entries with dups of first
for(int c=cnt;c<4;c++)
{
s.PendingRays[msk].origin.X(c) = s.PendingRays[msk].origin.X(0);
s.PendingRays[msk].origin.Y(c) = s.PendingRays[msk].origin.Y(0);
s.PendingRays[msk].origin.Z(c) = s.PendingRays[msk].origin.Z(0);
s.PendingRays[msk].direction.X(c) = s.PendingRays[msk].direction.X(0);
s.PendingRays[msk].direction.Y(c) = s.PendingRays[msk].direction.Y(0);
s.PendingRays[msk].direction.Z(c) = s.PendingRays[msk].direction.Z(0);
s.PendingStreamOutputs[msk][c]=s.PendingStreamOutputs[msk][0];
}
FlushStreamEntry(s,msk);
}
}
}

127
sp/src/raytrace/trace3.cpp Normal file
View File

@@ -0,0 +1,127 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
#include "raytrace.h"
#include <bspfile.h>
#include "bsplib.h"
static Vector VertCoord(dface_t const &f, int vnum)
{
int eIndex = dsurfedges[f.firstedge+vnum];
int point;
if( eIndex < 0 )
{
point = dedges[-eIndex].v[1];
}
else
{
point = dedges[eIndex].v[0];
}
dvertex_t *v=dvertexes+point;
return Vector(v->point[0],v->point[1],v->point[2]);
}
Vector colors[]={
Vector(0.5,0.5,1),
Vector(0.5,1,0.5),
Vector(0.5,1,1),
Vector(1,0.5,0.5),
Vector(1,0.5,1),
Vector(1,1,1)};
void RayTracingEnvironment::AddBSPFace(int id,dface_t const &face)
{
if (face.dispinfo!=-1) // displacements must be dealt with elsewhere
return;
texinfo_t *tx =(face.texinfo>=0)?&(texinfo[face.texinfo]):0;
// if (tx && (tx->flags & (SURF_SKY|SURF_NODRAW)))
// return;
if (tx)
{
printf("id %d flags=%x\n",id,tx->flags);
}
printf("side: ");
for(int v=0;v<face.numedges;v++)
{
printf("(%f %f %f) ",XYZ(VertCoord(face,v)));
}
printf("\n");
int ntris=face.numedges-2;
for(int tri=0;tri<ntris;tri++)
{
AddTriangle(id,VertCoord(face,0),VertCoord(face,(tri+1)%face.numedges),
VertCoord(face,(tri+2)%face.numedges),Vector(1,1,1)); //colors[id % NELEMS(colors)]);
}
}
void RayTracingEnvironment::InitializeFromLoadedBSP(void)
{
// CUtlVector<uint8> PlanesToSkip;
// SidesToSkip.EnsureCapacity(numplanes);
// for(int s=0;s<numplanes;s++)
// SidesToSkip.AddToTail(0);
// for(int b=0;b<numbrushes;b++)
// if ((dbrushes[b].contents & MASK_OPAQUE)==0)
// {
// // transparent brush - mark all its sides as "do not process"
// for(int s=0;s<dbrushes[b].numsides;s++)
// {
// PlanesToSkip[s+dbrushes[b].firstside]=1;
// }
// }
// // now, add all origfaces, omitting those whose sides are the ones we marked previously
// for(int c=0;c<numorigfaces;c++)
// {
// dface_t const &f=dorigfaces[c];
// if (SidesToSkip[f.AddBSPFace(c,dorigfaces[c]);
// }
// // ugly - I want to traverse all the faces. but there is no way to get from a face back to it's
// // original brush, and I need to get back to the face to the contents field of the brush. So I
// // will create a temporary mapping from a "side" to its brush. I can get from the face to it
// // side, which can get me back to its brush.
// CUtlVector<uint8> OrigFaceVisited;
// OrigFaceVisited.EnsureCapacity(numorigfaces);
// int n_added=0;
// for(int i=0;i<numorigfaces;i++)
// OrigFaceVisited.AddToTail(0);
// for(int l=0;l<numleafs;l++)
// {
// dleaf_t const &lf=dleafs[l];
// // if (lf.contents & MASK_OPAQUE)
// {
// for(int f=0;f<lf.numleaffaces;f++);
// {
// dface_t const &face=dfaces[f+lf.firstleafface];
// if (OrigFaceVisited[face.origFace]==0)
// {
// dface_t const &oface=dorigfaces[face.origFace];
// OrigFaceVisited[face.origFace]=1;
// n_added++;
// AddBSPFace(face.origFace,oface);
// }
// }
// }
// }
// printf("added %d of %d\n",n_added,numorigfaces);
// for(int c=0;c<numorigfaces;c++)
// {
// dface_t const &f=dorigfaces[c];
// AddBSPFace(c,dorigfaces[c]);
// }
for(int c=0;c<numfaces;c++)
{
// dface_t const &f=dfaces[c];
AddBSPFace(c,dorigfaces[c]);
}
// AddTriangle(1234,Vector(51,145,-700),Vector(71,165,-700),Vector(51,165,-700),colors[5]);
}

View File

@@ -0,0 +1,58 @@
//========= Copyright <20> 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CBASE_H
#define CBASE_H
#ifdef _WIN32
#pragma once
#endif
struct studiohdr_t;
#define CUSTOM_MEM_DBG 0
#if CUSTOM_MEM_DBG
#define NO_MALLOC_OVERRIDE
#endif // CUSTOM_MEM_DBG
#ifndef swap
template < typename T >
inline void swap( T& x, T& y )
{
T temp = x;
x = y;
y = temp;
}
#endif
#include <stdio.h>
#include <stdlib.h>
#include <tier0/platform.h>
#include <tier0/dbg.h>
#include <tier1/strtools.h>
#include <vstdlib/random.h>
#include <utlvector.h>
#include <const.h>
#include "string_t.h"
#include "globalvars_base.h"
#include <icvar.h>
#include "interface/dll_init.h"
#include "engine/ivmodelinfo.h"
#include "engine/ivmodelrender.h"
#include "util/igamesystem.h"
#include "editorCommon.h"
#endif // CBASE_H

View File

@@ -0,0 +1,303 @@
#include "cbase.h"
#include "editorCommon.h"
#include "view_shared.h"
#include "vtf/vtf.h"
//#include "magick++.h"
#ifdef SHADER_EDITOR_DLL_2006
#include "setjmp.h"
#endif
#include "jpeglib/jpeglib.h"
CHLSL_Image::CHLSL_Image()
{
pVtf = NULL;
bEnvmap = false;
pKVM = NULL;
}
CHLSL_Image::~CHLSL_Image()
{
DestroyImage();
}
void CHLSL_Image::DestroyImage()
{
if ( pVtf )
DestroyVTFTexture( pVtf );
pVtf = NULL;
}
bool CHLSL_Image::LoadFromVTF( const char *path )
{
pVtf = CreateVTFTexture();
if ( !pVtf )
return false;
CUtlBuffer vtf;
bool bSuccess = g_pFullFileSystem->ReadFile( path, 0, vtf ) && pVtf->Unserialize( vtf );
vtf.Purge();
if ( !bSuccess )
{
DestroyImage();
return false;
}
pVtf->ConvertImageFormat( IMAGE_FORMAT_DEFAULT, false );
bEnvmap = ( pVtf->Flags() & TEXTUREFLAGS_ENVMAP ) != 0;
return true;
}
void CHLSL_Image::InitProceduralMaterial()
{
}
void CHLSL_Image::DestroyProceduralMaterial()
{
}
#include "bitmap/tgawriter.h"
struct ValveJpegErrorHandler_t
{
struct jpeg_error_mgr m_Base;
jmp_buf m_ErrorContext;
};
static void ValveJpegErrorHandler( j_common_ptr cinfo )
{
ValveJpegErrorHandler_t *pError = reinterpret_cast< ValveJpegErrorHandler_t * >( cinfo->err );
char buffer[ JMSG_LENGTH_MAX ];
( *cinfo->err->format_message )( cinfo, buffer );
Warning( "%s\n", buffer );
longjmp( pError->m_ErrorContext, 1 );
}
CUtlVector<JOCTET> jOut;
#define BLOCK_SIZE 16384
void jInit_destination(j_compress_ptr cinfo)
{
jOut.Purge();
jOut.SetSize(BLOCK_SIZE);
cinfo->dest->next_output_byte = &jOut[0];
cinfo->dest->free_in_buffer = jOut.Count();
}
boolean jEmpty_output_buffer(j_compress_ptr cinfo)
{
size_t oldsize = jOut.Count();
jOut.SetCountNonDestructively(oldsize + BLOCK_SIZE);
cinfo->dest->next_output_byte = &jOut[oldsize];
cinfo->dest->free_in_buffer = jOut.Count() - oldsize;
return true;
}
void jTerm_destination(j_compress_ptr cinfo)
{
jOut.SetCountNonDestructively(jOut.Count() - cinfo->dest->free_in_buffer);
}
void CHLSL_Image::CreateScreenshot( CNodeView *n, const char *filepath )
{
Vector4D graphBounds;
n->GetGraphBoundaries( graphBounds );
int vsize_x, vsize_y;
n->GetSize( vsize_x, vsize_y );
const float zoomFactor = 1.0f / clamp( sedit_screenshot_zoom.GetFloat(), 0.01f, 100.0f );
float nodespace_width = graphBounds.z - graphBounds.x;
float nodespace_height = graphBounds.w - graphBounds.y;
float nodespace_width_pershot = vsize_x * zoomFactor;
float nodespace_height_pershot = vsize_y * zoomFactor;
int numshots_x = ceil( nodespace_width / nodespace_width_pershot );
int numshots_y = ceil( nodespace_height / nodespace_height_pershot );
Vector2D extraSpace;
extraSpace.x = (nodespace_width_pershot*numshots_x) - nodespace_width;
extraSpace.y = (nodespace_height_pershot*numshots_y) - nodespace_height;
extraSpace *= 0.5f;
n->vecScreenshotBounds.Init( graphBounds.x - extraSpace.x,
graphBounds.y - extraSpace.y,
graphBounds.z + extraSpace.x,
graphBounds.w + extraSpace.y );
int tgapixels_x = numshots_x * vsize_x - numshots_x;
int tgapixels_y = numshots_y * vsize_y - numshots_y;
unsigned int targetSize = tgapixels_x * 3 * tgapixels_y;
unsigned char *pTGA = ( unsigned char * )malloc( targetSize );
if ( !pTGA )
{
Warning( "Not enough memory available (failed to malloc %u bytes).\n", targetSize );
}
Vector2D pos_old = n->AccessViewPos();
float zoom_old = n->AccessViewZoom();
n->bRenderingScreenShot = true;
n->AccessViewZoom() = zoomFactor;
int vp_x, vp_y;
vp_x = vp_y = 0;
n->LocalToScreen( vp_x, vp_y );
int screen_sx, screen_sy;
engine->GetScreenSize( screen_sx, screen_sy );
vp_x++;
vp_y++;
vsize_x--;
vsize_y--;
n->AccessViewPos().Init();
CViewSetup view2D;
view2D.x = 0;
view2D.y = 0;
view2D.width = screen_sx;
view2D.height = screen_sy;
view2D.m_bRenderToSubrectOfLargerScreen = false;
Frustum _fplanes;
CMatRenderContextPtr pRenderContext( materials );
#ifdef SHADER_EDITOR_DLL_2006
render->Push2DView( view2D, 0, false, NULL, _fplanes );
#else
render->Push2DView( view2D, 0, NULL, _fplanes );
#endif
pRenderContext->PushRenderTargetAndViewport( NULL, view2D.x, view2D.y, view2D.width, view2D.height );
// bool bSuccess = TGAWriter::WriteDummyFileNoAlloc( filepath, tgapixels_x, tgapixels_y, IMAGE_FORMAT_RGBA8888 );
// Assert( bSuccess );
if ( pTGA )
{
for ( int sX = 0; sX < numshots_x; sX ++ )
{
for ( int sY = 0; sY < numshots_y; sY ++ )
{
Vector2D basepos( graphBounds.x + nodespace_width_pershot * 0.5f, graphBounds.w - nodespace_height_pershot * 0.5f );
basepos.x += sX * nodespace_width_pershot;
basepos.y -= sY * nodespace_height_pershot;
basepos.x *= -1.0f;
basepos += extraSpace;
n->AccessViewPos() = basepos;
pRenderContext->ClearColor4ub( 0, 0, 0, 0 );
pRenderContext->ClearBuffers( true, true );
vgui::ipanel()->PaintTraverse( n->GetVPanel(), true );
unsigned int sizeimg = vsize_x * 3 * vsize_y;
unsigned char *pImage = ( unsigned char * )malloc( sizeimg );
if ( pImage )
{
pRenderContext->ReadPixels( vp_x, vp_y, vsize_x, vsize_y, pImage, IMAGE_FORMAT_RGB888 );
for ( int pX = 0; pX < vsize_x; pX ++ )
{
for ( int pY = 0; pY < vsize_y; pY ++ )
{
int targetpixel = (sX * vsize_x + pX) * 3 +
( sY * vsize_y + pY ) * tgapixels_x * 3;
int srcpixel = pX * 3 + pY * vsize_x * 3;
Q_memcpy( &pTGA[targetpixel], &pImage[srcpixel], 3 );
}
}
#if 0
#if DEBUG
bool bSuccess =
#endif
TGAWriter::WriteRectNoAlloc( pImage, filepath, sX * vsize_x, sY * vsize_y, vsize_x, vsize_y, 0, IMAGE_FORMAT_RGB888 );
#if DEBUG
Assert( bSuccess );
#endif
#endif
free( pImage );
}
else
Warning( "Tiling error (failed to malloc %u bytes).\n", sizeimg );
}
}
}
if ( pTGA )
{
//unsigned int iMaxTGASize = 1024 + (tgapixels_x * tgapixels_y * 3);
//void *pTGA_BUFFER = malloc( iMaxTGASize );
//if ( pTGA_BUFFER )
//{
// CUtlBuffer buffer( pTGA_BUFFER, iMaxTGASize );
// TGAWriter::WriteToBuffer( pTGA, buffer, tgapixels_x, tgapixels_y, IMAGE_FORMAT_RGB888, IMAGE_FORMAT_RGB888 );
// filesystem->AsyncWrite( filepath, buffer.Base(), buffer.TellPut(), true );
//}
//else
//{
// Warning( "Not enough memory available (failed to malloc %u bytes).\n", iMaxTGASize );
//}
jpeg_compress_struct jInfo;
ValveJpegErrorHandler_t jErr;
jpeg_destination_mgr jDest;
jInfo.err = jpeg_std_error( &jErr.m_Base );
jInfo.err->error_exit = &ValveJpegErrorHandler;
jpeg_create_compress( &jInfo );
jInfo.dest = &jDest;
jInfo.dest->init_destination = &jInit_destination;
jInfo.dest->empty_output_buffer = &jEmpty_output_buffer;
jInfo.dest->term_destination = &jTerm_destination;
jInfo.image_width = tgapixels_x;
jInfo.image_height = tgapixels_y;
jInfo.input_components = 3;
jInfo.in_color_space = JCS_RGB;
jpeg_set_defaults( &jInfo );
jpeg_set_quality( &jInfo, clamp( sedit_screenshot_quali.GetInt(), 1, 100 ), FALSE );
jpeg_start_compress(&jInfo, TRUE);
JSAMPROW row_pointer[1];
int row_stride;
row_stride = jInfo.image_width * 3;
while (jInfo.next_scanline < jInfo.image_height)
{
row_pointer[0] = &pTGA[jInfo.next_scanline * row_stride];
jpeg_write_scanlines(&jInfo, row_pointer, 1);
}
jpeg_finish_compress(&jInfo);
jpeg_destroy_compress(&jInfo);
void *pBUFFER = malloc( jOut.Count() );
Q_memcpy( pBUFFER, jOut.Base(), jOut.Count() );
filesystem->AsyncWrite( filepath, pBUFFER, jOut.Count(), true );
jOut.Purge();
free( pTGA );
}
pRenderContext->PopRenderTargetAndViewport();
render->PopView( _fplanes );
n->bRenderingScreenShot = false;
n->AccessViewPos() = pos_old;
n->AccessViewZoom() = zoom_old;
}

View File

@@ -0,0 +1,35 @@
#ifndef CHLSL_IMAGE_H
#define CHLSL_IMAGE_H
#include "vtf/vtf.h"
#include "editorCommon.h"
class CHLSL_Image
{
public:
CHLSL_Image();
~CHLSL_Image();
void DestroyImage();
bool LoadFromVTF( const char *path );
bool IsEnvmap(){ return bEnvmap; };
IVTFTexture *GetVTF(){return pVtf;};
void InitProceduralMaterial();
void DestroyProceduralMaterial();
static void CreateScreenshot( CNodeView *n, const char *filepath );
private:
IVTFTexture *pVtf;
bool bEnvmap;
IMaterial *pProcMat;
KeyValues *pKVM;
};
#endif

View File

@@ -0,0 +1,829 @@
#include "cbase.h"
#include "editorCommon.h"
CHLSL_Vertex::CHLSL_Vertex()
{
Q_memset( this, 0, sizeof(CHLSL_Vertex) );
}
CHLSL_Vertex::~CHLSL_Vertex()
{
}
//CHLSL_Vertex::CHLSL_Vertex( const CHLSL_Vertex &o )
//{
//}
CHLSL_Triangle::CHLSL_Triangle()
{
vertices[ 0 ] = NULL;
vertices[ 1 ] = NULL;
vertices[ 2 ] = NULL;
}
CHLSL_Triangle::~CHLSL_Triangle()
{
}
//CHLSL_Triangle::CHLSL_Triangle( const CHLSL_Triangle &o )
//{
//}
CHLSL_Mesh::CHLSL_Mesh()
{
m_Vertices = NULL;
m_iNumVertices = 0;
m_Triangles = NULL;
m_iNumTriangles = 0;
}
CHLSL_Mesh::~CHLSL_Mesh()
{
delete [] m_Vertices;
delete [] m_Triangles;
}
CHLSL_Mesh::CHLSL_Mesh( const CHLSL_Mesh &o )
{
m_iNumVertices = o.m_iNumVertices;
m_iNumTriangles = o.m_iNumTriangles;
m_Vertices = new CHLSL_Vertex[m_iNumVertices];
Q_memcpy(m_Vertices,o.m_Vertices,sizeof(CHLSL_Vertex)*m_iNumVertices);
m_Triangles = new CHLSL_Triangle[m_iNumTriangles];
Q_memcpy(m_Triangles,o.m_Triangles,sizeof(CHLSL_Triangle)*m_iNumTriangles);
int vertexOffset = m_Vertices - o.m_Vertices;
for ( int i = 0; i < m_iNumTriangles; i++ )
{
m_Triangles[i].vertices[0] += vertexOffset;
m_Triangles[i].vertices[1] += vertexOffset;
m_Triangles[i].vertices[2] += vertexOffset;
}
}
void CHLSL_Mesh::CreateCylinder( float size, int subdiv )
{
subdiv /= 2;
delete [] m_Vertices;
delete [] m_Triangles;
int num_verts_u = subdiv + 1;
int num_verts_v = subdiv + 1;
int num_verts_side = num_verts_u * num_verts_v;
int num_verts_top = 1 + num_verts_u - 1;
m_iNumVertices = num_verts_side + num_verts_top * 2;
int num_tris_u = (num_verts_u-1);
int num_tris_v = (num_verts_v-1);
int num_tris_side = num_tris_u * num_tris_v * 2;
int num_tris_top = num_tris_u;
m_iNumTriangles = num_tris_side + num_tris_top * 2;
m_Vertices = new CHLSL_Vertex[ m_iNumVertices ];
m_Triangles = new CHLSL_Triangle[ m_iNumTriangles ];
QAngle rotate( 0, 0, 0 );
float yaw_step = 360.0f / (num_verts_u-1);
float up_step = size * 2.0f / (num_verts_v-1);
float size_radius = size * 0.5f;
Vector fwd, right, up, pos;
/// verts for side
for ( int vert_u = 0; vert_u < num_verts_u; vert_u++ )
{
AngleVectors( rotate, &fwd, &right, &up );
pos = up * size + fwd * size_radius;
for ( int vert_v = 0; vert_v < num_verts_v; vert_v++ )
{
int vindex = vert_u * num_verts_v +
vert_v;
Assert( vindex < m_iNumVertices );
CHLSL_Vertex &vert = m_Vertices[ vindex ];
Q_memcpy( vert.normal, fwd.Base(), sizeof( float ) * 3 );
Q_memcpy( vert.pos, pos.Base(), sizeof( float ) * 3 );
vert.uv[0][0] = vert_u / (float)( num_verts_u - 1 );
vert.uv[0][1] = vert_v / (float)( num_verts_v - 1 );
pos -= up * up_step;
}
rotate.y += yaw_step;
}
/// verts for top/bottom
for ( int v_side = 0; v_side < 2; v_side++ )
{
rotate.y = 0;
float sign = (v_side==1) ? -1.0f : 1.0f;
up.Init( 0, 0, sign );
Vector height = up * size;
for ( int v_u = 0; v_u < num_verts_top; v_u++ )
{
int vindex = num_verts_side +
v_side * num_verts_top +
v_u;
Assert( vindex < m_iNumVertices );
CHLSL_Vertex &vert = m_Vertices[ vindex ];
Vector2D uv;
Vector pos = height;
if ( v_u > 0 )
{
AngleVectors( rotate, &fwd, NULL, NULL );
pos += fwd * size_radius;
uv.x = -sign * fwd.x * 0.5f + 0.5f;
uv.y = fwd.y * 0.5f + 0.5f;
rotate.y += yaw_step * sign;
}
else
uv.Init( 0.5f, 0.5f );
Q_memcpy( vert.pos, pos.Base(), sizeof( float ) * 3 );
Q_memcpy( vert.normal, up.Base(), sizeof( float ) * 3 );
Q_memcpy( vert.uv, uv.Base(), sizeof( float ) * 2 );
}
}
/// tris for side
for ( int tri_u = 0; tri_u < num_tris_u; tri_u++ )
{
for ( int tri_v = 0; tri_v < num_tris_v; tri_v++ )
{
int tri_0 = tri_u * num_tris_v +
tri_v;
int tri_1 = tri_0 + num_tris_side / 2;
Assert( tri_0 < m_iNumTriangles );
Assert( tri_1 < m_iNumTriangles );
CHLSL_Triangle &t0 = m_Triangles[ tri_0 ];
CHLSL_Triangle &t1 = m_Triangles[ tri_1 ];
int v00 = tri_u * num_verts_v +
tri_v;
int v01 = v00 + 1;
int v10 = (tri_u+1) * num_verts_v +
tri_v;
int v11 = v10 + 1;
Assert( v00 < m_iNumVertices );
Assert( v01 < m_iNumVertices );
Assert( v10 < m_iNumVertices );
Assert( v11 < m_iNumVertices );
t0.vertices[ 0 ] = &m_Vertices[ v00 ];
t0.vertices[ 1 ] = &m_Vertices[ v10 ];
t0.vertices[ 2 ] = &m_Vertices[ v01 ];
t1.vertices[ 0 ] = &m_Vertices[ v10 ];
t1.vertices[ 1 ] = &m_Vertices[ v11 ];
t1.vertices[ 2 ] = &m_Vertices[ v01 ];
}
}
/// tris for top
for ( int dir = 0; dir < 2; dir++ )
{
int v_mid = num_verts_side +
dir * num_verts_top;
Assert( v_mid < m_iNumVertices );
for ( int tri_n = 0; tri_n < num_tris_top; tri_n++ )
{
int tIndex = num_tris_side +
dir * num_tris_top +
tri_n;
Assert( tIndex < m_iNumTriangles );
CHLSL_Triangle &t = m_Triangles[ tIndex ];
int v00 = v_mid + tri_n + 1;
int v10 = (tri_n < (num_tris_top-1)) ? v00 + 1 : v_mid + 1;
Assert( v00 < m_iNumVertices );
Assert( v10 < m_iNumVertices );
t.vertices[ 0 ] = &m_Vertices[ v00 ];
t.vertices[ 1 ] = &m_Vertices[ v_mid ];
t.vertices[ 2 ] = &m_Vertices[ v10 ];
}
}
GenerateTangentSpace();
}
void CHLSL_Mesh::CreatePlane( float size, int subdiv )
{
delete [] m_Vertices;
delete [] m_Triangles;
float dist_per_vert = size / subdiv * 2;
int num_verts_side = ( subdiv + 1 );
m_iNumVertices = num_verts_side * num_verts_side;
int num_tris_side = subdiv;
m_iNumTriangles = num_tris_side * num_tris_side * 2;
m_Vertices = new CHLSL_Vertex[ m_iNumVertices ];
m_Triangles = new CHLSL_Triangle[ m_iNumTriangles ];
Vector fwd( 0, 0, 1 );
Vector right( 0, -1, 0 );
Vector up( -1, 0, 0 );
for ( int vert_right = 0; vert_right < num_verts_side; vert_right++ )
{
for ( int vert_up = 0; vert_up < num_verts_side; vert_up++ )
{
int vertindex = vert_up * num_verts_side +
vert_right;
CHLSL_Vertex &vert = m_Vertices[ vertindex ];
Vector pos = right * -size + up * -size;
pos += right * vert_right * dist_per_vert;
pos += up * vert_up * dist_per_vert;
Vector2D uv( vert_right / (float)(num_verts_side - 1),
vert_up / (float)(num_verts_side - 1) );
Vector n = fwd;
Q_memcpy( vert.normal, n.Base(), sizeof( float ) * 3 );
Q_memcpy( vert.pos, pos.Base(), sizeof( float ) * 3 );
Q_memcpy( vert.uv, uv.Base(), sizeof( float ) * 2 );
}
}
for ( int tri_right = 0; tri_right < num_tris_side; tri_right++ )
{
for ( int tri_up = 0; tri_up < num_tris_side; tri_up++ )
{
int tri_index_0 = tri_up * num_tris_side +
tri_right;
int tri_index_1 = tri_index_0 + m_iNumTriangles / 2;
Assert( tri_index_0 < m_iNumTriangles );
Assert( tri_index_1 < m_iNumTriangles );
int v00_index = tri_up * num_verts_side +
tri_right;
int v10_index = v00_index + 1;
int v01_index = (tri_up+1) * num_verts_side +
tri_right;
int v11_index = v01_index + 1;
Assert( v00_index < m_iNumVertices );
Assert( v01_index < m_iNumVertices );
Assert( v10_index < m_iNumVertices );
Assert( v11_index < m_iNumVertices );
CHLSL_Triangle &t0 = m_Triangles[ tri_index_0 ];
CHLSL_Triangle &t1 = m_Triangles[ tri_index_1 ];
t0.vertices[ 0 ] = &m_Vertices[ v00_index ];
t0.vertices[ 1 ] = &m_Vertices[ v10_index ];
t0.vertices[ 2 ] = &m_Vertices[ v01_index ];
t1.vertices[ 0 ] = &m_Vertices[ v10_index ];
t1.vertices[ 1 ] = &m_Vertices[ v11_index ];
t1.vertices[ 2 ] = &m_Vertices[ v01_index ];
}
}
GenerateTangentSpace();
}
void CHLSL_Mesh::CreateCube( float size, int subdiv )
{
subdiv /= 3;
subdiv = max( subdiv, 1 );
delete [] m_Vertices;
delete [] m_Triangles;
float dist_per_vert = size / subdiv * 2;
int num_verts_side = ( subdiv + 1 );
int num_verts_plane = num_verts_side * num_verts_side;
int num_tris_side = subdiv;
int num_tris_plane = num_tris_side * num_tris_side * 2;
m_iNumVertices = num_verts_plane * 6;
m_iNumTriangles = num_tris_plane * 6;
m_Vertices = new CHLSL_Vertex[ m_iNumVertices ];
m_Triangles = new CHLSL_Triangle[ m_iNumTriangles ];
const Vector orient[6][3] =
{
Vector( 1, 0, 0 ),Vector( 0, 1, 0 ),Vector( 0, 0, -1 ),
Vector( 0, 1, 0 ),Vector( -1, 0, 0 ),Vector( 0, 0, -1 ),
Vector( -1, 0, 0 ),Vector( 0, -1, 0 ),Vector( 0, 0, -1 ),
Vector( 0, -1, 0 ),Vector( 1, 0, 0 ),Vector( 0, 0, -1 ),
Vector( 0, 0, 1 ),Vector( -1, 0, 0 ),Vector( 0, 1, 0 ),
Vector( 0, 0, -1 ),Vector( -1, 0, 0 ),Vector( 0, -1, 0 ),
};
for ( int plane = 0; plane < 6; plane++ )
{
int orientIndex = plane;
Vector fwd = orient[ orientIndex ][0];
Vector right = orient[ orientIndex ][1];
Vector up = orient[ orientIndex ][2];
for ( int vert_right = 0; vert_right < num_verts_side; vert_right++ )
{
for ( int vert_up = 0; vert_up < num_verts_side; vert_up++ )
{
int vertindex = plane * num_verts_plane +
vert_up * num_verts_side +
vert_right;
Assert( vertindex < m_iNumVertices );
CHLSL_Vertex &vert = m_Vertices[ vertindex ];
Vector pos = fwd * size;
pos -= right * size + up * size;
pos += right * vert_right * dist_per_vert;
pos += up * vert_up * dist_per_vert;
Vector2D uv( vert_right / (float)(num_verts_side - 1),
vert_up / (float)(num_verts_side - 1) );
Vector n = fwd;
Q_memcpy( vert.normal, n.Base(), sizeof( float ) * 3 );
Q_memcpy( vert.pos, pos.Base(), sizeof( float ) * 3 );
Q_memcpy( vert.uv, uv.Base(), sizeof( float ) * 2 );
}
}
}
for ( int plane = 0; plane < 6; plane++ )
{
bool bFlip = true; //plane > 2;
for ( int tri_right = 0; tri_right < num_tris_side; tri_right++ )
{
for ( int tri_up = 0; tri_up < num_tris_side; tri_up++ )
{
int tri_index_0 = plane * num_tris_plane +
tri_up * num_tris_side +
tri_right;
int tri_index_1 = tri_index_0 + num_tris_plane / 2;
Assert( tri_index_0 < m_iNumTriangles );
Assert( tri_index_1 < m_iNumTriangles );
int v00_index = plane * num_verts_plane +
tri_up * num_verts_side +
tri_right;
int v10_index = v00_index + 1;
int v01_index = plane * num_verts_plane +
(tri_up+1) * num_verts_side +
tri_right;
int v11_index = v01_index + 1;
Assert( v00_index < m_iNumVertices );
Assert( v01_index < m_iNumVertices );
Assert( v10_index < m_iNumVertices );
Assert( v11_index < m_iNumVertices );
CHLSL_Triangle &t0 = m_Triangles[ tri_index_0 ];
CHLSL_Triangle &t1 = m_Triangles[ tri_index_1 ];
int idx_1 = bFlip ? 1 : 2;
int idx_2 = bFlip ? 2 : 1;
t0.vertices[ 0 ] = &m_Vertices[ v00_index ];
t0.vertices[ idx_1 ] = &m_Vertices[ v10_index ];
t0.vertices[ idx_2 ] = &m_Vertices[ v01_index ];
t1.vertices[ 0 ] = &m_Vertices[ v10_index ];
t1.vertices[ idx_1 ] = &m_Vertices[ v11_index ];
t1.vertices[ idx_2 ] = &m_Vertices[ v01_index ];
}
}
}
GenerateTangentSpace();
}
void CHLSL_Mesh::CreateSphere( float radius, int subdiv )
{
subdiv = max( subdiv, 1 );
delete [] m_Vertices;
delete [] m_Triangles;
int subdivs_u = subdiv;
// two halfs
int subdivs_v = subdivs_u / 2;
float yaw_change = 360.0f / subdivs_u;
float pitch_change = 90.0f / subdivs_v;
int iverts_onehalf = (subdivs_v + 1) * subdivs_u;
m_iNumVertices = iverts_onehalf * 2;
m_Vertices = new CHLSL_Vertex[m_iNumVertices];
int itris_onehalf = (subdivs_v - 1) * subdivs_u * 2 + subdivs_u;
m_iNumTriangles = itris_onehalf * 2;
m_Triangles = new CHLSL_Triangle[m_iNumTriangles];
/// SETUP VERTICES
for ( int goUp = 0; goUp <= subdivs_v; goUp++ )
{
for ( int goRound = 0; goRound < subdivs_u; goRound++ )
{
QAngle center_d( 90, 0, 0 );
center_d.x -= goUp * pitch_change;
center_d.y += goRound * yaw_change;
if ( goUp == subdivs_v )
center_d.x = 0;
Vector dir;
AngleVectors( center_d, &dir );
int VertexSlot = goUp + (1+subdivs_v) * goRound;
//Msg("writing vert: %i\n", VertexSlot);
Vector normal = dir;
normal.NormalizeInPlace();
Vector pos = dir * radius;
if ( !goUp && goRound )
m_Vertices[ VertexSlot ] = m_Vertices[ 0 ];
else
{
//CHLSL_Vertex *pV = new CHLSL_Vertex();
//VectorCopy( pos.Base(), pV->pos );
//VectorCopy( normal.Base(), pV->normal );
//m_Vertices[ VertexSlot ] = *pV;
CHLSL_Vertex pV;
VectorCopy( pos.Base(), pV.pos );
VectorCopy( normal.Base(), pV.normal );
m_Vertices[ VertexSlot ] = pV;
}
}
}
for ( int goUp = 0; goUp <= subdivs_v; goUp++ )
{
for ( int goRound = 0; goRound < subdivs_u; goRound++ )
{
QAngle center_d( -90, 0, 0 );
center_d.x += goUp * pitch_change;
center_d.y += goRound * yaw_change;
if ( goUp == subdivs_v )
center_d.x = 0;
Vector dir;
AngleVectors( center_d, &dir );
int VertexSlot = goUp + (1+subdivs_v) * goRound + iverts_onehalf;
//Msg("2- writing vert: %i\n", VertexSlot);
Vector normal = dir;
normal.NormalizeInPlace();
Vector pos = dir * radius;
if ( !goUp && goRound )
m_Vertices[ VertexSlot ] = m_Vertices[ iverts_onehalf ];
else
{
//CHLSL_Vertex *pV = new CHLSL_Vertex();
//VectorCopy( pos.Base(), pV->pos );
//VectorCopy( normal.Base(), pV->normal );
//m_Vertices[ VertexSlot ] = *pV;
CHLSL_Vertex pV;
VectorCopy( pos.Base(), pV.pos );
VectorCopy( normal.Base(), pV.normal );
m_Vertices[ VertexSlot ] = pV;
}
}
}
/// SETUP TRIANGLE LINKS
int TriSlot_A = 0;
for ( int goUp = 1; goUp < subdivs_v; goUp++ )
{
for ( int goRound = 0; goRound < subdivs_u; goRound++ )
{
int VertexSlot = goUp + (1+subdivs_v) * goRound;
TriSlot_A = (goUp-1) * 2 + (subdivs_v-1) * goRound * 2;
//Msg("writing triangle: %i and %i\n", TriSlot, TriSlot+1);
int VertexSlot_NextU = goRound + 1;
if ( VertexSlot_NextU >= subdivs_u )
VertexSlot_NextU = 0;
VertexSlot_NextU = goUp + (1+subdivs_v) * VertexSlot_NextU;
m_Triangles[ TriSlot_A ].vertices[ 0 ] = &m_Vertices[ VertexSlot ];
m_Triangles[ TriSlot_A ].vertices[ 1 ] = &m_Vertices[ VertexSlot + 1 ];
m_Triangles[ TriSlot_A ].vertices[ 2 ] = &m_Vertices[ VertexSlot_NextU ];
TriSlot_A++;
m_Triangles[ TriSlot_A ].vertices[ 0 ] = &m_Vertices[ VertexSlot + 1 ];
m_Triangles[ TriSlot_A ].vertices[ 1 ] = &m_Vertices[ VertexSlot_NextU + 1];
m_Triangles[ TriSlot_A ].vertices[ 2 ] = &m_Vertices[ VertexSlot_NextU ];
}
}
TriSlot_A++;
int TriSlot_B = 0;
for ( int goUp = 1; goUp < subdivs_v; goUp++ )
{
for ( int goRound = 0; goRound < subdivs_u; goRound++ )
{
int VertexSlot = goUp + (1+subdivs_v) * goRound + iverts_onehalf;
TriSlot_B = TriSlot_A + (goUp-1) * 2 + (subdivs_v-1) * goRound * 2;
//Msg("writing triangle: %i and %i\n", TriSlot, TriSlot+1);
int VertexSlot_NextU = goRound + 1;
if ( VertexSlot_NextU >= subdivs_u )
VertexSlot_NextU = 0;
VertexSlot_NextU = goUp + (1+subdivs_v) * VertexSlot_NextU + iverts_onehalf;
m_Triangles[ TriSlot_B ].vertices[ 0 ] = &m_Vertices[ VertexSlot + 1 ];
m_Triangles[ TriSlot_B ].vertices[ 1 ] = &m_Vertices[ VertexSlot ];
m_Triangles[ TriSlot_B ].vertices[ 2 ] = &m_Vertices[ VertexSlot_NextU ];
TriSlot_B++;
m_Triangles[ TriSlot_B ].vertices[ 0 ] = &m_Vertices[ VertexSlot + 1 ];
m_Triangles[ TriSlot_B ].vertices[ 1 ] = &m_Vertices[ VertexSlot_NextU ];
m_Triangles[ TriSlot_B ].vertices[ 2 ] = &m_Vertices[ VertexSlot_NextU + 1];
}
}
TriSlot_B++;
for ( int goRound = 0; goRound < subdivs_u; goRound++ )
{
int VertexSlot = (1+subdivs_v) * goRound;
int VertexSlot_u_plus = goRound + 1;
if ( VertexSlot_u_plus >= subdivs_u )
VertexSlot_u_plus = 0;
VertexSlot_u_plus = (1+subdivs_v) * VertexSlot_u_plus + 1;
//Msg("writing triangle: %i\n", TriSlot_B);
m_Triangles[ TriSlot_B ].vertices[ 1 ] = &m_Vertices[ VertexSlot ];
m_Triangles[ TriSlot_B ].vertices[ 2 ] = &m_Vertices[ VertexSlot + 1 ];
m_Triangles[ TriSlot_B ].vertices[ 0 ] = &m_Vertices[ VertexSlot_u_plus ];
TriSlot_B++;
}
for ( int goRound = 0; goRound < subdivs_u; goRound++ )
{
int VertexSlot = (1+subdivs_v) * goRound + iverts_onehalf;
int VertexSlot_u_plus = goRound + 1;
if ( VertexSlot_u_plus >= subdivs_u )
VertexSlot_u_plus = 0;
VertexSlot_u_plus = (1+subdivs_v) * VertexSlot_u_plus + iverts_onehalf + 1;
//Msg("writing triangle: %i\n", TriSlot_B);
m_Triangles[ TriSlot_B ].vertices[ 0 ] = &m_Vertices[ VertexSlot + 1 ];
m_Triangles[ TriSlot_B ].vertices[ 1 ] = &m_Vertices[ VertexSlot ];
m_Triangles[ TriSlot_B ].vertices[ 2 ] = &m_Vertices[ VertexSlot_u_plus ];
TriSlot_B++;
}
/// SETUP UVS
// m_iNumTriangles
// m_iNumVertices
// iverts_onehalf
for ( int side = 0; side <= 1; side++ )
{
for ( int goUp = 0; goUp <= subdivs_v; goUp++ )
{
for ( int goRound = 0; goRound < subdivs_u; goRound++ )
{
int VertexSlot = goUp + (1+subdivs_v) * goRound + side * iverts_onehalf;
CHLSL_Vertex &vert = m_Vertices[ VertexSlot ];
Vector dir( vert.pos[0], vert.pos[1], 0 );
dir.NormalizeInPlace();
dir *= 0.5f * goUp/(float)subdivs_v;
vert.uv[0][ 0 ] = 0.5f + dir.x;
vert.uv[0][ 1 ] = 0.5f + dir.y;
}
}
}
//for ( int side = 0; side <= 1; side++ )
//{
// for ( int goUp = 0; goUp <= subdivs_v; goUp++ )
// {
// for ( int goRound = 0; goRound < subdivs_u; goRound++ )
// {
// int VertexSlot = goUp + (1+subdivs_v) * goRound + side * iverts_onehalf;
// CHLSL_Vertex &vert = m_Vertices[ VertexSlot ];
// float _a = goRound / float(subdivs_u-1);
// float _b = goUp / float(subdivs_v);
// vert.uv[0][ 0 ] = _a;
// vert.uv[0][ 1 ] = _b;
// }
// }
//}
GenerateTangentSpace();
}
void CHLSL_Mesh::GenerateTangentSpace()
{
//for ( int t = 0; t < m_iNumTriangles; t++ )
//{
// CHLSL_Triangle &tri = m_Triangles[ t ];
// for ( int v = 0; v < 3; v++ )
// {
// CHLSL_Vertex &vert = tri.vertices[ v ];
// }
//}
for (int a = 0; a < m_iNumVertices; a++)
{
CHLSL_Vertex &vert = m_Vertices[a];
Q_memset( vert.tangent_s, 0, sizeof( float ) * 4 );
Q_memset( vert.tangent_t, 0, sizeof( float ) * 3 );
}
CHLSL_Triangle *tri = m_Triangles;
for (int a = 0; a < m_iNumTriangles; a++)
{
CHLSL_Vertex &vert_1 = *tri->vertices[0];
CHLSL_Vertex &vert_2 = *tri->vertices[1];
CHLSL_Vertex &vert_3 = *tri->vertices[2];
Vector v1;
Vector v2;
Vector v3;
VectorCopy( vert_1.pos, v1.Base() );
VectorCopy( vert_2.pos, v2.Base() );
VectorCopy( vert_3.pos, v3.Base() );
#if 0
Vector w1( vert_1.uv[0][0], vert_1.uv[0][1], 0 );
Vector w2( vert_2.uv[0][0], vert_2.uv[0][1], 0 );
Vector w3( vert_3.uv[0][0], vert_3.uv[0][1], 0 );
Vector tan_s_2d( 1, 0, 0 );
Vector tan_t_2d( 0, 1, 0 );
Vector delta_vert2 = v2 - v1;
Vector delta_vert3 = v3 - v1;
Vector delta_uv2 = w2 - w1;
Vector delta_uv3 = w3 - w1;
Vector n;
VectorCopy( vert_1.normal, n.Base() );
delta_vert2 -= DotProduct( delta_vert2, n ) * n;
delta_vert3 -= DotProduct( delta_vert3, n ) * n;
//delta_vert2.NormalizeInPlace();
//delta_vert3.NormalizeInPlace();
delta_uv2.NormalizeInPlace();
delta_uv3.NormalizeInPlace();
Vector sdir( vec3_origin );
Vector tdir( vec3_origin );
sdir += DotProduct( tan_s_2d, delta_uv2 ) * delta_vert2;
sdir += DotProduct( tan_s_2d, delta_uv3 ) * delta_vert3;
tdir += DotProduct( tan_t_2d, delta_uv2 ) * delta_vert2;
tdir += DotProduct( tan_t_2d, delta_uv3 ) * delta_vert3;
#else
Vector2D w1( vert_1.uv[0][0], vert_1.uv[0][1] );
Vector2D w2( vert_2.uv[0][0], vert_2.uv[0][1] );
Vector2D w3( vert_3.uv[0][0], vert_3.uv[0][1] );
float x1 = v2.x - v1.x;
float x2 = v3.x - v1.x;
float y1 = v2.y - v1.y;
float y2 = v3.y - v1.y;
float z1 = v2.z - v1.z;
float z2 = v3.z - v1.z;
float s1 = w2.x - w1.x;
float s2 = w3.x - w1.x;
float t1 = w2.y - w1.y;
float t2 = w3.y - w1.y;
float r = (s1 * t2 - s2 * t1);
if ( r != 0 )
r = 1.0f / r;
Vector sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r);
Vector tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
(s1 * z2 - s2 * z1) * r);
#endif
for ( int i = 0; i < 3; i++ )
{
Assert( IsFinite( vert_1.tangent_s[i] ) );
Assert( IsFinite( vert_2.tangent_s[i] ) );
Assert( IsFinite( vert_3.tangent_s[i] ) );
Assert( IsFinite( vert_1.tangent_t[i] ) );
Assert( IsFinite( vert_2.tangent_t[i] ) );
Assert( IsFinite( vert_3.tangent_t[i] ) );
vert_1.tangent_s[i] += sdir[i];
vert_2.tangent_s[i] += sdir[i];
vert_3.tangent_s[i] += sdir[i];
vert_1.tangent_t[i] += tdir[i];
vert_2.tangent_t[i] += tdir[i];
vert_3.tangent_t[i] += tdir[i];
}
//tan1[i1] += sdir;
//tan1[i2] += sdir;
//tan1[i3] += sdir;
//
//tan2[i1] += tdir;
//tan2[i2] += tdir;
//tan2[i3] += tdir;
tri++;
}
for (int a = 0; a < m_iNumVertices; a++)
{
CHLSL_Vertex &vert = m_Vertices[a];
Vector n;
Vector s;
Vector t;
VectorCopy( vert.normal, n.Base() );
VectorCopy( vert.tangent_s, s.Base() );
VectorCopy( vert.tangent_t, t.Base() );
n.NormalizeInPlace();
s.NormalizeInPlace();
t.NormalizeInPlace();
#if 0
Vector delta = s + ( t - s ) * 0.5f;
Vector bidelta;
CrossProduct( delta, n, bidelta );
t = bidelta + ( delta - bidelta ) * 0.5f;
t -= n * DotProduct( t, n );
t.NormalizeInPlace();
CrossProduct( n, t, s );
s.NormalizeInPlace();
#endif
#if 1
//if ( !IsFinite(t.x) || !IsFinite(t.y) || !IsFinite(t.z) )
// t.Init(0,0,1);
//if ( !IsFinite(s.x) || !IsFinite(s.y) || !IsFinite(s.z) )
// s.Init(0,0,1);
s = (s - n * DotProduct(n, s));
t = (t - n * DotProduct(n, t)) * -1.0f;
s.NormalizeInPlace();
t.NormalizeInPlace();
float w = (DotProduct(CrossProduct(n, s), t) < 0.0F) ? 1.0F : -1.0F;
#endif
//t *= -1.0f;
VectorCopy( s.Base(), vert.tangent_s );
VectorCopy( t.Base(), vert.tangent_t );
vert.tangent_s[3] = w;
}
// for (long a = 0; a < m_iNumVertices; a++)
// {
//CHLSL_Vertex &vert = *m_Vertices[a];
// // const Vector& n =
//Vector normal( vert.pos[0], vert.pos[1], vert.pos[2] );
// const Vector& t = tan1[a];
//
// // Gram-Schmidt orthogonalize
// tangent[a] = VectorNormalize( (t - n * DotProduct(n, t)) );
//
// // Calculate handedness
// tangent[a].w = (Dot(Cross(n, t), tan2[a]) < 0.0F) ? -1.0F : 1.0F;
// }
}

View File

@@ -0,0 +1,65 @@
#ifndef CHLSL_MESH_H
#define CHLSL_MESH_H
#include "editorCommon.h"
struct CHLSL_Vertex;
struct CHLSL_Triangle;
class CHLSL_Mesh;
struct CHLSL_Vertex
{
CHLSL_Vertex();
~CHLSL_Vertex();
//CHLSL_Vertex( const CHLSL_Vertex &o );
float pos[3];
float normal[3];
float tangent_s[4];
float tangent_t[3];
float uv[3][2];
};
struct CHLSL_Triangle
{
CHLSL_Triangle();
~CHLSL_Triangle();
//CHLSL_Triangle( const CHLSL_Triangle &o );
CHLSL_Vertex *vertices[3];
};
class CHLSL_Mesh
{
public:
CHLSL_Mesh();
~CHLSL_Mesh();
CHLSL_Mesh( const CHLSL_Mesh &o );
void CreateSphere( float radius, int subdiv );
void CreateCube( float size, int subdiv );
void CreateCylinder( float size, int subdiv );
void CreatePlane( float size, int subdiv );
const int GetNumVertices(){ return m_iNumVertices; };
CHLSL_Vertex *GetVertices(){ return m_Vertices; };
const int GetNumTriangles(){ return m_iNumTriangles; };
CHLSL_Triangle *GetTriangles(){ return m_Triangles; };
private:
CHLSL_Vertex *m_Vertices;
int m_iNumVertices;
CHLSL_Triangle *m_Triangles;
int m_iNumTriangles;
void GenerateTangentSpace();
};
#endif

View File

@@ -0,0 +1,186 @@
#include "cbase.h"
#include "editorCommon.h"
CHLSL_Var::CHLSL_Var()
{
m_tType = HLSLVAR_FLOAT1;
m_bCanBeOverwritten = true;
m_bCanBeDeclared = true;
m_bGotDeclared = false;
bCustomName = false;
_varName = NULL;
pOwner = NULL;
m_iRTMapIndex = 0;
m_pTex = NULL;
m_pMat = NULL;
AllocCheck_Alloc();
}
CHLSL_Var::CHLSL_Var( const CHLSL_Var& other )
{
m_tType = other.m_tType;
m_iRTMapIndex = 0;
m_bCanBeOverwritten = other.m_bCanBeOverwritten;
m_bCanBeDeclared = other.m_bCanBeDeclared;
m_bGotDeclared = other.m_bGotDeclared;
bCustomName = other.bCustomName;
pOwner = NULL;
//if ( m_tType == HLSLVAR_PP_RT )
// m_pTex = other.m_pTex;
//else if ( m_tType == HLSLVAR_PP_MATERIAL )
// m_pMat = other.m_pMat;
//else
{
m_pTex = NULL;
m_pMat = NULL;
}
_varName = NULL;
if ( other._varName != NULL )
{
int len = Q_strlen(other._varName) + 2;
_varName = new char[len];
Q_snprintf(_varName,len,"%s",other._varName);
}
AllocCheck_Alloc();
}
CHLSL_Var::CHLSL_Var( HLSLVariableTypes type )
{
m_bCanBeOverwritten = true;
m_bCanBeDeclared = true;
m_bGotDeclared = false;
bCustomName = false;
_varName = NULL;
m_iRTMapIndex = 0;
pOwner = NULL;
m_tType = type;
m_pTex = NULL;
m_pMat = NULL;
AllocCheck_Alloc();
}
CHLSL_Var::~CHLSL_Var()
{
if ( _varName )
delete [] _varName;
AllocCheck_Free();
}
void CHLSL_Var::Init()
{
m_tType = HLSLVAR_FLOAT1;
m_bCanBeOverwritten = true;
m_bCanBeDeclared = true;
m_bGotDeclared = false;
bCustomName = false;
_varName = NULL;
m_iRTMapIndex = 0;
}
IMaterial *CHLSL_Var::GetMaterial()
{
Assert( m_tType == HLSLVAR_PP_MATERIAL );
//Assert( m_pMat );
return m_pMat;
}
ITexture *CHLSL_Var::GetTexture()
{
Assert( m_tType == HLSLVAR_PP_RT );
//Assert( m_pTex );
return m_pTex;
}
void CHLSL_Var::SetMaterial( IMaterial *pMat )
{
Assert( m_tType == HLSLVAR_PP_MATERIAL );
m_pMat = pMat;
}
void CHLSL_Var::SetTexture( ITexture *pTex )
{
Assert( m_tType == HLSLVAR_PP_RT );
m_pTex = pTex;
}
const bool &CHLSL_Var::WasDeclared()
{
return m_bGotDeclared;
}
const void CHLSL_Var::OnDeclare()
{
m_bGotDeclared = true;
}
void CHLSL_Var::DeclareMe( WriteContext_FXC &context, bool init )
{
if ( WasDeclared() )
return;
char tmp[MAXTARGC];
const char *codename = GetVarCodeNameFromFlag(GetType());
Q_snprintf( tmp, MAXTARGC, "%s ", codename );
context.buf_code.PutString( tmp );
if ( init )
{
Q_snprintf( tmp, MAXTARGC, "%s = (%s)0;\n", GetName(), codename );
context.buf_code.PutString( tmp );
}
OnDeclare();
}
const bool &CHLSL_Var::CanBeOverwritten()
{
return m_bCanBeOverwritten;
}
const void CHLSL_Var::MakeConstantOnly()
{
m_bCanBeOverwritten = false;
m_bCanBeDeclared = false;
}
const void CHLSL_Var::ResetVarInfo()
{
m_bGotDeclared = false;
}
CHLSL_SolverBase *CHLSL_Var::GetOwner()
{
return pOwner;
}
void CHLSL_Var::SetOwner( CHLSL_SolverBase *n )
{
pOwner = n;
}
void CHLSL_Var::Cleanup()
{
}
void CHLSL_Var::SetName( const char *name, bool Custom )
{
delete [] _varName;
int len = Q_strlen( name ) + 2;
_varName = new char[ len ];
Q_snprintf( _varName, len, "%s", name );
bCustomName = Custom;
}
const char *CHLSL_Var::GetName()
{
return _varName;
}
const bool CHLSL_Var::HasCustomName()
{
return bCustomName;
}

View File

@@ -0,0 +1,306 @@
#ifndef CHLSLVAR_H
#define CHLSLVAR_H
#include "editorCommon.h"
class CBaseNode;
class CHLSL_Var
{
public:
CHLSL_Var( HLSLVariableTypes type );
virtual ~CHLSL_Var();
CHLSL_Var( const CHLSL_Var& other );
const HLSLVariableTypes &GetType(){ return m_tType; };
const bool &WasDeclared();
const void OnDeclare();
void DeclareMe( WriteContext_FXC &context, bool init = false );
const bool &CanBeOverwritten();
const void MakeConstantOnly();
CHLSL_SolverBase *GetOwner();
void SetOwner( CHLSL_SolverBase *n );
const void ResetVarInfo();
void Cleanup();
void SetName( const char *name, bool Custom = false );
const char *GetName();
const bool HasCustomName();
const int &GetMapIndex(){ return m_iRTMapIndex; };
void ResetMapIndex(){ m_iRTMapIndex = 0; };
void SetMapIndex( const int idx ){ m_iRTMapIndex = idx; };
public:
IMaterial *GetMaterial();
ITexture *GetTexture();
void SetMaterial( IMaterial *pMat );
void SetTexture( ITexture *pTex );
private:
CHLSL_Var();
void Init();
HLSLVariableTypes m_tType;
int m_iRTMapIndex;
bool m_bCanBeDeclared;
bool m_bGotDeclared;
bool m_bCanBeOverwritten;
char *_varName;
bool bCustomName;
CHLSL_SolverBase *pOwner;
union
{
ITexture *m_pTex;
IMaterial *m_pMat;
};
};
//#if 1 //DEBUG
//extern void PrintError();
//#define ON_VAR_ERROR PrintError();
//#else
//#define ON_VAR_ERROR ((void)0);
//#endif
//
//inline CHLSL_Var& CHLSL_Var::operator=(const CHLSL_Var &o)
//{
// Q_memcpy( m_Vars, o.m_Vars, varsSize );
// return *this;
//}
//inline void CHLSL_Var::LoadType( const CHLSL_Var &o )
//{
// m_iVarSize = o.m_iVarSize;
// m_tType = o.m_tType;
//}
//
//inline CHLSL_Var& CHLSL_Var::operator+=(const CHLSL_Var &o)
//{
// if ( m_tType == o.m_tType )
// {
// for ( int i = 0; i < m_iVarSize; i++ )
// m_Vars[ i ] += o.m_Vars[ i ];
// }
// else if ( m_tType != HLSLVAR_FLOAT1 && o.m_tType == HLSLVAR_FLOAT1 )
// {
// for ( int i = 0; i < m_iVarSize; i++ )
// m_Vars[ i ] += o.m_Vars[ 0 ];
// }
// else
// ON_VAR_ERROR
//
// return *this;
//}
//
//inline CHLSL_Var CHLSL_Var::operator+(const CHLSL_Var& o) const
//{
// CHLSL_Var n;
// if ( m_tType == HLSLVAR_FLOAT1 && o.m_tType != HLSLVAR_FLOAT1 )
// {
// n = o;
// n.LoadType( o );
// n += *this;
// }
// else
// {
// n = *this;
// n.LoadType( *this );
// n += o;
// }
// return n;
//}
//
//inline CHLSL_Var& CHLSL_Var::operator-=(const CHLSL_Var &o)
//{
// if ( m_tType == o.m_tType )
// {
// for ( int i = 0; i < m_iVarSize; i++ )
// m_Vars[ i ] -= o.m_Vars[ i ];
// }
// else if ( m_tType != HLSLVAR_FLOAT1 && o.m_tType == HLSLVAR_FLOAT1 )
// {
// for ( int i = 0; i < m_iVarSize; i++ )
// m_Vars[ i ] -= o.m_Vars[ 0 ];
// }
// else
// ON_VAR_ERROR
//
// return *this;
//}
//
//inline CHLSL_Var CHLSL_Var::operator-(const CHLSL_Var& o) const
//{
// CHLSL_Var n;
//
// if ( m_tType == HLSLVAR_FLOAT1 && o.m_tType != HLSLVAR_FLOAT1 )
// {
// n = o;
// n.LoadType( o );
// n -= *this;
// }
// else
// {
// n = *this;
// n.LoadType( *this );
// n -= o;
// }
//
// return n;
//}
//
//inline CHLSL_Var& CHLSL_Var::operator*=(const CHLSL_Var &o)
//{
// if ( o.m_tType >= HLSLVAR_MATRIX3X3 )
// {
// VMatrix other;
// o.FillMatrix( &o, other );
// if ( m_tType >= HLSLVAR_MATRIX3X3 )
// {
// VMatrix local = GetMatrix();
// VMatrix dst;
// //MatrixMultiply( local, other, dst );
// MatrixMultiply( other, local, dst );
// }
// else if ( m_tType == HLSLVAR_FLOAT3 )
// {
// // 3 * 3x3
// // Vector3DMultiply
//
// // 3 * 4x3
// // Vector3DMultiplyPosition
//
// // 3 * 4x4
// // Vector3DMultiplyPositionProjective
//
// Vector out;
// switch ( o.m_tType )
// {
// case HLSLVAR_MATRIX3X3:
// Vector3DMultiply( other, GetVec3(), out );
// SetVec3( out );
// break;
// case HLSLVAR_MATRIX4X3:
// Vector3DMultiplyPosition( other, GetVec3(), out );
// SetVec3( out );
// break;
// case HLSLVAR_MATRIX4X4:
// // remove auto projection?
//#if 1
// Vector4D tmp( m_Vars[0], m_Vars[1], m_Vars[2], 1 );
// Vector4D outTmp;
// Vector4DMultiply( other, tmp, outTmp );
// //Vector lol( m_Vars[0], m_Vars[1], m_Vars[2] ), derp;
// //Vector3DMultiplyPositionProjective( other, lol, derp );
// //Msg("%f %f %f\n", derp.x, derp.y, derp.z);
// //out.x = outTmp.x; out.y = outTmp.y; out.z = outTmp.z;
// SetVec4( outTmp );
//#else
// Vector3DMultiplyPositionProjective( other, GetVec3(), out );
// SetVec3( out );
//#endif
// break;
// }
// }
// else if ( m_tType == HLSLVAR_FLOAT4 )
// {
// Vector4D out;
// switch ( o.m_tType )
// {
// case HLSLVAR_MATRIX3X3:
// case HLSLVAR_MATRIX4X3:
// case HLSLVAR_MATRIX4X4:
// Vector4DMultiply( other, GetVec4(), out );
// break;
// }
// SetVec4( out );
// }
// else
// ON_VAR_ERROR
// }
// else if ( m_tType == o.m_tType )
// {
// for ( int i = 0; i < m_iVarSize; i++ )
// m_Vars[ i ] *= o.m_Vars[ i ];
// }
// else if ( m_tType != HLSLVAR_FLOAT1 && o.m_tType == HLSLVAR_FLOAT1 )
// {
// for ( int i = 0; i < m_iVarSize; i++ )
// m_Vars[ i ] *= o.m_Vars[ 0 ];
// }
// else
// ON_VAR_ERROR
//
// return *this;
//}
//
//inline CHLSL_Var CHLSL_Var::operator*(const CHLSL_Var& o) const
//{
// CHLSL_Var n;
//
// if ( ( m_tType == HLSLVAR_FLOAT1 && o.m_tType != HLSLVAR_FLOAT1 ) ||
// ( m_tType >= HLSLVAR_MATRIX3X3 ) )
// {
// n = o;
// n.LoadType( o );
// n *= *this;
// }
// else
// {
// n = *this;
// n.LoadType( *this );
// n *= o;
// }
//
// return n;
//}
//
//inline CHLSL_Var& CHLSL_Var::operator/=(const CHLSL_Var &o)
//{
// if ( m_tType == o.m_tType ) //&& m_tType <= HLSLVAR_FLOAT4 )
// {
// for ( int i = 0; i < m_iVarSize; i++ )
// m_Vars[ i ] /= o.m_Vars[ i ];
// }
// else if ( m_tType != HLSLVAR_FLOAT1 && o.m_tType == HLSLVAR_FLOAT1 )
// {
// for ( int i = 0; i < m_iVarSize; i++ )
// m_Vars[ i ] /= o.m_Vars[ 0 ];
// }
// else
// ON_VAR_ERROR
//
// return *this;
//}
//
//inline CHLSL_Var CHLSL_Var::operator/(const CHLSL_Var& o) const
//{
// CHLSL_Var n;
//
// if ( ( m_tType == HLSLVAR_FLOAT1 && o.m_tType != HLSLVAR_FLOAT1 ) ||
// ( m_tType != o.m_tType && m_tType >= HLSLVAR_MATRIX3X3 ) )
// {
// n = o;
// n.LoadType( o );
// n *= *this;
// }
// else
// {
// n = *this;
// n.LoadType( *this );
// n *= o;
// }
//
// return n;
//}
#endif

View File

@@ -0,0 +1,218 @@
#include "cbase.h"
#include "editorCommon.h"
char *CKVPacker::ConvertKVSafeString( const char *pStr, bool bMakeEscaped )
{
//const bool MakeCopy = true;
if ( !pStr || !*pStr )
return NULL;
bool b_LF, b_CR, b_Backslash, b_DQuote;
int iNewSize = 1;
const char *pRead = pStr;
bool bWasEscaping = false;
while ( *pRead )
{
b_LF = *pRead == '\n';
b_CR = *pRead == '\r';
b_Backslash = *pRead == '\\';
b_DQuote = *pRead == '"';
if ( bMakeEscaped &&
(b_LF || b_CR || b_Backslash || b_DQuote) )
iNewSize++;
else if ( !bMakeEscaped &&
b_Backslash && !bWasEscaping ) //&&
{
//(*(pRead+1) == 'n') )
iNewSize--;
bWasEscaping = true;
}
else
bWasEscaping = false;
pRead++;
iNewSize++;
}
char *pOut = new char[ iNewSize ];
pRead = pStr;
char *pWrite = pOut;
while ( *pRead )
{
b_LF = *pRead == '\n';
b_CR = *pRead == '\r';
b_Backslash = *pRead == '\\';
b_DQuote = *pRead == '"';
if ( bMakeEscaped &&
(b_LF || b_CR || b_Backslash || b_DQuote) )
{
*pWrite = '\\';
pWrite++;
if ( b_LF )
*pWrite = 'n';
else if ( b_CR )
*pWrite = 'r';
else if ( b_DQuote )
*pWrite = '\'';
else
*pWrite = '\\';
}
else if ( !bMakeEscaped &&
b_Backslash )
{
pRead++;
if ( *pRead == 'n' )
*pWrite = '\n';
else if ( *pRead == 'r' )
*pWrite = '\r';
else if ( *pRead == '\'' )
*pWrite = '"';
else
*pWrite = *pRead;
}
else
*pWrite = *pRead;
pRead++;
pWrite++;
}
Assert( iNewSize - 1 == pWrite - pOut );
*pWrite = '\0';
//if ( !MakeCopy )
// delete [] pStr;
return pOut;
}
#define KVPACKER_MAX_CHARS_PER_STRING 1023
#define KVPACKER_AMT_STR "_num_strings"
#define KVPACKER_PARTIAL_STR "_partial_"
bool CKVPacker::KVPack( const char *pszStr, const char *pszKey, KeyValues *pKVTarget )
{
if ( !pszStr || !pszKey || !*pszKey )
return false;
const int iStrLen = Q_strlen( pszStr );
const int iNumStrings = iStrLen / KVPACKER_MAX_CHARS_PER_STRING + 1;
char tmpString[ KVPACKER_MAX_CHARS_PER_STRING + 1 ];
const char *pRead = pszStr;
char tmpKey[MAXTARGC];
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s", pszKey, KVPACKER_AMT_STR );
pKVTarget->SetInt( tmpKey, iNumStrings );
for ( int i = 0; i < iNumStrings; i++ )
{
Assert( pRead - pszStr <= iStrLen );
Q_snprintf( tmpString, sizeof(tmpString), "%s", pRead );
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s%02i", pszKey, KVPACKER_PARTIAL_STR, i );
pKVTarget->SetString( tmpKey, tmpString );
pRead += KVPACKER_MAX_CHARS_PER_STRING;
}
return true;
}
char *CKVPacker::KVUnpack( KeyValues *pKVSource, const char *pszKey )
{
if ( !pKVSource || !pszKey || !*pszKey )
return NULL;
char tmpKey[MAXTARGC];
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s", pszKey, KVPACKER_AMT_STR );
const int numEntries = pKVSource->GetInt( tmpKey );
if ( numEntries <= 0 )
return NULL;
int iStrlen = 1;
CUtlVector< const char* > hRowList;
for ( int i = 0; i < numEntries; i++ )
{
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s%02i", pszKey, KVPACKER_PARTIAL_STR, i );
const char *pszStr = pKVSource->GetString( tmpKey );
iStrlen += Q_strlen( pszStr );
hRowList.AddToTail( pszStr );
}
char *pszOut = new char[ iStrlen ];
*pszOut = '\0';
for ( int i = 0; i < hRowList.Count(); i++ )
{
Q_strcat( pszOut, hRowList[i], iStrlen );
}
hRowList.Purge();
return pszOut;
}
bool CKVPacker::KVCopyPacked( KeyValues *pKVSource, KeyValues *pKVTarget, const char *pszKey )
{
if ( !pKVSource || !pKVTarget )
return false;
char tmpKey[MAXTARGC];
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s", pszKey, KVPACKER_AMT_STR );
const int iNumStrings = pKVSource->GetInt( tmpKey );
pKVTarget->SetInt( tmpKey, iNumStrings );
int i = 0;
for ( ; i < iNumStrings; i++ )
{
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s%02i", pszKey, KVPACKER_PARTIAL_STR, i );
pKVTarget->SetString( tmpKey, pKVSource->GetString( tmpKey ) );
}
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s%02i", pszKey, KVPACKER_PARTIAL_STR, i );
for ( KeyValues *pTerminateMe = pKVTarget->FindKey( tmpKey ); pTerminateMe != NULL;
i++, Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s%02i", pszKey, KVPACKER_PARTIAL_STR, i ),
pTerminateMe = pKVTarget->FindKey( tmpKey ) )
{
pKVTarget->RemoveSubKey( pTerminateMe );
pTerminateMe->deleteThis();
}
return true;
}
void CKVPacker::KVClearPacked( const char *pszKey, KeyValues *pKVTarget )
{
if ( !pszKey || !*pszKey || !pKVTarget )
return;
char tmpKey[MAXTARGC];
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s", pszKey, KVPACKER_AMT_STR );
pKVTarget->SetInt( tmpKey, 0 );
int i = 0;
Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s%02i", pszKey, KVPACKER_PARTIAL_STR, i );
for ( KeyValues *pTerminateMe = pKVTarget->FindKey( tmpKey ); pTerminateMe != NULL;
i++, Q_snprintf( tmpKey, sizeof(tmpKey), "%s%s%02i", pszKey, KVPACKER_PARTIAL_STR, i ),
pTerminateMe = pKVTarget->FindKey( tmpKey ) )
{
pKVTarget->RemoveSubKey( pTerminateMe );
pTerminateMe->deleteThis();
}
}

View File

@@ -0,0 +1,22 @@
#ifndef C_KV_PACKER_H
#define C_KV_PACKER_H
#include "cbase.h"
#include "editorCommon.h"
class CKVPacker
{
public:
static char *ConvertKVSafeString( const char *pStr, bool bMakeEscaped );
static bool KVPack( const char *pszStr, const char *pszKey, KeyValues *pKVTarget );
static char *KVUnpack( KeyValues *pKVSource, const char *pszKey );
static bool KVCopyPacked( KeyValues *pKVSource, KeyValues *pKVTarget, const char *pszKey );
static void KVClearPacked( const char *pszKey, KeyValues *pKVTarget );
};
#endif

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