Add files via upload

This commit is contained in:
0TheSpy
2021-06-16 18:48:15 +03:00
committed by GitHub
parent eca863c879
commit 50b5fdf80c
99 changed files with 38600 additions and 0 deletions

304
SpyCustom/sdk/ListPanel.h Normal file
View File

@ -0,0 +1,304 @@
#ifndef LISTPANEL_H
#define LISTPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "utllinkedlist.h"
#include "utlvector.h"
#include "utlrbtree.h"
#include "VGUI.h"
#include "Panel.h"
class KeyValues;
namespace vgui
{
class ScrollBar;
class TextImage;
class ImagePanel;
class Label;
class Button;
class IDraggerEvent;
class FastSortListPanelItem;
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);
class ListPanel : public Panel
{
DECLARE_CLASS_SIMPLE(ListPanel, Panel);
public:
ListPanel(Panel* parent, const char* panelName);
~ListPanel();
enum ColumnFlags_e
{
COLUMN_FIXEDSIZE = 0x01,
COLUMN_RESIZEWITHWINDOW = 0x02,
COLUMN_IMAGE = 0x04,
COLUMN_HIDDEN = 0x08,
COLUMN_UNHIDABLE = 0x10,
};
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);
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);
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;
virtual void SetAllowUserModificationOfColumns(bool allowed);
virtual int AddItem(const KeyValues* data, unsigned int userData, bool bScrollToItem, bool bSortOnAdd);
void SetItemDragData(int itemID, const KeyValues* data);
virtual int GetItemCount(void);
virtual int GetItem(const char* itemName);
virtual KeyValues* GetItem(int itemID);
virtual int GetItemCurrentRow(int itemID);
virtual int GetItemIDFromRow(int currentRow);
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);
virtual void RemoveItem(int itemID);
virtual void RereadAllItems();
virtual void RemoveAll();
virtual void DeleteAllItems();
virtual void GetCellText(int itemID, int column, OUT_Z_BYTECAP(bufferSizeInBytes) wchar_t* buffer, int bufferSizeInBytes);
virtual IImage* GetCellImage(int itemID, int column);
virtual int FirstItem() const;
virtual int NextItem(int iItem) const;
virtual int InvalidItemID() const;
virtual bool IsValidItemID(int itemID);
virtual void SetItemVisible(int itemID, bool state);
virtual void SetItemDisabled(int itemID, bool state);
bool IsItemVisible(int itemID);
virtual void SetFont(HFont font);
virtual void SetImageList(ImageList* imageList, bool deleteImageListWhenDone);
virtual int GetSelectedItemsCount();
virtual int GetSelectedItem(int selectionIndex);
virtual void ClearSelectedItems();
virtual bool IsItemSelected(int itemID);
virtual void AddSelectedItem(int itemID);
virtual void SetSingleSelectedItem(int itemID);
virtual int GetSelectedColumn();
virtual void SetSelectIndividualCells(bool state);
void SetMultiselectEnabled(bool bState);
bool IsMultiselectEnabled() const;
virtual void SetSelectedCell(int row, int column);
virtual bool GetCellAtPos(int x, int y, int& row, int& column);
virtual bool GetCellBounds(int row, int column, int& x, int& y, int& wide, int& tall);
virtual void SetEmptyListText(const char* text);
virtual void SetEmptyListText(const wchar_t* text);
void ResetScrollBar();
virtual void OnCreateDragData(KeyValues* msg);
void SetIgnoreDoubleClick(bool state);
virtual void EnterEditMode(int itemID, int column, vgui::Panel* editPanel);
virtual void LeaveEditMode();
virtual bool IsInEditMode();
MESSAGE_FUNC_INT(ResizeColumnToContents, "ResizeColumnToContents", column);
#ifdef _X360
virtual void NavigateTo();
#endif
int m_nUserConfigFileVersion;
protected:
virtual Panel* GetCellRenderer(int row, int column);
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();
virtual void ApplyUserConfigSettings(KeyValues* userConfig);
virtual void GetUserConfigSettings(KeyValues* userConfig);
virtual bool HasUserConfigSettings();
public:
virtual void SetSortColumnEx(int iPrimarySortColumn, int iSecondarySortColumn, bool bSortAscending);
void GetSortColumnEx(int& iPrimarySortColumn, int& iSecondarySortColumn, bool& bSortAscending) const;
private:
void CleanupItem(FastSortListPanelItem* data);
void IndexItem(int itemID);
void UpdateSelection(vgui::MouseCode code, int x, int y, int row, int column);
void HandleMultiSelection(int itemID, int row, int column);
void HandleAddSelection(int itemID, int row, int column);
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;
};
CUtlLinkedList<column_t, unsigned char> m_ColumnsData;
CUtlVector<unsigned char> m_ColumnsHistory;
CUtlVector<unsigned char> m_CurrentColumns;
int m_iColumnDraggerMoved;
int m_lastBarWidth;
CUtlLinkedList<FastSortListPanelItem*, int> m_DataItems;
CUtlVector<int> m_VisibleItems;
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;
ImagePanel* m_pImagePanel;
Label* m_pLabel;
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;
CUtlVector<int> m_SelectedItems;
int m_LastItemSelected;
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

View File

@ -0,0 +1,72 @@
#ifndef MATERIALSYSTEMUTIL_H
#define MATERIALSYSTEMUTIL_H
#ifdef _WIN32
#pragma once
#endif
#include "imageformat.h"
#include "imaterialsystem.h"
class IMaterial;
class ITexture;
class KeyValues;
class KeyValues;
class CMaterialReference
{
public:
CMaterialReference(char const* pMaterialName = 0, const char* pTextureGroupName = 0, bool bComplain = true);
~CMaterialReference();
void Init(const char* pMaterialName, const char* pTextureGroupName, bool bComplain = true);
void Init(const char* pMaterialName, KeyValues* pVMTKeyValues);
void Init(IMaterial* pMaterial);
void Init(CMaterialReference& ref);
void Init(const char* pMaterialName, const char* pTextureGroupName, KeyValues* pVMTKeyValues);
void Shutdown();
bool IsValid() { return m_pMaterial != 0; }
operator IMaterial* () { return m_pMaterial; }
operator IMaterial* () const { return m_pMaterial; }
operator IMaterial const* () const { return m_pMaterial; }
IMaterial* operator->() { return m_pMaterial; }
private:
IMaterial* m_pMaterial;
};
class CTextureReference
{
public:
CTextureReference();
CTextureReference(const CTextureReference& ref);
~CTextureReference();
void Init(char const* pTexture, const char* pTextureGroupName, bool bComplain = true);
void InitProceduralTexture(const char* pTextureName, const char* pTextureGroupName, int w, int h, ImageFormat fmt, int nFlags);
void InitRenderTarget(int w, int h, RenderTargetSizeMode_t sizeMode, ImageFormat fmt, MaterialRenderTargetDepth_t depth, bool bHDR, char* pStrOptionalName = NULL);
#if defined( _X360 )
void InitRenderTargetTexture(int width, int height, RenderTargetSizeMode_t sizeMode, ImageFormat fmt, MaterialRenderTargetDepth_t depth, bool bHDR, char* pStrOptionalName = NULL);
void InitRenderTargetSurface(int width, int height, ImageFormat fmt, bool bSameAsTexture);
#endif
void Init(ITexture* pTexture);
void Shutdown(bool bDeleteIfUnReferenced = false);
bool IsValid() { return m_pTexture != 0; }
operator ITexture* () { return m_pTexture; }
operator ITexture const* () const { return m_pTexture; }
ITexture* operator->() { return m_pTexture; }
void operator=(CTextureReference& ref);
private:
ITexture* m_pTexture;
};
#endif

262
SpyCustom/sdk/Menu.h Normal file
View File

@ -0,0 +1,262 @@
#ifndef MENU_H
#define MENU_H
#ifdef _WIN32
#pragma once
#endif
#include "Panel.h"
#include "Label.h"
#include "utllinkedlist.h"
#include "utlvector.h"
namespace vgui
{
class MenuItem;
class ScrollBar;
class MenuSeparator;
class Menu : public Panel
{
DECLARE_CLASS_SIMPLE(Menu, Panel);
friend class MenuItem;
public:
enum MenuDirection_e
{
LEFT,
RIGHT,
UP,
DOWN,
CURSOR,
ALIGN_WITH_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);
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);
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);
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);
virtual int AddMenuItem(MenuItem* panel);
virtual void AddSeparator();
virtual void AddSeparatorAfterItem(int itemID);
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);
void DeleteItem(int itemID);
void DeleteAllItems();
virtual void SetFixedWidth(int width);
void SetContentAlignment(Label::Alignment alignment);
virtual void SetMenuItemHeight(int itemHeight);
virtual int GetMenuItemHeight() const;
virtual void SetNumberOfVisibleItems(int numItems);
void EnableUseMenuManager(bool bUseMenuManager);
virtual void PerformLayout(void);
virtual void SetBorder(class IBorder* border);
virtual void ApplySchemeSettings(IScheme* pScheme);
enum MenuTypeAheadMode
{
COMPAT_MODE = 0,
HOT_KEY_MODE,
TYPE_AHEAD_MODE,
};
virtual void SetTypeAheadMode(MenuTypeAheadMode mode);
virtual int GetTypeAheadMode();
virtual void OnKeyTyped(wchar_t unichar);
virtual void OnKeyCodeTyped(KeyCode code);
virtual void SetVisible(bool state);
virtual void ActivateItem(int itemID);
virtual void SilentActivateItem(int itemID);
virtual void ActivateItemByRow(int row);
virtual int GetActiveItem();
virtual int GetItemCount();
virtual int GetMenuID(int index);
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();
void SetMenuItemChecked(int itemID, bool state);
bool IsChecked(int index);
void SetMinimumWidth(int width);
int GetMinimumWidth();
virtual void SetFgColor(Color newColor);
virtual void SetBgColor(Color newColor);
virtual void SetFont(HFont font);
void SetCurrentKeyBinding(int itemID, char const* hotkey);
void ForceCalculateWidth();
void SetUseFallbackFont(bool bState, HFont hFallback);
protected:
int AddMenuItemCharCommand(MenuItem* item, const char* command, Panel* target, const KeyValues* userData);
int AddMenuItemKeyValuesCommand(MenuItem* item, KeyValues* message, Panel* target, const KeyValues* userData);
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);
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,
MENU_UP = -1,
MENU_DOWN = 1
};
#ifdef DBGFLAG_VALIDATE
virtual void Validate(CValidator& validator, char* pchName);
#endif
private:
MenuItem* GetParentMenuItem();
int m_iMenuItemHeight;
int m_iFixedWidth;
int m_iMinimumWidth;
int m_iNumVisibleLines;
ScrollBar* m_pScroller;
CUtlLinkedList<MenuItem*, int> m_MenuItems;
CUtlVector<int> m_VisibleSortedItems;
CUtlVector<int> m_SortedItems;
CUtlVector<int> m_Separators;
CUtlVector<MenuSeparator*> m_SeparatorPanels;
bool _sizedForScrollBar : 1;
bool m_bUseFallbackFont : 1;
bool _recalculateWidth : 1;
bool m_bUseMenuManager : 1;
int _menuWide;
int m_iCurrentlySelectedItemID;
int m_iInputMode;
int m_iCheckImageWidth;
int m_iProportionalScrollBarSize;
Label::Alignment m_Alignment;
Color _borderDark;
int m_iActivatedItem;
HFont m_hItemFont;
HFont m_hFallbackItemFont;
#define TYPEAHEAD_BUFSIZE 256
MenuTypeAheadMode m_eTypeAheadMode;
wchar_t m_szTypeAheadBuf[TYPEAHEAD_BUFSIZE];
int m_iNumTypeAheadChars;
double m_fLastTypeAheadTime;
};
}
#endif

107
SpyCustom/sdk/MenuItem.h Normal file
View File

@ -0,0 +1,107 @@
#ifndef MENUITEM_H
#define MENUITEM_H
#ifdef _WIN32
#pragma once
#endif
#include "VGUI.h"
#include "Button.h"
#include "Menu.h"
namespace vgui
{
class IBorder;
class TextImage;
class Menu;
class Image;
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();
virtual void FireActionSignal();
virtual bool CanBeDefaultButton(void);
void OnCursorEntered();
void OnCursorExited();
void CloseCascadeMenu();
MESSAGE_FUNC(OnKillFocus, "MenuClose");
bool HasMenu();
void SetTextImageSize(int wide, int tall);
void GetTextImageSize(int& wide, int& tall);
void GetArrowImageSize(int& wide, int& tall);
void GetCheckImageSize(int& wide, int& tall);
Menu* GetMenu();
virtual void PerformLayout();
void OnCursorMoved(int x, int y);
MESSAGE_FUNC(ArmItem, "ArmItem");
MESSAGE_FUNC(DisarmItem, "DisarmItem");
bool IsItemArmed();
void OpenCascadeMenu();
bool IsCheckable();
bool IsChecked();
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");
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;
bool m_bCheckable;
bool m_bChecked;
TextImage* m_pCascadeArrow;
Image* m_pCheck;
TextImage* m_pBlankCheck;
TextImage* m_pCurrentKeyBinding;
KeyValues* m_pUserData;
};
}
#endif

327
SpyCustom/sdk/MessageMap.h Normal file
View File

@ -0,0 +1,327 @@
#ifndef MESSAGEMAP_H
#define MESSAGEMAP_H
#ifdef _WIN32
#pragma once
#endif
#include "dmxelement.h"
#pragma pointers_to_members( full_generality, virtual_inheritance )
namespace vgui
{
#ifndef ARRAYSIZE
#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0]))
#endif
enum DataType_t
{
DATATYPE_VOID,
DATATYPE_CONSTCHARPTR,
DATATYPE_INT,
DATATYPE_FLOAT,
DATATYPE_PTR,
DATATYPE_BOOL,
DATATYPE_KEYVALUES,
DATATYPE_CONSTWCHARPTR,
DATATYPE_UINT64,
DATATYPE_HANDLE,
};
class Panel;
typedef uintp VPANEL;
typedef void (Panel::* MessageFunc_t)(void);
#pragma warning(disable:4121)
struct MessageMapItem_t
{
const char* name;
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; \
}
#define VGUI_USEKEYBINDINGMAPS 1
#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
#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
#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; \
#define MESSAGE_FUNC( name, scriptname ) _MessageFuncCommon( name, scriptname, 0, 0, 0, 0, 0 ); virtual void name( void )
#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_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 )
#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_PTR, #p1, vgui::DATATYPE_PTR, #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 )
#define MESSAGE_FUNC_PARAMS( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_KEYVALUES, NULL, 0, 0 ); virtual void name( KeyValues *p1 )
#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 )
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);
#define MAP_MESSAGE( type, name, func ) { name, (vgui::MessageFunc_t)(&type::func), 0 }
#define MAP_MESSAGE_PARAMS( type, name, func ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_KEYVALUES, NULL }
#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 }
#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 }
struct PanelMap_t
{
MessageMapItem_t* dataDesc;
int dataNumFields;
const char* dataClassName;
PanelMap_t* baseMap;
int processed;
};
#define DECLARE_PANELMAP() \
static vgui::PanelMap_t m_PanelMap; \
static vgui::MessageMapItem_t m_MessageMap[]; \
virtual vgui::PanelMap_t *GetPanelMap( void );
#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);
class CBuildFactoryHelper
{
public:
static CBuildFactoryHelper* m_sHelpers;
public:
CBuildFactoryHelper(char const* className, PANELCREATEFUNC func);
CBuildFactoryHelper* GetNext(void);
char const* GetClassName() const;
vgui::Panel* CreatePanel();
static vgui::Panel* InstancePanel(char const* className);
static void GetFactoryNames(CUtlVector< char const* >& list);
static CDmxElement* CreatePanelDmxElement(vgui::Panel* pPanel);
static Panel* UnserializeDmxElementPanel(CDmxElement* pElement);
static bool Serialize(CUtlBuffer& buf, vgui::Panel* pPanel);
static bool Unserialize(Panel** ppPanel, CUtlBuffer& buf, const char* pFileName = NULL);
private:
static bool HasFactory(char const* className);
CBuildFactoryHelper* m_pNext;
int m_Type;
PANELCREATEFUNC m_CreateFunc;
char const* m_pClassName;
};
#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;
#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;
}
#endif

15
SpyCustom/sdk/MouseCode.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef MOUSECODE_H
#define MOUSECODE_H
#ifdef _WIN32
#pragma once
#endif
#include "ButtonCode.h"
namespace vgui
{
typedef ButtonCode_t MouseCode;
}
#endif

70
SpyCustom/sdk/PHandle.h Normal file
View File

@ -0,0 +1,70 @@
#ifndef PHANDLE_H
#define PHANDLE_H
#ifdef _WIN32
#pragma once
#endif
#include "VGUI.h"
namespace vgui
{
class Panel;
class PHandle
{
public:
PHandle() : m_iPanelID(INVALID_PANEL) {}
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;
};
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;
};
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

962
SpyCustom/sdk/Panel.h Normal file
View File

@ -0,0 +1,962 @@
#ifndef PANEL_H
#define PANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "utlflags.h"
#include "vgui.h"
#include "Dar.h"
#include "MessageMap.h"
#if defined( VGUI_USEKEYBINDINGMAPS )
#include "KeyBindingMap.h"
#endif
#include "IClientPanel.h"
#include "IScheme.h"
#include "Controls.h"
#include "PHandle.h"
#include "PanelAnimationVar.h"
#include "color.h"
#include "keyvalues.h"
#include "ikeyvaluessystem.h"
#include "utlsymbol.h"
#include "BuildGroup.h"
#include "dmxelement.h"
#ifdef PostMessage
#undef PostMessage
#endif
#ifdef SetCursor
#undef SetCursor
#endif
class CUtlBuffer;
struct DmxElementUnpackStructure_t;
namespace vgui
{
#if !defined( _GAMECONSOLE )
#define VGUI_USEDRAGDROP 1
#endif
#if defined( VGUI_USEKEYBINDINGMAPS )
struct PanelKeyBindingMap;
#endif
template< class T >
inline T* SETUP_PANEL(T* panel)
{
panel->MakeReadyForUse();
return panel;
}
#define CREATE_PANEL(type, parent, name) (SETUP_PANEL(new type(parent, name)))
#if defined( VGUI_USEDRAGDROP )
struct DragDrop_t;
class Menu;
#endif
class Panel;
struct SizerAddArgs_t
{
SizerAddArgs_t()
{
m_flExpandFactor = 0.0f;
m_nPadding = 5;
m_bMinorExpand = true;
m_nMinX = -1;
m_nMinY = -1;
m_bIgnoreMemberMin = false;
}
SizerAddArgs_t& Expand(float flExpandFactor) { m_flExpandFactor = flExpandFactor; return *this; }
SizerAddArgs_t& Padding(int nPadding) { m_nPadding = nPadding; return *this; }
SizerAddArgs_t& MinorExpand(bool bMinorExpand) { m_bMinorExpand = bMinorExpand; return *this; }
SizerAddArgs_t& MinSize(int nMinX, int nMinY) { m_nMinX = nMinX; m_nMinY = nMinY; return *this; }
SizerAddArgs_t& MinX(int nMinX) { m_nMinX = nMinX; return *this; }
SizerAddArgs_t& MinY(int nMinY) { m_nMinY = nMinY; return *this; }
SizerAddArgs_t& IgnoreMemberMin(bool bIgnoreMemberMin = true) { m_bIgnoreMemberMin = bIgnoreMemberMin; return *this; }
SizerAddArgs_t& FixedSize(int nX, int nY)
{
IgnoreMemberMin(true);
MinSize(nX, nY);
Expand(0.f);
MinorExpand(false);
return *this;
}
float m_flExpandFactor;
int m_nPadding;
bool m_bMinorExpand;
int m_nMinX;
int m_nMinY;
bool m_bIgnoreMemberMin;
};
enum SizerLayoutDirection_t
{
ESLD_HORIZONTAL,
ESLD_VERTICAL
};
enum SizerElementType_t
{
ESET_SIZER,
ESET_PANEL,
ESET_SPACER,
};
class CSizerBase
{
public:
CSizerBase();
virtual ~CSizerBase();
int GetElementCount() { return m_Members.Count(); }
SizerElementType_t GetElementType(int i);
Panel* GetPanel(int i);
void SetElementArgs(int nIndex, const SizerAddArgs_t& args) { m_Members[nIndex].Fill(args); }
void InsertPanel(int nIndex, Panel* pPanel, const SizerAddArgs_t& args);
void InsertSizer(int nIndex, CSizerBase* pSizer, const SizerAddArgs_t& args);
void InsertSpacer(int nIndex, const SizerAddArgs_t& args);
void AddPanel(Panel* pPanel, const SizerAddArgs_t& args) { InsertPanel(GetElementCount(), pPanel, args); }
void AddSizer(CSizerBase* pSizer, const SizerAddArgs_t& args) { InsertSizer(GetElementCount(), pSizer, args); }
void AddSpacer(const SizerAddArgs_t& args) { InsertSpacer(GetElementCount(), args); }
void RemoveElement(int i, bool bDelete);
void RemoveAllMembers(bool bDelete);
void GetMinSize(int& OutX, int& OutY);
void RecursiveInvalidateCachedSize();
virtual void DoLayout(int BaseX, int BaseY, int SizeX, int SizeY) = 0;
virtual void CalculateSize() = 0;
protected:
class CSizerMember
{
friend class CSizerBase;
public:
SizerElementType_t GetElementType() const;
Panel* GetPanel() const;
void GetMemberMinSize(int& OutX, int& OutY);
void RecursiveInvalidateCachedSize();
void Place(int BaseX, int BaseY, int SizeX, int SizeY);
float GetExpandFactor() { return m_flExpandFactor; }
bool GetMinorExpand() { return m_bMinorExpand; }
void DiscardOwnedSizer();
bool IsVisible();
void Fill(const SizerAddArgs_t& args);
private:
void RecursiveRemove(bool bDelete);
Panel* m_pPanel;
CSizerBase* m_pSizer;
int m_nPadding;
float m_flExpandFactor;
bool m_bMinorExpand;
bool m_bIgnoreMemberMin;
int m_nMinX;
int m_nMinY;
};
CUtlVector<CSizerMember> m_Members;
int m_nMinXSize;
int m_nMinYSize;
};
inline int SizerMajorAxis(SizerLayoutDirection_t Dir, int X, int Y) { return (Dir == ESLD_HORIZONTAL) ? X : Y; }
inline int SizerMinorAxis(SizerLayoutDirection_t Dir, int X, int Y) { return (Dir == ESLD_VERTICAL) ? X : Y; }
inline int SizerXAxis(SizerLayoutDirection_t Dir, int MajorAxis, int MinorAxis) { return (Dir == ESLD_HORIZONTAL) ? MajorAxis : MinorAxis; }
inline int SizerYAxis(SizerLayoutDirection_t Dir, int MajorAxis, int MinorAxis) { return (Dir == ESLD_VERTICAL) ? MajorAxis : MinorAxis; }
class CBoxSizer : public CSizerBase
{
public:
CBoxSizer(SizerLayoutDirection_t LayoutDirection);
virtual void CalculateSize();
virtual void DoLayout(int BaseX, int BaseY, int SizeX, int SizeY);
protected:
SizerLayoutDirection_t m_LayoutDirection;
};
struct OverridableColorEntry
{
char const* name() { return m_pszScriptName; }
char const* m_pszScriptName;
Color* m_pColor;
Color m_colFromScript;
UtlSymId_t m_sColorNameFromScript;
bool m_bOverridden;
};
#define REGISTER_COLOR_AS_OVERRIDABLE( name, scriptname ) \
AddToOverridableColors( &name, scriptname );
#define DECLARE_VGUI_UNPACK() \
DECLARE_DMXELEMENT_UNPACK() \
private: \
static DmxElementUnpackStructure_t *s_pUnpackParams; \
public: \
virtual const DmxElementUnpackStructure_t* GetUnpackStructure() const { return s_pUnpackParams; }
#define DECLARE_VGUI_UNPACK_NAMESPACE( _namespace ) \
template <typename T> friend DmxElementUnpackStructure_t *DmxElementUnpackInit##_namespace(T *); \
private: \
static DmxElementUnpackStructure_t *s_pUnpackParams; \
public: \
virtual const DmxElementUnpackStructure_t* GetUnpackStructure() const { return s_pUnpackParams; }
#define BEGIN_VGUI_UNPACK( _structName ) BEGIN_DMXELEMENT_UNPACK( _structName )
#define END_VGUI_UNPACK( _structName ) \
END_DMXELEMENT_UNPACK( _structName, s_pUnpackParams ) \
DmxElementUnpackStructure_t *_structName::s_pUnpackParams = _structName##_UnpackInit::s_pUnpack;
#define BEGIN_VGUI_UNPACK_NAMESPACE( _nameSpace, _structName ) BEGIN_DMXELEMENT_UNPACK_NAMESPACE( _nameSpace, _structName )
#define END_VGUI_UNPACK_NAMESPACE( _nameSpace, _structName ) \
END_DMXELEMENT_UNPACK_NAMESPACE( _nameSpace, _structName, s_pUnpackParams ) \
DmxElementUnpackStructure_t *_structName::s_pUnpackParams = _namespace##_structName##_UnpackInit::s_pUnpack;
class IPanelAnimationPropertyConverter
{
public:
virtual void GetData(Panel* panel, KeyValues* kv, PanelAnimationMapEntry* entry) = 0;
virtual void SetData(Panel* panel, KeyValues* kv, PanelAnimationMapEntry* entry) = 0;
virtual void InitFromDefault(Panel* panel, PanelAnimationMapEntry* entry) = 0;
};
#if defined( VGUI_USEKEYBINDINGMAPS )
enum KeyBindingContextHandle_t
{
INVALID_KEYBINDINGCONTEXT_HANDLE = 0xffffffff,
};
#endif
#define PANEL_ROUND_CORNER_TOP_LEFT (1 << 0)
#define PANEL_ROUND_CORNER_TOP_RIGHT (1 << 1)
#define PANEL_ROUND_CORNER_BOTTOM_LEFT (1 << 2)
#define PANEL_ROUND_CORNER_BOTTOM_RIGHT (1 << 3)
#define PANEL_ROUND_CORNER_ALL PANEL_ROUND_CORNER_TOP_LEFT | PANEL_ROUND_CORNER_TOP_RIGHT | PANEL_ROUND_CORNER_BOTTOM_LEFT | PANEL_ROUND_CORNER_BOTTOM_RIGHT
class Panel : public IClientPanel
{
DECLARE_CLASS_SIMPLE_NOBASE(Panel);
DECLARE_DMXELEMENT_UNPACK_NAMESPACE(vgui);
public:
static void InitPropertyConverters(void);
static void AddPropertyConverter(char const* typeName, IPanelAnimationPropertyConverter* converter);
Panel();
Panel(Panel* parent);
Panel(Panel* parent, const char* panelName);
Panel(Panel* parent, const char* panelName, HScheme scheme);
virtual ~Panel();
virtual VPANEL GetVPanel() { return _vpanel; }
HPanel ToHandle() const;
void SetName(const char* panelName);
const char* GetName();
const char* GetClassName();
void MakeReadyForUse();
void SetPos(int x, int y);
void GetPos(int& x, int& y);
void SetSize(int wide, int tall);
void GetSize(int& wide, int& tall);
void SetBounds(int x, int y, int wide, int tall);
void GetBounds(int& x, int& y, int& wide, int& tall);
int GetWide();
void SetWide(int wide);
int GetTall();
void SetTall(int tall);
void SetMinimumSize(int wide, int tall);
void GetMinimumSize(int& wide, int& tall);
bool IsBuildModeEditable();
void SetBuildModeEditable(bool state);
bool IsBuildModeDeletable();
void SetBuildModeDeletable(bool state);
bool IsBuildModeActive();
void SetZPos(int z);
int GetZPos(void);
void SetAlpha(int alpha);
int GetAlpha();
virtual void SetVisible(bool state);
virtual bool IsVisible();
virtual bool IsFullyVisible();
virtual VPANEL IsWithinTraverse(int x, int y, bool traversePopups);
MESSAGE_FUNC(Repaint, "Repaint");
virtual void PostMessage(VPANEL target, KeyValues* message, float delaySeconds = 0.0f);
bool IsWithin(int x, int y);
void LocalToScreen(int& x, int& y);
void ScreenToLocal(int& x, int& y);
void ParentLocalToScreen(int& x, int& y);
void MakePopup(bool showTaskbarIcon = true, bool disabled = false);
virtual void OnMove();
virtual Panel* GetParent();
virtual VPANEL GetVParent();
virtual void SetParent(Panel* newParent);
virtual void SetParent(VPANEL newParent);
virtual bool HasParent(VPANEL potentialParent);
int GetChildCount();
Panel* GetChild(int index);
int FindChildIndexByName(const char* childName);
Panel* FindChildByName(const char* childName, bool recurseDown = false);
Panel* FindSiblingByName(const char* siblingName);
void CallParentFunction(KeyValues* message);
virtual bool LookupElementBounds(const char* elementName, int& x, int& y, int& wide, int& tall) { return false; }
virtual void SetAutoDelete(bool state);
virtual bool IsAutoDeleteSet();
virtual void DeletePanel();
virtual void AddActionSignalTarget(Panel* messageTarget);
virtual void AddActionSignalTarget(VPANEL messageTarget);
virtual void RemoveActionSignalTarget(Panel* oldTarget);
virtual void PostActionSignal(KeyValues* message);
virtual bool RequestInfoFromChild(const char* childName, KeyValues* outputData);
virtual void PostMessageToChild(const char* childName, KeyValues* messsage);
virtual void PostMessage(Panel* target, KeyValues* message, float delaySeconds = 0.0f);
virtual bool RequestInfo(KeyValues* outputData);
virtual bool SetInfo(KeyValues* inputData);
virtual void SetSilentMode(bool bSilent);
virtual void InstallMouseHandler(Panel* pHandler);
virtual void SetEnabled(bool state);
virtual bool IsEnabled();
virtual bool IsPopup();
virtual void GetClipRect(int& x0, int& y0, int& x1, int& y1);
virtual void MoveToFront();
enum PinCorner_e
{
PIN_TOPLEFT = 0,
PIN_TOPRIGHT,
PIN_BOTTOMLEFT,
PIN_BOTTOMRIGHT,
PIN_NO,
PIN_CENTER_TOP,
PIN_CENTER_RIGHT,
PIN_CENTER_BOTTOM,
PIN_CENTER_LEFT,
};
enum AutoResize_e
{
AUTORESIZE_NO = 0,
AUTORESIZE_RIGHT,
AUTORESIZE_DOWN,
AUTORESIZE_DOWNANDRIGHT,
};
void SetPinCorner(PinCorner_e pinCorner, int nOffsetX, int nOffsetY);
void SetAutoResize(PinCorner_e pinCorner, AutoResize_e resizeDir, int nPinOffsetX, int nPinOffsetY, int nUnpinnedCornerOffsetX, int nUnpinnedCornerOffsetY);
AutoResize_e GetAutoResize();
PinCorner_e GetPinCorner();
void GetPinOffset(int& dx, int& dy);
void GetResizeOffset(int& dx, int& dy);
void PinToSibling(const char* pszSibling, PinCorner_e pinOurCorner, PinCorner_e pinSibling);
void UpdateSiblingPin(void);
virtual void SetBgColor(Color color);
virtual void SetFgColor(Color color);
virtual Color GetBgColor();
virtual Color GetFgColor();
virtual void SetCursor(HCursor cursor);
virtual HCursor GetCursor();
virtual void RequestFocus(int direction = 0);
virtual bool HasFocus();
virtual void InvalidateLayout(bool layoutNow = false, bool reloadScheme = false);
virtual bool RequestFocusPrev(VPANEL panel = NULL);
virtual bool RequestFocusNext(VPANEL panel = NULL);
virtual void SetTabPosition(int position);
virtual int GetTabPosition();
virtual void SetBorder(IBorder* border);
virtual IBorder* GetBorder();
virtual void SetPaintBorderEnabled(bool state);
virtual void SetPaintBackgroundEnabled(bool state);
virtual void SetPaintEnabled(bool state);
virtual void SetPostChildPaintEnabled(bool state);
virtual void SetPaintBackgroundType(int type);
virtual void GetInset(int& left, int& top, int& right, int& bottom);
virtual void GetPaintSize(int& wide, int& tall);
virtual void SetBuildGroup(BuildGroup* buildGroup);
virtual bool IsBuildGroupEnabled();
virtual bool IsCursorNone();
virtual bool IsCursorOver();
virtual void MarkForDeletion();
virtual bool IsLayoutInvalid();
virtual Panel* HasHotkey(wchar_t key);
virtual bool IsOpaque();
bool IsRightAligned();
bool IsBottomAligned();
bool IsPercentage();
virtual HScheme GetScheme();
virtual void SetScheme(const char* tag);
virtual void SetScheme(HScheme scheme);
virtual Color GetSchemeColor(const char* keyName, IScheme* pScheme);
virtual Color GetSchemeColor(const char* keyName, Color defaultColor, IScheme* pScheme);
virtual void ApplySchemeSettings(IScheme* pScheme);
virtual void ApplySettings(KeyValues* inResourceData);
virtual void OnUnserialized(CDmxElement* pElement);
virtual void GetSettings(KeyValues* outResourceData);
virtual const char* GetDescription();
virtual const char* GetModuleName();
virtual void ApplyUserConfigSettings(KeyValues* userConfig);
virtual void GetUserConfigSettings(KeyValues* userConfig);
virtual bool HasUserConfigSettings();
virtual void OnMessage(const KeyValues* params, VPANEL fromPanel);
MESSAGE_FUNC_CHARPTR(OnCommand, "Command", command);
MESSAGE_FUNC(OnMouseCaptureLost, "MouseCaptureLost");
MESSAGE_FUNC(OnSetFocus, "SetFocus");
MESSAGE_FUNC(OnKillFocus, "KillFocus");
MESSAGE_FUNC(OnDelete, "Delete");
virtual void OnThink();
virtual void OnChildAdded(VPANEL child);
virtual void OnSizeChanged(int newWide, int newTall);
virtual void OnTick();
MESSAGE_FUNC_INT_INT(OnCursorMoved, "OnCursorMoved", x, y);
virtual void OnCursorEntered();
virtual void OnCursorExited();
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code);
virtual void OnMouseWheeled(int delta);
virtual void SetTriplePressAllowed(bool state);
virtual bool IsTriplePressAllowed() const;
virtual void OnMouseTriplePressed(MouseCode code);
static char const* KeyCodeToString(KeyCode code);
static wchar_t const* KeyCodeToDisplayString(KeyCode code);
static wchar_t const* KeyCodeModifiersToDisplayString(KeyCode code, int modifiers);
static KeyCode StringToKeyCode(char const* str);
#if defined( VGUI_USEKEYBINDINGMAPS )
static KeyBindingContextHandle_t CreateKeyBindingsContext(char const* filename, char const* pathID = 0);
virtual void SetKeyBindingsContext(KeyBindingContextHandle_t handle);
virtual KeyBindingContextHandle_t GetKeyBindingsContext() const;
virtual bool IsValidKeyBindingsContext() const;
static int GetPanelsWithKeyBindingsCount(KeyBindingContextHandle_t handle);
static Panel* GetPanelWithKeyBindings(KeyBindingContextHandle_t handle, int index);
static void RevertKeyBindings(KeyBindingContextHandle_t handle);
static void ReloadKeyBindings(KeyBindingContextHandle_t handle);
static void SaveKeyBindings(KeyBindingContextHandle_t handle);
static void SaveKeyBindingsToFile(KeyBindingContextHandle_t handle, char const* filename, char const* pathID = 0);
static void LoadKeyBindings(KeyBindingContextHandle_t handle);
static void LoadKeyBindingsForOnePanel(KeyBindingContextHandle_t handle, Panel* panelOfInterest);
virtual bool IsKeyRebound(KeyCode code, int modifiers);
virtual bool IsKeyOverridden(KeyCode code, int modifiers);
virtual void AddKeyBinding(char const* bindingName, int keycode, int modifiers);
KeyBindingMap_t* LookupBinding(char const* bindingName);
KeyBindingMap_t* LookupBindingByKeyCode(KeyCode code, int modifiers);
void LookupBoundKeys(char const* bindingName, CUtlVector< BoundKey_t* >& list);
BoundKey_t* LookupDefaultKey(char const* bindingName);
PanelKeyBindingMap* LookupMapForBinding(char const* bindingName);
int GetKeyMappingCount();
void RevertKeyBindingsToDefault();
void RemoveAllKeyBindings();
void ReloadKeyBindings();
virtual void EditKeyBindings();
void SaveKeyBindingsToBuffer(int level, CUtlBuffer& buf);
bool ParseKeyBindings(KeyValues* kv);
virtual char const* GetKeyBindingsFile() const;
virtual char const* GetKeyBindingsFilePathID() const;
void SetAllowKeyBindingChainToParent(bool state);
bool IsKeyBindingChainToParentAllowed() const;
#endif
virtual void OnKeyCodePressed(KeyCode code);
virtual void OnKeyCodeTyped(KeyCode code);
virtual void OnKeyTyped(wchar_t unichar);
virtual void OnKeyCodeReleased(KeyCode code);
virtual void OnKeyFocusTicked();
MESSAGE_FUNC(OnMouseFocusTicked, "OnMouseFocusTicked");
virtual void PaintBackground();
virtual void Paint();
virtual void PaintBorder();
virtual void PaintBuildOverlay();
virtual void PostChildPaint();
virtual void PerformLayout();
DECLARE_PANELMAP();
virtual VPANEL GetCurrentKeyFocus();
BaseTooltip* GetTooltip();
void SetTooltip(BaseTooltip* pToolTip, const char* pszText);
virtual bool IsProportional() { return _flags.IsFlagSet(IS_PROPORTIONAL); }
virtual void SetProportional(bool state);
virtual void SetMouseInputEnabled(bool state);
virtual void SetKeyBoardInputEnabled(bool state);
virtual bool IsMouseInputEnabled();
virtual bool IsKeyBoardInputEnabled();
void DisableMouseInputForThisPanel(bool bDisable);
bool IsMouseInputDisabledForThisPanel() const;
virtual void DrawTexturedBox(int x, int y, int wide, int tall, Color color, float normalizedAlpha);
virtual void DrawBox(int x, int y, int wide, int tall, Color color, float normalizedAlpha, bool hollow = false);
virtual void DrawBoxFade(int x, int y, int wide, int tall, Color color, float normalizedAlpha, unsigned int alpha0, unsigned int alpha1, bool bHorizontal, bool hollow = false);
virtual void DrawHollowBox(int x, int y, int wide, int tall, Color color, float normalizedAlpha);
virtual void DrawHollowBox(int x, int y, int wide, int tall, Color color, float normalizedAlpha, int cornerWide, int cornerTall);
unsigned char GetRoundedCorners() { return m_roundedCorners; }
void SetRoundedCorners(unsigned char cornerFlags) { m_roundedCorners = cornerFlags; }
bool ShouldDrawTopLeftCornerRounded() { return 0 != (m_roundedCorners & PANEL_ROUND_CORNER_TOP_LEFT); }
bool ShouldDrawTopRightCornerRounded() { return 0 != (m_roundedCorners & PANEL_ROUND_CORNER_TOP_RIGHT); }
bool ShouldDrawBottomLeftCornerRounded() { return 0 != (m_roundedCorners & PANEL_ROUND_CORNER_BOTTOM_LEFT); }
bool ShouldDrawBottomRightCornerRounded() { return 0 != (m_roundedCorners & PANEL_ROUND_CORNER_BOTTOM_RIGHT); }
virtual void SetDragEnabled(bool enabled);
virtual bool IsDragEnabled() const;
virtual void SetShowDragHelper(bool enabled);
virtual void OnDragFailed(CUtlVector< KeyValues* >& msglist);
virtual void SetBlockDragChaining(bool block);
virtual bool IsBlockingDragChaining() const;
virtual int GetDragStartTolerance() const;
virtual void SetDragSTartTolerance(int nTolerance);
virtual void SetDropEnabled(bool enabled, float m_flHoverContextTime = 0.0f);
virtual bool IsDropEnabled() const;
virtual bool GetDropContextMenu(Menu* menu, CUtlVector< KeyValues* >& msglist);
virtual void OnDropContextHoverShow(CUtlVector< KeyValues* >& msglist);
virtual void OnDropContextHoverHide(CUtlVector< KeyValues* >& msglist);
#if defined( VGUI_USEDRAGDROP )
virtual DragDrop_t* GetDragDropInfo();
#endif
virtual void OnGetAdditionalDragPanels(CUtlVector< Panel* >& dragabbles);
virtual void OnCreateDragData(KeyValues* msg);
virtual bool IsDroppable(CUtlVector< KeyValues* >& msglist);
virtual void OnDraggablePanelPaint();
virtual void OnDroppablePanelPaint(CUtlVector< KeyValues* >& msglist, CUtlVector< Panel* >& dragPanels);
virtual void OnPanelDropped(CUtlVector< KeyValues* >& msglist);
virtual void OnPanelEnteredDroppablePanel(CUtlVector< KeyValues* >& msglist);
virtual void OnPanelExitedDroppablePanel(CUtlVector< KeyValues* >& msglist);
virtual Panel* GetDropTarget(CUtlVector< KeyValues* >& msglist);
virtual Panel* GetDragPanel();
virtual bool IsBeingDragged();
virtual HCursor GetDropCursor(CUtlVector< KeyValues* >& msglist);
virtual HCursor GetDragFailCursor(CUtlVector< KeyValues* >& msglist) { return dc_no; }
Color GetDropFrameColor();
Color GetDragFrameColor();
virtual bool CanStartDragging(int startx, int starty, int mx, int my);
virtual void FillRectSkippingPanel(const Color clr, int x, int y, int w, int h, Panel* skipPanel);
virtual int GetPaintBackgroundType();
virtual void GetCornerTextureSize(int& w, int& h);
bool IsChildOfModalSubTree();
bool IsChildOfSurfaceModalPanel();
bool ShouldHandleInputMessage();
virtual void SetSkipChildDuringPainting(Panel* child);
void SetStartDragWhenMouseExitsPanel(bool state);
bool IsStartDragWhenMouseExitsPanel() const;
void SetMessageContextId_R(int nContextID);
void PostMessageToAllSiblings(KeyValues* msg, float delaySeconds = 0.0f);
template< class S >
void PostMessageToAllSiblingsOfType(KeyValues* msg, float delaySeconds = 0.0f);
void SetConsoleStylePanel(bool bConsoleStyle);
bool IsConsoleStylePanel() const;
enum NAV_DIRECTION { ND_UP, ND_DOWN, ND_LEFT, ND_RIGHT, ND_BACK, ND_NONE };
virtual Panel* NavigateUp();
virtual Panel* NavigateDown();
virtual Panel* NavigateLeft();
virtual Panel* NavigateRight();
virtual void NavigateTo();
virtual void NavigateFrom();
virtual void NavigateToChild(Panel* pNavigateTo);
Panel* SetNavUp(Panel* navUp);
Panel* SetNavDown(Panel* navDown);
Panel* SetNavLeft(Panel* navLeft);
Panel* SetNavRight(Panel* navRight);
NAV_DIRECTION GetLastNavDirection();
MESSAGE_FUNC_CHARPTR(OnNavigateTo, "OnNavigateTo", panelName);
MESSAGE_FUNC_CHARPTR(OnNavigateFrom, "OnNavigateFrom", panelName);
protected:
virtual void OnStartDragging();
virtual void OnContinueDragging();
virtual void OnFinishDragging(bool mousereleased, MouseCode code, bool aborted = false);
virtual void DragDropStartDragging();
virtual void GetDragData(CUtlVector< KeyValues* >& list);
virtual void CreateDragData();
virtual void PaintTraverse(bool Repaint, bool allowForce = true);
protected:
MESSAGE_FUNC_ENUM_ENUM(OnRequestFocus, "OnRequestFocus", VPANEL, subFocus, VPANEL, defaultPanel);
MESSAGE_FUNC_INT_INT(OnScreenSizeChanged, "OnScreenSizeChanged", oldwide, oldtall);
virtual void* QueryInterface(EInterfaceID id);
void AddToOverridableColors(Color* pColor, char const* scriptname)
{
int iIdx = m_OverridableColorEntries.AddToTail();
m_OverridableColorEntries[iIdx].m_pszScriptName = scriptname;
m_OverridableColorEntries[iIdx].m_pColor = pColor;
m_OverridableColorEntries[iIdx].m_bOverridden = false;
}
void ApplyOverridableColors(IScheme* pScheme);
void SetOverridableColor(Color* pColor, const Color& newColor);
protected:
void SetNavUp(const char* controlName);
void SetNavDown(const char* controlName);
void SetNavLeft(const char* controlName);
void SetNavRight(const char* controlName);
public:
Panel* GetNavUp(Panel* first = NULL);
Panel* GetNavDown(Panel* first = NULL);
Panel* GetNavLeft(Panel* first = NULL);
Panel* GetNavRight(Panel* first = NULL);
inline void SetWorldPositionCurrentFrame(bool bWorldPositionCurrentFrame) { m_bWorldPositionCurrentFrame = bWorldPositionCurrentFrame; }
inline bool GetWorldPositionCurrentFrame() { return m_bWorldPositionCurrentFrame; }
protected:
Panel* GetNavUpPanel();
Panel* GetNavDownPanel();
Panel* GetNavLeftPanel();
Panel* GetNavRightPanel();
bool m_PassUnhandledInput;
NAV_DIRECTION m_LastNavDirection;
void InternalInitDefaultValues(PanelAnimationMap* map);
private:
enum BuildModeFlags_t
{
BUILDMODE_EDITABLE = 0x01,
BUILDMODE_DELETABLE = 0x02,
BUILDMODE_SAVE_XPOS_RIGHTALIGNED = 0x04,
BUILDMODE_SAVE_XPOS_CENTERALIGNED = 0x08,
BUILDMODE_SAVE_YPOS_BOTTOMALIGNED = 0x10,
BUILDMODE_SAVE_YPOS_CENTERALIGNED = 0x20,
BUILDMODE_SAVE_WIDE_FULL = 0x40,
BUILDMODE_SAVE_TALL_FULL = 0x80,
BUILDMODE_SAVE_PROPORTIONAL_TO_PARENT = 0x100,
BUILDMODE_SAVE_PERCENTAGE = 0x200,
};
enum PanelFlags_t
{
MARKED_FOR_DELETION = 0x0001,
NEEDS_REPAINT = 0x0002,
PAINT_BORDER_ENABLED = 0x0004,
PAINT_BACKGROUND_ENABLED = 0x0008,
PAINT_ENABLED = 0x0010,
POST_CHILD_PAINT_ENABLED = 0x0020,
AUTODELETE_ENABLED = 0x0040,
NEEDS_LAYOUT = 0x0080,
NEEDS_SCHEME_UPDATE = 0x0100,
NEEDS_DEFAULT_SETTINGS_APPLIED = 0x0200,
#if defined( VGUI_USEKEYBINDINGMAPS )
ALLOW_CHAIN_KEYBINDING_TO_PARENT = 0x0400,
#endif
IN_PERFORM_LAYOUT = 0x0800,
IS_PROPORTIONAL = 0x1000,
TRIPLE_PRESS_ALLOWED = 0x2000,
DRAG_REQUIRES_PANEL_EXIT = 0x4000,
IS_MOUSE_DISABLED_FOR_THIS_PANEL_ONLY = 0x8000,
ALL_FLAGS = 0xFFFF,
};
virtual Panel* GetPanel() { return this; }
void Think();
void PerformApplySchemeSettings();
void InternalPerformLayout();
void InternalSetCursor();
MESSAGE_FUNC_INT_INT(InternalCursorMoved, "CursorMoved", xpos, ypos);
MESSAGE_FUNC(InternalCursorEntered, "CursorEntered");
MESSAGE_FUNC(InternalCursorExited, "CursorExited");
MESSAGE_FUNC_INT(InternalMousePressed, "MousePressed", code);
MESSAGE_FUNC_INT(InternalMouseDoublePressed, "MouseDoublePressed", code);
MESSAGE_FUNC_INT(InternalMouseTriplePressed, "MouseTriplePressed", code);
MESSAGE_FUNC_INT(InternalMouseReleased, "MouseReleased", code);
MESSAGE_FUNC_INT(InternalMouseWheeled, "MouseWheeled", delta);
MESSAGE_FUNC_INT(InternalKeyCodePressed, "KeyCodePressed", code);
MESSAGE_FUNC_INT(InternalKeyCodeTyped, "KeyCodeTyped", code);
MESSAGE_FUNC_INT(InternalKeyTyped, "KeyTyped", unichar);
MESSAGE_FUNC_INT(InternalKeyCodeReleased, "KeyCodeReleased", code);
MESSAGE_FUNC(InternalKeyFocusTicked, "KeyFocusTicked");
MESSAGE_FUNC(InternalMouseFocusTicked, "MouseFocusTicked");
MESSAGE_FUNC(InternalInvalidateLayout, "Invalidate");
MESSAGE_FUNC(InternalMove, "Move");
virtual void InternalFocusChanged(bool lost);
void Init(int x, int y, int wide, int tall);
void PreparePanelMap(PanelMap_t* panelMap);
bool InternalRequestInfo(PanelAnimationMap* map, KeyValues* outputData);
bool InternalSetInfo(PanelAnimationMap* map, KeyValues* inputData);
PanelAnimationMapEntry* FindPanelAnimationEntry(char const* scriptname, PanelAnimationMap* map);
void InternalApplySettings(PanelAnimationMap* map, KeyValues* inResourceData);
void ApplyAutoResizeSettings(KeyValues* inResourceData);
void FindDropTargetPanel_R(CUtlVector< VPANEL >& panelList, int x, int y, VPANEL check);
Panel* FindDropTargetPanel();
int GetProportionalScaledValue(int rootTall, int normalizedValue);
#if defined( VGUI_USEDRAGDROP )
DragDrop_t* m_pDragDrop;
Color m_clrDragFrame;
Color m_clrDropFrame;
#endif
BaseTooltip* m_pTooltips;
bool m_bToolTipOverridden;
PHandle m_SkipChild;
long m_lLastDoublePressTime;
HFont m_infoFont;
#if defined( VGUI_USEKEYBINDINGMAPS )
KeyBindingContextHandle_t m_hKeyBindingsContext;
#endif
VPANEL _vpanel;
CUtlString _panelName;
IBorder* _border;
CUtlFlags< unsigned short > _flags;
Dar<HPanel> _actionSignalTargetDar;
CUtlVector<OverridableColorEntry> m_OverridableColorEntries;
Color _fgColor;
Color _bgColor;
HBuildGroup _buildGroup;
short m_nPinDeltaX;
short m_nPinDeltaY;
short m_nResizeDeltaX;
short m_nResizeDeltaY;
HCursor _cursor;
unsigned short _buildModeFlags;
byte _pinCorner : 4;
byte _autoResizeDirection : 4;
GCC_DIAG_PUSH_OFF(overflow)
DECLARE_DMXELEMENT_BITFIELD(_pinCorner, byte, Panel)
DECLARE_DMXELEMENT_BITFIELD(_autoResizeDirection, byte, Panel)
GCC_DIAG_POP()
unsigned char _tabPosition;
HScheme m_iScheme;
bool m_bIsDMXSerialized : 1;
bool m_bUseSchemeColors : 1;
bool m_bIsSilent : 1;
bool m_bIsConsoleStylePanel : 1;
DECLARE_DMXELEMENT_BITFIELD(m_bUseSchemeColors, bool, Panel)
DECLARE_DMXELEMENT_BITFIELD(m_bIsSilent, bool, Panel)
char* _pinToSibling;
byte _pinToSiblingCorner;
byte _pinCornerToSibling;
PHandle m_pinSibling;
char* _tooltipText;
PHandle m_hMouseEventHandler;
bool m_bWorldPositionCurrentFrame;
CUtlSymbol m_sBorderName;
protected:
CUtlString m_sNavUpName;
PHandle m_NavUp;
CUtlString m_sNavDownName;
PHandle m_NavDown;
CUtlString m_sNavLeftName;
PHandle m_NavLeft;
CUtlString m_sNavRightName;
PHandle m_NavRight;
protected:
static int s_NavLock;
private:
CPanelAnimationVar(float, m_flAlpha, "alpha", "255");
CPanelAnimationVar(int, m_nPaintBackgroundType, "PaintBackgroundType", "0");
CPanelAnimationVarAliasType(int, m_nBgTextureId1, "Texture1", "vgui/hud/800corner1", "textureid");
CPanelAnimationVarAliasType(int, m_nBgTextureId2, "Texture2", "vgui/hud/800corner2", "textureid");
CPanelAnimationVarAliasType(int, m_nBgTextureId3, "Texture3", "vgui/hud/800corner3", "textureid");
CPanelAnimationVarAliasType(int, m_nBgTextureId4, "Texture4", "vgui/hud/800corner4", "textureid");
unsigned char m_roundedCorners;
friend class BuildGroup;
friend class BuildModeDialog;
friend class PHandle;
void OnOldMessage(KeyValues* params, VPANEL ifromPanel);
public:
virtual void GetSizerMinimumSize(int& wide, int& tall);
virtual void GetSizerClientArea(int& x, int& y, int& wide, int& tall);
CSizerBase* GetSizer();
void SetSizer(CSizerBase* pSizer);
protected:
CSizerBase* m_pSizer;
};
inline void Panel::DisableMouseInputForThisPanel(bool bDisable)
{
_flags.SetFlag(IS_MOUSE_DISABLED_FOR_THIS_PANEL_ONLY, bDisable);
}
inline bool Panel::IsMouseInputDisabledForThisPanel() const
{
return _flags.IsFlagSet(IS_MOUSE_DISABLED_FOR_THIS_PANEL_ONLY);
}
template< class S >
inline void Panel::PostMessageToAllSiblingsOfType(KeyValues* msg, float delaySeconds )
{
Panel* parent = GetParent();
if (parent)
{
int nChildCount = parent->GetChildCount();
for (int i = 0; i < nChildCount; ++i)
{
Panel* sibling = parent->GetChild(i);
if (sibling == this)
continue;
if (dynamic_cast<S*>(sibling))
{
PostMessage(sibling->GetVPanel(), msg->MakeCopy(), delaySeconds);
}
}
}
msg->deleteThis();
}
}
#endif

View File

@ -0,0 +1,153 @@
#ifndef PANELANIMATIONVAR_H
#define PANELANIMATIONVAR_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "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);
#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 )
#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

View File

@ -0,0 +1,210 @@
#ifndef PARTICLESPHERERENDERER_H
#define PARTICLESPHERERENDERER_H
#ifdef _WIN32
#pragma once
#endif
#include "particlemgr.h"
#include "particle_util.h"
class CParticleSphereRenderer
{
public:
CParticleSphereRenderer();
void Init(CParticleMgr* pParticleMgr, IMaterial* pMaterial);
void StartRender(VMatrix& effectMatrix);
void RenderParticle(
ParticleDraw* pDraw,
const Vector& vOriginalPos,
const Vector& vTransformedPos,
float flAlpha,
float flParticleSize,
float flAngle = 0.0f);
void RenderParticle_AddColor(
ParticleDraw* pDraw,
const Vector& vOriginalPos,
const Vector& vTransformedPos,
float flAlpha,
float flParticleSize,
const Vector& vToAdd0to1
);
const Vector& GetBaseColor() const;
void SetBaseColor(const Vector& vColor);
const CParticleLightInfo& GetAmbientLight() const;
void SetAmbientLight(const CParticleLightInfo& info);
const CParticleLightInfo& GetDirectionalLight() const;
void SetDirectionalLight(const CParticleLightInfo& info);
private:
void AddLightColor(
Vector const* pPos,
Vector const* pLightPos,
Vector const* pLightColor,
float flLightIntensity,
Vector* pOutColor);
inline void ClampColor(Vector& vColor);
private:
int m_iLastTickStartRenderCalled;
CParticleMgr* m_pParticleMgr;
Vector m_vBaseColor;
CParticleLightInfo m_AmbientLight;
CParticleLightInfo m_DirectionalLight;
bool m_bUsingPixelShaders;
};
inline void CParticleSphereRenderer::AddLightColor(
Vector const* pPos,
Vector const* pLightPos,
Vector const* pLightColor,
float flLightIntensity,
Vector* pOutColor)
{
if (flLightIntensity)
{
float fDist = pPos->DistToSqr(*pLightPos);
float fAmt;
if (fDist > 0.0001f)
fAmt = flLightIntensity / fDist;
else
fAmt = 1000.f;
*pOutColor += *pLightColor * fAmt;
}
}
inline void CParticleSphereRenderer::ClampColor(Vector& vColor)
{
float flMax = MAX(vColor.x, MAX(vColor.y, vColor.z));
if (flMax > 1)
{
vColor *= 255.0f / flMax;
}
else
{
vColor *= 255.0;
}
}
inline const Vector& CParticleSphereRenderer::GetBaseColor() const
{
return m_vBaseColor;
}
inline void CParticleSphereRenderer::SetBaseColor(const Vector& vColor)
{
m_vBaseColor = vColor;
}
inline const CParticleLightInfo& CParticleSphereRenderer::GetAmbientLight() const
{
return m_AmbientLight;
}
inline void CParticleSphereRenderer::SetAmbientLight(const CParticleLightInfo& info)
{
m_AmbientLight = info;
}
inline const CParticleLightInfo& CParticleSphereRenderer::GetDirectionalLight() const
{
return m_DirectionalLight;
}
inline void CParticleSphereRenderer::SetDirectionalLight(const CParticleLightInfo& info)
{
m_DirectionalLight = info;
}
inline void CParticleSphereRenderer::RenderParticle(
ParticleDraw* pDraw,
const Vector& vOriginalPos,
const Vector& vTransformedPos,
float flAlpha,
float flParticleSize,
float flAngle)
{
#ifdef _DEBUG
if (pDraw->GetMeshBuilder())
{
Assert(m_iLastTickStartRenderCalled == gpGlobals->tickcount);
}
#endif
Vector vColor = m_vBaseColor;
AddLightColor(&vOriginalPos, &m_AmbientLight.m_vPos, &m_AmbientLight.m_vColor, m_AmbientLight.m_flIntensity, &vColor);
if (!m_bUsingPixelShaders)
{
AddLightColor(&vOriginalPos, &m_DirectionalLight.m_vPos, &m_DirectionalLight.m_vColor, m_DirectionalLight.m_flIntensity, &vColor);
}
ClampColor(vColor);
RenderParticle_Color255SizeNormalAngle(
pDraw,
vTransformedPos,
vColor,
flAlpha,
flParticleSize,
vec3_origin,
flAngle);
}
inline void CParticleSphereRenderer::RenderParticle_AddColor(
ParticleDraw* pDraw,
const Vector& vOriginalPos,
const Vector& vTransformedPos,
float flAlpha,
float flParticleSize,
const Vector& vToAdd0to1
)
{
#ifdef _DEBUG
if (pDraw->GetMeshBuilder())
{
Assert(m_iLastTickStartRenderCalled == gpGlobals->tickcount);
}
#endif
Vector vColor = m_vBaseColor + vToAdd0to1;
AddLightColor(&vOriginalPos, &m_AmbientLight.m_vPos, &m_AmbientLight.m_vColor, m_AmbientLight.m_flIntensity, &vColor);
if (!m_bUsingPixelShaders)
{
AddLightColor(&vOriginalPos, &m_DirectionalLight.m_vPos, &m_DirectionalLight.m_vColor, m_DirectionalLight.m_flIntensity, &vColor);
}
ClampColor(vColor);
RenderParticle_Color255Size(
pDraw,
vTransformedPos,
vColor,
flAlpha,
flParticleSize);
}
#endif

234
SpyCustom/sdk/RichText.h Normal file
View File

@ -0,0 +1,234 @@
#ifndef RICHTEXT_H
#define RICHTEXT_H
#ifdef _WIN32
#pragma once
#endif
#include "Panel.h"
#include "utlvector.h"
namespace vgui
{
class ClickPanel;
class RichText : public Panel
{
DECLARE_CLASS_SIMPLE(RichText, Panel);
public:
RichText(Panel* parent, const char* panelName);
~RichText();
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);
void SetFont(HFont font);
void InsertChar(wchar_t ch);
void InsertString(const char* text);
void InsertString(const wchar_t* wszText);
void SelectNone();
void SelectAllText();
void SelectNoText();
MESSAGE_FUNC(CutSelected, "DoCutSelected");
MESSAGE_FUNC(CopySelected, "DoCopySelected");
void SetPanelInteractive(bool bInteractive) { m_bInteractive = bInteractive; }
void SetUnusedScrollbarInvisible(bool bInvis) { m_bUnusedScrollbarInvis = bInvis; }
void GotoTextStart();
void GotoTextEnd();
void SetVerticalScrollbar(bool state);
void SetMaximumCharCount(int maxChars);
void InsertColorChange(Color col);
void InsertIndentChange(int pixelsIndent);
void InsertClickableTextStart(const char* pchClickAction = NULL);
void InsertClickableTextEnd();
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);
void SetToFullHeight();
int GetNumLines();
virtual bool RequestInfo(KeyValues* outputData);
virtual void SetFgColor(Color color);
virtual void SetDrawOffsets(int ofsx, int ofsy);
bool IsScrollbarVisible();
void SetURLClickedHandler(Panel* pPanelToHandleClickMsg);
void SetUnderlineFont(HFont font);
bool IsAllTextAlphaZero() const;
bool HasText() const;
void SetDrawTextOnly();
protected:
virtual void OnThink();
virtual void PerformLayout();
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");
virtual void OnKillFocus();
virtual void OnMouseWheeled(int delta);
virtual void OnKeyCodeTyped(KeyCode code);
MESSAGE_FUNC_INT(OnClickPanel, "ClickPanel", index);
virtual void OnCursorMoved(int x, int y);
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code);
virtual void OnMouseFocusTicked();
virtual void OnCursorEntered();
virtual void OnCursorExited();
virtual void OnMouseCaptureLost();
virtual void OnSizeChanged(int newWide, int newTall);
virtual void OnSetFocus();
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
protected:
ScrollBar* _vertScrollBar;
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();
void GotoWordLeft();
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);
int GetStartDrawIndex(int& lineBreakIndexIndex);
int GetCursorLine();
int GetClickableTextIndexStart(int startIndex);
void CreateEditMenu();
MESSAGE_FUNC_INT(MoveScrollBar, "MoveScrollBar", delta);
MESSAGE_FUNC_INT(MoveScrollBarDirect, "MoveScrollBarDirect", delta);
void InvalidateLineBreakStream();
void RecalculateLineBreaks();
struct TFade
{
float flFadeStartTime;
float flFadeLength;
float flFadeSustain;
int iOriginalAlpha;
};
struct TFormatStream
{
Color color;
int pixelsIndent;
bool textClickable;
CUtlSymbol m_sClickableTextAction;
TFade fade;
int textStreamIndex;
};
bool m_bResetFades;
bool m_bInteractive;
bool m_bUnusedScrollbarInvis;
bool m_bAllTextAlphaIsZero;
CUtlVector<wchar_t> m_TextStream;
CUtlVector<int> m_LineBreaks;
CUtlVector<TFormatStream> m_FormatStream;
bool m_bRecalcLineBreaks;
int _recalculateBreaksIndex;
bool _invalidateVerticalScrollbarSlider;
int _cursorPos;
bool _mouseSelection;
bool _mouseDragSelection;
int _select[2];
int _pixelsIndent;
int _maxCharCount;
HFont _font;
HFont m_hFontUnderline;
Color _selectionColor;
Color _selectionTextColor;
bool _currentTextClickable;
CUtlVector<ClickPanel*> _clickableTextPanels;
int _clickableTextIndex;
Color _defaultTextColor;
int _drawOffsetX;
int _drawOffsetY;
Panel* m_pInterior;
PHandle m_hPanelToHandleClickingURLs;
Menu* m_pEditMenu;
char* m_pszInitialText;
bool _recalcSavedRenderState;
struct TRenderState
{
int x, y;
Color textColor;
int pixelsIndent;
bool textClickable;
int formatStreamIndex;
};
TRenderState m_CachedRenderState;
bool UpdateRenderState(int textStreamPos, TRenderState& renderState);
void CalculateFade(TRenderState& renderState);
void GenerateRenderStateForTextStreamIndex(int textStreamIndex, TRenderState& renderState);
int FindFormatStreamIndexForTextStreamPos(int textStreamIndex);
int DrawString(int iFirst, int iLast, TRenderState& renderState, HFont font);
};
}
#endif

51
SpyCustom/sdk/SndInfo.h Normal file
View File

@ -0,0 +1,51 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef SNDINFO_H
#define SNDINFO_H
#ifdef _WIN32
#pragma once
#endif
class Vector;
#include "utlsymbol.h"
//-----------------------------------------------------------------------------
// Purpose: Client side only
//-----------------------------------------------------------------------------
struct SndInfo_t
{
// Sound Guid
int m_nGuid;
FileNameHandle_t m_filenameHandle; // filesystem filename handle - call IFilesystem to conver this to a string
int m_nSoundSource;
int m_nChannel;
// If a sound is being played through a speaker entity (e.g., on a monitor,), this is the
// entity upon which to show the lips moving, if the sound has sentence data
int m_nSpeakerEntity;
float m_flVolume;
float m_flLastSpatializedVolume;
// Radius of this sound effect (spatialization is different within the radius)
float m_flRadius;
int m_nPitch;
Vector* m_pOrigin;
Vector* m_pDirection;
// if true, assume sound source can move and update according to entity
bool m_bUpdatePositions;
// true if playing linked sentence
bool m_bIsSentence;
// if true, bypass all dsp processing for this sound (ie: music)
bool m_bDryMix;
// true if sound is playing through in-game speaker entity.
bool m_bSpeaker;
// true if sound is playing with special DSP effect
bool m_bSpecialDSP;
// for snd_show, networked sounds get colored differently than local sounds
bool m_bFromServer;
};
#endif // SNDINFO_H

623
SpyCustom/sdk/SteamCommon.h Normal file
View File

@ -0,0 +1,623 @@
#ifndef INCLUDED_STEAM2_USERID_STRUCTS
#define INCLUDED_STEAM2_USERID_STRUCTS
#if defined(_MSC_VER) && (_MSC_VER > 1000)
#pragma once
#endif
#ifdef __cplusplus
extern "C"
{
#endif
#if defined ( _WIN32 )
#ifdef STEAM_EXPORTS
#define STEAM_API __declspec(dllexport)
#else
#define STEAM_API __declspec(dllimport)
#endif
#define STEAM_CALL __cdecl
#else
#define STEAM_API
#define STEAM_CALL
#endif
typedef void (STEAM_CALL* KeyValueIteratorCallback_t)(const char* Key, const char* Val, void* pvParam);
#define STEAM_USING_FILESYSTEM (0x00000001)
#define STEAM_USING_LOGGING (0x00000002)
#define STEAM_USING_USERID (0x00000004)
#define STEAM_USING_ACCOUNT (0x00000008)
#define STEAM_USING_ALL (0x0000000f)
#define STEAM_MAX_PATH (255)
#define STEAM_QUESTION_MAXLEN (255)
#define STEAM_SALT_SIZE (8)
#define STEAM_PROGRESS_PERCENT_SCALE (0x00001000)
#define STEAM_CARD_NUMBER_SIZE (17)
#define STEAM_CARD_HOLDERNAME_SIZE (100)
#define STEAM_CARD_EXPYEAR_SIZE (4)
#define STEAM_CARD_EXPMONTH_SIZE (2)
#define STEAM_CARD_CVV2_SIZE (5)
#define STEAM_BILLING_ADDRESS1_SIZE (128)
#define STEAM_BILLING_ADDRESS2_SIZE (128)
#define STEAM_BILLING_CITY_SIZE (50)
#define STEAM_BILLING_ZIP_SIZE (16)
#define STEAM_BILLING_STATE_SIZE (32)
#define STEAM_BILLING_COUNTRY_SIZE (32)
#define STEAM_BILLING_PHONE_SIZE (20)
#define STEAM_BILLING_EMAIL_ADDRESS_SIZE (100)
#define STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE (20)
#define STEAM_PROOF_OF_PURCHASE_TOKEN_SIZE (200)
#define STEAM_EXTERNAL_ACCOUNTNAME_SIZE (100)
#define STEAM_EXTERNAL_ACCOUNTPASSWORD_SIZE (80)
#define STEAM_BILLING_CONFIRMATION_CODE_SIZE (22)
#define STEAM_BILLING_CARD_APPROVAL_CODE_SIZE (100)
#define STEAM_BILLING_TRANS_DATE_SIZE (9)
#define STEAM_BILLING_TRANS_TIME_SIZE (9)
typedef unsigned int SteamHandle_t;
typedef void* SteamUserIDTicketValidationHandle_t;
typedef unsigned int SteamCallHandle_t;
#if defined(_MSC_VER)
typedef unsigned __int64 SteamUnsigned64_t;
#else
typedef unsigned long long SteamUnsigned64_t;
#endif
typedef enum
{
eSteamSeekMethodSet = 0,
eSteamSeekMethodCur = 1,
eSteamSeekMethodEnd = 2
} ESteamSeekMethod;
typedef enum
{
eSteamBufferMethodFBF = 0,
eSteamBufferMethodNBF = 1
} ESteamBufferMethod;
typedef enum
{
eSteamErrorNone = 0,
eSteamErrorUnknown = 1,
eSteamErrorLibraryNotInitialized = 2,
eSteamErrorLibraryAlreadyInitialized = 3,
eSteamErrorConfig = 4,
eSteamErrorContentServerConnect = 5,
eSteamErrorBadHandle = 6,
eSteamErrorHandlesExhausted = 7,
eSteamErrorBadArg = 8,
eSteamErrorNotFound = 9,
eSteamErrorRead = 10,
eSteamErrorEOF = 11,
eSteamErrorSeek = 12,
eSteamErrorCannotWriteNonUserConfigFile = 13,
eSteamErrorCacheOpen = 14,
eSteamErrorCacheRead = 15,
eSteamErrorCacheCorrupted = 16,
eSteamErrorCacheWrite = 17,
eSteamErrorCacheSession = 18,
eSteamErrorCacheInternal = 19,
eSteamErrorCacheBadApp = 20,
eSteamErrorCacheVersion = 21,
eSteamErrorCacheBadFingerPrint = 22,
eSteamErrorNotFinishedProcessing = 23,
eSteamErrorNothingToDo = 24,
eSteamErrorCorruptEncryptedUserIDTicket = 25,
eSteamErrorSocketLibraryNotInitialized = 26,
eSteamErrorFailedToConnectToUserIDTicketValidationServer = 27,
eSteamErrorBadProtocolVersion = 28,
eSteamErrorReplayedUserIDTicketFromClient = 29,
eSteamErrorReceiveResultBufferTooSmall = 30,
eSteamErrorSendFailed = 31,
eSteamErrorReceiveFailed = 32,
eSteamErrorReplayedReplyFromUserIDTicketValidationServer = 33,
eSteamErrorBadSignatureFromUserIDTicketValidationServer = 34,
eSteamErrorValidationStalledSoAborted = 35,
eSteamErrorInvalidUserIDTicket = 36,
eSteamErrorClientLoginRateTooHigh = 37,
eSteamErrorClientWasNeverValidated = 38,
eSteamErrorInternalSendBufferTooSmall = 39,
eSteamErrorInternalReceiveBufferTooSmall = 40,
eSteamErrorUserTicketExpired = 41,
eSteamErrorCDKeyAlreadyInUseOnAnotherClient = 42,
eSteamErrorNotLoggedIn = 101,
eSteamErrorAlreadyExists = 102,
eSteamErrorAlreadySubscribed = 103,
eSteamErrorNotSubscribed = 104,
eSteamErrorAccessDenied = 105,
eSteamErrorFailedToCreateCacheFile = 106,
eSteamErrorCallStalledSoAborted = 107,
eSteamErrorEngineNotRunning = 108,
eSteamErrorEngineConnectionLost = 109,
eSteamErrorLoginFailed = 110,
eSteamErrorAccountPending = 111,
eSteamErrorCacheWasMissingRetry = 112,
eSteamErrorLocalTimeIncorrect = 113,
eSteamErrorCacheNeedsDecryption = 114,
eSteamErrorAccountDisabled = 115,
eSteamErrorCacheNeedsRepair = 116,
eSteamErrorRebootRequired = 117,
eSteamErrorNetwork = 200,
eSteamErrorOffline = 201
} ESteamError;
typedef enum
{
eNoDetailedErrorAvailable,
eStandardCerrno,
eWin32LastError,
eWinSockLastError,
eDetailedPlatformErrorCount
} EDetailedPlatformErrorType;
typedef enum
{
eSteamFindLocalOnly,
eSteamFindRemoteOnly,
eSteamFindAll
} ESteamFindFilter;
typedef struct
{
ESteamError eSteamError;
EDetailedPlatformErrorType eDetailedErrorType;
int nDetailedErrorCode;
char szDesc[STEAM_MAX_PATH];
} TSteamError;
typedef struct
{
int bIsDir;
unsigned int uSizeOrCount;
int bIsLocal;
char cszName[STEAM_MAX_PATH];
long lLastAccessTime;
long lLastModificationTime;
long lCreationTime;
} TSteamElemInfo;
typedef struct
{
unsigned int uNumSubscriptions;
unsigned int uMaxNameChars;
unsigned int uMaxApps;
} TSteamSubscriptionStats;
typedef struct
{
unsigned int uNumApps;
unsigned int uMaxNameChars;
unsigned int uMaxInstallDirNameChars;
unsigned int uMaxVersionLabelChars;
unsigned int uMaxLaunchOptions;
unsigned int uMaxLaunchOptionDescChars;
unsigned int uMaxLaunchOptionCmdLineChars;
unsigned int uMaxNumIcons;
unsigned int uMaxIconSize;
unsigned int uMaxDependencies;
} TSteamAppStats;
typedef struct
{
char* szLabel;
unsigned int uMaxLabelChars;
unsigned int uVersionId;
int bIsNotAvailable;
} TSteamAppVersion;
typedef struct
{
char* szDesc;
unsigned int uMaxDescChars;
char* szCmdLine;
unsigned int uMaxCmdLineChars;
unsigned int uIndex;
unsigned int uIconIndex;
int bNoDesktopShortcut;
int bNoStartMenuShortcut;
int bIsLongRunningUnattended;
} TSteamAppLaunchOption;
typedef struct
{
char* szName;
unsigned int uMaxNameChars;
char* szLatestVersionLabel;
unsigned int uMaxLatestVersionLabelChars;
char* szCurrentVersionLabel;
unsigned int uMaxCurrentVersionLabelChars;
char* szInstallDirName;
unsigned int uMaxInstallDirNameChars;
unsigned int uId;
unsigned int uLatestVersionId;
unsigned int uCurrentVersionId;
unsigned int uMinCacheFileSizeMB;
unsigned int uMaxCacheFileSizeMB;
unsigned int uNumLaunchOptions;
unsigned int uNumIcons;
unsigned int uNumVersions;
unsigned int uNumDependencies;
} TSteamApp;
typedef enum
{
eNoCost = 0,
eBillOnceOnly = 1,
eBillMonthly = 2,
eProofOfPrepurchaseOnly = 3,
eGuestPass = 4,
eHardwarePromo = 5,
eNumBillingTypes,
} EBillingType;
typedef struct
{
char* szName;
unsigned int uMaxNameChars;
unsigned int* puAppIds;
unsigned int uMaxAppIds;
unsigned int uId;
unsigned int uNumApps;
EBillingType eBillingType;
unsigned int uCostInCents;
unsigned int uNumDiscounts;
int bIsPreorder;
int bRequiresShippingAddress;
unsigned int uDomesticShippingCostInCents;
unsigned int uInternationalShippingCostInCents;
bool bIsCyberCafeSubscription;
unsigned int uGameCode;
char szGameCodeDesc[STEAM_MAX_PATH];
bool bIsDisabled;
bool bRequiresCD;
unsigned int uTerritoryCode;
bool bIsSteam3Subscription;
} TSteamSubscription;
typedef struct
{
char szName[STEAM_MAX_PATH];
unsigned int uDiscountInCents;
unsigned int uNumQualifiers;
} TSteamSubscriptionDiscount;
typedef struct
{
char szName[STEAM_MAX_PATH];
unsigned int uRequiredSubscription;
int bIsDisqualifier;
} TSteamDiscountQualifier;
typedef struct TSteamProgress
{
int bValid;
unsigned int uPercentDone;
char szProgress[STEAM_MAX_PATH];
} TSteamProgress;
typedef enum
{
eSteamNotifyTicketsWillExpire,
eSteamNotifyAccountInfoChanged,
eSteamNotifyContentDescriptionChanged,
eSteamNotifyPleaseShutdown,
eSteamNotifyNewContentServer,
eSteamNotifySubscriptionStatusChanged,
eSteamNotifyContentServerConnectionLost,
eSteamNotifyCacheLoadingCompleted,
eSteamNotifyCacheNeedsDecryption,
eSteamNotifyCacheNeedsRepair
} ESteamNotificationCallbackEvent;
typedef void(*SteamNotificationCallback_t)(ESteamNotificationCallbackEvent eEvent, unsigned int nData);
typedef char SteamPersonalQuestion_t[STEAM_QUESTION_MAXLEN + 1];
typedef struct
{
unsigned char uchSalt[STEAM_SALT_SIZE];
} SteamSalt_t;
typedef enum
{
eVisa = 1,
eMaster = 2,
eAmericanExpress = 3,
eDiscover = 4,
eDinnersClub = 5,
eJCB = 6
} ESteamPaymentCardType;
typedef struct
{
ESteamPaymentCardType eCardType;
char szCardNumber[STEAM_CARD_NUMBER_SIZE + 1];
char szCardHolderName[STEAM_CARD_HOLDERNAME_SIZE + 1];
char szCardExpYear[STEAM_CARD_EXPYEAR_SIZE + 1];
char szCardExpMonth[STEAM_CARD_EXPMONTH_SIZE + 1];
char szCardCVV2[STEAM_CARD_CVV2_SIZE + 1];
char szBillingAddress1[STEAM_BILLING_ADDRESS1_SIZE + 1];
char szBillingAddress2[STEAM_BILLING_ADDRESS2_SIZE + 1];
char szBillingCity[STEAM_BILLING_CITY_SIZE + 1];
char szBillingZip[STEAM_BILLING_ZIP_SIZE + 1];
char szBillingState[STEAM_BILLING_STATE_SIZE + 1];
char szBillingCountry[STEAM_BILLING_COUNTRY_SIZE + 1];
char szBillingPhone[STEAM_BILLING_PHONE_SIZE + 1];
char szBillingEmailAddress[STEAM_BILLING_EMAIL_ADDRESS_SIZE + 1];
unsigned int uExpectedCostInCents;
unsigned int uExpectedTaxInCents;
char szShippingName[STEAM_CARD_HOLDERNAME_SIZE + 1];
char szShippingAddress1[STEAM_BILLING_ADDRESS1_SIZE + 1];
char szShippingAddress2[STEAM_BILLING_ADDRESS2_SIZE + 1];
char szShippingCity[STEAM_BILLING_CITY_SIZE + 1];
char szShippingZip[STEAM_BILLING_ZIP_SIZE + 1];
char szShippingState[STEAM_BILLING_STATE_SIZE + 1];
char szShippingCountry[STEAM_BILLING_COUNTRY_SIZE + 1];
char szShippingPhone[STEAM_BILLING_PHONE_SIZE + 1];
unsigned int uExpectedShippingCostInCents;
} TSteamPaymentCardInfo;
typedef struct
{
char szTypeOfProofOfPurchase[STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE + 1];
unsigned int uLengthOfBinaryProofOfPurchaseToken;
char cBinaryProofOfPurchaseToken[STEAM_PROOF_OF_PURCHASE_TOKEN_SIZE + 1];
} TSteamPrepurchaseInfo;
typedef struct
{
char szAccountName[STEAM_EXTERNAL_ACCOUNTNAME_SIZE + 1];
char szPassword[STEAM_EXTERNAL_ACCOUNTPASSWORD_SIZE + 1];
} TSteamExternalBillingInfo;
typedef enum
{
ePaymentCardInfo = 1,
ePrepurchasedInfo = 2,
eAccountBillingInfo = 3,
eExternalBillingInfo = 4,
ePaymentCardReceipt = 5,
ePrepurchaseReceipt = 6,
eEmptyReceipt = 7
} ESteamSubscriptionBillingInfoType;
typedef struct
{
ESteamSubscriptionBillingInfoType eBillingInfoType;
union {
TSteamPaymentCardInfo PaymentCardInfo;
TSteamPrepurchaseInfo PrepurchaseInfo;
TSteamExternalBillingInfo ExternalBillingInfo;
char bUseAccountBillingInfo;
};
} TSteamSubscriptionBillingInfo;
typedef enum
{
eSteamSubscriptionOK = 0,
eSteamSubscriptionPending = 1,
eSteamSubscriptionPreorder = 2,
eSteamSubscriptionPrepurchaseTransferred = 3,
eSteamSubscriptionPrepurchaseInvalid = 4,
eSteamSubscriptionPrepurchaseRejected = 5,
eSteamSubscriptionPrepurchaseRevoked = 6,
eSteamSubscriptionPaymentCardDeclined = 7,
eSteamSubscriptionCancelledByUser = 8,
eSteamSubscriptionCancelledByVendor = 9,
eSteamSubscriptionPaymentCardUseLimit = 10,
eSteamSubscriptionPaymentCardAlert = 11,
eSteamSubscriptionFailed = 12,
eSteamSubscriptionPaymentCardAVSFailure = 13,
eSteamSubscriptionPaymentCardInsufficientFunds = 14,
eSteamSubscriptionRestrictedCountry = 15
} ESteamSubscriptionStatus;
typedef struct
{
ESteamPaymentCardType eCardType;
char szCardLastFourDigits[4 + 1];
char szCardHolderName[STEAM_CARD_HOLDERNAME_SIZE + 1];
char szBillingAddress1[STEAM_BILLING_ADDRESS1_SIZE + 1];
char szBillingAddress2[STEAM_BILLING_ADDRESS2_SIZE + 1];
char szBillingCity[STEAM_BILLING_CITY_SIZE + 1];
char szBillingZip[STEAM_BILLING_ZIP_SIZE + 1];
char szBillingState[STEAM_BILLING_STATE_SIZE + 1];
char szBillingCountry[STEAM_BILLING_COUNTRY_SIZE + 1];
char szCardApprovalCode[STEAM_BILLING_CARD_APPROVAL_CODE_SIZE + 1];
char szTransDate[STEAM_BILLING_TRANS_DATE_SIZE + 1];
char szTransTime[STEAM_BILLING_TRANS_TIME_SIZE + 1];
unsigned int uPriceWithoutTax;
unsigned int uTaxAmount;
unsigned int uShippingCost;
} TSteamPaymentCardReceiptInfo;
typedef struct
{
char szTypeOfProofOfPurchase[STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE + 1];
} TSteamPrepurchaseReceiptInfo;
typedef struct
{
ESteamSubscriptionStatus eStatus;
ESteamSubscriptionStatus ePreviousStatus;
ESteamSubscriptionBillingInfoType eReceiptInfoType;
char szConfirmationCode[STEAM_BILLING_CONFIRMATION_CODE_SIZE + 1];
union {
TSteamPaymentCardReceiptInfo PaymentCardReceiptInfo;
TSteamPrepurchaseReceiptInfo PrepurchaseReceiptInfo;
};
} TSteamSubscriptionReceipt;
typedef enum
{
ePhysicalBytesReceivedThisSession = 1,
eAppReadyToLaunchStatus = 2,
eAppPreloadStatus = 3,
eAppEntireDepot = 4,
eCacheBytesPresent = 5
} ESteamAppUpdateStatsQueryType;
typedef struct
{
SteamUnsigned64_t uBytesTotal;
SteamUnsigned64_t uBytesPresent;
} TSteamUpdateStats;
typedef enum
{
eSteamUserAdministrator = 0x00000001,
eSteamUserDeveloper = 0x00000002,
eSteamUserCyberCafe = 0x00000004
} ESteamUserTypeFlags;
typedef enum
{
eSteamAccountStatusDefault = 0x00000000,
eSteamAccountStatusEmailVerified = 0x00000001,
eSteamAccountDisabled = 0x00000004
} ESteamAccountStatusBitFields;
typedef enum
{
eSteamBootstrapperError = -1,
eSteamBootstrapperDontCheckForUpdate = 0,
eSteamBootstrapperCheckForUpdateAndRerun = 7
} ESteamBootStrapperClientAppResult;
typedef enum
{
eSteamOnline = 0,
eSteamOffline = 1,
eSteamNoAuthMode = 2,
eSteamBillingOffline = 3
} eSteamOfflineStatus;
typedef struct
{
int eOfflineNow;
int eOfflineNextSession;
} TSteamOfflineStatus;
typedef struct
{
unsigned int uAppId;
int bIsSystemDefined;
char szMountPath[STEAM_MAX_PATH];
} TSteamAppDependencyInfo;
typedef enum
{
eSteamOpenFileRegular = 0x0,
eSteamOpenFileIgnoreLocal = 0x1,
eSteamOpenFileChecksumReads = 0x2
} ESteamOpenFileFlags;
typedef enum
{
eSteamValveCDKeyValidationServer = 0,
eSteamHalfLifeMasterServer = 1,
eSteamFriendsServer = 2,
eSteamCSERServer = 3,
eSteamHalfLife2MasterServer = 4,
eSteamRDKFMasterServer = 5,
eMaxServerTypes = 6
} ESteamServerType;
#ifdef __cplusplus
const SteamHandle_t STEAM_INVALID_HANDLE = 0;
const SteamCallHandle_t STEAM_INVALID_CALL_HANDLE = 0;
const SteamUserIDTicketValidationHandle_t STEAM_INACTIVE_USERIDTICKET_VALIDATION_HANDLE = 0;
const unsigned int STEAM_USE_LATEST_VERSION = 0xFFFFFFFF;
#else
#define STEAM_INVALID_HANDLE ((SteamHandle_t)(0))
#define STEAM_INVALID_CALL_HANDLE ((SteamCallHandle_t)(0))
#define STEAM_INACTIVE_USERIDTICKET_VALIDATION_HANDLE ((SteamUserIDTicketValidationHandle_t)(0))
#define STEAM_USE_LATEST_VERSION (0xFFFFFFFFu);
#endif
typedef unsigned short SteamInstanceID_t;
#if defined ( _WIN32 )
typedef unsigned __int64 SteamLocalUserID_t;
#else
typedef unsigned long long SteamLocalUserID_t;
#endif
typedef struct
{
unsigned int Low32bits;
unsigned int High32bits;
} TSteamSplitLocalUserID;
typedef struct
{
SteamInstanceID_t m_SteamInstanceID;
union
{
SteamLocalUserID_t As64bits;
TSteamSplitLocalUserID Split;
} m_SteamLocalUserID;
} TSteamGlobalUserID;
#ifdef __cplusplus
}
#endif
#endif

280
SpyCustom/sdk/TextEntry.h Normal file
View File

@ -0,0 +1,280 @@
#ifndef TEXTENTRY_H
#define TEXTENTRY_H
#ifdef _WIN32
#pragma once
#endif
#include "VGUI.h"
#include "Color.h"
#include "Panel.h"
#include "Label.h"
#include "ListPanel.h"
#include "utlvector.h"
namespace vgui
{
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;
virtual void GotoLeft();
virtual void GotoRight();
virtual void GotoUp();
virtual void GotoDown();
virtual void GotoWordRight();
virtual void GotoWordLeft();
virtual void GotoFirstOfLine();
virtual void GotoEndOfLine();
virtual void GotoTextStart();
virtual void GotoTextEnd();
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);
virtual void MoveCursor(int line, int pixelsAcross);
virtual void SetDisabledBgColor(Color col);
virtual void SetMultiline(bool state);
virtual bool IsMultiline();
virtual void SetVerticalScrollbar(bool state);
virtual void SetCatchEnterKey(bool state);
virtual void SendNewLine(bool send);
virtual void SetMaximumCharCount(int maxChars);
virtual int GetMaximumCharCount();
virtual void SetAutoProgressOnHittingCharLimit(bool state);
virtual void SetWrap(bool wrap);
virtual void RecalculateLineBreaks();
virtual void LayoutVerticalScrollBarSlider();
virtual bool RequestInfo(KeyValues* outputData);
void SetToFullHeight();
void SetToFullWidth();
int GetNumLines();
void SelectAllText(bool bResetCursorPos);
void SelectNoText();
void SelectAllOnFirstFocus(bool status);
void SetDrawWidth(int width);
int GetDrawWidth();
void SetHorizontalScrolling(bool status);
void SetAllowNonAsciiCharacters(bool state);
void SetAllowNumericInputOnly(bool state);
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();
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);
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();
virtual bool SelectCheck(bool fromMouse = false);
MESSAGE_FUNC_WCHARPTR(OnSetText, "SetText", text);
MESSAGE_FUNC(OnSliderMoved, "ScrollBarSliderMoved");
virtual void OnKillFocus();
virtual void OnMouseWheeled(int delta);
virtual void OnKeyCodePressed(KeyCode code);
virtual void OnKeyCodeTyped(KeyCode code);
virtual void OnKeyTyped(wchar_t unichar);
virtual void OnCursorMoved(int x, int y);
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnMouseTriplePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code);
virtual void OnKeyFocusTicked();
virtual void OnMouseFocusTicked();
virtual void OnCursorEntered();
virtual void OnCursorExited();
virtual void OnMouseCaptureLost();
virtual void OnSizeChanged(int newWide, int newTall);
virtual int GetStartDrawIndex(int& lineBreakIndexIndex);
public:
virtual float GetValueAsFloat();
virtual int GetValueAsInt();
protected:
void ScrollRight();
void ScrollLeft();
bool IsCursorOffRightSideOfWindow(int cursorPos);
bool IsCursorOffLeftSideOfWindow(int cursorPos);
void ScrollLeftForResize();
void OnSetFocus();
void OnChangeIME(bool forward);
bool NeedsEllipses(HFont font, int* pIndex);
private:
MESSAGE_FUNC_INT(OnSetState, "SetState", state);
int GetCurrentLineStart();
int GetCurrentLineEnd();
bool IsLineBreak(int index);
int GetCursorLine();
void MoveScrollBar(int delta);
void CalcBreakIndex();
void CreateEditMenu();
public:
Menu* GetEditMenu();
private:
void FlipToLastIME();
public:
virtual void GetTextRange(wchar_t* buf, int from, int numchars);
virtual void GetTextRange(char* buf, int from, int numchars);
private:
CUtlVector<wchar_t> m_TextStream;
CUtlVector<wchar_t> m_UndoTextStream;
CUtlVector<int> m_LineBreaks;
int _cursorPos;
bool _cursorIsAtEnd;
bool _putCursorAtEnd;
int _undoCursorPos;
bool _cursorBlink;
bool _hideText;
bool _editable;
bool _mouseSelection;
bool _mouseDragSelection;
int _mouseSelectCursorStart;
long _cursorNextBlinkTime;
int _cursorBlinkRate;
int _select[2];
int _pixelsIndent;
int _charCount;
int _maxCharCount;
HFont _font;
HFont _smallfont;
bool _dataChanged;
bool _multiline;
bool _verticalScrollbar;
ScrollBar* _vertScrollBar;
Color _cursorColor;
Color _disabledFgColor;
Color _disabledBgColor;
Color _selectionColor;
Color _selectionTextColor;
Color _defaultSelectionBG2Color;
int _currentStartLine;
int _currentStartIndex;
bool _horizScrollingAllowed;
Color _focusEdgeColor;
bool _catchEnterKey;
bool _wrap;
bool _sendNewLines;
int _drawWidth;
Menu* m_pEditMenu;
int _recalculateBreaksIndex;
bool _selectAllOnFirstFocus : 1;
bool _selectAllOnFocusAlways : 1;
bool _firstFocusStatus;
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

118
SpyCustom/sdk/TextImage.h Normal file
View File

@ -0,0 +1,118 @@
#ifndef TEXTIMAGE_H
#define TEXTIMAGE_H
#ifdef _WIN32
#pragma once
#endif
#include "VGUI.h"
#include "ILocalize.h"
#include "Image.h"
#include "utlvector.h"
#include "UtlSortVector.h"
class KeyValues;
namespace vgui
{
struct label_colorchange_t
{
Color color;
int textStreamIndex;
};
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;
}
};
class TextImage : public Image
{
public:
TextImage(const char* text);
TextImage(const wchar_t* wszText);
~TextImage();
public:
virtual void SetText(const char* text);
virtual void SetText(const wchar_t* text, bool bClearUnlocalizedSymbol = false);
virtual void GetText(char* buffer, int bufferSize);
virtual void GetText(wchar_t* buffer, int bufferLength);
virtual void GetUnlocalizedText(char* buffer, int bufferSize);
virtual StringIndex_t GetUnlocalizedTextSymbol();
virtual void SetFont(vgui::HFont font);
virtual vgui::HFont GetFont();
void SetDrawWidth(int width);
void GetDrawWidth(int& width);
void ResizeImageToContent();
void ResizeImageToContentMaxWidth(int nMaxWidth);
virtual void SetSize(int wide, int tall);
virtual void GetContentSize(int& wide, int& tall);
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(); }
const wchar_t* GetEllipsesPosition(void) const { return m_pwszEllipsesPosition; }
bool IsWrapping() const { return m_LineBreaks.Count() != 0; }
protected:
void SizeText(wchar_t* tempText, int stringLength);
virtual void GetTextSize(int& wide, int& tall);
private:
void RecalculateEllipsesPosition();
wchar_t* _utext;
short _textBufferLen;
short _textLen;
vgui::HFont _font;
vgui::HFont _fallbackFont;
int _drawWidth;
StringIndex_t _unlocalizedTextSymbol;
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;
bool m_bWrapCenter;
CUtlVector<int> m_LineXIndent;
CUtlSortVector<label_colorchange_t, CColorChangeListLess> m_ColorChangeStream;
};
}
#endif

View File

@ -0,0 +1,38 @@
#ifndef TOGGLEBUTTON_H
#define TOGGLEBUTTON_H
#ifdef _WIN32
#pragma once
#endif
#include "VGUI.h"
#include "Button.h"
namespace vgui
{
class ToggleButton : public Button
{
DECLARE_CLASS_SIMPLE(ToggleButton, Button);
public:
ToggleButton(Panel* parent, const char* panelName, const char* text);
virtual void DoClick();
protected:
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;
};
}
#endif

66
SpyCustom/sdk/Tooltip.h Normal file
View File

@ -0,0 +1,66 @@
#ifndef TOOLTIP_H
#define TOOLTIP_H
#ifdef _WIN32
#pragma once
#endif
#include "VGUI.h"
#include "Controls.h"
#include "utlvector.h"
namespace vgui
{
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;
int _tooltipDelay;
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

139
SpyCustom/sdk/lightdesc.h Normal file
View File

@ -0,0 +1,139 @@
#ifndef LIGHTDESC_H
#define LIGHTDESC_H
#include "ssemath.h"
#include "vector.h"
enum LightType_t
{
MATERIAL_LIGHT_DISABLE = 0,
MATERIAL_LIGHT_POINT,
MATERIAL_LIGHT_DIRECTIONAL,
MATERIAL_LIGHT_SPOT,
};
enum LightType_OptimizationFlags_t
{
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0 = 1,
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION1 = 2,
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION2 = 4,
LIGHTTYPE_OPTIMIZATIONFLAGS_DERIVED_VALUES_CALCED = 8,
};
struct LightDesc_t
{
LightType_t m_Type;
Vector m_Color;
Vector m_Position;
Vector m_Direction;
float m_Range;
float m_Falloff;
float m_Attenuation0;
float m_Attenuation1;
float m_Attenuation2;
float m_Theta;
float m_Phi;
float m_ThetaDot;
float m_PhiDot;
unsigned int m_Flags;
protected:
float OneOver_ThetaDot_Minus_PhiDot;
float m_RangeSquared;
public:
void RecalculateDerivedValues(void);
LightDesc_t(void)
{
}
LightDesc_t(const Vector& pos, const Vector& color)
{
InitPoint(pos, color);
}
LightDesc_t(const Vector& pos, const Vector& color, const Vector& point_at,
float inner_cone_boundary, float outer_cone_boundary)
{
InitSpot(pos, color, point_at, inner_cone_boundary, outer_cone_boundary);
}
void InitPoint(const Vector& pos, const Vector& color);
void InitDirectional(const Vector& dir, const Vector& color);
void InitSpot(const Vector& pos, const Vector& color, const Vector& point_at,
float inner_cone_boundary, float outer_cone_boundary);
void ComputeLightAtPoints(const FourVectors& pos, const FourVectors& normal,
FourVectors& color, bool DoHalfLambert = false) const;
void ComputeNonincidenceLightAtPoints(const FourVectors& pos, FourVectors& color) const;
void ComputeLightAtPointsForDirectional(const FourVectors& pos,
const FourVectors& normal,
FourVectors& color, bool DoHalfLambert = false) const;
void SetupOldStyleAttenuation(float fQuadatricAttn, float fLinearAttn, float fConstantAttn);
void SetupNewStyleAttenuation(float fFiftyPercentDistance, float fZeroPercentDistance);
bool IsDirectionWithinLightCone(const Vector& rdir) const
{
return ((m_Type != MATERIAL_LIGHT_SPOT) || (rdir.Dot(m_Direction) >= m_PhiDot));
}
float OneOverThetaDotMinusPhiDot() const
{
return OneOver_ThetaDot_Minus_PhiDot;
}
};
inline void LightDesc_t::InitPoint(const Vector& pos, const Vector& color)
{
m_Type = MATERIAL_LIGHT_POINT;
m_Color = color;
m_Position = pos;
m_Range = 0.0;
m_Attenuation0 = 1.0;
m_Attenuation1 = 0;
m_Attenuation2 = 0;
RecalculateDerivedValues();
}
inline void LightDesc_t::InitDirectional(const Vector& dir, const Vector& color)
{
m_Type = MATERIAL_LIGHT_DIRECTIONAL;
m_Color = color;
m_Direction = dir;
m_Range = 0.0;
m_Attenuation0 = 1.0;
m_Attenuation1 = 0;
m_Attenuation2 = 0;
RecalculateDerivedValues();
}
inline void LightDesc_t::InitSpot(const Vector& pos, const Vector& color, const Vector& point_at,
float inner_cone_boundary, float outer_cone_boundary)
{
m_Type = MATERIAL_LIGHT_SPOT;
m_Color = color;
m_Position = pos;
m_Direction = point_at;
m_Direction -= pos;
VectorNormalizeFast(m_Direction);
m_Falloff = 5.0;
m_Theta = inner_cone_boundary;
m_Phi = outer_cone_boundary;
m_Range = 0.0;
m_Attenuation0 = 1.0;
m_Attenuation1 = 0;
m_Attenuation2 = 0;
RecalculateDerivedValues();
}
#endif

View File

@ -0,0 +1,21 @@
#ifndef LOCALFLEXCONTROLLER_H
#define LOCALFLEXCONTROLLER_H
#ifdef _WIN32
#pragma once
#endif
#include "platform.h"
enum LocalFlexController_t
{
DUMMY_FLEX_CONTROLLER = 0x7fffffff
};
inline LocalFlexController_t& operator++(LocalFlexController_t& a) { return a = LocalFlexController_t(int(a) + 1); }
inline LocalFlexController_t& operator--(LocalFlexController_t& a) { return a = LocalFlexController_t(int(a) - 1); }
inline LocalFlexController_t operator++(LocalFlexController_t& a, int) { LocalFlexController_t t = a; a = LocalFlexController_t(int(a) + 1); return t; }
inline LocalFlexController_t operator--(LocalFlexController_t& a, int) { LocalFlexController_t t = a; a = LocalFlexController_t(int(a) - 1); return t; }
#endif

421
SpyCustom/sdk/logging.h Normal file
View File

@ -0,0 +1,421 @@
#ifndef LOGGING_H
#define LOGGING_H
#if !defined(__SPU__)
#if defined( COMPILER_MSVC )
#pragma once
#endif
#include "color.h"
#include "icommandline.h"
#include <stdio.h>
#if defined( _X360 )
#include "xbox/xbox_console.h"
#endif
#if defined( _WIN32 ) || (defined(POSIX) && !defined(_GAMECONSOLE))
#include "win32consoleio.h"
#endif
class CLoggingSystem;
class CThreadFastMutex;
const int MAX_LOGGING_MESSAGE_LENGTH = 2048;
const int MAX_LOGGING_IDENTIFIER_LENGTH = 32;
const int MAX_LOGGING_CHANNEL_COUNT = 256;
const int MAX_LOGGING_TAG_COUNT = 1024;
const int MAX_LOGGING_TAG_CHARACTER_COUNT = 8192;
const int MAX_LOGGING_LISTENER_COUNT = 16;
const Color UNSPECIFIED_LOGGING_COLOR(0, 0, 0, 0);
typedef int LoggingChannelID_t;
const LoggingChannelID_t INVALID_LOGGING_CHANNEL_ID = -1;
enum LoggingSeverity_t
{
LS_MESSAGE = 0,
LS_WARNING = 1,
LS_ASSERT = 2,
LS_ERROR = 3,
LS_HIGHEST_SEVERITY = 4,
};
enum LoggingResponse_t
{
LR_CONTINUE,
LR_DEBUGGER,
LR_ABORT,
};
enum LoggingChannelFlags_t
{
LCF_CONSOLE_ONLY = 0x00000001,
LCF_DO_NOT_ECHO = 0x00000002,
};
typedef void (*RegisterTagsFunc)();
struct LoggingContext_t
{
LoggingChannelID_t m_ChannelID;
LoggingChannelFlags_t m_Flags;
LoggingSeverity_t m_Severity;
Color m_Color;
};
class ILoggingListener
{
public:
virtual void Log(const LoggingContext_t* pContext, const tchar* pMessage) = 0;
};
class ILoggingResponsePolicy
{
public:
virtual LoggingResponse_t OnLog(const LoggingContext_t* pContext) = 0;
};
class CSimpleLoggingListener : public ILoggingListener
{
public:
CSimpleLoggingListener(bool bQuietPrintf = false, bool bQuietDebugger = false) :
m_bQuietPrintf(bQuietPrintf),
m_bQuietDebugger(bQuietDebugger)
{
}
virtual void Log(const LoggingContext_t* pContext, const tchar* pMessage)
{
#ifdef _X360
if (!m_bQuietDebugger && XBX_IsConsoleConnected())
{
XBX_DebugString(XMAKECOLOR(0, 0, 0), pMessage);
}
else
#endif
{
#if !defined( _CERT ) && !defined( DBGFLAG_STRINGS_STRIP )
if (!m_bQuietPrintf)
{
_tprintf(_T("%s"), pMessage);
}
#endif
#ifdef _WIN32
if (!m_bQuietDebugger && Plat_IsInDebugSession())
{
Plat_DebugString(pMessage);
}
#endif
}
}
bool m_bQuietPrintf;
bool m_bQuietDebugger;
};
class CSimpleWindowsLoggingListener : public ILoggingListener
{
public:
virtual void Log(const LoggingContext_t* pContext, const tchar* pMessage)
{
if (Plat_IsInDebugSession())
{
Plat_DebugString(pMessage);
}
if (pContext->m_Severity == LS_ERROR)
{
if (Plat_IsInDebugSession())
DebuggerBreak();
Plat_MessageBox("Error", pMessage);
}
}
};
#if !defined(_GAMECONSOLE)
class CColorizedLoggingListener : public CSimpleLoggingListener
{
public:
CColorizedLoggingListener(bool bQuietPrintf = false, bool bQuietDebugger = false) : CSimpleLoggingListener(bQuietPrintf, bQuietDebugger)
{
InitWin32ConsoleColorContext(&m_ColorContext);
}
virtual void Log(const LoggingContext_t* pContext, const tchar* pMessage)
{
if (!m_bQuietPrintf)
{
int nPrevColor = -1;
if (pContext->m_Color != UNSPECIFIED_LOGGING_COLOR)
{
nPrevColor = SetWin32ConsoleColor(&m_ColorContext,
pContext->m_Color.r(), pContext->m_Color.g(), pContext->m_Color.b(),
MAX(MAX(pContext->m_Color.r(), pContext->m_Color.g()), pContext->m_Color.b()) > 128);
}
_tprintf(_T("%s"), pMessage);
if (nPrevColor >= 0)
{
RestoreWin32ConsoleColor(&m_ColorContext, nPrevColor);
}
}
#ifdef _WIN32
if (!m_bQuietDebugger && Plat_IsInDebugSession())
{
Plat_DebugString(pMessage);
}
#endif
}
Win32ConsoleColorContext_t m_ColorContext;
};
#endif
class CDefaultLoggingResponsePolicy : public ILoggingResponsePolicy
{
public:
virtual LoggingResponse_t OnLog(const LoggingContext_t* pContext)
{
if (pContext->m_Severity == LS_ASSERT && !CommandLine()->FindParm("-noassert"))
{
return LR_DEBUGGER;
}
else if (pContext->m_Severity == LS_ERROR)
{
return LR_ABORT;
}
else
{
return LR_CONTINUE;
}
}
};
class CNonFatalLoggingResponsePolicy : public ILoggingResponsePolicy
{
public:
virtual LoggingResponse_t OnLog(const LoggingContext_t* pContext)
{
if ((pContext->m_Severity == LS_ASSERT && !CommandLine()->FindParm("-noassert")) || pContext->m_Severity == LS_ERROR)
{
return LR_DEBUGGER;
}
else
{
return LR_CONTINUE;
}
}
};
class CLoggingSystem
{
public:
struct LoggingChannel_t;
CLoggingSystem();
~CLoggingSystem();
LoggingChannelID_t RegisterLoggingChannel(const char* pChannelName, RegisterTagsFunc registerTagsFunc, int flags = 0, LoggingSeverity_t minimumSeverity = LS_MESSAGE, Color spewColor = UNSPECIFIED_LOGGING_COLOR);
LoggingChannelID_t FindChannel(const char* pChannelName) const;
int GetChannelCount() const { return m_nChannelCount; }
LoggingChannel_t* GetChannel(LoggingChannelID_t channelID);
const LoggingChannel_t* GetChannel(LoggingChannelID_t channelID) const;
bool HasTag(LoggingChannelID_t channelID, const char* pTag) const { return GetChannel(channelID)->HasTag(pTag); }
bool IsValidChannelID(LoggingChannelID_t channelID) const { return (channelID >= 0) && (channelID < m_nChannelCount); }
bool IsChannelEnabled(LoggingChannelID_t channelID, LoggingSeverity_t severity) const { return IsValidChannelID(channelID) && GetChannel(channelID)->IsEnabled(severity); }
void SetChannelSpewLevel(LoggingChannelID_t channelID, LoggingSeverity_t minimumSeverity);
void SetChannelSpewLevelByName(const char* pName, LoggingSeverity_t minimumSeverity);
void SetChannelSpewLevelByTag(const char* pTag, LoggingSeverity_t minimumSeverity);
void SetGlobalSpewLevel(LoggingSeverity_t minimumSeverity);
Color GetChannelColor(LoggingChannelID_t channelID) const { return GetChannel(channelID)->m_SpewColor; }
void SetChannelColor(LoggingChannelID_t channelID, Color color) { GetChannel(channelID)->m_SpewColor = color; }
LoggingChannelFlags_t GetChannelFlags(LoggingChannelID_t channelID) const { return GetChannel(channelID)->m_Flags; }
void SetChannelFlags(LoggingChannelID_t channelID, LoggingChannelFlags_t flags) { GetChannel(channelID)->m_Flags = flags; }
void AddTagToCurrentChannel(const char* pTagName);
void PushLoggingState(bool bThreadLocal = false, bool bClearState = true);
void PopLoggingState(bool bThreadLocal = false);
void RegisterLoggingListener(ILoggingListener* pListener);
bool IsListenerRegistered(ILoggingListener* pListener);
void ResetCurrentLoggingState();
void SetLoggingResponsePolicy(ILoggingResponsePolicy* pLoggingResponse);
LoggingResponse_t LogDirect(LoggingChannelID_t channelID, LoggingSeverity_t severity, Color color, const tchar* pMessage);
struct LoggingTag_t
{
const char* m_pTagName;
LoggingTag_t* m_pNextTag;
};
struct LoggingChannel_t
{
bool HasTag(const char* pTag) const
{
LoggingTag_t* pCurrentTag = m_pFirstTag;
while (pCurrentTag != NULL)
{
if (stricmp(pCurrentTag->m_pTagName, pTag) == 0)
{
return true;
}
pCurrentTag = pCurrentTag->m_pNextTag;
}
return false;
}
bool IsEnabled(LoggingSeverity_t severity) const { return severity >= m_MinimumSeverity; }
void SetSpewLevel(LoggingSeverity_t severity) { m_MinimumSeverity = severity; }
LoggingChannelID_t m_ID;
LoggingChannelFlags_t m_Flags;
LoggingSeverity_t m_MinimumSeverity;
Color m_SpewColor;
char m_Name[MAX_LOGGING_IDENTIFIER_LENGTH];
LoggingTag_t* m_pFirstTag;
};
private:
struct LoggingState_t
{
int m_nPreviousStackEntry;
int m_nListenerCount;
ILoggingListener* m_RegisteredListeners[MAX_LOGGING_LISTENER_COUNT];
ILoggingResponsePolicy* m_pLoggingResponse;
};
LoggingState_t* GetCurrentState();
const LoggingState_t* GetCurrentState() const;
int FindUnusedStateIndex();
LoggingTag_t* AllocTag(const char* pTagName);
int m_nChannelCount;
LoggingChannel_t m_RegisteredChannels[MAX_LOGGING_CHANNEL_COUNT];
int m_nChannelTagCount;
LoggingTag_t m_ChannelTags[MAX_LOGGING_TAG_COUNT];
int m_nTagNamePoolIndex;
char m_TagNamePool[MAX_LOGGING_TAG_CHARACTER_COUNT];
CThreadFastMutex* m_pStateMutex;
int m_nGlobalStateIndex;
static const int MAX_LOGGING_STATE_COUNT = 16;
LoggingState_t m_LoggingStates[MAX_LOGGING_STATE_COUNT];
CDefaultLoggingResponsePolicy m_DefaultLoggingResponse;
CSimpleLoggingListener m_DefaultLoggingListener;
};
#ifdef DBGFLAG_STRINGS_STRIP
#define InternalMsg( Channel, Severity, ... ) do { if ( Severity == LS_ERROR && LoggingSystem_IsChannelEnabled( Channel, Severity ) ) LoggingSystem_Log( Channel, Severity, ##__VA_ARGS__ ); } while( 0 )
#else
#define InternalMsg( Channel, Severity, ... ) do { if ( LoggingSystem_IsChannelEnabled( Channel, Severity ) ) LoggingSystem_Log( Channel, Severity, ##__VA_ARGS__ ); } while( 0 )
#endif
#define Log_Msg( Channel, ... ) InternalMsg( Channel, LS_MESSAGE, ##__VA_ARGS__ )
#define Log_Warning( Channel, ... ) InternalMsg( Channel, LS_WARNING, ##__VA_ARGS__ )
#define Log_Error( Channel, ... ) InternalMsg( Channel, LS_ERROR, ##__VA_ARGS__ )
#ifdef DBGFLAG_STRINGS_STRIP
#define Log_Assert( ... ) LR_CONTINUE
#else
#define Log_Assert( Message, ... ) LoggingSystem_LogAssert( Message, ##__VA_ARGS__ )
#endif
#define DECLARE_LOGGING_CHANNEL( Channel ) extern LoggingChannelID_t Channel
#define DEFINE_LOGGING_CHANNEL_NO_TAGS( Channel, ChannelName, ... ) \
LoggingChannelID_t Channel = LoggingSystem_RegisterLoggingChannel( ChannelName, NULL, ##__VA_ARGS__ )
#define BEGIN_DEFINE_LOGGING_CHANNEL( Channel, ChannelName, ... ) \
static void Register_##Channel##_Tags(); \
LoggingChannelID_t Channel = LoggingSystem_RegisterLoggingChannel( ChannelName, Register_##Channel##_Tags, ##__VA_ARGS__ ); \
void Register_##Channel##_Tags() \
{
#define ADD_LOGGING_CHANNEL_TAG( Tag ) LoggingSystem_AddTagToCurrentChannel( Tag )
#define END_DEFINE_LOGGING_CHANNEL() \
}
PLATFORM_INTERFACE LoggingChannelID_t LoggingSystem_RegisterLoggingChannel(const char* pName, RegisterTagsFunc registerTagsFunc, int flags = 0, LoggingSeverity_t severity = LS_MESSAGE, Color color = UNSPECIFIED_LOGGING_COLOR);
PLATFORM_INTERFACE void LoggingSystem_RegisterLoggingListener(ILoggingListener* pListener);
PLATFORM_INTERFACE void LoggingSystem_UnregisterLoggingListener(ILoggingListener* pListener);
PLATFORM_INTERFACE void LoggingSystem_ResetCurrentLoggingState();
PLATFORM_INTERFACE void LoggingSystem_SetLoggingResponsePolicy(ILoggingResponsePolicy* pResponsePolicy);
PLATFORM_INTERFACE void LoggingSystem_PushLoggingState(bool bThreadLocal = false, bool bClearState = true);
PLATFORM_INTERFACE void LoggingSystem_PopLoggingState(bool bThreadLocal = false);
PLATFORM_INTERFACE void LoggingSystem_AddTagToCurrentChannel(const char* pTagName);
PLATFORM_INTERFACE LoggingChannelID_t LoggingSystem_FindChannel(const char* pChannelName);
PLATFORM_INTERFACE int LoggingSystem_GetChannelCount();
PLATFORM_INTERFACE LoggingChannelID_t LoggingSystem_GetFirstChannelID();
PLATFORM_INTERFACE LoggingChannelID_t LoggingSystem_GetNextChannelID(LoggingChannelID_t channelID);
PLATFORM_INTERFACE const CLoggingSystem::LoggingChannel_t* LoggingSystem_GetChannel(LoggingChannelID_t channelID);
PLATFORM_INTERFACE bool LoggingSystem_HasTag(LoggingChannelID_t channelID, const char* pTag);
PLATFORM_INTERFACE bool LoggingSystem_IsChannelEnabled(LoggingChannelID_t channelID, LoggingSeverity_t severity);
PLATFORM_INTERFACE void LoggingSystem_SetChannelSpewLevel(LoggingChannelID_t channelID, LoggingSeverity_t minimumSeverity);
PLATFORM_INTERFACE void LoggingSystem_SetChannelSpewLevelByName(const char* pName, LoggingSeverity_t minimumSeverity);
PLATFORM_INTERFACE void LoggingSystem_SetChannelSpewLevelByTag(const char* pTag, LoggingSeverity_t minimumSeverity);
PLATFORM_INTERFACE void LoggingSystem_SetGlobalSpewLevel(LoggingSeverity_t minimumSeverity);
PLATFORM_INTERFACE int32 LoggingSystem_GetChannelColor(LoggingChannelID_t channelID);
PLATFORM_INTERFACE void LoggingSystem_SetChannelColor(LoggingChannelID_t channelID, int color);
PLATFORM_INTERFACE LoggingChannelFlags_t LoggingSystem_GetChannelFlags(LoggingChannelID_t channelID);
PLATFORM_INTERFACE void LoggingSystem_SetChannelFlags(LoggingChannelID_t channelID, LoggingChannelFlags_t flags);
PLATFORM_INTERFACE LoggingResponse_t LoggingSystem_Log(LoggingChannelID_t channelID, LoggingSeverity_t severity, PRINTF_FORMAT_STRING const char* pMessageFormat, ...) FMTFUNCTION(3, 4);
PLATFORM_OVERLOAD LoggingResponse_t LoggingSystem_Log(LoggingChannelID_t channelID, LoggingSeverity_t severity, Color spewColor, PRINTF_FORMAT_STRING const char* pMessageFormat, ...) FMTFUNCTION(4, 5);
PLATFORM_INTERFACE LoggingResponse_t LoggingSystem_LogDirect(LoggingChannelID_t channelID, LoggingSeverity_t severity, Color spewColor, const char* pMessage);
PLATFORM_INTERFACE LoggingResponse_t LoggingSystem_LogAssert(PRINTF_FORMAT_STRING const char* pMessageFormat, ...) FMTFUNCTION(1, 2);
#endif
#endif

66
SpyCustom/sdk/math_pfns.h Normal file
View File

@ -0,0 +1,66 @@
#ifndef _MATH_PFNS_H_
#define _MATH_PFNS_H_
#if defined( _X360 )
#include <xboxmath.h>
#endif
#if !defined( _X360 )
extern float (*pfSqrt)(float x);
extern float (*pfRSqrt)(float x);
extern float (*pfRSqrtFast)(float x);
extern void (*pfFastSinCos)(float x, float* s, float* c);
extern float (*pfFastCos)(float x);
#define FastSqrt(x) (*pfSqrt)(x)
#define FastRSqrt(x) (*pfRSqrt)(x)
#define FastRSqrtFast(x) (*pfRSqrtFast)(x)
#define FastSinCos(x,s,c) (*pfFastSinCos)(x,s,c)
#define FastCos(x) (*pfFastCos)(x)
#if defined(__i386__) || defined(_M_IX86)
#undef FastSqrt
#define FastSqrt(x) ::sqrtf(x)
#endif
#endif
#if defined( _X360 )
FORCEINLINE float _VMX_Sqrt(float x)
{
return __fsqrts(x);
}
FORCEINLINE float _VMX_RSqrt(float x)
{
float rroot = __frsqrte(x);
return (0.5f * rroot) * (3.0f - (x * rroot) * rroot);
}
FORCEINLINE float _VMX_RSqrtFast(float x)
{
return __frsqrte(x);
}
FORCEINLINE void _VMX_SinCos(float a, float* pS, float* pC)
{
XMScalarSinCos(pS, pC, a);
}
FORCEINLINE float _VMX_Cos(float a)
{
return XMScalarCos(a);
}
#define FastSqrt(x) _VMX_Sqrt(x)
#define FastRSqrt(x) _VMX_RSqrt(x)
#define FastRSqrtFast(x) _VMX_RSqrtFast(x)
#define FastSinCos(x,s,c) _VMX_SinCos(x,s,c)
#define FastCos(x) _VMX_Cos(x)
#endif
#endif

1785
SpyCustom/sdk/mathlib.h Normal file

File diff suppressed because it is too large Load Diff

40
SpyCustom/sdk/mem.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef TIER0_MEM_H
#define TIER0_MEM_H
#ifdef _WIN32
#pragma once
#endif
#include <stddef.h>
#ifdef LINUX
#undef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
#include "platform.h"
#if !defined(STATIC_TIER0) && !defined(_STATIC_LINKED)
#ifdef TIER0_DLL_EXPORT
# define MEM_INTERFACE DLL_EXPORT
#else
# define MEM_INTERFACE DLL_IMPORT
#endif
#else
#define MEM_INTERFACE extern
#endif
MEM_INTERFACE void* MemAllocScratch(int nMemSize);
MEM_INTERFACE void MemFreeScratch();
#ifdef _LINUX
MEM_INTERFACE void ZeroMemory(void* mem, size_t length);
#endif
#endif

567
SpyCustom/sdk/memalloc.h Normal file
View File

@ -0,0 +1,567 @@
#ifndef TIER0_MEMALLOC_H
#define TIER0_MEMALLOC_H
#ifdef _WIN32
#pragma once
#endif
#ifndef POSIX
#endif
#if defined( _MEMTEST )
#ifdef _WIN32
#define USE_MEM_DEBUG 1
#endif
#endif
#define MEM_DEBUG_CLASSNAME 1
#include <stddef.h>
#if defined( OSX )
#include <malloc/malloc.h>
#endif
#include "mem.h"
#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE)
struct _CrtMemState;
#define MEMALLOC_VERSION 1
typedef size_t(*MemAllocFailHandler_t)(size_t);
class IMemAlloc
{
public:
virtual void* Alloc(size_t nSize) = 0;
virtual void* Realloc(void* pMem, size_t nSize) = 0;
virtual void Free(void* pMem) = 0;
virtual void* Expand_NoLongerSupported(void* pMem, size_t nSize) = 0;
virtual void* Alloc(size_t nSize, const char* pFileName, int nLine) = 0;
virtual void* Realloc(void* pMem, size_t nSize, const char* pFileName, int nLine) = 0;
virtual void Free(void* pMem, const char* pFileName, int nLine) = 0;
virtual void* Expand_NoLongerSupported(void* pMem, size_t nSize, const char* pFileName, int nLine) = 0;
virtual size_t GetSize(void* pMem) = 0;
virtual void PushAllocDbgInfo(const char* pFileName, int nLine) = 0;
virtual void PopAllocDbgInfo() = 0;
virtual long CrtSetBreakAlloc(long lNewBreakAlloc) = 0;
virtual int CrtSetReportMode(int nReportType, int nReportMode) = 0;
virtual int CrtIsValidHeapPointer(const void* pMem) = 0;
virtual int CrtIsValidPointer(const void* pMem, unsigned int size, int access) = 0;
virtual int CrtCheckMemory(void) = 0;
virtual int CrtSetDbgFlag(int nNewFlag) = 0;
virtual void CrtMemCheckpoint(_CrtMemState* pState) = 0;
virtual void DumpStats() = 0;
virtual void DumpStatsFileBase(char const* pchFileBase) = 0;
virtual void* CrtSetReportFile(int nRptType, void* hFile) = 0;
virtual void* CrtSetReportHook(void* pfnNewHook) = 0;
virtual int CrtDbgReport(int nRptType, const char* szFile,
int nLine, const char* szModule, const char* pMsg) = 0;
virtual int heapchk() = 0;
virtual bool IsDebugHeap() = 0;
virtual void GetActualDbgInfo(const char*& pFileName, int& nLine) = 0;
virtual void RegisterAllocation(const char* pFileName, int nLine, int nLogicalSize, int nActualSize, unsigned nTime) = 0;
virtual void RegisterDeallocation(const char* pFileName, int nLine, int nLogicalSize, int nActualSize, unsigned nTime) = 0;
virtual int GetVersion() = 0;
virtual void CompactHeap() = 0;
virtual MemAllocFailHandler_t SetAllocFailHandler(MemAllocFailHandler_t pfnMemAllocFailHandler) = 0;
virtual void DumpBlockStats(void*) = 0;
#if defined( _MEMTEST )
virtual void SetStatsExtraInfo(const char* pMapName, const char* pComment) = 0;
#endif
virtual size_t MemoryAllocFailed() = 0;
virtual uint32 GetDebugInfoSize() = 0;
virtual void SaveDebugInfo(void* pvDebugInfo) = 0;
virtual void RestoreDebugInfo(const void* pvDebugInfo) = 0;
virtual void InitDebugInfo(void* pvDebugInfo, const char* pchRootFileName, int nLine) = 0;
virtual void GlobalMemoryStatus(size_t* pUsedMemory, size_t* pFreeMemory) = 0;
};
MEM_INTERFACE IMemAlloc* g_pMemAlloc;
#ifdef MEMALLOC_REGIONS
#ifndef MEMALLOC_REGION
#define MEMALLOC_REGION 0
#endif
inline void* MemAlloc_Alloc(size_t nSize)
{
return g_pMemAlloc->RegionAlloc(MEMALLOC_REGION, nSize);
}
inline void* MemAlloc_Alloc(size_t nSize, const char* pFileName, int nLine)
{
return g_pMemAlloc->RegionAlloc(MEMALLOC_REGION, nSize, pFileName, nLine);
}
#else
#undef MEMALLOC_REGION
inline void* MemAlloc_Alloc(size_t nSize)
{
return g_pMemAlloc->Alloc(nSize);
}
inline void* MemAlloc_Alloc(size_t nSize, const char* pFileName, int nLine)
{
return g_pMemAlloc->Alloc(nSize, pFileName, nLine);
}
#endif
inline void MemAlloc_Free(void* ptr)
{
g_pMemAlloc->Free(ptr);
}
inline void MemAlloc_Free(void* ptr, const char* pFileName, int nLine)
{
g_pMemAlloc->Free(ptr, pFileName, nLine);
}
inline bool ValueIsPowerOfTwo(size_t value)
{
return (value & (value - 1)) == 0;
}
inline void* MemAlloc_AllocAligned(size_t size, size_t align)
{
unsigned char* pAlloc, * pResult;
if (!IsPowerOfTwo(align))
return NULL;
align = (align > sizeof(void*) ? align : sizeof(void*)) - 1;
if ((pAlloc = (unsigned char*)g_pMemAlloc->Alloc(sizeof(void*) + align + size)) == (unsigned char*)NULL)
return NULL;
pResult = (unsigned char*)((size_t)(pAlloc + sizeof(void*) + align) & ~align);
((unsigned char**)(pResult))[-1] = pAlloc;
return (void*)pResult;
}
inline void* MemAlloc_AllocAligned(size_t size, size_t align, const char* pszFile, int nLine)
{
unsigned char* pAlloc, * pResult;
if (!IsPowerOfTwo(align))
return NULL;
align = (align > sizeof(void*) ? align : sizeof(void*)) - 1;
if ((pAlloc = (unsigned char*)g_pMemAlloc->Alloc(sizeof(void*) + align + size, pszFile, nLine)) == (unsigned char*)NULL)
return NULL;
pResult = (unsigned char*)((size_t)(pAlloc + sizeof(void*) + align) & ~align);
((unsigned char**)(pResult))[-1] = pAlloc;
return (void*)pResult;
}
inline void* MemAlloc_AllocAlignedUnattributed(size_t size, size_t align)
{
unsigned char* pAlloc, * pResult;
if (!ValueIsPowerOfTwo(align))
return NULL;
align = (align > sizeof(void*) ? align : sizeof(void*)) - 1;
if ((pAlloc = (unsigned char*)MemAlloc_Alloc(sizeof(void*) + align + size)) == (unsigned char*)NULL)
return NULL;
pResult = (unsigned char*)((size_t)(pAlloc + sizeof(void*) + align) & ~align);
((unsigned char**)(pResult))[-1] = pAlloc;
return (void*)pResult;
}
inline void* MemAlloc_AllocAlignedFileLine(size_t size, size_t align, const char* pszFile, int nLine)
{
unsigned char* pAlloc, * pResult;
if (!ValueIsPowerOfTwo(align))
return NULL;
align = (align > sizeof(void*) ? align : sizeof(void*)) - 1;
if ((pAlloc = (unsigned char*)MemAlloc_Alloc(sizeof(void*) + align + size, pszFile, nLine)) == (unsigned char*)NULL)
return NULL;
pResult = (unsigned char*)((size_t)(pAlloc + sizeof(void*) + align) & ~align);
((unsigned char**)(pResult))[-1] = pAlloc;
return (void*)pResult;
}
inline void* MemAlloc_ReallocAligned(void* ptr, size_t size, size_t align)
{
if (!IsPowerOfTwo(align))
return NULL;
if (((size_t)ptr & (align - 1)) != 0)
return NULL;
if (!ptr)
return MemAlloc_AllocAligned(size, align);
void* pAlloc, * pResult;
pAlloc = ptr;
pAlloc = (void*)(((size_t)pAlloc & ~(sizeof(void*) - 1)) - sizeof(void*));
pAlloc = *((void**)pAlloc);
size_t nOffset = (size_t)ptr - (size_t)pAlloc;
size_t nOldSize = g_pMemAlloc->GetSize(pAlloc);
if (nOldSize >= size + nOffset)
return ptr;
pResult = MemAlloc_AllocAligned(size, align);
memcpy(pResult, ptr, nOldSize - nOffset);
g_pMemAlloc->Free(pAlloc);
return pResult;
}
inline void MemAlloc_FreeAligned(void* pMemBlock)
{
void* pAlloc;
if (pMemBlock == NULL)
return;
pAlloc = pMemBlock;
pAlloc = (void*)(((size_t)pAlloc & ~(sizeof(void*) - 1)) - sizeof(void*));
pAlloc = *((void**)pAlloc);
g_pMemAlloc->Free(pAlloc);
}
inline void MemAlloc_FreeAligned(void* pMemBlock, const char* pFileName, int nLine)
{
void* pAlloc;
if (pMemBlock == NULL)
return;
pAlloc = pMemBlock;
pAlloc = (void*)(((size_t)pAlloc & ~(sizeof(void*) - 1)) - sizeof(void*));
pAlloc = *((void**)pAlloc);
g_pMemAlloc->Free(pAlloc, pFileName, nLine);
}
inline size_t MemAlloc_GetSizeAligned(void* pMemBlock)
{
void* pAlloc;
if (pMemBlock == NULL)
return 0;
pAlloc = pMemBlock;
pAlloc = (void*)(((size_t)pAlloc & ~(sizeof(void*) - 1)) - sizeof(void*));
pAlloc = *((void**)pAlloc);
return g_pMemAlloc->GetSize(pAlloc) - ((byte*)pMemBlock - (byte*)pAlloc);
}
#if (defined(_DEBUG) || defined(USE_MEM_DEBUG))
#define MEM_ALLOC_CREDIT_(tag) CMemAllocAttributeAlloction memAllocAttributeAlloction( tag, __LINE__ )
#define MemAlloc_PushAllocDbgInfo( pszFile, line ) g_pMemAlloc->PushAllocDbgInfo( pszFile, line )
#define MemAlloc_PopAllocDbgInfo() g_pMemAlloc->PopAllocDbgInfo()
#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) g_pMemAlloc->RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime )
#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) g_pMemAlloc->RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime )
#else
#define MEM_ALLOC_CREDIT_(tag) ((void)0)
#define MemAlloc_PushAllocDbgInfo( pszFile, line ) ((void)0)
#define MemAlloc_PopAllocDbgInfo() ((void)0)
#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#endif
#define MemAlloc_DumpStats() g_pMemAlloc->DumpStats()
#define MemAlloc_CompactHeap() g_pMemAlloc->CompactHeap()
#define MemAlloc_OutOfMemory() g_pMemAlloc->OutOfMemory()
#define MemAlloc_CompactIncremental() g_pMemAlloc->CompactIncremental()
#define MemAlloc_DumpStatsFileBase( _filename ) g_pMemAlloc->DumpStatsFileBase( _filename )
#define MemAlloc_CrtCheckMemory() g_pMemAlloc->CrtCheckMemory()
#define MemAlloc_GlobalMemoryStatus( _usedMemory, _freeMemory ) g_pMemAlloc->GlobalMemoryStatus( _usedMemory, _freeMemory )
#define MemAlloc_MemoryAllocFailed() g_pMemAlloc->MemoryAllocFailed()
#define MemAlloc_GetDebugInfoSize() g_pMemAlloc->GetDebugInfoSize()
#define MemAlloc_SaveDebugInfo( pvDebugInfo ) g_pMemAlloc->SaveDebugInfo( pvDebugInfo )
#define MemAlloc_RestoreDebugInfo( pvDebugInfo ) g_pMemAlloc->RestoreDebugInfo( pvDebugInfo )
#define MemAlloc_InitDebugInfo( pvDebugInfo, pchRootFileName, nLine ) g_pMemAlloc->InitDebugInfo( pvDebugInfo, pchRootFileName, nLine )
#define MemAlloc_GetSize( x ) g_pMemAlloc->GetSize( x );
class CMemAllocAttributeAlloction
{
public:
CMemAllocAttributeAlloction(const char* pszFile, int line)
{
MemAlloc_PushAllocDbgInfo(pszFile, line);
}
~CMemAllocAttributeAlloction()
{
MemAlloc_PopAllocDbgInfo();
}
};
#define MEM_ALLOC_CREDIT() MEM_ALLOC_CREDIT_(__FILE__)
#if defined(_WIN32) && ( defined(_DEBUG) || defined(USE_MEM_DEBUG) )
#pragma warning(disable:4290)
#pragma warning(push)
#include <typeinfo>
#if defined(_CPPRTTI) && defined(MEM_DEBUG_CLASSNAME)
#define MEM_ALLOC_CREDIT_CLASS() MEM_ALLOC_CREDIT_( typeid(*this).name() )
#define MEM_ALLOC_CLASSNAME(type) (typeid((type*)(0)).name())
#else
#define MEM_ALLOC_CREDIT_CLASS() MEM_ALLOC_CREDIT_( __FILE__ )
#define MEM_ALLOC_CLASSNAME(type) (__FILE__)
#endif
#ifdef _MSC_VER
#define MEM_ALLOC_CREDIT_FUNCTION() MEM_ALLOC_CREDIT_( __FUNCTION__ )
#else
#define MEM_ALLOC_CREDIT_FUNCTION() (__FILE__)
#endif
#pragma warning(pop)
#else
#define MEM_ALLOC_CREDIT_CLASS()
#define MEM_ALLOC_CLASSNAME(type) NULL
#define MEM_ALLOC_CREDIT_FUNCTION()
#endif
#if (defined(_DEBUG) || defined(USE_MEM_DEBUG))
struct MemAllocFileLine_t
{
const char* pszFile;
int line;
};
#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag ) \
static CUtlMap<void *, MemAllocFileLine_t, int> g_##tag##Allocs( DefLessFunc( void *) ); \
static const char *g_psz##tag##Alloc = strcpy( (char *)g_pMemAlloc->Alloc( strlen( #tag "Alloc" ) + 1, "intentional leak", 0 ), #tag "Alloc" );
#define MemAlloc_RegisterExternalAllocation( tag, p, size ) \
if ( !p ) \
; \
else \
{ \
MemAllocFileLine_t fileLine = { g_psz##tag##Alloc, 0 }; \
g_pMemAlloc->GetActualDbgInfo( fileLine.pszFile, fileLine.line ); \
if ( fileLine.pszFile != g_psz##tag##Alloc ) \
{ \
g_##tag##Allocs.Insert( p, fileLine ); \
} \
\
MemAlloc_RegisterAllocation( fileLine.pszFile, fileLine.line, size, size, 0); \
}
#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) \
if ( !p ) \
; \
else \
{ \
MemAllocFileLine_t fileLine = { g_psz##tag##Alloc, 0 }; \
CUtlMap<void *, MemAllocFileLine_t, int>::IndexType_t iRecordedFileLine = g_##tag##Allocs.Find( p ); \
if ( iRecordedFileLine != g_##tag##Allocs.InvalidIndex() ) \
{ \
fileLine = g_##tag##Allocs[iRecordedFileLine]; \
g_##tag##Allocs.RemoveAt( iRecordedFileLine ); \
} \
\
MemAlloc_RegisterDeallocation( fileLine.pszFile, fileLine.line, size, size, 0); \
}
#else
#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag )
#define MemAlloc_RegisterExternalAllocation( tag, p, size ) ((void)0)
#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) ((void)0)
#endif
#elif defined( POSIX )
#if defined( OSX )
inline void* memalign(size_t alignment, size_t size) { void* pTmp = NULL; pTmp = malloc(size); return pTmp; }
#endif
inline void* _aligned_malloc(size_t nSize, size_t align) { return memalign(align, nSize); }
inline void _aligned_free(void* ptr) { free(ptr); }
inline void* MemAlloc_Alloc(size_t nSize, const char* pFileName = NULL, int nLine = 0) { return malloc(nSize); }
inline void MemAlloc_Free(void* ptr, const char* pFileName = NULL, int nLine = 0) { free(ptr); }
inline void* MemAlloc_AllocAligned(size_t size, size_t align, const char* pszFile = NULL, int nLine = 0) { return memalign(align, size); }
inline void* MemAlloc_AllocAlignedFileLine(size_t size, size_t align, const char* pszFile = NULL, int nLine = 0) { return memalign(align, size); }
inline void MemAlloc_FreeAligned(void* pMemBlock, const char* pszFile = NULL, int nLine = 0) { free(pMemBlock); }
#if defined( OSX )
inline size_t _msize(void* ptr) { return malloc_size(ptr); }
#else
inline size_t _msize(void* ptr) { return malloc_usable_size(ptr); }
#endif
inline void* MemAlloc_ReallocAligned(void* ptr, size_t size, size_t align)
{
void* ptr_new_aligned = memalign(align, size);
if (ptr_new_aligned)
{
size_t old_size = _msize(ptr);
size_t copy_size = (size < old_size) ? size : old_size;
memcpy(ptr_new_aligned, ptr, copy_size);
free(ptr);
}
return ptr_new_aligned;
}
#else
#define MemAlloc_GetDebugInfoSize() g_pMemAlloc->GetDebugInfoSize()
#define MemAlloc_SaveDebugInfo( pvDebugInfo ) g_pMemAlloc->SaveDebugInfo( pvDebugInfo )
#define MemAlloc_RestoreDebugInfo( pvDebugInfo ) g_pMemAlloc->RestoreDebugInfo( pvDebugInfo )
#define MemAlloc_InitDebugInfo( pvDebugInfo, pchRootFileName, nLine ) g_pMemAlloc->InitDebugInfo( pvDebugInfo, pchRootFileName, nLine )
#endif
#if !defined(STEAM) && defined(NO_MALLOC_OVERRIDE)
#define MEM_ALLOC_CREDIT_(tag) ((void)0)
#define MEM_ALLOC_CREDIT() MEM_ALLOC_CREDIT_(__FILE__)
#define MEM_ALLOC_CREDIT_FUNCTION()
#define MEM_ALLOC_CREDIT_CLASS()
#define MEM_ALLOC_CLASSNAME(type) NULL
#define MemAlloc_PushAllocDbgInfo( pszFile, line )
#define MemAlloc_PopAllocDbgInfo()
#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#define MemAlloc_DumpStats() ((void)0)
#define MemAlloc_CompactHeap() ((void)0)
#define MemAlloc_OutOfMemory() ((void)0)
#define MemAlloc_CompactIncremental() ((void)0)
#define MemAlloc_DumpStatsFileBase( _filename ) ((void)0)
inline bool MemAlloc_CrtCheckMemory() { return true; }
inline void MemAlloc_GlobalMemoryStatus(size_t* pusedMemory, size_t* pfreeMemory)
{
*pusedMemory = 0;
*pfreeMemory = 0;
}
#define MemAlloc_MemoryAllocFailed() 0
#define MemAlloc_GetDebugInfoSize() 0
#define MemAlloc_SaveDebugInfo( pvDebugInfo ) ((void)0)
#define MemAlloc_RestoreDebugInfo( pvDebugInfo ) ((void)0)
#define MemAlloc_InitDebugInfo( pvDebugInfo, pchRootFileName, nLine ) ((void)0)
#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag )
#define MemAlloc_RegisterExternalAllocation( tag, p, size ) ((void)0)
#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) ((void)0)
#endif
#if defined( POSIX ) && !defined( NO_HOOK_MALLOC )
PLATFORM_INTERFACE void MemoryLogMessage(char const* s);
PLATFORM_INTERFACE void EnableMemoryLogging(bool bOnOff);
PLATFORM_INTERFACE void DumpMemoryLog(int nThresh);
PLATFORM_INTERFACE void DumpMemorySummary(void);
PLATFORM_INTERFACE void SetMemoryMark(void);
PLATFORM_INTERFACE void DumpChangedMemory(int nThresh);
#else
FORCEINLINE void MemoryLogMessage(char const* s)
{
}
FORCEINLINE void EnableMemoryLogging(bool bOnOff)
{
}
FORCEINLINE void DumpMemoryLog(int nThresh)
{
}
FORCEINLINE void DumpMemorySummary(void)
{
}
FORCEINLINE void SetMemoryMark(void)
{
}
FORCEINLINE void DumpChangedMemory(int nThresh)
{
}
#endif
#ifdef POSIX
PLATFORM_INTERFACE size_t ApproximateProcessMemoryUsage(void);
#else
FORCEINLINE size_t ApproximateProcessMemoryUsage(void)
{
return 0;
}
#endif
struct aligned_tmp_t
{
};
template< int bytesAlignment = 16, class T = aligned_tmp_t >
class CAlignedNewDelete : public T
{
public:
void* operator new(size_t nSize)
{
return MemAlloc_AllocAligned(nSize, bytesAlignment);
}
void* operator new(size_t nSize, int nBlockUse, const char* pFileName, int nLine)
{
return MemAlloc_AllocAlignedFileLine(nSize, bytesAlignment, pFileName, nLine);
}
void operator delete(void* pData)
{
if (pData)
{
MemAlloc_FreeAligned(pData);
}
}
void operator delete(void* pData, int nBlockUse, const char* pFileName, int nLine)
{
if (pData)
{
MemAlloc_FreeAligned(pData, pFileName, nLine);
}
}
};
#endif

16
SpyCustom/sdk/memdbgoff.h Normal file
View File

@ -0,0 +1,16 @@
#ifdef MEM_OVERRIDE_ON
#undef malloc
#undef realloc
#undef calloc
#undef free
#undef _expand
#undef _msize
#undef new
#undef _aligned_malloc
#undef _aligned_free
#undef _malloc_dbg
#undef MEM_OVERRIDE_ON
#endif

219
SpyCustom/sdk/memdbgon.h Normal file
View File

@ -0,0 +1,219 @@
#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE)
#if defined(_DEBUG) && !defined(USE_MEM_DEBUG)
#define USE_MEM_DEBUG 1
#endif
#if defined(NO_HOOK_MALLOC)
#undef USE_MEM_DEBUG
#endif
#if (defined(_DEBUG) || !defined(_INC_CRTDBG)) || defined(MEMDBGON_H)
#include "basetypes.h"
#ifdef _WIN32
#include <tchar.h>
#else
#include <wchar.h>
#endif
#include <string.h>
#include <malloc.h>
#include "commonmacros.h"
#include "memalloc.h"
#if defined(USE_MEM_DEBUG)
#if defined( POSIX )
#define _NORMAL_BLOCK 1
#include <cstddef>
#include <glob.h>
#include <new>
#include <sys/types.h>
#if !defined( DID_THE_OPERATOR_NEW )
#define DID_THE_OPERATOR_NEW
void* operator new(size_t nSize, int blah, const char* pFileName, int nLine);
void* operator new[](size_t nSize, int blah, const char* pFileName, int nLine);
#endif
#else
#if !defined(_DEBUG)
#define _DEBUG 1
#include <crtdbg.h>
#undef _DEBUG
#else
#include <crtdbg.h>
#endif
#endif
#endif
#include "memdbgoff.h"
#define MEM_OVERRIDE_ON 1
#undef malloc
#undef realloc
#undef calloc
#undef _expand
#undef free
#undef _msize
#undef _aligned_malloc
#undef _aligned_free
#ifndef MEMDBGON_H
inline void* MemAlloc_InlineCallocMemset(void* pMem, size_t nCount, size_t nElementSize)
{
memset(pMem, 0, nElementSize * nCount);
return pMem;
}
#endif
#define calloc(c, s) MemAlloc_InlineCallocMemset(malloc(c*s), c, s)
#define free(p) g_pMemAlloc->Free( p )
#define _msize(p) g_pMemAlloc->GetSize( p )
#define _expand(p, s) _expand_NoLongerSupported(p, s)
#define _aligned_free( p ) MemAlloc_FreeAligned( p )
#if defined(USE_MEM_DEBUG)
#define malloc(s) g_pMemAlloc->Alloc( s, __FILE__, __LINE__)
#define realloc(p, s) g_pMemAlloc->Realloc( p, s, __FILE__, __LINE__ )
#define _aligned_malloc( s, a ) MemAlloc_AllocAligned( s, a, __FILE__, __LINE__ )
#define _malloc_dbg(s, t, f, l) WHYCALLINGTHISDIRECTLY(s)
#if !defined( LINUX )
#if defined(__AFX_H__) && defined(DEBUG_NEW)
#define new DEBUG_NEW
#else
#undef new
#define MEMALL_DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new MEMALL_DEBUG_NEW
#endif
#endif
#undef _strdup
#undef strdup
#undef _wcsdup
#undef wcsdup
#define _strdup(s) MemAlloc_StrDup(s, __FILE__, __LINE__)
#define strdup(s) MemAlloc_StrDup(s, __FILE__, __LINE__)
#define _wcsdup(s) MemAlloc_WcStrDup(s, __FILE__, __LINE__)
#define wcsdup(s) MemAlloc_WcStrDup(s, __FILE__, __LINE__)
#if !defined(MEMDBGON_H)
inline char* MemAlloc_StrDup(const char* pString, const char* pFileName, unsigned nLine)
{
char* pMemory;
if (!pString)
return NULL;
size_t len = strlen(pString) + 1;
if ((pMemory = (char*)g_pMemAlloc->Alloc(len, pFileName, nLine)) != NULL)
{
return strcpy(pMemory, pString);
}
return NULL;
}
inline wchar_t* MemAlloc_WcStrDup(const wchar_t* pString, const char* pFileName, unsigned nLine)
{
wchar_t* pMemory;
if (!pString)
return NULL;
size_t len = (wcslen(pString) + 1);
if ((pMemory = (wchar_t*)g_pMemAlloc->Alloc(len * sizeof(wchar_t), pFileName, nLine)) != NULL)
{
return wcscpy(pMemory, pString);
}
return NULL;
}
#endif
#else
#define malloc(s) g_pMemAlloc->Alloc( s )
#define realloc(p, s) g_pMemAlloc->Realloc( p, s )
#define _aligned_malloc( s, a ) MemAlloc_AllocAligned( s, a )
#ifndef _malloc_dbg
#define _malloc_dbg(s, t, f, l) WHYCALLINGTHISDIRECTLY(s)
#endif
#undef new
#undef _strdup
#undef strdup
#undef _wcsdup
#undef wcsdup
#define _strdup(s) MemAlloc_StrDup(s)
#define strdup(s) MemAlloc_StrDup(s)
#define _wcsdup(s) MemAlloc_WcStrDup(s)
#define wcsdup(s) MemAlloc_WcStrDup(s)
#if !defined(MEMDBGON_H)
inline char* MemAlloc_StrDup(const char* pString)
{
char* pMemory;
if (!pString)
return NULL;
size_t len = strlen(pString) + 1;
if ((pMemory = (char*)g_pMemAlloc->Alloc(len)) != NULL)
{
return strcpy(pMemory, pString);
}
return NULL;
}
inline wchar_t* MemAlloc_WcStrDup(const wchar_t* pString)
{
wchar_t* pMemory;
if (!pString)
return NULL;
size_t len = (wcslen(pString) + 1);
if ((pMemory = (wchar_t*)g_pMemAlloc->Alloc(len * sizeof(wchar_t))) != NULL)
{
return wcscpy(pMemory, pString);
}
return NULL;
}
#endif
#endif
#define MEMDBGON_H
#else
#if defined(USE_MEM_DEBUG)
#ifndef _STATIC_LINKED
#pragma message ("Note: file includes crtdbg.h directly, therefore will cannot use memdbgon.h in non-debug build")
#else
#error "Error: file includes crtdbg.h directly, therefore will cannot use memdbgon.h in non-debug build. Not recoverable in static build"
#endif
#endif
#endif
#else
#include "memalloc.h"
#endif

590
SpyCustom/sdk/mempool.h Normal file
View File

@ -0,0 +1,590 @@
#ifndef MEMPOOL_H
#define MEMPOOL_H
#ifdef _WIN32
#pragma once
#endif
#include "memalloc.h"
#include "tslist.h"
#include "platform.h"
#include "utlvector.h"
#include "utlrbtree.h"
typedef void (*MemoryPoolReportFunc_t)(PRINTF_FORMAT_STRING char const* pMsg, ...);
class CUtlMemoryPool
{
public:
enum MemoryPoolGrowType_t
{
GROW_NONE = 0,
GROW_FAST = 1,
GROW_SLOW = 2
};
CUtlMemoryPool(int blockSize, int numElements, int growMode = GROW_FAST, const char* pszAllocOwner = NULL, int nAlignment = 0);
~CUtlMemoryPool();
void* Alloc();
void* Alloc(size_t amount);
void* AllocZero();
void* AllocZero(size_t amount);
void Free(void* pMem);
void Clear();
static void SetErrorReportFunc(MemoryPoolReportFunc_t func);
int Count() const { return m_BlocksAllocated; }
int PeakCount() const { return m_PeakAlloc; }
int BlockSize() const { return m_BlockSize; }
int Size() const;
bool IsAllocationWithinPool(void* pMem) const;
protected:
class CBlob
{
public:
CBlob* m_pPrev, * m_pNext;
int m_NumBytes;
char m_Data[1];
char m_Padding[3];
};
void Init();
void AddNewBlob();
void ReportLeaks();
int m_BlockSize;
int m_BlocksPerBlob;
int m_GrowMode;
int m_BlocksAllocated;
int m_PeakAlloc;
unsigned short m_nAlignment;
unsigned short m_NumBlobs;
void* m_pHeadOfFreeList;
const char* m_pszAllocOwner;
CBlob m_BlobHead;
static MemoryPoolReportFunc_t g_ReportFunc;
};
class CMemoryPoolMT : public CUtlMemoryPool
{
public:
CMemoryPoolMT(int blockSize, int numElements, int growMode = GROW_FAST, const char* pszAllocOwner = NULL, int nAlignment = 0) : CUtlMemoryPool(blockSize, numElements, growMode, pszAllocOwner, nAlignment) {}
void* Alloc() { AUTO_LOCK(m_mutex); return CUtlMemoryPool::Alloc(); }
void* Alloc(size_t amount) { AUTO_LOCK(m_mutex); return CUtlMemoryPool::Alloc(amount); }
void* AllocZero() { AUTO_LOCK(m_mutex); return CUtlMemoryPool::AllocZero(); }
void* AllocZero(size_t amount) { AUTO_LOCK(m_mutex); return CUtlMemoryPool::AllocZero(amount); }
void Free(void* pMem) { AUTO_LOCK(m_mutex); CUtlMemoryPool::Free(pMem); }
void Clear() { AUTO_LOCK(m_mutex); return CUtlMemoryPool::Clear(); }
private:
CThreadFastMutex m_mutex;
};
template< class T >
class CClassMemoryPool : public CUtlMemoryPool
{
public:
CClassMemoryPool(int numElements, int growMode = GROW_FAST, int nAlignment = 0) :
CUtlMemoryPool(sizeof(T), numElements, growMode, MEM_ALLOC_CLASSNAME(T), nAlignment) {}
T* Alloc();
T* AllocZero();
void Free(T* pMem);
void Clear();
};
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE = false, int COMPACT_THRESHOLD = 4 >
class CAlignedMemPool
{
enum
{
BLOCK_SIZE = COMPILETIME_MAX(ALIGN_VALUE(ITEM_SIZE, ALIGNMENT), 8),
};
public:
CAlignedMemPool();
void* Alloc();
void Free(void* p);
static int __cdecl CompareChunk(void* const* ppLeft, void* const* ppRight);
void Compact();
int NumTotal() { AUTO_LOCK(m_mutex); return m_Chunks.Count() * (CHUNK_SIZE / BLOCK_SIZE); }
int NumAllocated() { AUTO_LOCK(m_mutex); return NumTotal() - m_nFree; }
int NumFree() { AUTO_LOCK(m_mutex); return m_nFree; }
int BytesTotal() { AUTO_LOCK(m_mutex); return NumTotal() * BLOCK_SIZE; }
int BytesAllocated() { AUTO_LOCK(m_mutex); return NumAllocated() * BLOCK_SIZE; }
int BytesFree() { AUTO_LOCK(m_mutex); return NumFree() * BLOCK_SIZE; }
int ItemSize() { return ITEM_SIZE; }
int BlockSize() { return BLOCK_SIZE; }
int ChunkSize() { return CHUNK_SIZE; }
private:
struct FreeBlock_t
{
FreeBlock_t* pNext;
byte reserved[BLOCK_SIZE - sizeof(FreeBlock_t*)];
};
CUtlVector<void*> m_Chunks;
FreeBlock_t* m_pFirstFree;
int m_nFree;
CAllocator m_Allocator;
double m_TimeLastCompact;
CThreadFastMutex m_mutex;
};
template <typename T, int nInitialCount = 0, bool bDefCreateNewIfEmpty = true >
class CObjectPool
{
public:
CObjectPool()
{
int i = nInitialCount;
while (i-- > 0)
{
m_AvailableObjects.PushItem(new T);
}
}
~CObjectPool()
{
Purge();
}
int NumAvailable()
{
return m_AvailableObjects.Count();
}
void Purge()
{
T* p = NULL;
while (m_AvailableObjects.PopItem(&p))
{
delete p;
}
}
T* GetObject(bool bCreateNewIfEmpty = bDefCreateNewIfEmpty)
{
T* p = NULL;
if (!m_AvailableObjects.PopItem(&p))
{
p = (bCreateNewIfEmpty) ? new T : NULL;
}
return p;
}
void PutObject(T* p)
{
m_AvailableObjects.PushItem(p);
}
private:
CTSList<T*> m_AvailableObjects;
};
template <size_t PROVIDED_ITEM_SIZE, int ITEM_COUNT>
class CFixedBudgetMemoryPool
{
public:
CFixedBudgetMemoryPool()
{
m_pBase = m_pLimit = 0;
COMPILE_TIME_ASSERT(ITEM_SIZE % 4 == 0);
}
bool Owns(void* p)
{
return (p >= m_pBase && p < m_pLimit);
}
void* Alloc()
{
MEM_ALLOC_CREDIT_CLASS();
#ifndef USE_MEM_DEBUG
if (!m_pBase)
{
LOCAL_THREAD_LOCK();
if (!m_pBase)
{
byte* pMemory = m_pBase = (byte*)malloc(ITEM_COUNT * ITEM_SIZE);
m_pLimit = m_pBase + (ITEM_COUNT * ITEM_SIZE);
for (int i = 0; i < ITEM_COUNT; i++)
{
m_freeList.Push((TSLNodeBase_t*)pMemory);
pMemory += ITEM_SIZE;
}
}
}
void* p = m_freeList.Pop();
if (p)
return p;
#endif
return malloc(ITEM_SIZE);
}
void Free(void* p)
{
#ifndef USE_MEM_DEBUG
if (Owns(p))
m_freeList.Push((TSLNodeBase_t*)p);
else
#endif
free(p);
}
void Clear()
{
#ifndef USE_MEM_DEBUG
if (m_pBase)
{
free(m_pBase);
}
m_pBase = m_pLimit = 0;
Construct(&m_freeList);
#endif
}
bool IsEmpty()
{
#ifndef USE_MEM_DEBUG
if (m_pBase && m_freeList.Count() != ITEM_COUNT)
return false;
#endif
return true;
}
enum
{
ITEM_SIZE = ALIGN_VALUE(PROVIDED_ITEM_SIZE, TSLIST_NODE_ALIGNMENT)
};
CTSListBase m_freeList;
byte* m_pBase;
byte* m_pLimit;
};
#define BIND_TO_FIXED_BUDGET_POOL( poolName ) \
inline void* operator new( size_t size ) { return poolName.Alloc(); } \
inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { return poolName.Alloc(); } \
inline void operator delete( void* p ) { poolName.Free(p); } \
inline void operator delete( void* p, int nBlockUse, const char *pFileName, int nLine ) { poolName.Free(p); }
template< class T >
inline T* CClassMemoryPool<T>::Alloc()
{
T* pRet;
{
MEM_ALLOC_CREDIT_CLASS();
pRet = (T*)CUtlMemoryPool::Alloc();
}
if (pRet)
{
Construct(pRet);
}
return pRet;
}
template< class T >
inline T* CClassMemoryPool<T>::AllocZero()
{
T* pRet;
{
MEM_ALLOC_CREDIT_CLASS();
pRet = (T*)CUtlMemoryPool::AllocZero();
}
if (pRet)
{
Construct(pRet);
}
return pRet;
}
template< class T >
inline void CClassMemoryPool<T>::Free(T* pMem)
{
if (pMem)
{
Destruct(pMem);
}
CUtlMemoryPool::Free(pMem);
}
template< class T >
inline void CClassMemoryPool<T>::Clear()
{
CUtlRBTree<void*, int> freeBlocks;
SetDefLessFunc(freeBlocks);
void* pCurFree = m_pHeadOfFreeList;
while (pCurFree != NULL)
{
freeBlocks.Insert(pCurFree);
pCurFree = *((void**)pCurFree);
}
for (CBlob* pCur = m_BlobHead.m_pNext; pCur != &m_BlobHead; pCur = pCur->m_pNext)
{
int nElements = pCur->m_NumBytes / this->m_BlockSize;
T* p = (T*)AlignValue(pCur->m_Data, this->m_nAlignment);
T* pLimit = p + nElements;
while (p < pLimit)
{
if (freeBlocks.Find(p) == freeBlocks.InvalidIndex())
{
Destruct(p);
}
p++;
}
}
CUtlMemoryPool::Clear();
}
#define DECLARE_FIXEDSIZE_ALLOCATOR( _class ) \
public: \
inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \
inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \
inline void operator delete( void* p ) { s_Allocator.Free(p); } \
inline void operator delete( void* p, int nBlockUse, const char *pFileName, int nLine ) { s_Allocator.Free(p); } \
private: \
static CUtlMemoryPool s_Allocator
#define DEFINE_FIXEDSIZE_ALLOCATOR( _class, _initsize, _grow ) \
CUtlMemoryPool _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool")
#define DEFINE_FIXEDSIZE_ALLOCATOR_ALIGNED( _class, _initsize, _grow, _alignment ) \
CUtlMemoryPool _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool", _alignment )
#define DECLARE_FIXEDSIZE_ALLOCATOR_MT( _class ) \
public: \
inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \
inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \
inline void operator delete( void* p ) { s_Allocator.Free(p); } \
inline void operator delete( void* p, int nBlockUse, const char *pFileName, int nLine ) { s_Allocator.Free(p); } \
private: \
static CMemoryPoolMT s_Allocator
#define DEFINE_FIXEDSIZE_ALLOCATOR_MT( _class, _initsize, _grow ) \
CMemoryPoolMT _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool")
#define DECLARE_FIXEDSIZE_ALLOCATOR_EXTERNAL( _class ) \
public: \
inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_pAllocator->Alloc(size); } \
inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_pAllocator->Alloc(size); } \
inline void operator delete( void* p ) { s_pAllocator->Free(p); } \
private: \
static CUtlMemoryPool* s_pAllocator
#define DEFINE_FIXEDSIZE_ALLOCATOR_EXTERNAL( _class, _allocator ) \
CUtlMemoryPool* _class::s_pAllocator = _allocator
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE, int COMPACT_THRESHOLD >
inline CAlignedMemPool<ITEM_SIZE, ALIGNMENT, CHUNK_SIZE, CAllocator, GROWMODE, COMPACT_THRESHOLD>::CAlignedMemPool()
: m_pFirstFree(0),
m_nFree(0),
m_TimeLastCompact(0)
{
{ COMPILE_TIME_ASSERT(sizeof(FreeBlock_t) >= BLOCK_SIZE); }
{ COMPILE_TIME_ASSERT(ALIGN_VALUE(sizeof(FreeBlock_t), ALIGNMENT) == sizeof(FreeBlock_t)); }
}
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE, int COMPACT_THRESHOLD >
inline void* CAlignedMemPool<ITEM_SIZE, ALIGNMENT, CHUNK_SIZE, CAllocator, GROWMODE, COMPACT_THRESHOLD>::Alloc()
{
AUTO_LOCK(m_mutex);
if (!m_pFirstFree)
{
if (!GROWMODE && m_Chunks.Count())
{
return NULL;
}
FreeBlock_t* pNew = (FreeBlock_t*)m_Allocator.Alloc(CHUNK_SIZE);
Assert((unsigned)pNew % ALIGNMENT == 0);
m_Chunks.AddToTail(pNew);
m_nFree = CHUNK_SIZE / BLOCK_SIZE;
m_pFirstFree = pNew;
for (int i = 0; i < m_nFree - 1; i++)
{
pNew->pNext = pNew + 1;
pNew++;
}
pNew->pNext = NULL;
}
void* p = m_pFirstFree;
m_pFirstFree = m_pFirstFree->pNext;
m_nFree--;
return p;
}
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE, int COMPACT_THRESHOLD >
inline void CAlignedMemPool<ITEM_SIZE, ALIGNMENT, CHUNK_SIZE, CAllocator, GROWMODE, COMPACT_THRESHOLD>::Free(void* p)
{
AUTO_LOCK(m_mutex);
FreeBlock_t* pFree = ((FreeBlock_t*)p);
FreeBlock_t* pCur = m_pFirstFree;
FreeBlock_t* pPrev = NULL;
while (pCur && pFree > pCur)
{
pPrev = pCur;
pCur = pCur->pNext;
}
pFree->pNext = pCur;
if (pPrev)
{
pPrev->pNext = pFree;
}
else
{
m_pFirstFree = pFree;
}
m_nFree++;
if (m_nFree >= (CHUNK_SIZE / BLOCK_SIZE) * COMPACT_THRESHOLD)
{
double time = Plat_FloatTime();
double compactTime = (m_nFree >= (CHUNK_SIZE / BLOCK_SIZE) * COMPACT_THRESHOLD * 4) ? 15.0 : 30.0;
if (m_TimeLastCompact > time || m_TimeLastCompact + compactTime < time)
{
Compact();
m_TimeLastCompact = time;
}
}
}
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE, int COMPACT_THRESHOLD >
inline void CAlignedMemPool<ITEM_SIZE, ALIGNMENT, CHUNK_SIZE, CAllocator, GROWMODE, COMPACT_THRESHOLD>::Compact()
{
FreeBlock_t* pCur = m_pFirstFree;
FreeBlock_t* pPrev = NULL;
m_Chunks.Sort(CompareChunk);
#ifdef VALIDATE_ALIGNED_MEM_POOL
{
FreeBlock_t* p = m_pFirstFree;
while (p)
{
if (p->pNext && p > p->pNext)
{
__asm { int 3 }
}
p = p->pNext;
}
for (int i = 0; i < m_Chunks.Count(); i++)
{
if (i + 1 < m_Chunks.Count())
{
if (m_Chunks[i] > m_Chunks[i + 1])
{
__asm { int 3 }
}
}
}
}
#endif
int i;
for (i = 0; i < m_Chunks.Count(); i++)
{
int nBlocksPerChunk = CHUNK_SIZE / BLOCK_SIZE;
FreeBlock_t* pChunkLimit = ((FreeBlock_t*)m_Chunks[i]) + nBlocksPerChunk;
int nFromChunk = 0;
if (pCur == m_Chunks[i])
{
FreeBlock_t* pFirst = pCur;
while (pCur && pCur >= m_Chunks[i] && pCur < pChunkLimit)
{
pCur = pCur->pNext;
nFromChunk++;
}
pCur = pFirst;
}
while (pCur && pCur >= m_Chunks[i] && pCur < pChunkLimit)
{
if (nFromChunk != nBlocksPerChunk)
{
if (pPrev)
{
pPrev->pNext = pCur;
}
else
{
m_pFirstFree = pCur;
}
pPrev = pCur;
}
else if (pPrev)
{
pPrev->pNext = NULL;
}
else
{
m_pFirstFree = NULL;
}
pCur = pCur->pNext;
}
if (nFromChunk == nBlocksPerChunk)
{
m_Allocator.Free(m_Chunks[i]);
m_nFree -= nBlocksPerChunk;
m_Chunks[i] = 0;
}
}
for (i = m_Chunks.Count() - 1; i >= 0; i--)
{
if (!m_Chunks[i])
{
m_Chunks.FastRemove(i);
}
}
}
#endif

231
SpyCustom/sdk/meshreader.h Normal file
View File

@ -0,0 +1,231 @@
#ifndef MESHREADER_H
#define MESHREADER_H
#ifdef _WIN32
#pragma once
#endif
class CBaseMeshReader : protected MeshDesc_t
{
public:
CBaseMeshReader();
~CBaseMeshReader();
void BeginRead(
IMesh* pMesh,
int firstVertex = 0,
int numVertices = 0,
int firstIndex = 0,
int numIndices = 0);
void EndRead();
void BeginRead_Direct(const MeshDesc_t& desc, int numVertices, int nIndices);
void Reset();
protected:
IMesh* m_pMesh;
int m_MaxVertices;
int m_MaxIndices;
};
class CMeshReader : public CBaseMeshReader
{
public:
public:
int NumIndices() const;
unsigned short Index(int index) const;
const Vector& Position(int iVertex) const;
unsigned int Color(int iVertex) const;
const float* TexCoord(int iVertex, int stage) const;
void TexCoord2f(int iVertex, int stage, float& s, float& t) const;
const Vector2D& TexCoordVector2D(int iVertex, int stage) const;
int NumBoneWeights() const;
float Wrinkle(int iVertex) const;
const Vector& Normal(int iVertex) const;
void Normal(int iVertex, Vector& vNormal) const;
const Vector& TangentS(int iVertex) const;
const Vector& TangentT(int iVertex) const;
float BoneWeight(int iVertex) const;
#ifdef NEW_SKINNING
float* BoneMatrix(int iVertex) const;
#else
unsigned char* BoneMatrix(int iVertex) const;
#endif
};
inline CBaseMeshReader::CBaseMeshReader()
{
m_pMesh = NULL;
}
inline CBaseMeshReader::~CBaseMeshReader()
{
Assert(!m_pMesh);
}
inline void CBaseMeshReader::BeginRead(
IMesh* pMesh,
int firstVertex,
int numVertices,
int firstIndex,
int numIndices)
{
Assert(pMesh && (!m_pMesh));
if (numVertices < 0)
{
numVertices = pMesh->VertexCount();
}
if (numIndices < 0)
{
numIndices = pMesh->IndexCount();
}
m_pMesh = pMesh;
m_MaxVertices = numVertices;
m_MaxIndices = numIndices;
VertexCompressionType_t compressionType = CompressionType(pMesh->GetVertexFormat());
Assert(compressionType == VERTEX_COMPRESSION_NONE);
if (compressionType != VERTEX_COMPRESSION_NONE)
{
Warning("Cannot use CBaseMeshReader with compressed vertices! Will get junk data or a crash.\n");
}
pMesh->ModifyBeginEx(true, firstVertex, numVertices, firstIndex, numIndices, *this);
Reset();
}
inline void CBaseMeshReader::EndRead()
{
Assert(m_pMesh);
m_pMesh->ModifyEnd(*this);
m_pMesh = NULL;
}
inline void CBaseMeshReader::BeginRead_Direct(const MeshDesc_t& desc, int nVertices, int nIndices)
{
MeshDesc_t* pThis = this;
*pThis = desc;
m_MaxVertices = nVertices;
m_MaxIndices = nIndices;
Assert(desc.m_CompressionType == VERTEX_COMPRESSION_NONE);
if (desc.m_CompressionType != VERTEX_COMPRESSION_NONE)
{
Warning("Cannot use CBaseMeshReader with compressed vertices!\n");
}
}
inline void CBaseMeshReader::Reset()
{
}
inline int CMeshReader::NumIndices() const
{
return m_MaxIndices;
}
inline unsigned short CMeshReader::Index(int index) const
{
Assert((index >= 0) && (index < m_MaxIndices));
return m_pIndices[index * m_nIndexSize];
}
inline const Vector& CMeshReader::Position(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(Vector*)((char*)m_pPosition + iVertex * m_VertexSize_Position);
}
inline unsigned int CMeshReader::Color(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
unsigned char* pColor = m_pColor + iVertex * m_VertexSize_Color;
return (pColor[0] << 16) | (pColor[1] << 8) | (pColor[2]) | (pColor[3] << 24);
}
inline const float* CMeshReader::TexCoord(int iVertex, int iStage) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return (float*)((char*)m_pTexCoord[iStage] + iVertex * m_VertexSize_TexCoord[iStage]);
}
inline void CMeshReader::TexCoord2f(int iVertex, int iStage, float& s, float& t) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
float* p = (float*)((char*)m_pTexCoord[iStage] + iVertex * m_VertexSize_TexCoord[iStage]);
s = p[0];
t = p[1];
}
inline const Vector2D& CMeshReader::TexCoordVector2D(int iVertex, int iStage) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
Vector2D* p = (Vector2D*)((char*)m_pTexCoord[iStage] + iVertex * m_VertexSize_TexCoord[iStage]);
return *p;
}
inline float CMeshReader::Wrinkle(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(float*)((char*)m_pWrinkle + iVertex * m_VertexSize_Wrinkle);
}
inline int CMeshReader::NumBoneWeights() const
{
return m_NumBoneWeights;
}
inline const Vector& CMeshReader::Normal(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(const Vector*)(const float*)((char*)m_pNormal + iVertex * m_VertexSize_Normal);
}
inline void CMeshReader::Normal(int iVertex, Vector& vNormal) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
const float* p = (const float*)((char*)m_pNormal + iVertex * m_VertexSize_Normal);
vNormal.Init(p[0], p[1], p[2]);
}
inline const Vector& CMeshReader::TangentS(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(const Vector*)((char*)m_pTangentS + iVertex * m_VertexSize_TangentS);
}
inline const Vector& CMeshReader::TangentT(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(const Vector*)((char*)m_pTangentT + iVertex * m_VertexSize_TangentT);
}
inline float CMeshReader::BoneWeight(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
float* p = (float*)((char*)m_pBoneWeight + iVertex * m_VertexSize_BoneWeight);
return *p;
}
#endif

16
SpyCustom/sdk/meshutils.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef MESHUTILS_H
#define MESHUTILS_H
#ifdef _WIN32
#pragma once
#endif
void GenerateSequentialIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
void GenerateQuadIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
void GeneratePolygonIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
void GenerateLineStripIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
void GenerateLineLoopIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
#endif

View File

@ -0,0 +1,74 @@
#ifndef MESSAGEBOX_H
#define MESSAGEBOX_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui.h"
#include "Frame.h"
#ifdef MessageBox
#undef MessageBox
#endif
namespace vgui
{
class MessageBox : public Frame
{
DECLARE_CLASS_SIMPLE(MessageBox, Frame);
public:
MessageBox(const char* title, const char* text, Panel* parent = NULL);
MessageBox(const wchar_t* wszTitle, const wchar_t* wszText, Panel* parent = NULL);
~MessageBox();
virtual void DoModal(Frame* pFrameOver = NULL);
virtual void ShowWindow(Frame* pFrameOver = NULL);
virtual void SetCommand(const char* command);
virtual void SetCommand(KeyValues* command);
virtual void SetOKButtonVisible(bool state);
virtual void SetOKButtonText(const char* buttonText);
virtual void SetOKButtonText(const wchar_t* wszButtonText);
void SetCancelButtonVisible(bool state);
void SetCancelButtonText(const char* buttonText);
void SetCancelButtonText(const wchar_t* wszButtonText);
void SetCancelCommand(KeyValues* command);
virtual void DisableCloseButton(bool state);
virtual void OnCommand(const char* pCommand);
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;
};
}
#endif

57
SpyCustom/sdk/minidump.h Normal file
View File

@ -0,0 +1,57 @@
#ifndef MINIDUMP_H
#define MINIDUMP_H
#ifdef _WIN32
#pragma once
#endif
#include "platform.h"
PLATFORM_INTERFACE void SetMinidumpFilenamePrefix(const char* pszPrefix);
PLATFORM_INTERFACE void SetMinidumpComment(const char* pszComment);
PLATFORM_INTERFACE void WriteMiniDump(const char* pszFilenameSuffix = NULL);
typedef void (*FnWMain)(int, tchar* []);
typedef void (*FnVoidPtrFn)(void*);
#if defined(_WIN32) && !defined(_X360)
typedef void (*FnWMain)(int, tchar* []);
typedef int (*FnWMainIntRet)(int, tchar* []);
typedef void (*FnVoidPtrFn)(void*);
enum ECatchAndWriteMinidumpAction
{
k_ECatchAndWriteMiniDumpAbort = 0,
k_ECatchAndWriteMiniDumpReThrow = 1,
k_ECatchAndWriteMiniDumpIgnore = 2,
};
PLATFORM_INTERFACE void CatchAndWriteMiniDump(FnWMain pfn, int argc, tchar* argv[]);
PLATFORM_INTERFACE void CatchAndWriteMiniDumpForVoidPtrFn(FnVoidPtrFn pfn, void* pv, bool bExitQuietly);
PLATFORM_INTERFACE void CatchAndWriteMiniDumpEx(FnWMain pfn, int argc, tchar* argv[], ECatchAndWriteMinidumpAction eAction);
PLATFORM_INTERFACE int CatchAndWriteMiniDumpExReturnsInt(FnWMainIntRet pfn, int argc, tchar* argv[], ECatchAndWriteMinidumpAction eAction);
PLATFORM_INTERFACE void CatchAndWriteMiniDumpExForVoidPtrFn(FnVoidPtrFn pfn, void* pv, ECatchAndWriteMinidumpAction eAction);
struct _EXCEPTION_POINTERS;
typedef void (*FnMiniDump)(unsigned int uStructuredExceptionCode, _EXCEPTION_POINTERS* pExceptionInfo, const char* pszFilenameSuffix);
PLATFORM_INTERFACE FnMiniDump SetMiniDumpFunction(FnMiniDump pfn);
PLATFORM_INTERFACE bool WriteMiniDumpUsingExceptionInfo(
unsigned int uStructuredExceptionCode,
_EXCEPTION_POINTERS* pExceptionInfo,
int minidumpType,
const char* pszFilenameSuffix = NULL,
tchar* ptchMinidumpFileNameBuffer = NULL
);
PLATFORM_INTERFACE void MinidumpSetUnhandledExceptionFunction(FnMiniDump pfn);
PLATFORM_INTERFACE void EnableCrashingOnCrashes();
#endif
#endif

148
SpyCustom/sdk/modelloader.h Normal file
View File

@ -0,0 +1,148 @@
#if !defined( MOD_LOADER_H )
#define MOD_LOADER_H
#ifdef _WIN32
#pragma once
#endif
struct model_t;
class IMaterial;
class IFileList;
#include "utlmemory.h"
abstract_class IModelLoader
{
public:
enum REFERENCETYPE
{
FMODELLOADER_NOTLOADEDORREFERENCED = 0,
FMODELLOADER_LOADED = (1 << 0),
FMODELLOADER_SERVER = (1 << 1),
FMODELLOADER_CLIENT = (1 << 2),
FMODELLOADER_CLIENTDLL = (1 << 3),
FMODELLOADER_STATICPROP = (1 << 4),
FMODELLOADER_DETAILPROP = (1 << 5),
FMODELLOADER_REFERENCEMASK = (FMODELLOADER_SERVER | FMODELLOADER_CLIENT | FMODELLOADER_CLIENTDLL | FMODELLOADER_STATICPROP | FMODELLOADER_DETAILPROP),
FMODELLOADER_TOUCHED_BY_PRELOAD = (1 << 15),
FMODELLOADER_LOADED_BY_PRELOAD = (1 << 16),
FMODELLOADER_TOUCHED_MATERIALS = (1 << 17),
};
enum ReloadType_t
{
RELOAD_LOD_CHANGED = 0,
RELOAD_EVERYTHING,
RELOAD_REFRESH_MODELS,
};
virtual void Init(void) = 0;
virtual void Shutdown(void) = 0;
virtual int GetCount(void) = 0;
virtual model_t* GetModelForIndex(int i) = 0;
virtual const char* GetName(const model_t* model) = 0;
virtual void* GetExtraData(model_t* model) = 0;
virtual int GetModelFileSize(const char* name) = 0;
virtual model_t* GetModelForName(const char* name, REFERENCETYPE referencetype) = 0;
virtual model_t* ReferenceModel(const char* name, REFERENCETYPE referencetype) = 0;
virtual void UnreferenceModel(model_t* model, REFERENCETYPE referencetype) = 0;
virtual void UnreferenceAllModels(REFERENCETYPE referencetype) = 0;
virtual void UnloadUnreferencedModels(void) = 0;
virtual void PurgeUnusedModels(void) = 0;
virtual bool Map_GetRenderInfoAllocated(void) = 0;
virtual void Map_SetRenderInfoAllocated(bool allocated) = 0;
virtual void Map_LoadDisplacements(model_t* model, bool bRestoring) = 0;
virtual void Print(void) = 0;
virtual bool Map_IsValid(char const* mapname) = 0;
virtual void RecomputeSurfaceFlags(model_t* mod) = 0;
virtual void Studio_ReloadModels(ReloadType_t reloadType) = 0;
virtual bool IsLoaded(const model_t* mod) = 0;
virtual bool LastLoadedMapHasHDRLighting(void) = 0;
virtual void ReloadFilesInList(IFileList* pFilesToReload) = 0;
virtual const char* GetActiveMapName(void) = 0;
};
extern IModelLoader* modelloader;
class CMapLoadHelper
{
public:
CMapLoadHelper(int lumpToLoad);
~CMapLoadHelper(void);
byte* LumpBase(void);
int LumpSize(void);
int LumpOffset(void);
int LumpVersion() const;
const char* GetMapName(void);
char* GetLoadName(void);
char* GetDiskName(void);
struct worldbrushdata_t* GetMap(void);
static void Init(model_t* pMapModel, const char* pLoadname);
static void InitFromMemory(model_t* pMapModel, const void* pData, int nDataSize);
static void Shutdown(void);
static int GetRefCount(void);
static void FreeLightingLump();
static int LumpSize(int lumpId);
static int LumpOffset(int lumpId);
void LoadLumpElement(int nElemIndex, int nElemSize, void* pData);
void LoadLumpData(int offset, int size, void* pData);
private:
int m_nLumpSize;
int m_nLumpOffset;
int m_nLumpVersion;
byte* m_pRawData;
byte* m_pData;
byte* m_pUncompressedData;
int m_nLumpID;
char m_szLumpFilename[MAX_PATH];
};
void Mod_RecomputeTranslucency(model_t* mod, int nSkin, int nBody, void * pClientRenderable);
int Mod_GameLumpSize(int lumpId);
int Mod_GameLumpVersion(int lumpId);
bool Mod_LoadGameLump(int lumpId, void* pBuffer, int size);
int Mod_GetMaterialCount(model_t* mod);
int Mod_GetModelMaterials(model_t* mod, int count, IMaterial** ppMaterial);
bool Mod_MarkWaterSurfaces(model_t* pModel);
void ConnectMDLCacheNotify();
void DisconnectMDLCacheNotify();
void InitStudioModelState(model_t* pModel);
char* GetMapNameOnDisk(char* pDiskName, const char* pFullMapName, unsigned int nDiskNameSize);
extern bool g_bLoadedMapHasBakedPropLighting;
extern bool g_bBakedPropLightingNoSeparateHDR;
#endif

15
SpyCustom/sdk/modes.h Normal file
View File

@ -0,0 +1,15 @@
#if !defined( MODES_H )
#define MODES_H
#ifdef _WIN32
#pragma once
#endif
typedef struct vmode_s
{
int width;
int height;
int bpp;
int refreshRate;
} vmode_t;
#endif

178
SpyCustom/sdk/mouthinfo.h Normal file
View File

@ -0,0 +1,178 @@
#if !defined( MOUTHINFO_H )
#define MOUTHINFO_H
#ifdef _WIN32
#pragma once
#endif
class CAudioSource;
#pragma pack(push,4)
class CVoiceData
{
public:
CVoiceData(void)
{
m_flElapsed = 0.0f;
m_pAudioSource = NULL;
m_bIgnorePhonemes = false;
}
void SetElapsedTime(float t)
{
m_flElapsed = t;
}
float GetElapsedTime() const
{
return m_flElapsed;
}
void SetSource(CAudioSource* source, bool bIgnorePhonemes)
{
m_pAudioSource = source;
m_bIgnorePhonemes = bIgnorePhonemes;
}
bool ShouldIgnorePhonemes() const
{
return m_bIgnorePhonemes;
}
CAudioSource* GetSource()
{
return m_pAudioSource;
}
private:
float m_flElapsed;
CAudioSource* m_pAudioSource;
bool m_bIgnorePhonemes;
};
#define UNKNOWN_VOICE_SOURCE -1
class CMouthInfo
{
public:
byte mouthopen;
byte sndcount;
int sndavg;
public:
CMouthInfo(void) { m_nVoiceSources = 0; m_needsEnvelope = false; }
virtual ~CMouthInfo(void) { ClearVoiceSources(); }
int GetNumVoiceSources(void);
CVoiceData* GetVoiceSource(int number);
void ClearVoiceSources(void);
int GetIndexForSource(CAudioSource* source);
bool IsSourceReferenced(CAudioSource* source);
CVoiceData* AddSource(CAudioSource* source, bool bIgnorePhonemes);
void RemoveSource(CAudioSource* source);
void RemoveSourceByIndex(int index);
bool IsActive(void);
bool NeedsEnvelope() { return m_needsEnvelope != 0; }
void ActivateEnvelope() { m_needsEnvelope = true; }
private:
enum
{
MAX_VOICE_DATA = 4
};
short m_nVoiceSources;
short m_needsEnvelope;
CVoiceData m_VoiceSources[MAX_VOICE_DATA];
};
#pragma pack(pop)
inline bool CMouthInfo::IsActive(void)
{
return (GetNumVoiceSources() > 0) ? true : false;
}
inline int CMouthInfo::GetNumVoiceSources(void)
{
return m_nVoiceSources;
}
inline CVoiceData* CMouthInfo::GetVoiceSource(int number)
{
if (number < 0 || number >= m_nVoiceSources)
return NULL;
return &m_VoiceSources[number];
}
inline void CMouthInfo::ClearVoiceSources(void)
{
m_nVoiceSources = 0;
}
inline int CMouthInfo::GetIndexForSource(CAudioSource* source)
{
for (int i = 0; i < m_nVoiceSources; i++)
{
CVoiceData* v = &m_VoiceSources[i];
if (!v)
continue;
if (v->GetSource() == source)
return i;
}
return UNKNOWN_VOICE_SOURCE;
}
inline bool CMouthInfo::IsSourceReferenced(CAudioSource* source)
{
if (GetIndexForSource(source) != UNKNOWN_VOICE_SOURCE)
return true;
return false;
}
inline void CMouthInfo::RemoveSource(CAudioSource* source)
{
int idx = GetIndexForSource(source);
if (idx == UNKNOWN_VOICE_SOURCE)
return;
RemoveSourceByIndex(idx);
}
inline void CMouthInfo::RemoveSourceByIndex(int index)
{
if (index < 0 || index >= m_nVoiceSources)
return;
m_VoiceSources[index] = m_VoiceSources[--m_nVoiceSources];
}
inline CVoiceData* CMouthInfo::AddSource(CAudioSource* source, bool bIgnorePhonemes)
{
int idx = GetIndexForSource(source);
if (idx == UNKNOWN_VOICE_SOURCE)
{
if (m_nVoiceSources < MAX_VOICE_DATA)
{
idx = m_nVoiceSources++;
}
else
{
return NULL;
}
}
CVoiceData* data = &m_VoiceSources[idx];
data->SetSource(source, bIgnorePhonemes);
data->SetElapsedTime(0.0f);
return data;
}
#endif

View File

@ -0,0 +1,63 @@
#ifndef NETWORKSTRINGTABLEDEFS_H
#define NETWORKSTRINGTABLEDEFS_H
#ifdef _WIN32
#pragma once
#endif
typedef int TABLEID;
#define INVALID_STRING_TABLE -1
const unsigned short INVALID_STRING_INDEX = (unsigned short)-1;
#define MAX_TABLES 32
#define INTERFACENAME_NETWORKSTRINGTABLESERVER "VEngineServerStringTable001"
#define INTERFACENAME_NETWORKSTRINGTABLECLIENT "VEngineClientStringTable001"
class INetworkStringTable;
typedef void (*pfnStringChanged)(void* object, INetworkStringTable* stringTable, int stringNumber, char const* newString, void const* newData);
class INetworkStringTable
{
public:
virtual ~INetworkStringTable(void) {};
virtual const char* GetTableName(void) const = 0;
virtual TABLEID GetTableId(void) const = 0;
virtual int GetNumStrings(void) const = 0;
virtual int GetMaxStrings(void) const = 0;
virtual int GetEntryBits(void) const = 0;
virtual void SetTick(int tick) = 0;
virtual bool ChangedSinceTick(int tick) const = 0;
virtual int AddString(bool bIsServer, const char* value, int length = -1, const void* userdata = 0) = 0;
virtual const char* GetString(int stringNumber) = 0;
virtual void SetStringUserData(int stringNumber, int length, const void* userdata) = 0;
virtual const void* GetStringUserData(int stringNumber, int* length) = 0;
virtual int FindStringIndex(char const* string) = 0;
virtual void SetStringChangedCallback(void* object, pfnStringChanged changeFunc) = 0;
};
class INetworkStringTableContainer
{
public:
virtual ~INetworkStringTableContainer(void) {};
virtual INetworkStringTable* CreateStringTable(const char* tableName, int maxentries, int userdatafixedsize = 0, int userdatanetworkbits = 0) = 0;
virtual void RemoveAllTables(void) = 0;
virtual INetworkStringTable* FindTable(const char* tableName) const = 0;
virtual INetworkStringTable* GetTable(TABLEID stringTable) const = 0;
virtual int GetNumTables(void) const = 0;
virtual INetworkStringTable* CreateStringTableEx(const char* tableName, int maxentries, int userdatafixedsize = 0, int userdatanetworkbits = 0, bool bIsFilenames = false) = 0;
virtual void SetAllowClientSideAddString(INetworkStringTable* table, bool bAllowClientSideAddString) = 0;
};
#endif

737
SpyCustom/sdk/networkvar.h Normal file
View File

@ -0,0 +1,737 @@
#ifndef NETWORKVAR_H
#define NETWORKVAR_H
#ifdef _WIN32
#pragma once
#endif
#include "dbg.h"
#include "convar.h"
#if defined( CLIENT_DLL ) || defined( GAME_DLL )
#include "basehandle.h"
#endif
#pragma warning( disable : 4284 )
#define MyOffsetOf( type, var ) ( (int)&((type*)0)->var )
#ifdef _DEBUG
extern bool g_bUseNetworkVars;
#define CHECK_USENETWORKVARS if(g_bUseNetworkVars)
#else
#define CHECK_USENETWORKVARS
#endif
inline int InternalCheckDeclareClass(const char* pClassName, const char* pClassNameMatch, void* pTestPtr, void* pBasePtr)
{
Assert(pTestPtr == pBasePtr);
Assert((void*)pClassName == (void*)pClassNameMatch);
return 0;
}
template <typename T>
inline int CheckDeclareClass_Access(T*, const char* pShouldBe)
{
return T::CheckDeclareClass(pShouldBe);
}
#ifndef _STATIC_LINKED
#ifdef _MSC_VER
#if defined(_DEBUG) && (_MSC_VER > 1200 )
#define VALIDATE_DECLARE_CLASS 1
#endif
#endif
#endif
#ifdef VALIDATE_DECLARE_CLASS
#define DECLARE_CLASS( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass; \
template <typename T> friend int CheckDeclareClass_Access(T *, const char *pShouldBe); \
static int CheckDeclareClass( const char *pShouldBe ) \
{ \
InternalCheckDeclareClass( pShouldBe, #className, (ThisClass*)0xFFFFF, (BaseClass*)(ThisClass*)0xFFFFF ); \
return CheckDeclareClass_Access( (BaseClass *)NULL, #baseClassName ); \
}
#define DECLARE_CLASS_GAMEROOT( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass; \
template <typename T> friend int CheckDeclareClass_Access(T *, const char *pShouldBe); \
static int CheckDeclareClass( const char *pShouldBe ) \
{ \
return InternalCheckDeclareClass( pShouldBe, #className, (ThisClass*)0xFFFFF, (BaseClass*)(ThisClass*)0xFFFFF ); \
}
#define DECLARE_CLASS_NOFRIEND( className, baseClassName ) \
DECLARE_CLASS( className, baseClassName )
#define DECLARE_CLASS_NOBASE( className ) \
typedef className ThisClass; \
template <typename T> friend int CheckDeclareClass_Access(T *, const char *pShouldBe); \
static int CheckDeclareClass( const char *pShouldBe ) \
{ \
return InternalCheckDeclareClass( pShouldBe, #className, 0, 0 ); \
}
#else
#define DECLARE_CLASS( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass;
#define DECLARE_CLASS_GAMEROOT( className, baseClassName ) DECLARE_CLASS( className, baseClassName )
#define DECLARE_CLASS_NOFRIEND( className, baseClassName ) DECLARE_CLASS( className, baseClassName )
#define DECLARE_CLASS_NOBASE( className ) typedef className ThisClass;
#endif
class CBaseEntity;
class CAutoInitEntPtr
{
public:
CAutoInitEntPtr()
{
m_pEnt = NULL;
}
CBaseEntity* m_pEnt;
};
#define DECLARE_NETWORKVAR_CHAIN() \
CAutoInitEntPtr __m_pChainEntity; \
void NetworkStateChanged() { CHECK_USENETWORKVARS __m_pChainEntity.m_pEnt->NetworkStateChanged(); } \
void NetworkStateChanged( void *pVar ) { CHECK_USENETWORKVARS __m_pChainEntity.m_pEnt->NetworkStateChanged(); }
#define IMPLEMENT_NETWORKVAR_CHAIN( varName ) \
(varName)->__m_pChainEntity.m_pEnt = this;
template< class T >
static inline void DispatchNetworkStateChanged(T* pObj)
{
CHECK_USENETWORKVARS pObj->NetworkStateChanged();
}
template< class T >
static inline void DispatchNetworkStateChanged(T* pObj, void* pVar)
{
CHECK_USENETWORKVARS pObj->NetworkStateChanged(pVar);
}
#define DECLARE_EMBEDDED_NETWORKVAR() \
template <typename T> friend int ServerClassInit(T *); \
template <typename T> friend int ClientClassInit(T *); \
virtual void NetworkStateChanged() {} virtual void NetworkStateChanged( void *pProp ) {}
#define CNetworkVarEmbedded( type, name ) \
class NetworkVar_##name; \
friend class NetworkVar_##name; \
static inline int GetOffset_##name() { return MyOffsetOf(ThisClass,name); } \
typedef ThisClass ThisClass_##name; \
class NetworkVar_##name : public type \
{ \
template< class T > NetworkVar_##name& operator=( const T &val ) { *((type*)this) = val; return *this; } \
public: \
void CopyFrom( const type &src ) { *((type *)this) = src; NetworkStateChanged(); } \
virtual void NetworkStateChanged() \
{ \
DispatchNetworkStateChanged( (ThisClass_##name*)( ((char*)this) - GetOffset_##name() ) ); \
} \
virtual void NetworkStateChanged( void *pVar ) \
{ \
DispatchNetworkStateChanged( (ThisClass_##name*)( ((char*)this) - GetOffset_##name() ), pVar ); \
} \
}; \
NetworkVar_##name name;
template<typename T>
FORCEINLINE void NetworkVarConstruct(T& x) { x = T(0); }
FORCEINLINE void NetworkVarConstruct(color32_s& x) { x.r = x.g = x.b = x.a = 0; }
template< class Type, class Changer >
class CNetworkVarBase
{
public:
inline CNetworkVarBase()
{
NetworkVarConstruct(m_Value);
}
template< class C >
const Type& operator=(const C& val)
{
return Set((const Type)val);
}
template< class C >
const Type& operator=(const CNetworkVarBase< C, Changer >& val)
{
return Set((const Type)val.m_Value);
}
const Type& Set(const Type& val)
{
if (memcmp(&m_Value, &val, sizeof(Type)))
{
NetworkStateChanged();
m_Value = val;
}
return m_Value;
}
Type& GetForModify()
{
NetworkStateChanged();
return m_Value;
}
template< class C >
const Type& operator+=(const C& val)
{
return Set(m_Value + (const Type)val);
}
template< class C >
const Type& operator-=(const C& val)
{
return Set(m_Value - (const Type)val);
}
template< class C >
const Type& operator/=(const C& val)
{
return Set(m_Value / (const Type)val);
}
template< class C >
const Type& operator*=(const C& val)
{
return Set(m_Value * (const Type)val);
}
template< class C >
const Type& operator^=(const C& val)
{
return Set(m_Value ^ (const Type)val);
}
template< class C >
const Type& operator|=(const C& val)
{
return Set(m_Value | (const Type)val);
}
const Type& operator++()
{
return (*this += 1);
}
Type operator--()
{
return (*this -= 1);
}
Type operator++(int)
{
Type val = m_Value;
(*this += 1);
return val;
}
Type operator--(int)
{
Type val = m_Value;
(*this -= 1);
return val;
}
template< class C >
const Type& operator&=(const C& val)
{
return Set(m_Value & (const Type)val);
}
operator const Type& () const
{
return m_Value;
}
const Type& Get() const
{
return m_Value;
}
const Type* operator->() const
{
return &m_Value;
}
Type m_Value;
protected:
inline void NetworkStateChanged()
{
Changer::NetworkStateChanged(this);
}
};
template< class Type, class Changer >
class CNetworkColor32Base : public CNetworkVarBase< Type, Changer >
{
public:
inline void Init(byte rVal, byte gVal, byte bVal)
{
SetR(rVal);
SetG(gVal);
SetB(bVal);
}
inline void Init(byte rVal, byte gVal, byte bVal, byte aVal)
{
SetR(rVal);
SetG(gVal);
SetB(bVal);
SetA(aVal);
}
const Type& operator=(const Type& val)
{
return this->Set(val);
}
const Type& operator=(const CNetworkColor32Base<Type, Changer>& val)
{
return CNetworkVarBase<Type, Changer>::Set(val.m_Value);
}
inline byte GetR() const { return CNetworkColor32Base<Type, Changer>::m_Value.r; }
inline byte GetG() const { return CNetworkColor32Base<Type, Changer>::m_Value.g; }
inline byte GetB() const { return CNetworkColor32Base<Type, Changer>::m_Value.b; }
inline byte GetA() const { return CNetworkColor32Base<Type, Changer>::m_Value.a; }
inline void SetR(byte val) { SetVal(CNetworkColor32Base<Type, Changer>::m_Value.r, val); }
inline void SetG(byte val) { SetVal(CNetworkColor32Base<Type, Changer>::m_Value.g, val); }
inline void SetB(byte val) { SetVal(CNetworkColor32Base<Type, Changer>::m_Value.b, val); }
inline void SetA(byte val) { SetVal(CNetworkColor32Base<Type, Changer>::m_Value.a, val); }
protected:
inline void SetVal(byte& out, const byte& in)
{
if (out != in)
{
CNetworkVarBase< Type, Changer >::NetworkStateChanged();
out = in;
}
}
};
template< class Type, class Changer >
class CNetworkVectorBase : public CNetworkVarBase< Type, Changer >
{
public:
inline void Init(float ix = 0, float iy = 0, float iz = 0)
{
SetX(ix);
SetY(iy);
SetZ(iz);
}
const Type& operator=(const Type& val)
{
return CNetworkVarBase< Type, Changer >::Set(val);
}
const Type& operator=(const CNetworkVectorBase<Type, Changer>& val)
{
return CNetworkVarBase<Type, Changer>::Set(val.m_Value);
}
inline float GetX() const { return CNetworkVectorBase<Type, Changer>::m_Value.x; }
inline float GetY() const { return CNetworkVectorBase<Type, Changer>::m_Value.y; }
inline float GetZ() const { return CNetworkVectorBase<Type, Changer>::m_Value.z; }
inline float operator[](int i) const { return CNetworkVectorBase<Type, Changer>::m_Value[i]; }
inline void SetX(float val) { DetectChange(CNetworkVectorBase<Type, Changer>::m_Value.x, val); }
inline void SetY(float val) { DetectChange(CNetworkVectorBase<Type, Changer>::m_Value.y, val); }
inline void SetZ(float val) { DetectChange(CNetworkVectorBase<Type, Changer>::m_Value.z, val); }
inline void Set(int i, float val) { DetectChange(CNetworkVectorBase<Type, Changer>::m_Value[i], val); }
bool operator==(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value == (Type)val;
}
bool operator!=(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value != (Type)val;
}
const Type operator+(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value + val;
}
const Type operator-(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value - val;
}
const Type operator*(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value * val;
}
const Type& operator*=(float val)
{
return CNetworkVarBase< Type, Changer >::Set(CNetworkVectorBase<Type, Changer>::m_Value * val);
}
const Type operator*(float val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value * val;
}
const Type operator/(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value / val;
}
private:
inline void DetectChange(float& out, float in)
{
if (out != in)
{
CNetworkVectorBase<Type, Changer>::NetworkStateChanged();
out = in;
}
}
};
template< class Type, class Changer >
class CNetworkQuaternionBase : public CNetworkVarBase< Type, Changer >
{
public:
inline void Init(float ix = 0, float iy = 0, float iz = 0, float iw = 0)
{
SetX(ix);
SetY(iy);
SetZ(iz);
SetW(iw);
}
const Type& operator=(const Type& val)
{
return CNetworkVarBase< Type, Changer >::Set(val);
}
const Type& operator=(const CNetworkQuaternionBase<Type, Changer>& val)
{
return CNetworkVarBase<Type, Changer>::Set(val.m_Value);
}
inline float GetX() const { return CNetworkQuaternionBase<Type, Changer>::m_Value.x; }
inline float GetY() const { return CNetworkQuaternionBase<Type, Changer>::m_Value.y; }
inline float GetZ() const { return CNetworkQuaternionBase<Type, Changer>::m_Value.z; }
inline float GetW() const { return CNetworkQuaternionBase<Type, Changer>::m_Value.w; }
inline float operator[](int i) const { return CNetworkQuaternionBase<Type, Changer>::m_Value[i]; }
inline void SetX(float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value.x, val); }
inline void SetY(float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value.y, val); }
inline void SetZ(float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value.z, val); }
inline void SetW(float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value.w, val); }
inline void Set(int i, float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value[i], val); }
bool operator==(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value == (Type)val;
}
bool operator!=(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value != (Type)val;
}
const Type operator+(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value + val;
}
const Type operator-(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value - val;
}
const Type operator*(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value * val;
}
const Type& operator*=(float val)
{
return CNetworkQuaternionBase< Type, Changer >::Set(CNetworkQuaternionBase<Type, Changer>::m_Value * val);
}
const Type operator*(float val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value * val;
}
const Type operator/(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value / val;
}
private:
inline void DetectChange(float& out, float in)
{
if (out != in)
{
CNetworkQuaternionBase<Type, Changer>::NetworkStateChanged();
out = in;
}
}
};
#if defined( CLIENT_DLL ) || defined( GAME_DLL )
inline void NetworkVarConstruct(CBaseHandle& x) {}
template< class Type, class Changer >
class CNetworkHandleBase : public CNetworkVarBase< CBaseHandle, Changer >
{
public:
const Type* operator=(const Type* val)
{
return Set(val);
}
const Type& operator=(const CNetworkHandleBase<Type, Changer>& val)
{
const CBaseHandle& handle = CNetworkVarBase<CBaseHandle, Changer>::Set(val.m_Value);
return *(const Type*)handle.Get();
}
bool operator !() const
{
return !CNetworkHandleBase<Type, Changer>::m_Value.Get();
}
operator Type* () const
{
return static_cast<Type*>(CNetworkHandleBase<Type, Changer>::m_Value.Get());
}
const Type* Set(const Type* val)
{
if (CNetworkHandleBase<Type, Changer>::m_Value != val)
{
this->NetworkStateChanged();
CNetworkHandleBase<Type, Changer>::m_Value = val;
}
return val;
}
Type* Get() const
{
return static_cast<Type*>(CNetworkHandleBase<Type, Changer>::m_Value.Get());
}
Type* operator->() const
{
return static_cast<Type*>(CNetworkHandleBase<Type, Changer>::m_Value.Get());
}
bool operator==(const Type* val) const
{
return CNetworkHandleBase<Type, Changer>::m_Value == val;
}
bool operator!=(const Type* val) const
{
return CNetworkHandleBase<Type, Changer>::m_Value != val;
}
};
#define CNetworkHandle( type, name ) CNetworkHandleInternal( type, name, NetworkStateChanged )
#define CNetworkHandleInternal( type, name, stateChangedFn ) \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkHandleBase, stateChangedFn )
#endif
#define CNetworkVar( type, name ) \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkVarBase, NetworkStateChanged )
#define CNetworkVarForDerived( type, name ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {} \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkVarBase, NetworkStateChanged_##name )
#define CNetworkVectorForDerived( name ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {} \
CNetworkVectorInternal( Vector, name, NetworkStateChanged_##name )
#define CNetworkHandleForDerived( type, name ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {} \
CNetworkHandleInternal( type, name, NetworkStateChanged_##name )
#define CNetworkArrayForDerived( type, name, count ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {} \
CNetworkArrayInternal( type, name, count, NetworkStateChanged_##name )
#define IMPLEMENT_NETWORK_VAR_FOR_DERIVED( name ) \
virtual void NetworkStateChanged_##name() { CHECK_USENETWORKVARS NetworkStateChanged(); } \
virtual void NetworkStateChanged_##name( void *pVar ) { CHECK_USENETWORKVARS NetworkStateChanged( pVar ); }
#define CNetworkVarForDerived_OnByDefault( type, name ) \
virtual void NetworkStateChanged_##name() { CHECK_USENETWORKVARS NetworkStateChanged(); } \
virtual void NetworkStateChanged_##name( void *pVar ) { CHECK_USENETWORKVARS NetworkStateChanged( pVar ); } \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkVarBase, NetworkStateChanged_##name )
#define DISABLE_NETWORK_VAR_FOR_DERIVED( name ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {}
#define CNetworkVector( name ) CNetworkVectorInternal( Vector, name, NetworkStateChanged )
#define CNetworkQAngle( name ) CNetworkVectorInternal( QAngle, name, NetworkStateChanged )
#define CNetworkVectorInternal( type, name, stateChangedFn ) \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkVectorBase, stateChangedFn )
#define CNetworkQuaternion( name ) \
NETWORK_VAR_START( Quaternion, name ) \
NETWORK_VAR_END( Quaternion, name, CNetworkQuaternionBase, NetworkStateChanged )
#define CNetworkColor32( name ) \
NETWORK_VAR_START( color32, name ) \
NETWORK_VAR_END( color32, name, CNetworkColor32Base, NetworkStateChanged )
#define CNetworkString( name, length ) \
class NetworkVar_##name; \
friend class NetworkVar_##name; \
typedef ThisClass MakeANetworkVar_##name; \
class NetworkVar_##name \
{ \
public: \
NetworkVar_##name() { m_Value[0] = '\0'; } \
operator const char*() const { return m_Value; } \
const char* Get() const { return m_Value; } \
char* GetForModify() \
{ \
NetworkStateChanged(); \
return m_Value; \
} \
protected: \
inline void NetworkStateChanged() \
{ \
CHECK_USENETWORKVARS ((ThisClass*)(((char*)this) - MyOffsetOf(ThisClass,name)))->NetworkStateChanged(); \
} \
private: \
char m_Value[length]; \
}; \
NetworkVar_##name name;
#define CNetworkArrayInternal( type, name, count, stateChangedFn ) \
class NetworkVar_##name; \
friend class NetworkVar_##name; \
typedef ThisClass MakeANetworkVar_##name; \
class NetworkVar_##name \
{ \
public: \
inline NetworkVar_##name() \
{ \
for ( int i = 0 ; i < count ; ++i ) \
NetworkVarConstruct( m_Value[i] ); \
} \
template <typename T> friend int ServerClassInit(T *); \
const type& operator[]( int i ) const \
{ \
return Get( i ); \
} \
\
const type& Get( int i ) const \
{ \
Assert( i >= 0 && i < count ); \
return m_Value[i]; \
} \
\
type& GetForModify( int i ) \
{ \
Assert( i >= 0 && i < count ); \
NetworkStateChanged( i ); \
return m_Value[i]; \
} \
\
void Set( int i, const type &val ) \
{ \
Assert( i >= 0 && i < count ); \
if( memcmp( &m_Value[i], &val, sizeof(type) ) ) \
{ \
NetworkStateChanged( i ); \
m_Value[i] = val; \
} \
} \
const type* Base() const { return m_Value; } \
int Count() const { return count; } \
protected: \
inline void NetworkStateChanged( int index ) \
{ \
CHECK_USENETWORKVARS ((ThisClass*)(((char*)this) - MyOffsetOf(ThisClass,name)))->stateChangedFn( &m_Value[index] ); \
} \
type m_Value[count]; \
}; \
NetworkVar_##name name;
#define CNetworkArray( type, name, count ) CNetworkArrayInternal( type, name, count, NetworkStateChanged )
#define NETWORK_VAR_START( type, name ) \
class NetworkVar_##name; \
friend class NetworkVar_##name; \
typedef ThisClass MakeANetworkVar_##name; \
class NetworkVar_##name \
{ \
public: \
template <typename T> friend int ServerClassInit(T *);
#define NETWORK_VAR_END( type, name, base, stateChangedFn ) \
public: \
static inline void NetworkStateChanged( void *ptr ) \
{ \
CHECK_USENETWORKVARS ((ThisClass*)(((char*)ptr) - MyOffsetOf(ThisClass,name)))->stateChangedFn( ptr ); \
} \
}; \
base< type, NetworkVar_##name > name;
#endif

View File

@ -0,0 +1,222 @@
#ifndef PARTICLE_ITERATORS_H
#define PARTICLE_ITERATORS_H
#ifdef _WIN32
#pragma once
#endif
#include "imesh.h"
#include "particledraw.h"
#define NUM_PARTICLES_PER_BATCH 200
#ifndef _XBOX
#define MAX_TOTAL_PARTICLES 2048
#else
#define MAX_TOTAL_PARTICLES 1024
#endif
class CParticleRenderIterator
{
friend class CParticleMgr;
friend class CParticleEffectBinding;
public:
CParticleRenderIterator();
const Particle* GetFirst();
const Particle* GetNext(float sortKey);
ParticleDraw* GetParticleDraw() const;
private:
void TestFlushBatch();
private:
CParticleEffectBinding* m_pEffectBinding;
CEffectMaterial* m_pMaterial;
ParticleDraw* m_pParticleDraw;
CMeshBuilder* m_pMeshBuilder;
IMesh* m_pMesh;
bool m_bBucketSort;
float m_MinZ;
float m_MaxZ;
float m_zCoords[MAX_TOTAL_PARTICLES];
int m_nZCoords;
Particle* m_pCur;
bool m_bGotFirst;
float m_flPrevZ;
int m_nParticlesInCurrentBatch;
};
class CParticleSimulateIterator
{
friend class CParticleMgr;
friend class CParticleEffectBinding;
public:
CParticleSimulateIterator();
Particle* GetFirst();
Particle* GetNext();
float GetTimeDelta() const;
void RemoveParticle(Particle* pParticle);
void RemoveAllParticles();
private:
CParticleEffectBinding* m_pEffectBinding;
CEffectMaterial* m_pMaterial;
float m_flTimeDelta;
bool m_bGotFirst;
Particle* m_pNextParticle;
};
inline CParticleRenderIterator::CParticleRenderIterator()
{
m_pCur = NULL;
m_bGotFirst = false;
m_flPrevZ = 0;
m_nParticlesInCurrentBatch = 0;
m_MinZ = 1e24;
m_MaxZ = -1e24;
m_nZCoords = 0;
}
inline const Particle* CParticleRenderIterator::GetFirst()
{
Assert(!m_bGotFirst);
m_bGotFirst = true;
m_pCur = m_pMaterial->m_Particles.m_pNext;
if (m_pCur == &m_pMaterial->m_Particles)
return NULL;
m_pParticleDraw->m_pSubTexture = m_pCur->m_pSubTexture;
return m_pCur;
}
inline void CParticleRenderIterator::TestFlushBatch()
{
++m_nParticlesInCurrentBatch;
if (m_nParticlesInCurrentBatch >= NUM_PARTICLES_PER_BATCH)
{
m_pMeshBuilder->End(false, true);
m_pMeshBuilder->Begin(m_pMesh, MATERIAL_QUADS, NUM_PARTICLES_PER_BATCH * 4);
m_nParticlesInCurrentBatch = 0;
}
}
inline const Particle* CParticleRenderIterator::GetNext(float sortKey)
{
Assert(m_bGotFirst);
Assert(m_pCur);
TestFlushBatch();
Particle* pNext = m_pCur->m_pNext;
if (m_bBucketSort)
{
m_MinZ = MIN(sortKey, m_MinZ);
m_MaxZ = MAX(sortKey, m_MaxZ);
m_zCoords[m_nZCoords] = sortKey;
++m_nZCoords;
}
else
{
if (m_pCur != m_pMaterial->m_Particles.m_pNext && m_flPrevZ > sortKey)
{
SwapParticles(m_pCur->m_pPrev, m_pCur);
}
else
{
m_flPrevZ = sortKey;
}
}
m_pCur = pNext;
if (m_pCur == &m_pMaterial->m_Particles)
return NULL;
m_pParticleDraw->m_pSubTexture = m_pCur->m_pSubTexture;
return m_pCur;
}
inline ParticleDraw* CParticleRenderIterator::GetParticleDraw() const
{
return m_pParticleDraw;
}
inline CParticleSimulateIterator::CParticleSimulateIterator()
{
m_pNextParticle = NULL;
#ifdef _DEBUG
m_bGotFirst = false;
#endif
}
inline Particle* CParticleSimulateIterator::GetFirst()
{
#ifdef _DEBUG
if (m_bGotFirst)
{
Assert(m_pNextParticle == &m_pMaterial->m_Particles);
}
#endif
Particle* pRet = m_pMaterial->m_Particles.m_pNext;
if (pRet == &m_pMaterial->m_Particles)
return NULL;
#ifdef _DEBUG
m_bGotFirst = true;
#endif
m_pNextParticle = pRet->m_pNext;
return pRet;
}
inline Particle* CParticleSimulateIterator::GetNext()
{
Particle* pRet = m_pNextParticle;
if (pRet == &m_pMaterial->m_Particles)
return NULL;
m_pNextParticle = pRet->m_pNext;
return pRet;
}
inline void CParticleSimulateIterator::RemoveParticle(Particle* pParticle)
{
m_pEffectBinding->RemoveParticle(pParticle);
}
inline void CParticleSimulateIterator::RemoveAllParticles()
{
Particle* pParticle = GetFirst();
while (pParticle)
{
RemoveParticle(pParticle);
pParticle = GetNext();
}
}
inline float CParticleSimulateIterator::GetTimeDelta() const
{
return m_flTimeDelta;
}
#endif

View File

@ -0,0 +1,66 @@
#ifndef PARTICLE_PARSE_H
#define PARTICLE_PARSE_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "utlstring.h"
#include "ifilelist.h"
enum ParticleAttachment_t
{
PATTACH_ABSORIGIN = 0,
PATTACH_ABSORIGIN_FOLLOW,
PATTACH_CUSTOMORIGIN,
PATTACH_POINT,
PATTACH_POINT_FOLLOW,
PATTACH_WORLDORIGIN,
PATTACH_ROOTBONE_FOLLOW,
MAX_PATTACH_TYPES,
};
extern int GetAttachTypeFromString(const char* pszString);
#define PARTICLE_DISPATCH_FROM_ENTITY (1<<0)
#define PARTICLE_DISPATCH_RESET_PARTICLES (1<<1)
struct te_tf_particle_effects_colors_t
{
Vector m_vecColor1;
Vector m_vecColor2;
};
struct te_tf_particle_effects_control_point_t
{
ParticleAttachment_t m_eParticleAttachment;
Vector m_vecOffset;
};
void ParseParticleEffects(bool bLoadSheets, bool bPrecache);
void ParseParticleEffectsMap(const char* pMapName, bool bLoadSheets, IFileList* pFilesToReload = NULL);
void GetParticleManifest(CUtlVector<CUtlString>& list);
void PrecacheStandardParticleSystems();
class IFileList;
void ReloadParticleEffectsInList(IFileList* pFilesToReload);
void DispatchParticleEffect(const char* pszParticleName, ParticleAttachment_t iAttachType, CBaseEntity* pEntity, const char* pszAttachmentName, bool bResetAllParticlesOnEntity = false);
void DispatchParticleEffect(const char* pszParticleName, ParticleAttachment_t iAttachType, CBaseEntity* pEntity = NULL, int iAttachmentPoint = -1, bool bResetAllParticlesOnEntity = false);
void DispatchParticleEffect(const char* pszParticleName, Vector vecOrigin, QAngle vecAngles, CBaseEntity* pEntity = NULL);
void DispatchParticleEffect(const char* pszParticleName, Vector vecOrigin, Vector vecStart, QAngle vecAngles, CBaseEntity* pEntity = NULL);
void DispatchParticleEffect(int iEffectIndex, Vector vecOrigin, Vector vecStart, QAngle vecAngles, CBaseEntity* pEntity = NULL);
void DispatchParticleEffect(const char* pszParticleName, ParticleAttachment_t iAttachType, CBaseEntity* pEntity, const char* pszAttachmentName, Vector vecColor1, Vector vecColor2, bool bUseColors = true, bool bResetAllParticlesOnEntity = false);
void DispatchParticleEffect(const char* pszParticleName, Vector vecOrigin, QAngle vecAngles, Vector vecColor1, Vector vecColor2, bool bUseColors = true, CBaseEntity* pEntity = NULL, int iAttachType = PATTACH_CUSTOMORIGIN);
void StopParticleEffects(CBaseEntity* pEntity);
#endif

View File

@ -0,0 +1,110 @@
#ifndef PARTICLEPROPERTY_H
#define PARTICLEPROPERTY_H
#ifdef _WIN32
#pragma once
#endif
#include "smartptr.h"
#include "globalvars_base.h"
#include "particles_new.h"
#include "particle_parse.h"
class CBaseEntity;
class CNewParticleEffect;
#ifdef CLIENT_DLL
#define INVALID_PARTICLE_ATTACHMENT 0
#else
#define INVALID_PARTICLE_ATTACHMENT -1
#endif
struct ParticleControlPoint_t
{
ParticleControlPoint_t()
{
iControlPoint = 0;
iAttachType = PATTACH_ABSORIGIN_FOLLOW;
iAttachmentPoint = 0;
vecOriginOffset = vec3_origin;
}
int iControlPoint;
ParticleAttachment_t iAttachType;
int iAttachmentPoint;
Vector vecOriginOffset;
EHANDLE hEntity;
};
struct ParticleEffectList_t
{
ParticleEffectList_t()
{
pParticleEffect = NULL;
}
CUtlVector<ParticleControlPoint_t> pControlPoints;
CSmartPtr<CNewParticleEffect> pParticleEffect;
};
extern int GetAttachTypeFromString(const char* pszString);
class CParticleProperty
{
DECLARE_CLASS_NOBASE(CParticleProperty);
DECLARE_EMBEDDED_NETWORKVAR();
DECLARE_PREDICTABLE();
DECLARE_DATADESC();
public:
CParticleProperty();
~CParticleProperty();
void Init(CBaseEntity* pEntity);
CBaseEntity* GetOuter(void) { return m_pOuter; }
CNewParticleEffect* Create(const char* pszParticleName, ParticleAttachment_t iAttachType, const char* pszAttachmentName);
CNewParticleEffect* Create(const char* pszParticleName, ParticleAttachment_t iAttachType, int iAttachmentPoint = INVALID_PARTICLE_ATTACHMENT, Vector vecOriginOffset = vec3_origin);
void AddControlPoint(CNewParticleEffect* pEffect, int iPoint, C_BaseEntity* pEntity, ParticleAttachment_t iAttachType, const char* pszAttachmentName = NULL, Vector vecOriginOffset = vec3_origin);
void AddControlPoint(int iEffectIndex, int iPoint, C_BaseEntity* pEntity, ParticleAttachment_t iAttachType, int iAttachmentPoint = INVALID_PARTICLE_ATTACHMENT, Vector vecOriginOffset = vec3_origin);
inline void SetControlPointParent(CNewParticleEffect* pEffect, int whichControlPoint, int parentIdx);
void SetControlPointParent(int iEffectIndex, int whichControlPoint, int parentIdx);
void StopEmission(CNewParticleEffect* pEffect = NULL, bool bWakeOnStop = false, bool bDestroyAsleepSystems = false);
void StopEmissionAndDestroyImmediately(CNewParticleEffect* pEffect = NULL);
void StopParticlesInvolving(CBaseEntity* pEntity);
void StopParticlesNamed(const char* pszEffectName, bool bForceRemoveInstantly = false);
void StopParticlesWithNameAndAttachment(const char* pszEffectName, int iAttachmentPoint, bool bForceRemoveInstantly = false);
void OnParticleSystemUpdated(CNewParticleEffect* pEffect, float flTimeDelta);
void OnParticleSystemDeleted(CNewParticleEffect* pEffect);
#ifdef CLIENT_DLL
void OwnerSetDormantTo(bool bDormant);
#endif
void ReplaceParticleEffect(CNewParticleEffect* pOldEffect, CNewParticleEffect* pNewEffect);
void DebugPrintEffects(void);
int FindEffect(const char* pEffectName, int nStart = 0);
inline CNewParticleEffect* GetParticleEffectFromIdx(int idx);
private:
int GetParticleAttachment(C_BaseEntity* pEntity, const char* pszAttachmentName, const char* pszParticleName);
int FindEffect(CNewParticleEffect* pEffect);
void UpdateParticleEffect(ParticleEffectList_t* pEffect, bool bInitializing = false, int iOnlyThisControlPoint = -1);
void UpdateControlPoint(ParticleEffectList_t* pEffect, int iPoint, bool bInitializing);
private:
CBaseEntity* m_pOuter;
CUtlVector<ParticleEffectList_t> m_ParticleEffects;
int m_iDormancyChangedAtFrame;
friend class CBaseEntity;
};
#include "particle_property_inlines.h"
#endif

View File

@ -0,0 +1,25 @@
#ifndef PARTICLEPROPERTY_H
#pragma message("Do not include particle_property_inlines.h from anywhere other than particle_property.h!")
#pragma error
#endif
#ifndef PARTICLEPROPERTY_INLINES_H
#define PARTICLEPROPERTY_INLINES_H
#ifdef _WIN32
#pragma once
#endif
void CParticleProperty::SetControlPointParent(CNewParticleEffect* pEffect, int whichControlPoint, int parentIdx)
{
pEffect->SetControlPointParent(whichControlPoint, parentIdx);
}
CNewParticleEffect* CParticleProperty::GetParticleEffectFromIdx(int idx)
{
return m_ParticleEffects[idx].pParticleEffect.GetObject();
}
#endif

View File

@ -0,0 +1,289 @@
#ifndef PARTICLE_UTIL_H
#define PARTICLE_UTIL_H
#include "IMesh.h"
#include "particledraw.h"
#include "particlemgr.h"
#include "cdll_client_int.h"
#include "timedevent.h"
inline float FLerp(float minVal, float maxVal, float t)
{
return minVal + (maxVal - minVal) * t;
}
inline Vector VecLerp(const Vector& minVal, const Vector& maxVal, float t)
{
return minVal + (maxVal - minVal) * t;
}
inline float FRand(float minVal, float maxVal)
{
return minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
}
inline void PhysicallySimulate(Vector& pos, Vector& velocity, const Vector& acceleration, const float fTimeDelta)
{
pos = pos + (velocity + (acceleration * fTimeDelta * 0.5f)) * fTimeDelta;
velocity = velocity + acceleration * fTimeDelta;
}
inline Vector GetGravityVector()
{
return Vector(0, 0, -150);
}
inline void RenderParticle_Color255SizeSpecularTCoord3(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const unsigned char* specular,
const float tCoord
)
{
if (alpha < 0.5f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha);
pBuilder->Position3f(pos.x - size, pos.y - size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord3f(0, pDraw->m_pSubTexture->m_tCoordMins[0], pDraw->m_pSubTexture->m_tCoordMaxs[1], tCoord);
pBuilder->Specular3ubv(specular);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x - size, pos.y + size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord3f(0, pDraw->m_pSubTexture->m_tCoordMins[0], pDraw->m_pSubTexture->m_tCoordMins[1], tCoord);
pBuilder->Specular3ubv(specular);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x + size, pos.y + size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord3f(0, pDraw->m_pSubTexture->m_tCoordMaxs[0], pDraw->m_pSubTexture->m_tCoordMins[1], tCoord);
pBuilder->Specular3ubv(specular);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x + size, pos.y - size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord3f(0, pDraw->m_pSubTexture->m_tCoordMaxs[0], pDraw->m_pSubTexture->m_tCoordMaxs[1], tCoord);
pBuilder->Specular3ubv(specular);
pBuilder->AdvanceVertex();
}
inline void RenderParticle_Color255Size(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size)
{
if (alpha < 0.5f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha);
pBuilder->Position3f(pos.x - size, pos.y - size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord2f(0, pDraw->m_pSubTexture->m_tCoordMins[0], pDraw->m_pSubTexture->m_tCoordMaxs[1]);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x - size, pos.y + size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord2f(0, pDraw->m_pSubTexture->m_tCoordMins[0], pDraw->m_pSubTexture->m_tCoordMins[1]);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x + size, pos.y + size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord2f(0, pDraw->m_pSubTexture->m_tCoordMaxs[0], pDraw->m_pSubTexture->m_tCoordMins[1]);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x + size, pos.y - size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord2f(0, pDraw->m_pSubTexture->m_tCoordMaxs[0], pDraw->m_pSubTexture->m_tCoordMaxs[1]);
pBuilder->AdvanceVertex();
}
inline void RenderParticle_Color255SizeNormal(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const Vector& vNormal)
{
if (alpha < 0.5f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha);
}
inline void RenderParticle_Color255SizeNormalAngle(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const Vector& vNormal,
const float angle)
{
if (alpha < 0.5f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha);
float ca = (float)cos(angle);
float sa = (float)sin(angle);
}
inline void RenderParticle_ColorSize(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size
)
{
if (alpha < 0.001f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x * 254.9f);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y * 254.9f);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z * 254.9f);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha * 254.9f);
}
inline void RenderParticle_ColorSizeAngle(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const float angle)
{
if (alpha < 0.001f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x * 254.9f);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y * 254.9f);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z * 254.9f);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha * 254.9f);
float sa, ca;
SinCos(angle, &sa, &ca);
}
inline void RenderParticle_ColorSizeAngles(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const QAngle& angles)
{
if (alpha < 0.001f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x * 254.9f);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y * 254.9f);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z * 254.9f);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha * 254.9f);
Vector vNorm, vWidth, vHeight;
AngleVectors(angles, &vNorm, &vWidth, &vHeight);
Vector vVertex = pos;
}
inline float GetAlphaDistanceFade(
const Vector& pos,
const float fadeNearDist,
const float fadeFarDist)
{
if (-pos.z > fadeFarDist)
{
return 1;
}
else if (-pos.z > fadeNearDist)
{
return (-pos.z - fadeNearDist) / (fadeFarDist - fadeNearDist);
}
else
{
return 0;
}
}
inline Vector WorldGetLightForPoint(const Vector& vPos, bool bClamp)
{
#if defined(PARTICLEPROTOTYPE_APP)
return Vector(1, 1, 1);
#else
return engine->GetLightForPoint(vPos, bClamp);
#endif
}
#endif

View File

@ -0,0 +1,56 @@
#ifndef PARTICLEDRAW_H
#define PARTICLEDRAW_H
class IMaterial;
class CMeshBuilder;
class CParticleSubTexture;
class ParticleDraw
{
friend class CParticleEffectBinding;
public:
ParticleDraw();
void Init(CMeshBuilder* pMeshBuilder, IMaterial* pMaterial, float fTimeDelta);
float GetTimeDelta() const;
CMeshBuilder* GetMeshBuilder();
CParticleSubTexture* m_pSubTexture;
private:
CMeshBuilder* m_pMeshBuilder;
IMaterial* m_pMaterial;
float m_fTimeDelta;
};
inline ParticleDraw::ParticleDraw()
{
m_pMaterial = 0;
}
inline void ParticleDraw::Init(CMeshBuilder* pMeshBuilder, IMaterial* pMaterial, float fTimeDelta)
{
m_pMeshBuilder = pMeshBuilder;
m_pMaterial = pMaterial;
m_fTimeDelta = fTimeDelta;
}
inline float ParticleDraw::GetTimeDelta() const
{
return m_fTimeDelta;
}
inline CMeshBuilder* ParticleDraw::GetMeshBuilder()
{
return m_pMeshBuilder;
}
#endif

617
SpyCustom/sdk/particlemgr.h Normal file
View File

@ -0,0 +1,617 @@
#ifndef PARTICLEMGR_H
#define PARTICLEMGR_H
#ifdef _WIN32
#pragma once
#endif
#include "imaterial.h"
#include "imaterialsystem.h"
#include "vector.h"
#include "vmatrix.h"
#include "Mathlib.h"
#include "iclientrenderable.h"
#include "clientleafsystem.h"
#include "fasttimer.h"
#include "utllinkedlist.h"
#include "UtlDict.h"
#ifdef WIN32
#include <typeinfo>
#else
#include <typeinfo>
#endif
#include "utlintrusivelist.h"
#include "utlobjectreference.h"
#include "utlstring.h"
class IParticleEffect;
class IClientParticleListener;
struct Particle;
class ParticleDraw;
class CMeshBuilder;
class CUtlMemoryPool;
class CEffectMaterial;
class CParticleSimulateIterator;
class CParticleRenderIterator;
class IThreadPool;
class CParticleSystemDefinition;
class CParticleMgr;
class CNewParticleEffect;
class CParticleCollection;
#define INVALID_MATERIAL_HANDLE NULL
class CParticleSubTexture;
class CParticleSubTextureGroup;
struct Particle
{
Particle* m_pPrev, * m_pNext;
CParticleSubTexture* m_pSubTexture;
Vector m_Pos;
};
typedef CParticleSubTexture* PMaterialHandle;
class CEffectMaterial
{
public:
CEffectMaterial();
public:
CParticleSubTextureGroup* m_pGroup;
Particle m_Particles;
CEffectMaterial* m_pHashedNext;
};
class CParticleSubTextureGroup
{
public:
CParticleSubTextureGroup();
~CParticleSubTextureGroup();
IMaterial* m_pPageMaterial;
};
class CParticleSubTexture
{
public:
CParticleSubTexture();
float m_tCoordMins[2];
float m_tCoordMaxs[2];
CParticleSubTextureGroup* m_pGroup;
CParticleSubTextureGroup m_DefaultGroup;
#ifdef _DEBUG
char* m_szDebugName;
#endif
IMaterial* m_pMaterial;
};
abstract_class IParticleEffect
{
public:
virtual ~IParticleEffect() {}
virtual void Update(float fTimeDelta) {}
virtual void StartRender(VMatrix & effectMatrix) {}
virtual bool ShouldSimulate() const = 0;
virtual void SetShouldSimulate(bool bSim) = 0;
virtual void SimulateParticles(CParticleSimulateIterator* pIterator) = 0;
virtual void RenderParticles(CParticleRenderIterator* pIterator) = 0;
virtual void NotifyRemove() {}
virtual void NotifyDestroyParticle(Particle* pParticle) {}
virtual const Vector& GetSortOrigin() = 0;
virtual const Vector* GetParticlePosition(Particle* pParticle) { return &pParticle->m_Pos; }
virtual const char* GetEffectName() { return "???"; }
};
#define REGISTER_EFFECT( effect ) \
IParticleEffect* effect##_Factory() \
{ \
return new effect; \
} \
struct effect##_RegistrationHelper \
{ \
effect##_RegistrationHelper() \
{ \
ParticleMgr()->RegisterEffect( typeid( effect ).name(), effect##_Factory ); \
} \
}; \
static effect##_RegistrationHelper g_##effect##_RegistrationHelper
#define REGISTER_EFFECT_USING_CREATE( effect ) \
IParticleEffect* effect##_Factory() \
{ \
return effect::Create( #effect ).GetObject(); \
} \
struct effect##_RegistrationHelper \
{ \
effect##_RegistrationHelper() \
{ \
ParticleMgr()->RegisterEffect( typeid( effect ).name(), effect##_Factory ); \
} \
}; \
static effect##_RegistrationHelper g_##effect##_RegistrationHelper
class CParticleEffectBinding : public CDefaultClientRenderable
{
friend class CParticleMgr;
friend class CParticleSimulateIterator;
friend class CNewParticleEffect;
public:
CParticleEffectBinding();
~CParticleEffectBinding();
public:
void SimulateParticles(float flTimeDelta);
PMaterialHandle FindOrAddMaterial(const char* pMaterialName);
Particle* AddParticle(int sizeInBytes, PMaterialHandle pMaterial);
void SetBBox(const Vector& bbMin, const Vector& bbMax, bool bDisableAutoUpdate = true);
void GetWorldspaceBounds(Vector* pMins, Vector* pMaxs);
const matrix3x4_t& GetLocalSpaceTransform() const;
void SetLocalSpaceTransform(const matrix3x4_t& transform);
bool EnlargeBBoxToContain(const Vector& pt);
void SetDrawThruLeafSystem(int bDraw);
void SetDrawBeforeViewModel(int bDraw);
int GetRemoveFlag() { return GetFlag(FLAGS_REMOVE); }
void SetRemoveFlag() { SetFlag(FLAGS_REMOVE, 1); }
int GetAlwaysSimulate() { return GetFlag(FLAGS_ALWAYSSIMULATE); }
void SetAlwaysSimulate(int bAlwaysSimulate) { SetFlag(FLAGS_ALWAYSSIMULATE, bAlwaysSimulate); }
void SetIsNewParticleSystem(void) { SetFlag(FLAGS_NEW_PARTICLE_SYSTEM, 1); }
int WasDrawnPrevFrame() { return GetFlag(FLAGS_DRAWN_PREVFRAME); }
void SetWasDrawnPrevFrame(int bWasDrawnPrevFrame) { SetFlag(FLAGS_DRAWN_PREVFRAME, bWasDrawnPrevFrame); }
int IsEffectCameraSpace() { return GetFlag(FLAGS_CAMERASPACE); }
void SetEffectCameraSpace(int bCameraSpace) { SetFlag(FLAGS_CAMERASPACE, bCameraSpace); }
int GetAutoApplyLocalTransform() const { return GetFlag(FLAGS_AUTOAPPLYLOCALTRANSFORM); }
void SetAutoApplyLocalTransform(int b) { SetFlag(FLAGS_AUTOAPPLYLOCALTRANSFORM, b); }
int GetAutoUpdateBBox() { return GetFlag(FLAGS_AUTOUPDATEBBOX); }
void SetAutoUpdateBBox(int bAutoUpdate) { SetFlag(FLAGS_AUTOUPDATEBBOX, bAutoUpdate); }
int GetNumActiveParticles();
void SetParticleCullRadius(float flMaxParticleRadius);
int GetActiveParticleList(int nCount, Particle** ppParticleList);
void DetectChanges();
private:
void SetFlag(int flag, int bOn) { if (bOn) m_Flags |= flag; else m_Flags &= ~flag; }
int GetFlag(int flag) const { return m_Flags & flag; }
void Init(CParticleMgr* pMgr, IParticleEffect* pSim);
void Term();
void RemoveParticle(Particle* pParticle);
void StartDrawMaterialParticles(
CEffectMaterial* pMaterial,
float flTimeDelta,
IMesh*& pMesh,
CMeshBuilder& builder,
ParticleDraw& particleDraw,
bool bWireframe);
int DrawMaterialParticles(
bool bBucketSort,
CEffectMaterial* pMaterial,
float flTimeDelta,
bool bWireframe
);
void GrowBBoxFromParticlePositions(CEffectMaterial* pMaterial, bool& bboxSet, Vector& bbMin, Vector& bbMax);
void RenderStart(VMatrix& mTempModel, VMatrix& mTempView);
void RenderEnd(VMatrix& mModel, VMatrix& mView);
void BBoxCalcStart(Vector& bbMin, Vector& bbMax);
void BBoxCalcEnd(bool bboxSet, Vector& bbMin, Vector& bbMax);
void DoBucketSort(
CEffectMaterial* pMaterial,
float* zCoords,
int nZCoords,
float minZ,
float maxZ);
int GetRemovalInProgressFlag() { return GetFlag(FLAGS_REMOVALINPROGRESS); }
void SetRemovalInProgressFlag() { SetFlag(FLAGS_REMOVALINPROGRESS, 1); }
int GetNeedsBBoxUpdate() { return GetFlag(FLAGS_NEEDS_BBOX_UPDATE); }
void SetNeedsBBoxUpdate(int bFirstUpdate) { SetFlag(FLAGS_NEEDS_BBOX_UPDATE, bFirstUpdate); }
int GetFirstFrameFlag() { return GetFlag(FLAGS_FIRST_FRAME); }
void SetFirstFrameFlag(int bFirstUpdate) { SetFlag(FLAGS_FIRST_FRAME, bFirstUpdate); }
int WasDrawn() { return GetFlag(FLAGS_DRAWN); }
void SetDrawn(int bDrawn) { SetFlag(FLAGS_DRAWN, bDrawn); }
bool RecalculateBoundingBox();
CEffectMaterial* GetEffectMaterial(CParticleSubTexture* pSubTexture);
public:
virtual const Vector& GetRenderOrigin(void);
virtual const QAngle& GetRenderAngles(void);
virtual const matrix3x4_t& RenderableToWorldTransform();
virtual void GetRenderBounds(Vector& mins, Vector& maxs);
virtual bool ShouldDraw(void);
virtual int DrawModel(int flags, const RenderableInstance_t& instance);
private:
enum
{
FLAGS_REMOVE = (1 << 0),
FLAGS_REMOVALINPROGRESS = (1 << 1),
FLAGS_NEEDS_BBOX_UPDATE = (1 << 2),
FLAGS_AUTOUPDATEBBOX = (1 << 3),
FLAGS_ALWAYSSIMULATE = (1 << 4),
FLAGS_DRAWN = (1 << 5),
FLAGS_DRAWN_PREVFRAME = (1 << 6),
FLAGS_CAMERASPACE = (1 << 7),
FLAGS_DRAW_THRU_LEAF_SYSTEM = (1 << 8),
FLAGS_DRAW_BEFORE_VIEW_MODEL = (1 << 9),
FLAGS_AUTOAPPLYLOCALTRANSFORM = (1 << 10),
FLAGS_FIRST_FRAME = (1 << 11),
FLAGS_NEW_PARTICLE_SYSTEM = (1 << 12)
};
VMatrix m_LocalSpaceTransform;
bool m_bLocalSpaceTransformIdentity;
Vector m_Min;
Vector m_Max;
Vector m_LastMin;
Vector m_LastMax;
float m_flParticleCullRadius;
unsigned short m_nActiveParticles;
unsigned short m_FrameCode;
unsigned short m_ListIndex;
IParticleEffect* m_pSim;
CParticleMgr* m_pParticleMgr;
int m_Flags;
enum { EFFECT_MATERIAL_HASH_SIZE = 8 };
CEffectMaterial* m_EffectMaterialHash[EFFECT_MATERIAL_HASH_SIZE];
#ifdef INFESTED_PARTICLES
public:
#endif
CUtlLinkedList<CEffectMaterial*, unsigned short> m_Materials;
unsigned short m_UpdateBBoxCounter;
};
class CParticleLightInfo
{
public:
Vector m_vPos;
Vector m_vColor;
float m_flIntensity;
};
typedef IParticleEffect* (*CreateParticleEffectFN)();
enum
{
TOOLPARTICLESYSTEMID_INVALID = -1,
};
class CParticleCollection;
class CNonDrawingParticleSystem
{
public:
CNonDrawingParticleSystem* m_pNext;
CNonDrawingParticleSystem* m_pPrev;
CParticleCollection* m_pSystem;
FORCEINLINE CParticleCollection* operator()(void) const
{
return m_pSystem;
}
FORCEINLINE CParticleCollection* Get(void) const
{
return m_pSystem;
}
~CNonDrawingParticleSystem(void);
};
class CClientTools;
class CParticleMgr
{
friend class CParticleEffectBinding;
friend class CParticleCollection;
friend class CNonDrawingParticleSystem;
friend class CClientTools;
public:
CParticleMgr();
virtual ~CParticleMgr();
bool Init(unsigned long nPreallocatedParticles, IMaterialSystem* pMaterial);
void Term();
void LevelInit();
void RegisterEffect(const char* pEffectType, CreateParticleEffectFN func);
IParticleEffect* CreateEffect(const char* pEffectType);
bool AddEffect(CParticleEffectBinding* pEffect, IParticleEffect* pSim);
void RemoveEffect(CParticleEffectBinding* pEffect);
void AddEffect(CNewParticleEffect* pEffect);
void RemoveEffect(CNewParticleEffect* pEffect);
void RemoveAllEffects();
void IncrementFrameCode();
void Simulate(float fTimeDelta);
void PostRender();
void DrawBeforeViewModelEffects();
VMatrix& GetModelView();
Particle* AllocParticle(int size);
void FreeParticle(Particle*);
PMaterialHandle GetPMaterial(const char* pMaterialName);
IMaterial* PMaterialToIMaterial(PMaterialHandle hMaterial);
void RepairPMaterial(PMaterialHandle hMaterial);
void GetDirectionalLightInfo(CParticleLightInfo& info) const;
void SetDirectionalLightInfo(const CParticleLightInfo& info);
void SpewInfo(bool bDetail);
void AddEffectListener(IClientParticleListener* pListener);
void RemoveEffectListener(IClientParticleListener* pListener);
int AllocateToolParticleEffectId();
void RemoveAllNewEffects();
CNewParticleEffect* FirstNewEffect();
CNewParticleEffect* NextNewEffect(CNewParticleEffect* pEffect);
void RenderParticleSystems(bool bEnable);
bool ShouldRenderParticleSystems() const;
void RemoveOldParticleEffects(float flTime);
int GetNumParticles() const { return m_nCurrentParticlesAllocated; }
CNonDrawingParticleSystem* CreateNonDrawingEffect(const char* pEffectName);
private:
struct RetireInfo_t
{
CParticleCollection* m_pCollection;
float m_flScreenArea;
bool m_bFirstFrame;
};
void UpdateAllEffects(float flTimeDelta);
void UpdateNewEffects(float flTimeDelta);
void SpewActiveParticleSystems();
CParticleSubTextureGroup* FindOrAddSubTextureGroup(IMaterial* pPageMaterial);
int ComputeParticleDefScreenArea(int nInfoCount, RetireInfo_t* pInfo, float* pTotalArea, CParticleSystemDefinition* pDef,
const CViewSetup& view, const VMatrix& worldToPixels, float flFocalDist);
bool RetireParticleCollections(CParticleSystemDefinition* pDef, int nCount, RetireInfo_t* pInfo, float flScreenArea, float flMaxTotalArea);
void BuildParticleSimList(CUtlVector< CNewParticleEffect* >& list);
bool EarlyRetireParticleSystems(int nCount, CNewParticleEffect** ppEffects);
static int RetireSort(const void* p1, const void* p2);
private:
int m_nCurrentParticlesAllocated;
CParticleLightInfo m_DirectionalLight;
unsigned short m_FrameCode;
bool m_bUpdatingEffects;
bool m_bRenderParticleEffects;
CUtlLinkedList<CParticleEffectBinding*, unsigned short> m_Effects;
CUtlIntrusiveDList< CNewParticleEffect > m_NewEffects;
CUtlIntrusiveDList< CNonDrawingParticleSystem > m_NonDrawingParticleSystems;
CUtlVector< IClientParticleListener*> m_effectListeners;
IMaterialSystem* m_pMaterialSystem;
VMatrix m_mModelView;
CUtlVector<CParticleSubTextureGroup*> m_SubTextureGroups;
CUtlDict<CParticleSubTexture*, unsigned short> m_SubTextures;
CParticleSubTexture m_DefaultInvalidSubTexture;
CUtlMap< const char*, CreateParticleEffectFN > m_effectFactories;
int m_nToolParticleEffectId;
IThreadPool* m_pThreadPool[2];
};
inline int CParticleMgr::AllocateToolParticleEffectId()
{
return m_nToolParticleEffectId++;
}
class IClientParticleListener
{
public:
virtual void OnParticleEffectAdded(IParticleEffect* pEffect) = 0;
virtual void OnParticleEffectRemoved(IParticleEffect* pEffect) = 0;
};
float Helper_GetTime();
float Helper_GetFrameTime();
float Helper_RandomFloat(float minVal, float maxVal);
int Helper_RandomInt(int minVal, int maxVal);
inline VMatrix& CParticleMgr::GetModelView()
{
return m_mModelView;
}
inline const matrix3x4_t& CParticleEffectBinding::GetLocalSpaceTransform() const
{
return m_LocalSpaceTransform.As3x4();
}
CParticleMgr* ParticleMgr();
struct StandardParticle_t : public Particle
{
void SetColor(float r, float g, float b);
void SetAlpha(float a);
Vector m_Velocity;
float m_Lifetime;
unsigned char m_EffectData;
unsigned short m_EffectDataWord;
unsigned char m_Color[4];
};
inline void TransformParticle(const VMatrix& vMat, const Vector& vIn, Vector& vOut)
{
vOut.x = vMat.m[0][0] * vIn.x + vMat.m[0][1] * vIn.y + vMat.m[0][2] * vIn.z + vMat.m[0][3];
vOut.y = vMat.m[1][0] * vIn.x + vMat.m[1][1] * vIn.y + vMat.m[1][2] * vIn.z + vMat.m[1][3];
vOut.z = vMat.m[2][0] * vIn.x + vMat.m[2][1] * vIn.y + vMat.m[2][2] * vIn.z + vMat.m[2][3];
}
inline void StandardParticle_t::SetColor(float r, float g, float b)
{
m_Color[0] = (unsigned char)(r * 255.9f);
m_Color[1] = (unsigned char)(g * 255.9f);
m_Color[2] = (unsigned char)(b * 255.9f);
}
inline void StandardParticle_t::SetAlpha(float a)
{
m_Color[3] = (unsigned char)(a * 255.9f);
}
inline void UnlinkParticle(Particle* pParticle)
{
pParticle->m_pPrev->m_pNext = pParticle->m_pNext;
pParticle->m_pNext->m_pPrev = pParticle->m_pPrev;
}
inline void InsertParticleBefore(Particle* pInsert, Particle* pNext)
{
pInsert->m_pNext = pNext;
pInsert->m_pPrev = pNext->m_pPrev;
pInsert->m_pNext->m_pPrev = pInsert->m_pPrev->m_pNext = pInsert;
}
inline void InsertParticleAfter(Particle* pInsert, Particle* pPrev)
{
pInsert->m_pPrev = pPrev;
pInsert->m_pNext = pPrev->m_pNext;
pInsert->m_pNext->m_pPrev = pInsert->m_pPrev->m_pNext = pInsert;
}
inline void SwapParticles(Particle* pPrev, Particle* pCur)
{
UnlinkParticle(pCur);
InsertParticleBefore(pCur, pPrev);
}
#include "particle_iterators.h"
#endif

1954
SpyCustom/sdk/particles.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,295 @@
#ifndef PARTICLES_NEW_H
#define PARTICLES_NEW_H
#ifdef _WIN32
#pragma once
#endif
#include "particlemgr.h"
#include "particles.h"
#include "particlesphererenderer.h"
#include "smartptr.h"
#include "particles_simple.h"
#include "utlobjectreference.h"
class CNewParticleEffect : public IParticleEffect, public CParticleCollection, public CDefaultClientRenderable
{
public:
DECLARE_CLASS_NOBASE(CNewParticleEffect);
DECLARE_REFERENCED_CLASS(CNewParticleEffect);
public:
friend class CRefCountAccessor;
CNewParticleEffect* m_pNext;
CNewParticleEffect* m_pPrev;
void SetSortOrigin(const Vector& vSortOrigin);
bool ShouldDraw(void);
virtual bool IsTransparent(void);
virtual bool IsTwoPass(void);
virtual bool UsesPowerOfTwoFrameBufferTexture(void);
virtual bool UsesFullFrameBufferTexture(void);
const QAngle& GetRenderAngles(void);
const matrix3x4_t& RenderableToWorldTransform();
void GetRenderBounds(Vector& mins, Vector& maxs);
void DetectChanges(void);
const Vector& GetRenderOrigin(void);
PMaterialHandle GetPMaterial(const char* name);
bool RecalculateBoundingBox();
Particle* AddParticle(unsigned int particleSize, PMaterialHandle material, const Vector& origin);
const char* GetEffectName();
void SetDontRemove(bool bSet);
void SetDrawn(bool bDrawn);
void SetFirstFrameFlag(bool bFirst);
void SetNeedsBBoxUpdate(bool bNeedsUpdate);
void SetAutoUpdateBBox(bool bNeedsUpdate);
void SetRemoveFlag(void);
bool GetRemoveFlag(void);
bool GetFirstFrameFlag(void);
bool GetNeedsBBoxUpdate(void);
bool GetAutoUpdateBBox(void);
bool ShouldPerformCullCheck() const;
void MarkShouldPerformCullCheck(bool bEnable);
CBaseEntity* GetOwner(void) { return m_hOwner; }
void SetOwner(CBaseEntity* pOwner) { m_hOwner = pOwner; }
CNewParticleEffect* ReplaceWith(const char* pParticleSystemName);
static CSmartPtr<CNewParticleEffect> Create(CBaseEntity* pOwner, const char* pParticleSystemName,
const char* pDebugName = NULL);
static CSmartPtr<CNewParticleEffect> Create(CBaseEntity* pOwner, CParticleSystemDefinition* pDef,
const char* pDebugName = NULL);
virtual int DrawModel(int flags);
void DebugDrawBbox(bool bCulled);
public:
void StopEmission(bool bInfiniteOnly = false, bool bRemoveAllParticles = false, bool bWakeOnStop = false);
void SetDormant(bool bDormant);
void SetControlPoint(int nWhichPoint, const Vector& v);
void SetControlPointEntity(int nWhichPoint, CBaseEntity* pEntity);
void SetControlPointOrientation(int nWhichPoint, const Quaternion& q);
void SetControlPointOrientation(int nWhichPoint, const Vector& forward, const Vector& right, const Vector& up);
void SetControlPointForwardVector(int nWhichPoint, const Vector& v);
void SetControlPointUpVector(int nWhichPoint, const Vector& v);
void SetControlPointRightVector(int nWhichPoint, const Vector& v);
FORCEINLINE EHANDLE const& GetControlPointEntity(int nWhichPoint)
{
return m_hControlPointOwners[nWhichPoint];
}
public:
virtual void SimulateParticles(CParticleSimulateIterator* pIterator)
{
}
virtual void RenderParticles(CParticleRenderIterator* pIterator)
{
}
virtual void SetParticleCullRadius(float radius);
virtual void NotifyRemove(void);
virtual const Vector& GetSortOrigin(void);
virtual void Update(float flTimeDelta);
void SetDynamicallyAllocated(bool bDynamic = true);
virtual bool ShouldSimulate() const { return m_bSimulate; }
virtual void SetShouldSimulate(bool bSim) { m_bSimulate = bSim; }
int AllocateToolParticleEffectId();
int GetToolParticleEffectId() const;
CNewParticleEffect(CBaseEntity* pOwner, const char* pEffectName);
CNewParticleEffect(CBaseEntity* pOwner, CParticleSystemDefinition* pEffect);
virtual ~CNewParticleEffect();
protected:
int IsReleased();
const char* m_pDebugName;
bool m_bDontRemove : 1;
bool m_bRemove : 1;
bool m_bDrawn : 1;
bool m_bNeedsBBoxUpdate : 1;
bool m_bIsFirstFrame : 1;
bool m_bAutoUpdateBBox : 1;
bool m_bAllocated : 1;
bool m_bSimulate : 1;
bool m_bShouldPerformCullCheck : 1;
int m_nToolParticleEffectId;
Vector m_vSortOrigin;
EHANDLE m_hOwner;
EHANDLE m_hControlPointOwners[MAX_PARTICLE_CONTROL_POINTS];
Vector m_LastMin;
Vector m_LastMax;
private:
void AddRef();
void Release();
void RecordControlPointOrientation(int nWhichPoint);
void Construct();
int m_RefCount;
CNewParticleEffect(const CNewParticleEffect&);
};
inline int CNewParticleEffect::GetToolParticleEffectId() const
{
return m_nToolParticleEffectId;
}
inline int CNewParticleEffect::AllocateToolParticleEffectId()
{
m_nToolParticleEffectId = ParticleMgr()->AllocateToolParticleEffectId();
return m_nToolParticleEffectId;
}
inline void CNewParticleEffect::SetSortOrigin(const Vector& vSortOrigin)
{
m_vSortOrigin = vSortOrigin;
}
inline const Vector& CNewParticleEffect::GetSortOrigin(void)
{
return m_vSortOrigin;
}
inline bool CNewParticleEffect::ShouldDraw(void)
{
return true;
}
inline bool CNewParticleEffect::IsTransparent(void)
{
return CParticleCollection::IsTranslucent();
}
inline const QAngle& CNewParticleEffect::GetRenderAngles(void)
{
return vec3_angle;
}
inline const matrix3x4_t& CNewParticleEffect::RenderableToWorldTransform()
{
static matrix3x4_t mat;
SetIdentityMatrix(mat);
PositionMatrix(GetRenderOrigin(), mat);
return mat;
}
inline Vector const& CNewParticleEffect::GetRenderOrigin(void)
{
return m_vSortOrigin;
}
inline PMaterialHandle CNewParticleEffect::GetPMaterial(const char* name)
{
Assert(0);
return NULL;
}
inline Particle* CNewParticleEffect::AddParticle(unsigned int particleSize, PMaterialHandle material, const Vector& origin)
{
Assert(0);
return NULL;
}
inline const char* CNewParticleEffect::GetEffectName()
{
return GetName();
}
inline void CNewParticleEffect::SetDontRemove(bool bSet)
{
m_bDontRemove = bSet;
}
inline void CNewParticleEffect::SetDrawn(bool bDrawn)
{
m_bDrawn = bDrawn;
}
inline void CNewParticleEffect::SetFirstFrameFlag(bool bFirst)
{
m_bIsFirstFrame = bFirst;
}
inline void CNewParticleEffect::SetDynamicallyAllocated(bool bDynamic)
{
m_bAllocated = bDynamic;
}
inline void CNewParticleEffect::SetNeedsBBoxUpdate(bool bNeedsUpdate)
{
m_bNeedsBBoxUpdate = bNeedsUpdate;
}
inline void CNewParticleEffect::SetAutoUpdateBBox(bool bNeedsUpdate)
{
m_bAutoUpdateBBox = bNeedsUpdate;
}
inline void CNewParticleEffect::SetRemoveFlag(void)
{
m_bRemove = true;
}
inline bool CNewParticleEffect::GetRemoveFlag(void)
{
return m_bRemove;
}
inline bool CNewParticleEffect::GetFirstFrameFlag(void)
{
return m_bIsFirstFrame;
}
inline bool CNewParticleEffect::GetNeedsBBoxUpdate(void)
{
return m_bNeedsBBoxUpdate;
}
inline bool CNewParticleEffect::GetAutoUpdateBBox(void)
{
return m_bAutoUpdateBBox;
}
inline bool CNewParticleEffect::ShouldPerformCullCheck() const
{
return m_bShouldPerformCullCheck;
}
inline void CNewParticleEffect::MarkShouldPerformCullCheck(bool bEnable)
{
m_bShouldPerformCullCheck = bEnable;
}
inline CSmartPtr<CNewParticleEffect> CNewParticleEffect::Create(CBaseEntity* pOwner, const char* pParticleSystemName, const char* pDebugName)
{
CNewParticleEffect* pRet = new CNewParticleEffect(pOwner, pParticleSystemName);
pRet->m_pDebugName = pDebugName;
pRet->SetDynamicallyAllocated(true);
return pRet;
}
inline CSmartPtr<CNewParticleEffect> CNewParticleEffect::Create(CBaseEntity* pOwner, CParticleSystemDefinition* pDef, const char* pDebugName)
{
CNewParticleEffect* pRet = new CNewParticleEffect(pOwner, pDef);
pRet->m_pDebugName = pDebugName;
pRet->SetDynamicallyAllocated(true);
return pRet;
}
typedef CUtlReference<CNewParticleEffect> HPARTICLEFFECT;
#endif

View File

@ -0,0 +1,206 @@
#ifndef PARTICLES_SIMPLE_H
#define PARTICLES_SIMPLE_H
#ifdef _WIN32
#pragma once
#endif
#include "particlemgr.h"
#include "ParticleSphereRenderer.h"
#include "smartptr.h"
class CParticleEffect : public IParticleEffect
{
public:
DECLARE_CLASS_NOBASE(CParticleEffect);
friend class CRefCountAccessor;
void SetSortOrigin(const Vector& vSortOrigin);
PMaterialHandle GetPMaterial(const char* name);
Particle* AddParticle(unsigned int particleSize, PMaterialHandle material, const Vector& origin);
CParticleEffectBinding& GetBinding() { return m_ParticleEffect; }
const char* GetEffectName();
void AddFlags(int iFlags) { m_Flags |= iFlags; }
void RemoveFlags(int iFlags) { m_Flags &= ~iFlags; }
void SetDontRemove(bool bSet)
{
if (bSet)
AddFlags(FLAG_DONT_REMOVE);
else
RemoveFlags(FLAG_DONT_REMOVE);
}
public:
virtual void SetParticleCullRadius(float radius);
virtual void NotifyRemove(void);
virtual const Vector& GetSortOrigin();
virtual void NotifyDestroyParticle(Particle* pParticle);
virtual void Update(float flTimeDelta);
void SetDynamicallyAllocated(bool bDynamic = true);
virtual bool ShouldSimulate() const { return m_bSimulate; }
virtual void SetShouldSimulate(bool bSim) { m_bSimulate = bSim; }
int AllocateToolParticleEffectId();
int GetToolParticleEffectId() const;
protected:
CParticleEffect(const char* pDebugName);
virtual ~CParticleEffect();
int IsReleased();
enum
{
FLAG_ALLOCATED = (1 << 1),
FLAG_DONT_REMOVE = (1 << 2),
};
char const* m_pDebugName;
CParticleEffectBinding m_ParticleEffect;
Vector m_vSortOrigin;
int m_Flags;
bool m_bSimulate;
int m_nToolParticleEffectId;
private:
void AddRef();
void Release();
int m_RefCount;
CParticleEffect(const CParticleEffect&);
};
inline int CParticleEffect::GetToolParticleEffectId() const
{
return m_nToolParticleEffectId;
}
inline int CParticleEffect::AllocateToolParticleEffectId()
{
m_nToolParticleEffectId = ParticleMgr()->AllocateToolParticleEffectId();
return m_nToolParticleEffectId;
}
enum SimpleParticleFlag_t
{
SIMPLE_PARTICLE_FLAG_WINDBLOWN = 0x1,
SIMPLE_PARTICLE_FLAG_NO_VEL_DECAY = 0x2
};
class SimpleParticle : public Particle
{
public:
SimpleParticle() : m_iFlags(0) {}
Vector m_vecVelocity;
float m_flRoll;
float m_flDieTime;
float m_flLifetime;
unsigned char m_uchColor[3];
unsigned char m_uchStartAlpha;
unsigned char m_uchEndAlpha;
unsigned char m_uchStartSize;
unsigned char m_uchEndSize;
unsigned char m_iFlags;
float m_flRollDelta;
};
class CSimpleEmitter : public CParticleEffect
{
public:
DECLARE_CLASS(CSimpleEmitter, CParticleEffect);
static CSmartPtr<CSimpleEmitter> Create(const char* pDebugName);
virtual void SimulateParticles(CParticleSimulateIterator* pIterator);
virtual void RenderParticles(CParticleRenderIterator* pIterator);
void SetNearClip(float nearClipMin, float nearClipMax);
void SetDrawBeforeViewModel(bool state = true);
SimpleParticle* AddSimpleParticle(PMaterialHandle hMaterial, const Vector& vOrigin, float flDieTime = 3, unsigned char uchSize = 10);
void SetShouldDrawForSplitScreenUser(int nSlot);
protected:
CSimpleEmitter(const char* pDebugName = NULL);
virtual ~CSimpleEmitter();
virtual float UpdateAlpha(const SimpleParticle* pParticle);
virtual float UpdateScale(const SimpleParticle* pParticle);
virtual float UpdateRoll(SimpleParticle* pParticle, float timeDelta);
virtual void UpdateVelocity(SimpleParticle* pParticle, float timeDelta);
virtual Vector UpdateColor(const SimpleParticle* pParticle);
float m_flNearClipMin;
float m_flNearClipMax;
int m_nSplitScreenPlayerSlot;
private:
CSimpleEmitter(const CSimpleEmitter&);
};
class CEmberEffect : public CSimpleEmitter
{
public:
CEmberEffect(const char* pDebugName);
static CSmartPtr<CEmberEffect> Create(const char* pDebugName);
virtual void UpdateVelocity(SimpleParticle* pParticle, float timeDelta);
virtual Vector UpdateColor(const SimpleParticle* pParticle);
private:
CEmberEffect(const CEmberEffect&);
};
class CFireSmokeEffect : public CSimpleEmitter
{
public:
CFireSmokeEffect(const char* pDebugName);
static CSmartPtr<CFireSmokeEffect> Create(const char* pDebugName);
virtual void UpdateVelocity(SimpleParticle* pParticle, float timeDelta);
virtual float UpdateAlpha(const SimpleParticle* pParticle);
protected:
VPlane m_planeClip;
private:
CFireSmokeEffect(const CFireSmokeEffect&);
};
class CFireParticle : public CSimpleEmitter
{
public:
CFireParticle(const char* pDebugName);
static CSmartPtr<CFireParticle> Create(const char* pDebugName);
virtual Vector UpdateColor(const SimpleParticle* pParticle);
private:
CFireParticle(const CFireParticle&);
};
#endif

1280
SpyCustom/sdk/platform.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,113 @@
#ifndef PLAYERNET_VARS_H
#define PLAYERNET_VARS_H
#ifdef _WIN32
#pragma once
#endif
#include "shared_classnames.h"
#include "networkvar.h"
#include "datamap.h"
#define NUM_AUDIO_LOCAL_SOUNDS 8
struct fogparams_t
{
DECLARE_CLASS_NOBASE(fogparams_t);
DECLARE_EMBEDDED_NETWORKVAR();
#ifndef CLIENT_DLL
DECLARE_SIMPLE_DATADESC();
#endif
bool operator !=(const fogparams_t& other) const;
CNetworkVector(dirPrimary);
CNetworkColor32(colorPrimary);
CNetworkColor32(colorSecondary);
CNetworkColor32(colorPrimaryLerpTo);
CNetworkColor32(colorSecondaryLerpTo);
CNetworkVar(float, start);
CNetworkVar(float, end);
CNetworkVar(float, farz);
CNetworkVar(float, maxdensity);
CNetworkVar(float, startLerpTo);
CNetworkVar(float, endLerpTo);
CNetworkVar(float, lerptime);
CNetworkVar(float, duration);
CNetworkVar(bool, enable);
CNetworkVar(bool, blend);
};
#ifdef CLIENT_DLL
#define CFogController C_FogController
#endif
class CFogController;
struct fogplayerparams_t
{
DECLARE_CLASS_NOBASE(fogplayerparams_t);
DECLARE_EMBEDDED_NETWORKVAR();
#ifndef CLIENT_DLL
DECLARE_SIMPLE_DATADESC();
#endif
CNetworkHandle(CFogController, m_hCtrl);
float m_flTransitionTime;
color32 m_OldColor;
float m_flOldStart;
float m_flOldEnd;
color32 m_NewColor;
float m_flNewStart;
float m_flNewEnd;
fogplayerparams_t()
{
m_hCtrl.Set(NULL);
m_flTransitionTime = -1.0f;
m_OldColor.r = m_OldColor.g = m_OldColor.b = m_OldColor.a = 0;
m_flOldStart = 0.0f;
m_flOldEnd = 0.0f;
m_NewColor.r = m_NewColor.g = m_NewColor.b = m_NewColor.a = 0;
m_flNewStart = 0.0f;
m_flNewEnd = 0.0f;
}
};
struct sky3dparams_t
{
DECLARE_CLASS_NOBASE(sky3dparams_t);
DECLARE_EMBEDDED_NETWORKVAR();
#ifndef CLIENT_DLL
DECLARE_SIMPLE_DATADESC();
#endif
CNetworkVar(int, scale);
CNetworkVector(origin);
CNetworkVar(int, area);
CNetworkVarEmbedded(fogparams_t, fog);
};
struct audioparams_t
{
DECLARE_CLASS_NOBASE(audioparams_t);
DECLARE_EMBEDDED_NETWORKVAR();
#ifndef CLIENT_DLL
DECLARE_SIMPLE_DATADESC();
#endif
CNetworkArray(Vector, localSound, NUM_AUDIO_LOCAL_SOUNDS)
CNetworkVar(int, soundscapeIndex);
CNetworkVar(int, localBits);
CNetworkHandle(CBaseEntity, ent);
};
#endif

View File

@ -0,0 +1,22 @@
#ifndef PRECIPITATION_SHARED_H
#define PRECIPITATION_SHARED_H
#ifdef _WIN32
#pragma once
#endif
enum PrecipitationType_t
{
PRECIPITATION_TYPE_RAIN = 0,
PRECIPITATION_TYPE_SNOW,
PRECIPITATION_TYPE_ASH,
PRECIPITATION_TYPE_SNOWFALL,
PRECIPITATION_TYPE_PARTICLERAIN,
PRECIPITATION_TYPE_PARTICLEASH,
PRECIPITATION_TYPE_PARTICLERAINSTORM,
PRECIPITATION_TYPE_PARTICLESNOW,
NUM_PRECIPITATION_TYPES
};
#endif

View File

@ -0,0 +1,185 @@
#ifndef PREDICTABLE_ENTITY_H
#define PREDICTABLE_ENTITY_H
#ifdef _WIN32
#pragma once
#endif
#include "platform.h"
#include "predictioncopy.h"
#include "shared_classnames.h"
#ifndef NO_ENTITY_PREDICTION
#define UsePrediction() 1
#else
#define UsePrediction() 0
#endif
#if defined( CLIENT_DLL )
#include "iclassmap.h"
#include "recvproxy.h"
class SendTable;
#else
#include "sendproxy.h"
#endif
#if defined( CLIENT_DLL )
#define DECLARE_NETWORKCLASS() \
DECLARE_CLIENTCLASS()
#define DECLARE_NETWORKCLASS_NOBASE() \
DECLARE_CLIENTCLASS_NOBASE()
#else
#define DECLARE_NETWORKCLASS() \
DECLARE_SERVERCLASS()
#define DECLARE_NETWORKCLASS_NOBASE() \
DECLARE_SERVERCLASS_NOBASE()
#endif
#if defined( CLIENT_DLL )
#ifndef NO_ENTITY_PREDICTION
#define DECLARE_PREDICTABLE() \
public: \
static typedescription_t m_PredDesc[]; \
static datamap_t m_PredMap; \
virtual datamap_t *GetPredDescMap( void ); \
template <typename T> friend datamap_t *PredMapInit(T *)
#else
#define DECLARE_PREDICTABLE() template <typename T> friend datamap_t *PredMapInit(T *)
#endif
#ifndef NO_ENTITY_PREDICTION
#define BEGIN_PREDICTION_DATA( className ) \
datamap_t className::m_PredMap = { 0, 0, #className, &BaseClass::m_PredMap }; \
datamap_t *className::GetPredDescMap( void ) { return &m_PredMap; } \
BEGIN_PREDICTION_DATA_GUTS( className )
#define BEGIN_PREDICTION_DATA_NO_BASE( className ) \
datamap_t className::m_PredMap = { 0, 0, #className, NULL }; \
datamap_t *className::GetPredDescMap( void ) { return &m_PredMap; } \
BEGIN_PREDICTION_DATA_GUTS( className )
#define BEGIN_PREDICTION_DATA_GUTS( className ) \
template <typename T> datamap_t *PredMapInit(T *); \
template <> datamap_t *PredMapInit<className>( className * ); \
namespace className##_PredDataDescInit \
{ \
datamap_t *g_PredMapHolder = PredMapInit( (className *)NULL ); \
} \
\
template <> datamap_t *PredMapInit<className>( className * ) \
{ \
typedef className classNameTypedef; \
static typedescription_t predDesc[] = \
{ \
{ FIELD_VOID,0, {0,0},0,0,0,0,0,0},
#define END_PREDICTION_DATA() \
}; \
\
if ( sizeof( predDesc ) > sizeof( predDesc[0] ) ) \
{ \
classNameTypedef::m_PredMap.dataNumFields = ARRAYSIZE( predDesc ) - 1; \
classNameTypedef::m_PredMap.dataDesc = &predDesc[1]; \
} \
else \
{ \
classNameTypedef::m_PredMap.dataNumFields = 1; \
classNameTypedef::m_PredMap.dataDesc = predDesc; \
} \
return &classNameTypedef::m_PredMap; \
}
#else
#define BEGIN_PREDICTION_DATA( className ) \
template <> inline datamap_t *PredMapInit<className>( className * ) \
{ \
if ( 0 ) \
{ \
typedef className classNameTypedef; \
typedescription_t predDesc[] = \
{ \
{ FIELD_VOID,0, {0,0},0,0,0,0,0,0},
#define BEGIN_PREDICTION_DATA_NO_BASE( className ) BEGIN_PREDICTION_DATA( className )
#define END_PREDICTION_DATA() \
}; \
predDesc[0].flags = 0; \
} \
}
#endif
#else
#define DECLARE_PREDICTABLE()
#define BEGIN_PREDICTION_DATA( className )
#define END_PREDICTION_DATA()
#endif
#if defined( CLIENT_DLL )
#define LINK_ENTITY_TO_CLASS( localName, className ) \
static C_BaseEntity *C##className##Factory( void ) \
{ \
return static_cast< C_BaseEntity * >( new className ); \
}; \
class C##localName##Foo \
{ \
public: \
C##localName##Foo( void ) \
{ \
GetClassMap().Add( #localName, #className, sizeof( className ), \
&C##className##Factory ); \
} \
}; \
static C##localName##Foo g_C##localName##Foo;
#define BEGIN_NETWORK_TABLE( className, tableName ) BEGIN_RECV_TABLE( className, tableName )
#define BEGIN_NETWORK_TABLE_NOBASE( className, tableName ) BEGIN_RECV_TABLE_NOBASE( className, tableName )
#define END_NETWORK_TABLE END_RECV_TABLE
#define IMPLEMENT_NETWORKCLASS_ALIASED(className, dataTable) \
IMPLEMENT_CLIENTCLASS( C_##className, dataTable, C##className )
#define IMPLEMENT_NETWORKCLASS(className, dataTable) \
IMPLEMENT_CLIENTCLASS(className, dataTable, className)
#define IMPLEMENT_NETWORKCLASS_DT(className, dataTable) \
IMPLEMENT_CLIENTCLASS_DT(className, dataTable, className)
#else
#define BEGIN_NETWORK_TABLE( className, tableName ) BEGIN_SEND_TABLE( className, tableName )
#define BEGIN_NETWORK_TABLE_NOBASE( className, tableName ) BEGIN_SEND_TABLE_NOBASE( className, tableName )
#define END_NETWORK_TABLE END_SEND_TABLE
#define IMPLEMENT_NETWORKCLASS_ALIASED(className, dataTable) \
IMPLEMENT_SERVERCLASS( C##className, dataTable )
#define IMPLEMENT_NETWORKCLASS(className, dataTable) \
IMPLEMENT_SERVERCLASS(className, dataTable)
#define IMPLEMENT_NETWORKCLASS_DT(className, dataTable) \
IMPLEMENT_SERVERCLASS_ST(className, dataTable)
#endif
abstract_class IPredictableList
{
public:
virtual CBaseEntity* GetPredictable(int slot) = 0;
virtual int GetPredictableCount(void) = 0;
};
extern IPredictableList* predictables;
#endif

View File

@ -0,0 +1,53 @@
#ifndef PREDICTABLEID_H
#define PREDICTABLEID_H
#ifdef _WIN32
#pragma once
#endif
#if !defined( NO_ENTITY_PREDICTION )
class CPredictableId
{
public:
CPredictableId(void);
static void ResetInstanceCounters(void);
bool IsActive(void) const;
void Init(int player, int command, const char* classname, const char* module, int line);
int GetPlayer(void) const;
int GetHash(void) const;
int GetInstanceNumber(void) const;
int GetCommandNumber(void) const;
void SetAcknowledged(bool ack);
bool GetAcknowledged(void) const;
int GetRaw(void) const;
void SetRaw(int raw);
char const* Describe(void) const;
bool operator ==(const CPredictableId& other) const;
bool operator !=(const CPredictableId& other) const;
private:
void SetCommandNumber(int commandNumber);
void SetPlayer(int playerIndex);
void SetInstanceNumber(int counter);
struct bitfields
{
unsigned int ack : 1;
unsigned int player : 5;
unsigned int command : 10;
unsigned int hash : 12;
unsigned int instance : 4;
} m_PredictableID;
};
FORCEINLINE void NetworkVarConstruct(CPredictableId& x) {}
#endif
#endif

View File

@ -0,0 +1,278 @@
#ifndef PREDICTIONCOPY_H
#define PREDICTIONCOPY_H
#ifdef _WIN32
#pragma once
#endif
#include <memory.h>
#include "datamap.h"
#include "ehandle.h"
#include "utlstring.h"
#if defined( CLIENT_DLL )
class C_BaseEntity;
typedef CHandle<C_BaseEntity> EHANDLE;
#if defined( _DEBUG )
class IGameSystem;
IGameSystem* GetPredictionCopyTester(void);
#endif
#else
class CBaseEntity;
typedef CHandle<CBaseEntity> EHANDLE;
#endif
enum
{
PC_EVERYTHING = 0,
PC_NON_NETWORKED_ONLY,
PC_NETWORKED_ONLY,
};
#define PC_DATA_PACKED true
#define PC_DATA_NORMAL false
typedef void (*FN_FIELD_COMPARE)(const char* classname, const char* fieldname, const char* fieldtype,
bool networked, bool noterrorchecked, bool differs, bool withintolerance, const char* value);
class CPredictionCopy
{
public:
typedef enum
{
DIFFERS = 0,
IDENTICAL,
WITHINTOLERANCE,
} difftype_t;
CPredictionCopy(int type, void* dest, bool dest_packed, void const* src, bool src_packed,
bool counterrors = false, bool reporterrors = false, bool performcopy = true,
bool describefields = false, FN_FIELD_COMPARE func = NULL);
void CopyShort(difftype_t dt, short* outvalue, const short* invalue, int count);
void CopyInt(difftype_t dt, int* outvalue, const int* invalue, int count);
void CopyBool(difftype_t dt, bool* outvalue, const bool* invalue, int count);
void CopyFloat(difftype_t dt, float* outvalue, const float* invalue, int count);
void CopyString(difftype_t dt, char* outstring, const char* instring);
void CopyVector(difftype_t dt, Vector& outValue, const Vector& inValue);
void CopyVector(difftype_t dt, Vector* outValue, const Vector* inValue, int count);
void CopyQuaternion(difftype_t dt, Quaternion& outValue, const Quaternion& inValue);
void CopyQuaternion(difftype_t dt, Quaternion* outValue, const Quaternion* inValue, int count);
void CopyEHandle(difftype_t dt, EHANDLE* outvalue, EHANDLE const* invalue, int count);
void FORCEINLINE CopyData(difftype_t dt, int size, char* outdata, const char* indata)
{
if (!m_bPerformCopy)
return;
if (dt == IDENTICAL)
return;
memcpy(outdata, indata, size);
}
int TransferData(const char* operation, int entindex, datamap_t* dmap);
private:
void TransferData_R(int chaincount, datamap_t* dmap);
void DetermineWatchField(const char* operation, int entindex, datamap_t* dmap);
void DumpWatchField(typedescription_t* field);
void WatchMsg(PRINTF_FORMAT_STRING const char* fmt, ...);
difftype_t CompareShort(short* outvalue, const short* invalue, int count);
difftype_t CompareInt(int* outvalue, const int* invalue, int count);
difftype_t CompareBool(bool* outvalue, const bool* invalue, int count);
difftype_t CompareFloat(float* outvalue, const float* invalue, int count);
difftype_t CompareData(int size, char* outdata, const char* indata);
difftype_t CompareString(char* outstring, const char* instring);
difftype_t CompareVector(Vector& outValue, const Vector& inValue);
difftype_t CompareVector(Vector* outValue, const Vector* inValue, int count);
difftype_t CompareQuaternion(Quaternion& outValue, const Quaternion& inValue);
difftype_t CompareQuaternion(Quaternion* outValue, const Quaternion* inValue, int count);
difftype_t CompareEHandle(EHANDLE* outvalue, EHANDLE const* invalue, int count);
void DescribeShort(difftype_t dt, short* outvalue, const short* invalue, int count);
void DescribeInt(difftype_t dt, int* outvalue, const int* invalue, int count);
void DescribeBool(difftype_t dt, bool* outvalue, const bool* invalue, int count);
void DescribeFloat(difftype_t dt, float* outvalue, const float* invalue, int count);
void DescribeData(difftype_t dt, int size, char* outdata, const char* indata);
void DescribeString(difftype_t dt, char* outstring, const char* instring);
void DescribeVector(difftype_t dt, Vector& outValue, const Vector& inValue);
void DescribeVector(difftype_t dt, Vector* outValue, const Vector* inValue, int count);
void DescribeQuaternion(difftype_t dt, Quaternion& outValue, const Quaternion& inValue);
void DescribeQuaternion(difftype_t dt, Quaternion* outValue, const Quaternion* inValue, int count);
void DescribeEHandle(difftype_t dt, EHANDLE* outvalue, EHANDLE const* invalue, int count);
void WatchShort(difftype_t dt, short* outvalue, const short* invalue, int count);
void WatchInt(difftype_t dt, int* outvalue, const int* invalue, int count);
void WatchBool(difftype_t dt, bool* outvalue, const bool* invalue, int count);
void WatchFloat(difftype_t dt, float* outvalue, const float* invalue, int count);
void WatchData(difftype_t dt, int size, char* outdata, const char* indata);
void WatchString(difftype_t dt, char* outstring, const char* instring);
void WatchVector(difftype_t dt, Vector& outValue, const Vector& inValue);
void WatchVector(difftype_t dt, Vector* outValue, const Vector* inValue, int count);
void WatchQuaternion(difftype_t dt, Quaternion& outValue, const Quaternion& inValue);
void WatchQuaternion(difftype_t dt, Quaternion* outValue, const Quaternion* inValue, int count);
void WatchEHandle(difftype_t dt, EHANDLE* outvalue, EHANDLE const* invalue, int count);
void ReportFieldsDiffer(PRINTF_FORMAT_STRING const char* fmt, ...);
void DescribeFields(difftype_t dt, PRINTF_FORMAT_STRING const char* fmt, ...);
bool CanCheck(void);
void CopyFields(int chaincount, datamap_t* pMap, typedescription_t* pFields, int fieldCount);
private:
int m_nType;
void* m_pDest;
void const* m_pSrc;
int m_nDestOffsetIndex;
int m_nSrcOffsetIndex;
bool m_bErrorCheck;
bool m_bReportErrors;
bool m_bDescribeFields;
typedescription_t* m_pCurrentField;
char const* m_pCurrentClassName;
datamap_t* m_pCurrentMap;
bool m_bShouldReport;
bool m_bShouldDescribe;
int m_nErrorCount;
bool m_bPerformCopy;
FN_FIELD_COMPARE m_FieldCompareFunc;
typedescription_t* m_pWatchField;
char const* m_pOperation;
};
typedef void (*FN_FIELD_DESCRIPTION)(const char* classname, const char* fieldname, const char* fieldtype,
bool networked, const char* value);
class CPredictionDescribeData
{
public:
CPredictionDescribeData(void const* src, bool src_packed, FN_FIELD_DESCRIPTION func = 0);
void DescribeShort(const short* invalue, int count);
void DescribeInt(const int* invalue, int count);
void DescribeBool(const bool* invalue, int count);
void DescribeFloat(const float* invalue, int count);
void DescribeData(int size, const char* indata);
void DescribeString(const char* instring);
void DescribeVector(const Vector& inValue);
void DescribeVector(const Vector* inValue, int count);
void DescribeQuaternion(const Quaternion& inValue);
void DescribeQuaternion(const Quaternion* inValue, int count);
void DescribeEHandle(EHANDLE const* invalue, int count);
void DumpDescription(datamap_t* pMap);
private:
void DescribeFields_R(int chain_count, datamap_t* pMap, typedescription_t* pFields, int fieldCount);
void const* m_pSrc;
int m_nSrcOffsetIndex;
void Describe(PRINTF_FORMAT_STRING const char* fmt, ...);
typedescription_t* m_pCurrentField;
char const* m_pCurrentClassName;
datamap_t* m_pCurrentMap;
bool m_bShouldReport;
FN_FIELD_DESCRIPTION m_FieldDescFunc;
};
#if defined( CLIENT_DLL )
class CValueChangeTracker
{
public:
CValueChangeTracker();
void Reset();
void StartTrack(char const* pchContext);
void EndTrack();
bool IsActive() const;
void SetupTracking(C_BaseEntity* ent, char const* pchFieldName);
void ClearTracking();
void Spew();
C_BaseEntity* GetEntity();
private:
enum
{
eChangeTrackerBufSize = 128,
};
void GetValue(char* buf, size_t bufsize);
bool m_bActive : 1;
bool m_bTracking : 1;
EHANDLE m_hEntityToTrack;
CUtlVector< typedescription_t* > m_FieldStack;
CUtlString m_strFieldName;
CUtlString m_strContext;
char m_OrigValueBuf[eChangeTrackerBufSize];
CUtlVector< CUtlString > m_History;
};
extern CValueChangeTracker* g_pChangeTracker;
class CValueChangeTrackerScope
{
public:
CValueChangeTrackerScope(char const* pchContext)
{
m_bCallEndTrack = true;
g_pChangeTracker->StartTrack(pchContext);
}
CValueChangeTrackerScope(C_BaseEntity* pEntity, char const* pchContext)
{
m_bCallEndTrack = g_pChangeTracker->GetEntity() == pEntity;
if (m_bCallEndTrack)
{
g_pChangeTracker->StartTrack(pchContext);
}
}
~CValueChangeTrackerScope()
{
if (m_bCallEndTrack)
{
g_pChangeTracker->EndTrack();
}
}
private:
bool m_bCallEndTrack;
};
#if defined( _DEBUG )
#define PREDICTION_TRACKVALUECHANGESCOPE( context ) CValueChangeTrackerScope scope( context );
#define PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( entity, context ) CValueChangeTrackerScope scope( entity, context );
#define PREDICTION_STARTTRACKVALUE( context ) g_pChangeTracker->StartTrack( context );
#define PREDICTION_ENDTRACKVALUE() g_pChangeTracker->EndTrack();
#define PREDICTION_SPEWVALUECHANGES() g_pChangeTracker->Spew();
#else
#define PREDICTION_TRACKVALUECHANGESCOPE( context )
#define PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( entity, context )
#define PREDICTION_STARTTRACKVALUE( context )
#define PREDICTION_ENDTRACKVALUE()
#define PREDICTION_SPEWVALUECHANGES()
#endif
#endif
#endif

111
SpyCustom/sdk/ragdoll.h Normal file
View File

@ -0,0 +1,111 @@
#ifndef RAGDOLL_H
#define RAGDOLL_H
#ifdef _WIN32
#pragma once
#endif
#include "ragdoll_shared.h"
#define RAGDOLL_VISUALIZE 0
class C_BaseEntity;
class CStudioHdr;
struct mstudiobone_t;
class Vector;
class IPhysicsObject;
class CBoneAccessor;
abstract_class IRagdoll
{
public:
virtual ~IRagdoll() {}
virtual void RagdollBone(C_BaseEntity * ent, mstudiobone_t * pbones, int boneCount, bool* boneSimulated, CBoneAccessor & pBoneToWorld) = 0;
virtual const Vector& GetRagdollOrigin() = 0;
virtual void GetRagdollBounds(Vector& mins, Vector& maxs) = 0;
virtual int RagdollBoneCount() const = 0;
virtual IPhysicsObject* GetElement(int elementNum) = 0;
virtual void DrawWireframe(void) = 0;
virtual void VPhysicsUpdate(IPhysicsObject* pObject) = 0;
};
class CRagdoll : public IRagdoll
{
public:
CRagdoll();
~CRagdoll(void);
DECLARE_SIMPLE_DATADESC();
void Init(
C_BaseEntity* ent,
CStudioHdr* pstudiohdr,
const Vector& forceVector,
int forceBone,
const matrix3x4_t* pDeltaBones0,
const matrix3x4_t* pDeltaBones1,
const matrix3x4_t* pCurrentBonePosition,
float boneDt);
virtual void RagdollBone(C_BaseEntity* ent, mstudiobone_t* pbones, int boneCount, bool* boneSimulated, CBoneAccessor& pBoneToWorld);
virtual const Vector& GetRagdollOrigin();
virtual void GetRagdollBounds(Vector& theMins, Vector& theMaxs);
void BuildRagdollBounds(C_BaseEntity* ent);
virtual IPhysicsObject* GetElement(int elementNum);
virtual IPhysicsConstraintGroup* GetConstraintGroup() { return m_ragdoll.pGroup; }
virtual void DrawWireframe();
virtual void VPhysicsUpdate(IPhysicsObject* pPhysics);
virtual int RagdollBoneCount() const { return m_ragdoll.listCount; }
void SetInitialBonePosition(CStudioHdr* pstudiohdr, const CBoneAccessor& pDesiredBonePosition);
bool IsValid() { return m_ragdoll.listCount > 0; }
bool IsAsleep(void) const { return m_allAsleep; }
void ResetRagdollSleepAfterTime(void);
float GetLastVPhysicsUpdateTime() const { return m_lastUpdate; }
private:
void CheckSettleStationaryRagdoll();
void PhysForceRagdollToSleep();
ragdoll_t m_ragdoll;
Vector m_mins, m_maxs;
Vector m_origin;
float m_lastUpdate;
bool m_allAsleep;
Vector m_vecLastOrigin;
float m_flLastOriginChangeTime;
float m_flAwakeTime;
#if RAGDOLL_VISUALIZE
matrix3x4_t m_savedBone1[MAXSTUDIOBONES];
matrix3x4_t m_savedBone2[MAXSTUDIOBONES];
matrix3x4_t m_savedBone3[MAXSTUDIOBONES];
#endif
public:
ragdoll_t* GetRagdoll(void) { return &m_ragdoll; }
};
CRagdoll* CreateRagdoll(
C_BaseEntity* ent,
CStudioHdr* pstudiohdr,
const Vector& forceVector,
int forceBone,
const matrix3x4_t* pDeltaBones0,
const matrix3x4_t* pDeltaBones1,
const matrix3x4_t* pCurrentBonePosition,
float boneDt);
void NoteRagdollCreationTick(C_BaseEntity* pRagdoll);
bool WasRagdollCreatedOnCurrentTick(C_BaseEntity* pRagdoll);
#endif

View File

@ -0,0 +1,135 @@
#ifndef RAGDOLL_SHARED_H
#define RAGDOLL_SHARED_H
#ifdef _WIN32
#pragma once
#endif
class IPhysicsObject;
class IPhysicsConstraint;
class IPhysicsConstraintGroup;
class IPhysicsCollision;
class IPhysicsEnvironment;
class IPhysicsSurfaceProps;
struct matrix3x4_t;
struct vcollide_t;
struct studiohdr_t;
class CStudioHdr;
class CBoneAccessor;
#include "vector.h"
#include "bone_accessor.h"
#define RAGDOLL_MAX_ELEMENTS 24
#define RAGDOLL_INDEX_BITS 5
#define CORE_DISSOLVE_FADE_START 0.2f
#define CORE_DISSOLVE_MODEL_FADE_START 0.1f
#define CORE_DISSOLVE_MODEL_FADE_LENGTH 0.05f
#define CORE_DISSOLVE_FADEIN_LENGTH 0.1f
struct ragdollelement_t
{
Vector originParentSpace;
IPhysicsObject* pObject;
IPhysicsConstraint* pConstraint;
int parentIndex;
};
struct ragdollanimatedfriction_t
{
float flFrictionTimeIn;
float flFrictionTimeOut;
float flFrictionTimeHold;
int iMinAnimatedFriction;
int iMaxAnimatedFriction;
};
struct ragdoll_t
{
int listCount;
bool allowStretch;
bool unused;
IPhysicsConstraintGroup* pGroup;
ragdollelement_t list[RAGDOLL_MAX_ELEMENTS];
int boneIndex[RAGDOLL_MAX_ELEMENTS];
ragdollanimatedfriction_t animfriction;
};
struct ragdollparams_t
{
void* pGameData;
vcollide_t* pCollide;
CStudioHdr* pStudioHdr;
int modelIndex;
Vector forcePosition;
Vector forceVector;
int forceBoneIndex;
const matrix3x4_t* pCurrentBones;
float jointFrictionScale;
bool allowStretch;
bool fixedConstraints;
};
class CRagdollLRURetirement : public CAutoGameSystemPerFrame
{
public:
CRagdollLRURetirement(char const* name) : CAutoGameSystemPerFrame(name)
{
}
virtual void Update(float frametime);
virtual void FrameUpdatePostEntityThink(void);
void MoveToTopOfLRU(CBaseAnimating* pRagdoll, bool bImportant = false);
void SetMaxRagdollCount(int iMaxCount) { m_iMaxRagdolls = iMaxCount; }
virtual void LevelInitPreEntity(void);
int CountRagdolls(bool bOnlySimulatingRagdolls) { return bOnlySimulatingRagdolls ? m_iSimulatedRagdollCount : m_iRagdollCount; }
private:
typedef CHandle<CBaseAnimating> CRagdollHandle;
CUtlLinkedList< CRagdollHandle > m_LRU;
CUtlLinkedList< CRagdollHandle > m_LRUImportantRagdolls;
int m_iMaxRagdolls;
int m_iSimulatedRagdollCount;
int m_iRagdollCount;
};
extern CRagdollLRURetirement s_RagdollLRU;
class CRagdollLowViolenceManager
{
public:
CRagdollLowViolenceManager() { m_bLowViolence = false; }
void SetLowViolence(const char* pMapName);
bool IsLowViolence(void) { return m_bLowViolence; }
private:
bool m_bLowViolence;
};
extern CRagdollLowViolenceManager g_RagdollLVManager;
bool RagdollCreate(ragdoll_t& ragdoll, const ragdollparams_t& params, IPhysicsEnvironment* pPhysEnv);
void RagdollActivate(ragdoll_t& ragdoll, vcollide_t* pCollide, int modelIndex, bool bForceWake = true);
void RagdollSetupCollisions(ragdoll_t& ragdoll, vcollide_t* pCollide, int modelIndex);
void RagdollDestroy(ragdoll_t& ragdoll);
bool RagdollGetBoneMatrix(const ragdoll_t& ragdoll, CBoneAccessor& pBoneToWorld, int objectIndex);
int RagdollExtractBoneIndices(int* boneIndexOut, CStudioHdr* pStudioHdr, vcollide_t* pCollide);
void RagdollComputeExactBbox(const ragdoll_t& ragdoll, const Vector& origin, Vector& outMins, Vector& outMaxs);
bool RagdollIsAsleep(const ragdoll_t& ragdoll);
void RagdollSetupAnimatedFriction(IPhysicsEnvironment* pPhysEnv, ragdoll_t* ragdoll, int iModelIndex);
void RagdollApplyAnimationAsVelocity(ragdoll_t& ragdoll, const matrix3x4_t* pBoneToWorld);
void RagdollApplyAnimationAsVelocity(ragdoll_t& ragdoll, const matrix3x4_t* pPrevBones, const matrix3x4_t* pCurrentBones, float dt);
void RagdollSolveSeparation(ragdoll_t& ragdoll, CBaseEntity* pEntity);
#endif

77
SpyCustom/sdk/random.h Normal file
View File

@ -0,0 +1,77 @@
#ifndef VSTDLIB_RANDOM_H
#define VSTDLIB_RANDOM_H
#include "vstdlib.h"
#include "basetypes.h"
#include "threadtools.h"
#include "interface.h"
#define NTAB 32
#pragma warning(push)
#pragma warning( disable:4251 )
class IUniformRandomStream
{
public:
virtual void SetSeed(int iSeed) = 0;
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;
};
class VSTDLIB_CLASS CUniformRandomStream : public IUniformRandomStream
{
public:
CUniformRandomStream();
virtual void SetSeed(int iSeed);
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;
};
class VSTDLIB_CLASS CGaussianRandomStream
{
public:
CGaussianRandomStream(IUniformRandomStream* pUniformStream = NULL);
void AttachToStream(IUniformRandomStream* pUniformStream = NULL);
float RandomFloat(float flMean = 0.0f, float flStdDev = 1.0f);
private:
IUniformRandomStream* m_pUniformStream;
bool m_bHaveValue;
float m_flRandomValue;
CThreadFastMutex m_mutex;
};
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);
VSTDLIB_INTERFACE void InstallUniformRandomStream(IUniformRandomStream* pStream);
#pragma warning(pop)
#endif

View File

@ -0,0 +1,109 @@
#ifndef RANGECHECKEDVAR_H
#define RANGECHECKEDVAR_H
#ifdef _WIN32
#pragma once
#endif
#include "dbg.h"
#include "threadtools.h"
#include "vector.h"
#include <float.h>
class CDisableRangeChecks
{
public:
CDisableRangeChecks();
~CDisableRangeChecks();
};
template< class T >
inline void RangeCheck(const T& value, int minValue, int maxValue)
{
#ifdef _DEBUG
extern bool g_bDoRangeChecks;
if (ThreadInMainThread() && g_bDoRangeChecks)
{
Assert(_finite(value));
}
#endif
}
inline void RangeCheck(const Vector& value, int minValue, int maxValue)
{
#ifdef _DEBUG
RangeCheck(value.x, minValue, maxValue);
RangeCheck(value.y, minValue, maxValue);
RangeCheck(value.z, minValue, maxValue);
#endif
}
template< class T, int minValue, int maxValue, int startValue >
class CRangeCheckedVar
{
public:
inline CRangeCheckedVar()
{
m_Val = startValue;
}
inline CRangeCheckedVar(const T& value)
{
*this = value;
}
T GetRaw() const
{
return m_Val;
}
inline void Clamp()
{
if (m_Val < minValue)
m_Val = minValue;
else if (m_Val > maxValue)
m_Val = maxValue;
}
inline operator const T& () const
{
return m_Val;
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator=(const T& value)
{
RangeCheck(value, minValue, maxValue);
m_Val = value;
return *this;
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator+=(const T& value)
{
return (*this = m_Val + value);
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator-=(const T& value)
{
return (*this = m_Val - value);
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator*=(const T& value)
{
return (*this = m_Val * value);
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator/=(const T& value)
{
return (*this = m_Val / value);
}
private:
T m_Val;
};
#endif

45
SpyCustom/sdk/recvproxy.h Normal file
View File

@ -0,0 +1,45 @@
#ifndef RECVPROXY_H
#define RECVPROXY_H
class CRecvProxyData;
void RecvProxy_IntToEHandle(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_IntToMoveParent(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_IntToColor32(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_IntSubOne(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_ShortSubOne(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_InterpolationAmountChanged(const CRecvProxyData* pData, void* pStruct, void* pOut);
RecvProp RecvPropTime(
char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE);
#if !defined( NO_ENTITY_PREDICTION ) && defined( USE_PREDICTABLEID )
RecvProp RecvPropPredictableId(
char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE);
#endif
RecvProp RecvPropEHandle(
char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE,
RecvVarProxyFn proxyFn = RecvProxy_IntToEHandle);
RecvProp RecvPropBool(
char* pVarName,
int offset,
int sizeofVar);
RecvProp RecvPropIntWithMinusOneFlag(
char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE,
RecvVarProxyFn proxyFn = RecvProxy_IntSubOne);
#endif

320
SpyCustom/sdk/refcount.h Normal file
View File

@ -0,0 +1,320 @@
#ifndef REFCOUNT_H
#define REFCOUNT_H
#include "threadtools.h"
#if defined( _WIN32 )
#pragma once
#endif
class IRefCounted
{
public:
virtual int AddRef() = 0;
virtual int Release() = 0;
};
template <class REFCOUNTED_ITEM_PTR>
inline int SafeRelease(REFCOUNTED_ITEM_PTR& pRef)
{
REFCOUNTED_ITEM_PTR* ppRef = &pRef;
if (*ppRef)
{
int result = (*ppRef)->Release();
*ppRef = NULL;
return result;
}
return 0;
}
template <class T = IRefCounted>
class CAutoRef
{
public:
CAutoRef(T* pRef)
: m_pRef(pRef)
{
if (m_pRef)
m_pRef->AddRef();
}
~CAutoRef()
{
if (m_pRef)
m_pRef->Release();
}
private:
T* m_pRef;
};
#define RetAddRef( p ) ( (p)->AddRef(), (p) )
#define InlineAddRef( p ) ( (p)->AddRef(), (p) )
template <class T>
class CBaseAutoPtr
{
public:
CBaseAutoPtr() : m_pObject(0) {}
CBaseAutoPtr(T* pFrom) : m_pObject(pFrom) {}
operator const void* () const { return m_pObject; }
operator void* () { return m_pObject; }
operator const T* () const { return m_pObject; }
operator const T* () { return m_pObject; }
operator T* () { return m_pObject; }
int operator=(int i) { AssertMsg(i == 0, "Only NULL allowed on integer assign"); m_pObject = 0; return 0; }
T* operator=(T* p) { m_pObject = p; return p; }
bool operator !() const { return (!m_pObject); }
bool operator!=(int i) const { AssertMsg(i == 0, "Only NULL allowed on integer compare"); return (m_pObject != NULL); }
bool operator==(const void* p) const { return (m_pObject == p); }
bool operator!=(const void* p) const { return (m_pObject != p); }
bool operator==(T* p) const { return operator==((void*)p); }
bool operator!=(T* p) const { return operator!=((void*)p); }
bool operator==(const CBaseAutoPtr<T>& p) const { return operator==((const void*)p); }
bool operator!=(const CBaseAutoPtr<T>& p) const { return operator!=((const void*)p); }
T* operator->() { return m_pObject; }
T& operator *() { return *m_pObject; }
T** operator &() { return &m_pObject; }
const T* operator->() const { return m_pObject; }
const T& operator *() const { return *m_pObject; }
T* const* operator &() const { return &m_pObject; }
protected:
CBaseAutoPtr(const CBaseAutoPtr<T>& from) : m_pObject(from.m_pObject) {}
void operator=(const CBaseAutoPtr<T>& from) { m_pObject = from.m_pObject; }
T* m_pObject;
};
template <class T>
class CRefPtr : public CBaseAutoPtr<T>
{
typedef CBaseAutoPtr<T> BaseClass;
public:
CRefPtr() {}
CRefPtr(T* pInit) : BaseClass(pInit) {}
CRefPtr(const CRefPtr<T>& from) : BaseClass(from) {}
~CRefPtr() { if (BaseClass::m_pObject) BaseClass::m_pObject->Release(); }
void operator=(const CRefPtr<T>& from) { BaseClass::operator=(from); }
int operator=(int i) { return BaseClass::operator=(i); }
T* operator=(T* p) { return BaseClass::operator=(p); }
operator bool() const { return !BaseClass::operator!(); }
operator bool() { return !BaseClass::operator!(); }
void SafeRelease() { if (BaseClass::m_pObject) BaseClass::m_pObject->Release(); BaseClass::m_pObject = 0; }
void AssignAddRef(T* pFrom) { SafeRelease(); if (pFrom) pFrom->AddRef(); BaseClass::m_pObject = pFrom; }
void AddRefAssignTo(T*& pTo) { ::SafeRelease(pTo); if (BaseClass::m_pObject) BaseClass::m_pObject->AddRef(); pTo = BaseClass::m_pObject; }
};
class CRefMT
{
public:
static int Increment(int* p) { return ThreadInterlockedIncrement((long*)p); }
static int Decrement(int* p) { return ThreadInterlockedDecrement((long*)p); }
};
class CRefST
{
public:
static int Increment(int* p) { return ++(*p); }
static int Decrement(int* p) { return --(*p); }
};
template <const bool bSelfDelete, typename CRefThreading = CRefMT>
class NO_VTABLE CRefCountServiceBase
{
protected:
CRefCountServiceBase()
: m_iRefs(1)
{
}
virtual ~CRefCountServiceBase()
{
}
virtual bool OnFinalRelease()
{
return true;
}
int GetRefCount() const
{
return m_iRefs;
}
int DoAddRef()
{
return CRefThreading::Increment(&m_iRefs);
}
int DoRelease()
{
int result = CRefThreading::Decrement(&m_iRefs);
if (result)
return result;
if (OnFinalRelease() && bSelfDelete)
delete this;
return 0;
}
private:
int m_iRefs;
};
class CRefCountServiceNull
{
protected:
static int DoAddRef() { return 1; }
static int DoRelease() { return 1; }
};
template <typename CRefThreading = CRefMT>
class NO_VTABLE CRefCountServiceDestruct
{
protected:
CRefCountServiceDestruct()
: m_iRefs(1)
{
}
virtual ~CRefCountServiceDestruct()
{
}
int GetRefCount() const
{
return m_iRefs;
}
int DoAddRef()
{
return CRefThreading::Increment(&m_iRefs);
}
int DoRelease()
{
int result = CRefThreading::Decrement(&m_iRefs);
if (result)
return result;
this->~CRefCountServiceDestruct();
return 0;
}
private:
int m_iRefs;
};
typedef CRefCountServiceBase<true, CRefST> CRefCountServiceST;
typedef CRefCountServiceBase<false, CRefST> CRefCountServiceNoDeleteST;
typedef CRefCountServiceBase<true, CRefMT> CRefCountServiceMT;
typedef CRefCountServiceBase<false, CRefMT> CRefCountServiceNoDeleteMT;
typedef CRefCountServiceNoDeleteMT CRefCountServiceNoDelete;
typedef CRefCountServiceMT CRefCountService;
template < class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted : public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted1 : public BASE1,
public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted1() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class BASE2, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted2 : public BASE1, public BASE2,
public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted2() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class BASE2, class BASE3, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted3 : public BASE1, public BASE2, public BASE3,
public REFCOUNT_SERVICE
{
virtual ~CRefCounted3() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class BASE2, class BASE3, class BASE4, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted4 : public BASE1, public BASE2, public BASE3, public BASE4,
public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted4() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class BASE2, class BASE3, class BASE4, class BASE5, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted5 : public BASE1, public BASE2, public BASE3, public BASE4, public BASE5,
public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted5() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template <class BASE_REFCOUNTED, int FINAL_REFS, const char* pszName>
class CRefDebug : public BASE_REFCOUNTED
{
public:
#ifdef _DEBUG
CRefDebug()
{
AssertMsg(this->GetRefCount() == 1, "Expected initial ref count of 1");
DevMsg("%s:create 0x%x\n", (pszName) ? pszName : "", this);
}
virtual ~CRefDebug()
{
AssertDevMsg(this->GetRefCount() == FINAL_REFS, "Object still referenced on destroy?");
DevMsg("%s:destroy 0x%x\n", (pszName) ? pszName : "", this);
}
int AddRef()
{
DevMsg("%s:(0x%x)->AddRef() --> %d\n", (pszName) ? pszName : "", this, this->GetRefCount() + 1);
return BASE_REFCOUNTED::AddRef();
}
int Release()
{
DevMsg("%s:(0x%x)->Release() --> %d\n", (pszName) ? pszName : "", this, this->GetRefCount() - 1);
Assert(this->GetRefCount() > 0);
return BASE_REFCOUNTED::Release();
}
#endif
};
#endif

View File

@ -0,0 +1,96 @@
#ifndef SCENEENTITY_SHARED_H
#define SCENEENTITY_SHARED_H
#ifdef _WIN32
#pragma once
#endif
#if defined( CLIENT_DLL )
#define CBaseFlex C_BaseFlex
#define CSceneEntity C_SceneEntity
#endif
#include "iscenetokenprocessor.h"
class CBaseFlex;
class CChoreoEvent;
class CChoreoScene;
class CChoreoActor;
class CSceneEntity;
class CSceneEventInfo
{
public:
CSceneEventInfo()
:
m_pEvent(0),
m_pScene(0),
m_pActor(0),
m_bStarted(false),
m_iLayer(-1),
m_iPriority(0),
m_nSequence(0),
m_bIsGesture(false),
m_flWeight(0.0f),
m_hTarget(),
m_bIsMoving(false),
m_bHasArrived(false),
m_flInitialYaw(0.0f),
m_flTargetYaw(0.0f),
m_flFacingYaw(0.0f),
m_nType(0),
m_flNext(0.0f),
m_bClientSide(false)
{
}
CChoreoEvent* m_pEvent;
CChoreoScene* m_pScene;
CChoreoActor* m_pActor;
bool m_bStarted;
public:
int m_iLayer;
int m_iPriority;
int m_nSequence;
bool m_bIsGesture;
float m_flWeight;
EHANDLE m_hTarget;
bool m_bIsMoving;
bool m_bHasArrived;
float m_flInitialYaw;
float m_flTargetYaw;
float m_flFacingYaw;
int m_nType;
float m_flNext;
bool m_bClientSide;
void InitWeight(CBaseFlex* pActor);
float UpdateWeight(CBaseFlex* pActor);
};
class CSceneTokenProcessor : public ISceneTokenProcessor
{
public:
const char* CurrentToken(void);
bool GetToken(bool crossline);
bool TokenAvailable(void);
void Error(PRINTF_FORMAT_STRING const char* fmt, ...);
void SetBuffer(char* buffer);
private:
const char* m_pBuffer;
char m_szToken[1024];
};
extern CSceneTokenProcessor g_TokenProcessor;
void Scene_Printf(PRINTF_FORMAT_STRING const char* pFormat, ...);
extern ConVar scene_clientflex;
#endif

View File

@ -0,0 +1,79 @@
#ifndef SDK_HUD_CHAT_H
#define SDK_HUD_CHAT_H
#ifdef _WIN32
#pragma once
#endif
#include "hud_basechat.h"
#include "GetVFunc.hpp"
class CHudChatLine : public CBaseHudChatLine
{
DECLARE_CLASS_SIMPLE(CHudChatLine, CBaseHudChatLine);
public:
CHudChatLine(vgui::Panel* parent, const char* panelName) : CBaseHudChatLine(parent, panelName) {}
virtual void ApplySchemeSettings(vgui::IScheme* pScheme);
void PerformFadeout(void);
void MsgFunc_SayText(bf_read& msg);
private:
CHudChatLine(const CHudChatLine&);
};
class CHudChatInputLine : public CBaseHudChatInputLine
{
DECLARE_CLASS_SIMPLE(CHudChatInputLine, CBaseHudChatInputLine);
public:
CHudChatInputLine(CBaseHudChat* parent, char const* panelName) : CBaseHudChatInputLine(parent, panelName) {}
virtual void ApplySchemeSettings(vgui::IScheme* pScheme);
};
class CHudChat : public CBaseHudChat
{
DECLARE_CLASS_SIMPLE(CHudChat, CBaseHudChat);
public:
CHudChat(const char* pElementName);
virtual void CreateChatInputLine(void);
virtual void CreateChatLines(void);
virtual void Init(void);
virtual void Reset(void);
virtual void ApplySchemeSettings(vgui::IScheme* pScheme);
void MsgFunc_SayText(bf_read& msg);
void MsgFunc_TextMsg(bf_read& msg);
enum ChatFilters
{
CHAT_FILTER_NONE = 0,
CHAT_FILTER_JOINLEAVE = 0x000001,
CHAT_FILTER_NAMECHANGE = 0x000002,
CHAT_FILTER_PUBLICCHAT = 0x000004,
CHAT_FILTER_SERVERMSG = 0x000008,
CHAT_FILTER_TEAMCHANGE = 0x000010,
CHAT_FILTER_ACHIEVEMENT = 0x000020,
};
void ChatPrintf2(int iPlayerIndex, int iFilter, const char* fmt, ...)
{
char msg[1024];
va_list args;
va_start(args, fmt);
vsnprintf(msg, 1024, fmt, args);
getvfunc<void(__cdecl*)(void*, int, int, const char*, ...)>(this, 27)(this, iPlayerIndex, iFilter, fmt);
va_end(args);
}
int GetChatInputOffset(void);
};
#endif

5073
SpyCustom/sdk/seemath.h Normal file

File diff suppressed because it is too large Load Diff

52
SpyCustom/sdk/sendproxy.h Normal file
View File

@ -0,0 +1,52 @@
#ifndef SENDPROXY_H
#define SENDPROXY_H
#include "dt_send.h"
class DVariant;
void SendProxy_Color32ToInt(const SendProp* pProp, const void* pStruct, const void* pData, DVariant* pOut, int iElement, int objectID);
void SendProxy_EHandleToInt(const SendProp* pProp, const void* pStruct, const void* pVarData, DVariant* pOut, int iElement, int objectID);
void SendProxy_IntAddOne(const SendProp* pProp, const void* pStruct, const void* pVarData, DVariant* pOut, int iElement, int objectID);
void SendProxy_ShortAddOne(const SendProp* pProp, const void* pStruct, const void* pVarData, DVariant* pOut, int iElement, int objectID);
SendProp SendPropBool(
const char* pVarName,
int offset,
int sizeofVar);
SendProp SendPropEHandle(
const char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE,
int flags = 0,
SendVarProxyFn proxyFn = SendProxy_EHandleToInt);
SendProp SendPropTime(
const char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE);
#if !defined( NO_ENTITY_PREDICTION )
SendProp SendPropPredictableId(
const char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE);
#endif
SendProp SendPropIntWithMinusOneFlag(
const char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE,
int bits = -1,
SendVarProxyFn proxyFn = SendProxy_IntAddOne);
SendProp SendPropStringT(const char* pVarName, int offset, int sizeofVar);
void* SendProxy_OnlyToTeam(const SendProp* pProp, const void* pStruct, const void* pVarData, CSendProxyRecipients* pRecipients, int objectID);
#endif

View File

@ -0,0 +1,34 @@
#ifndef SEQUENCE_TRANSITIONER_H
#define SEQUENCE_TRANSITIONER_H
#ifdef _WIN32
#pragma once
#endif
class CSequenceTransitioner
{
public:
void CheckForSequenceChange(
CStudioHdr* hdr,
int nCurSequence,
bool bForceNewSequence,
bool bInterpolate
);
void UpdateCurrent(
CStudioHdr* hdr,
int nCurSequence,
float flCurCycle,
float flCurPlaybackRate,
float flCurTime
);
void RemoveAll(void) { m_animationQueue.RemoveAll(); };
public:
CUtlVector< CAnimationLayer > m_animationQueue;
};
#endif

47
SpyCustom/sdk/shake.h Normal file
View File

@ -0,0 +1,47 @@
#ifndef SHAKE_H
#define SHAKE_H
#ifdef _WIN32
#pragma once
#endif
struct ScreenShake_t
{
int command;
float amplitude;
float frequency;
float duration;
};
enum ShakeCommand_t
{
SHAKE_START = 0,
SHAKE_STOP,
SHAKE_AMPLITUDE,
SHAKE_FREQUENCY,
SHAKE_START_RUMBLEONLY,
SHAKE_START_NORUMBLE,
};
extern int gmsgShake;
extern int gmsgFade;
#define FFADE_IN 0x0001
#define FFADE_OUT 0x0002
#define FFADE_MODULATE 0x0004
#define FFADE_STAYOUT 0x0008
#define FFADE_PURGE 0x0010
#define SCREENFADE_FRACBITS 9
struct ScreenFade_t
{
unsigned short duration;
unsigned short holdTime;
short fadeFlags;
byte r, g, b, a;
};
#endif

View File

@ -0,0 +1,17 @@
#ifndef SHARED_CLASSNAMES_H
#define SHARED_CLASSNAMES_H
#ifdef _WIN32
#pragma once
#endif
#if defined( CLIENT_DLL )
#define CBaseEntity C_BaseEntity
#define CBaseCombatCharacter C_BaseCombatCharacter
#define CBaseAnimating C_BaseAnimating
#define CBasePlayer C_BasePlayer
#endif
#endif

838
SpyCustom/sdk/shareddefs.h Normal file
View File

@ -0,0 +1,838 @@
#ifndef SHADERAPI_SHAREDDEFS_H
#define SHADERAPI_SHAREDDEFS_H
#ifdef _WIN32
#pragma once
#endif
enum ShaderShadeMode_t
{
SHADER_FLAT = 0,
SHADER_SMOOTH
};
enum ShaderTexCoordComponent_t
{
SHADER_TEXCOORD_S = 0,
SHADER_TEXCOORD_T,
SHADER_TEXCOORD_U
};
enum ShaderTexFilterMode_t
{
SHADER_TEXFILTERMODE_NEAREST,
SHADER_TEXFILTERMODE_LINEAR,
SHADER_TEXFILTERMODE_NEAREST_MIPMAP_NEAREST,
SHADER_TEXFILTERMODE_LINEAR_MIPMAP_NEAREST,
SHADER_TEXFILTERMODE_NEAREST_MIPMAP_LINEAR,
SHADER_TEXFILTERMODE_LINEAR_MIPMAP_LINEAR,
SHADER_TEXFILTERMODE_ANISOTROPIC
};
enum ShaderTexWrapMode_t
{
SHADER_TEXWRAPMODE_CLAMP,
SHADER_TEXWRAPMODE_REPEAT,
SHADER_TEXWRAPMODE_BORDER
};
enum TextureStage_t
{
SHADER_TEXTURE_STAGE0 = 0,
SHADER_TEXTURE_STAGE1,
};
enum Sampler_t
{
SHADER_SAMPLER0 = 0,
SHADER_SAMPLER1,
SHADER_SAMPLER2,
SHADER_SAMPLER3,
SHADER_SAMPLER4,
SHADER_SAMPLER5,
SHADER_SAMPLER6,
SHADER_SAMPLER7,
SHADER_SAMPLER8,
SHADER_SAMPLER9,
SHADER_SAMPLER10,
SHADER_SAMPLER11,
SHADER_SAMPLER12,
SHADER_SAMPLER13,
SHADER_SAMPLER14,
SHADER_SAMPLER15,
};
enum VertexTextureSampler_t
{
SHADER_VERTEXTEXTURE_SAMPLER0 = 0,
SHADER_VERTEXTEXTURE_SAMPLER1,
SHADER_VERTEXTEXTURE_SAMPLER2,
SHADER_VERTEXTEXTURE_SAMPLER3,
};
#if defined( _X360 )
#define REVERSE_DEPTH_ON_X360
#endif
#if defined( REVERSE_DEPTH_ON_X360 )
#define ReverseDepthOnX360() true
#else
#define ReverseDepthOnX360() false
#endif
#include "bittools.h"
#define TICK_INTERVAL (gpGlobals->interval_per_tick)
#define TIME_TO_TICKS( dt ) ( (int)( 0.5f + (float)(dt) / TICK_INTERVAL ) )
#define TICKS_TO_TIME( t ) ( TICK_INTERVAL *( t ) )
#define ROUND_TO_TICKS( t ) ( TICK_INTERVAL * TIME_TO_TICKS( t ) )
#define TICK_NEVER_THINK (-1)
#define ANIMATION_CYCLE_BITS 15
#define ANIMATION_CYCLE_MINFRAC (1.0f / (1<<ANIMATION_CYCLE_BITS))
#define CONCEPT_WEIGHT 5.0f
class CViewVectors
{
public:
CViewVectors() {}
CViewVectors(
Vector vView,
Vector vHullMin,
Vector vHullMax,
Vector vDuckHullMin,
Vector vDuckHullMax,
Vector vDuckView,
Vector vObsHullMin,
Vector vObsHullMax,
Vector vDeadViewHeight)
{
m_vView = vView;
m_vHullMin = vHullMin;
m_vHullMax = vHullMax;
m_vDuckHullMin = vDuckHullMin;
m_vDuckHullMax = vDuckHullMax;
m_vDuckView = vDuckView;
m_vObsHullMin = vObsHullMin;
m_vObsHullMax = vObsHullMax;
m_vDeadViewHeight = vDeadViewHeight;
}
Vector m_vView;
Vector m_vHullMin;
Vector m_vHullMax;
Vector m_vDuckHullMin;
Vector m_vDuckHullMax;
Vector m_vDuckView;
Vector m_vObsHullMin;
Vector m_vObsHullMax;
Vector m_vDeadViewHeight;
};
#define VEC_VIEW g_pGameRules->GetViewVectors()->m_vView
#define VEC_HULL_MIN g_pGameRules->GetViewVectors()->m_vHullMin
#define VEC_HULL_MAX g_pGameRules->GetViewVectors()->m_vHullMax
#define VEC_DUCK_HULL_MIN g_pGameRules->GetViewVectors()->m_vDuckHullMin
#define VEC_DUCK_HULL_MAX g_pGameRules->GetViewVectors()->m_vDuckHullMax
#define VEC_DUCK_VIEW g_pGameRules->GetViewVectors()->m_vDuckView
#define VEC_OBS_HULL_MIN g_pGameRules->GetViewVectors()->m_vObsHullMin
#define VEC_OBS_HULL_MAX g_pGameRules->GetViewVectors()->m_vObsHullMax
#define VEC_DEAD_VIEWHEIGHT g_pGameRules->GetViewVectors()->m_vDeadViewHeight
#define WATERJUMP_HEIGHT 8
#define MAX_CLIMB_SPEED 200
#define TIME_TO_DUCK_MSECS 400
#define TIME_TO_UNDUCK_MSECS 200
inline float FractionDucked(int msecs)
{
return clamp((float)msecs / (float)TIME_TO_DUCK_MSECS, 0.0f, 1.0f);
}
inline float FractionUnDucked(int msecs)
{
return clamp((float)msecs / (float)TIME_TO_UNDUCK_MSECS, 0.0f, 1.0f);
}
#define MAX_WEAPON_SLOTS 6
#define MAX_WEAPON_POSITIONS 20
#define MAX_ITEM_TYPES 6
#define MAX_WEAPONS 48
#define MAX_ITEMS 5
#define WEAPON_NOCLIP -1
#define MAX_AMMO_TYPES 32
#define MAX_AMMO_SLOTS 32
#define HUD_PRINTNOTIFY 1
#define HUD_PRINTCONSOLE 2
#define HUD_PRINTTALK 3
#define HUD_PRINTCENTER 4
#define CLOSE_CAPTION_WARNIFMISSING ( 1<<0 )
#define CLOSE_CAPTION_FROMPLAYER ( 1<<1 )
#define CLOSE_CAPTION_GENDER_MALE ( 1<<2 )
#define CLOSE_CAPTION_GENDER_FEMALE ( 1<<3 )
#define HIDEHUD_WEAPONSELECTION ( 1<<0 )
#define HIDEHUD_FLASHLIGHT ( 1<<1 )
#define HIDEHUD_ALL ( 1<<2 )
#define HIDEHUD_HEALTH ( 1<<3 )
#define HIDEHUD_PLAYERDEAD ( 1<<4 )
#define HIDEHUD_NEEDSUIT ( 1<<5 )
#define HIDEHUD_MISCSTATUS ( 1<<6 )
#define HIDEHUD_CHAT ( 1<<7 )
#define HIDEHUD_CROSSHAIR ( 1<<8 )
#define HIDEHUD_VEHICLE_CROSSHAIR ( 1<<9 )
#define HIDEHUD_INVEHICLE ( 1<<10 )
#define HIDEHUD_BONUS_PROGRESS ( 1<<11 )
#define HIDEHUD_RADAR ( 1<<12 )
#define HIDEHUD_BITCOUNT 13
#define bits_SUIT_DEVICE_SPRINT 0x00000001
#define bits_SUIT_DEVICE_FLASHLIGHT 0x00000002
#define bits_SUIT_DEVICE_BREATHER 0x00000004
#define MAX_SUIT_DEVICES 3
#define MAX_PLAYERS 33
#define MAX_PLACE_NAME_LENGTH 18
#define TEAM_ANY -1
#define TEAM_INVALID -1
#define TEAM_UNASSIGNED 0
#define TEAM_SPECTATOR 1
#define LAST_SHARED_TEAM TEAM_SPECTATOR
#define FIRST_GAME_TEAM (LAST_SHARED_TEAM+1)
#define MAX_TEAMS 32
#define MAX_TEAM_NAME_LENGTH 32
#define WEAPON_NOT_CARRIED 0
#define WEAPON_IS_CARRIED_BY_PLAYER 1
#define WEAPON_IS_ACTIVE 2
#define SKILL_EASY 1
#define SKILL_MEDIUM 2
#define SKILL_HARD 3
#define ITEM_FLAG_SELECTONEMPTY (1<<0)
#define ITEM_FLAG_NOAUTORELOAD (1<<1)
#define ITEM_FLAG_NOAUTOSWITCHEMPTY (1<<2)
#define ITEM_FLAG_LIMITINWORLD (1<<3)
#define ITEM_FLAG_EXHAUSTIBLE (1<<4)
#define ITEM_FLAG_DOHITLOCATIONDMG (1<<5)
#define ITEM_FLAG_NOAMMOPICKUPS (1<<6)
#define ITEM_FLAG_NOITEMPICKUP (1<<7)
#define MAX_VIEWMODELS 2
#define MAX_BEAM_ENTS 10
#define TRACER_TYPE_DEFAULT 0x00000001
#define TRACER_TYPE_GUNSHIP 0x00000002
#define TRACER_TYPE_STRIDER 0x00000004
#define TRACER_TYPE_GAUSS 0x00000008
#define TRACER_TYPE_WATERBULLET 0x00000010
#define MUZZLEFLASH_TYPE_DEFAULT 0x00000001
#define MUZZLEFLASH_TYPE_GUNSHIP 0x00000002
#define MUZZLEFLASH_TYPE_STRIDER 0x00000004
enum
{
MUZZLEFLASH_AR2 = 0,
MUZZLEFLASH_SHOTGUN,
MUZZLEFLASH_SMG1,
MUZZLEFLASH_SMG2,
MUZZLEFLASH_PISTOL,
MUZZLEFLASH_COMBINE,
MUZZLEFLASH_357,
MUZZLEFLASH_RPG,
MUZZLEFLASH_COMBINE_TURRET,
MUZZLEFLASH_FIRSTPERSON = 0x100,
};
#define TRACER_FLAG_WHIZ 0x0001
#define TRACER_FLAG_USEATTACHMENT 0x0002
#define TRACER_DONT_USE_ATTACHMENT -1
enum
{
ENTITY_DISSOLVE_NORMAL = 0,
ENTITY_DISSOLVE_ELECTRICAL,
ENTITY_DISSOLVE_ELECTRICAL_LIGHT,
ENTITY_DISSOLVE_CORE,
ENTITY_DISSOLVE_BITS = 3
};
#define HITGROUP_GENERIC 0
#define HITGROUP_HEAD 1
#define HITGROUP_CHEST 2
#define HITGROUP_STOMACH 3
#define HITGROUP_LEFTARM 4
#define HITGROUP_RIGHTARM 5
#define HITGROUP_LEFTLEG 6
#define HITGROUP_RIGHTLEG 7
#define HITGROUP_GEAR 10
enum PLAYER_ANIM
{
PLAYER_IDLE,
PLAYER_WALK,
PLAYER_JUMP,
PLAYER_SUPERJUMP,
PLAYER_DIE,
PLAYER_ATTACK1,
PLAYER_IN_VEHICLE,
PLAYER_RELOAD,
PLAYER_START_AIMING,
PLAYER_LEAVE_AIMING,
};
#ifdef HL2_DLL
#define PLAYER_FATAL_FALL_SPEED 922.5f
#define PLAYER_MAX_SAFE_FALL_SPEED 526.5f
#define PLAYER_LAND_ON_FLOATING_OBJECT 173
#define PLAYER_MIN_BOUNCE_SPEED 173
#define PLAYER_FALL_PUNCH_THRESHOLD 303.0f
#else
#define PLAYER_FATAL_FALL_SPEED 1024
#define PLAYER_MAX_SAFE_FALL_SPEED 580
#define PLAYER_LAND_ON_FLOATING_OBJECT 200
#define PLAYER_MIN_BOUNCE_SPEED 200
#define PLAYER_FALL_PUNCH_THRESHOLD (float)350
#endif
#define DAMAGE_FOR_FALL_SPEED 100.0f / ( PLAYER_FATAL_FALL_SPEED - PLAYER_MAX_SAFE_FALL_SPEED )
#define AUTOAIM_2DEGREES 0.0348994967025
#define AUTOAIM_5DEGREES 0.08715574274766
#define AUTOAIM_8DEGREES 0.1391731009601
#define AUTOAIM_10DEGREES 0.1736481776669
#define AUTOAIM_20DEGREES 0.3490658503989
#define AUTOAIM_SCALE_DEFAULT 1.0f
#define AUTOAIM_SCALE_DIRECT_ONLY 0.0f
#define DMG_GENERIC 0
#define DMG_CRUSH (1 << 0)
#define DMG_BULLET (1 << 1)
#define DMG_SLASH (1 << 2)
#define DMG_BURN (1 << 3)
#define DMG_VEHICLE (1 << 4)
#define DMG_FALL (1 << 5)
#define DMG_BLAST (1 << 6)
#define DMG_CLUB (1 << 7)
#define DMG_SHOCK (1 << 8)
#define DMG_SONIC (1 << 9)
#define DMG_ENERGYBEAM (1 << 10)
#define DMG_PREVENT_PHYSICS_FORCE (1 << 11)
#define DMG_NEVERGIB (1 << 12)
#define DMG_ALWAYSGIB (1 << 13)
#define DMG_DROWN (1 << 14)
#define DMG_PARALYZE (1 << 15)
#define DMG_NERVEGAS (1 << 16)
#define DMG_POISON (1 << 17)
#define DMG_RADIATION (1 << 18)
#define DMG_DROWNRECOVER (1 << 19)
#define DMG_ACID (1 << 20)
#define DMG_SLOWBURN (1 << 21)
#define DMG_REMOVENORAGDOLL (1<<22)
#define DMG_PHYSGUN (1<<23)
#define DMG_PLASMA (1<<24)
#define DMG_AIRBOAT (1<<25)
#define DMG_DISSOLVE (1<<26)
#define DMG_BLAST_SURFACE (1<<27)
#define DMG_DIRECT (1<<28)
#define DMG_BUCKSHOT (1<<29)
#define DMG_LASTGENERICFLAG DMG_BUCKSHOT
#define DAMAGE_NO 0
#define DAMAGE_EVENTS_ONLY 1
#define DAMAGE_YES 2
#define DAMAGE_AIM 3
enum
{
OBS_MODE_NONE = 0,
OBS_MODE_DEATHCAM,
OBS_MODE_FREEZECAM,
OBS_MODE_FIXED,
OBS_MODE_IN_EYE,
OBS_MODE_CHASE,
OBS_MODE_ROAMING,
NUM_OBSERVER_MODES,
};
#define LAST_PLAYER_OBSERVERMODE OBS_MODE_ROAMING
enum {
OBS_ALLOW_ALL = 0,
OBS_ALLOW_TEAM,
OBS_ALLOW_NONE,
OBS_ALLOW_NUM_MODES,
};
enum
{
TYPE_TEXT = 0,
TYPE_INDEX,
TYPE_URL,
TYPE_FILE,
};
enum
{
VGUI_SCREEN_ACTIVE = 0x1,
VGUI_SCREEN_VISIBLE_TO_TEAMMATES = 0x2,
VGUI_SCREEN_ATTACHED_TO_VIEWMODEL = 0x4,
VGUI_SCREEN_TRANSPARENT = 0x8,
VGUI_SCREEN_ONLY_USABLE_BY_OWNER = 0x10,
VGUI_SCREEN_MAX_BITS = 5
};
typedef enum
{
USE_OFF = 0,
USE_ON = 1,
USE_SET = 2,
USE_TOGGLE = 3
} USE_TYPE;
#define COLOR_RED Color(255, 64, 64, 255)
#define COLOR_BLUE Color(153, 204, 255, 255)
#define COLOR_YELLOW Color(255, 178, 0, 255)
#define COLOR_GREEN Color(153, 255, 153, 255)
#define COLOR_GREY Color(204, 204, 204, 255)
enum
{
DONT_BLEED = -1,
BLOOD_COLOR_RED = 0,
BLOOD_COLOR_YELLOW,
BLOOD_COLOR_GREEN,
BLOOD_COLOR_MECH,
#if defined( HL2_EPISODIC )
BLOOD_COLOR_ANTLION,
BLOOD_COLOR_ZOMBIE,
BLOOD_COLOR_ANTLION_WORKER,
BLOOD_COLOR_BLOB,
BLOOD_COLOR_BLOB_FROZEN,
#endif
#if defined( INFESTED_DLL )
BLOOD_COLOR_BLOB,
BLOOD_COLOR_BLOB_FROZEN,
#endif
BLOOD_COLOR_BRIGHTGREEN,
};
enum PassengerRole_t
{
VEHICLE_ROLE_NONE = -1,
VEHICLE_ROLE_DRIVER = 0,
LAST_SHARED_VEHICLE_ROLE,
};
enum
{
FX_WATER_IN_SLIME = 0x1,
};
#define MAX_CONTEXT_LENGTH 32
#define NO_THINK_CONTEXT -1
enum
{
EFL_KILLME = (1 << 0),
EFL_DORMANT = (1 << 1),
EFL_NOCLIP_ACTIVE = (1 << 2),
EFL_SETTING_UP_BONES = (1 << 3),
EFL_KEEP_ON_RECREATE_ENTITIES = (1 << 4),
EFL_DIRTY_SHADOWUPDATE = (1 << 5),
EFL_NOTIFY = (1 << 6),
EFL_FORCE_CHECK_TRANSMIT = (1 << 7),
EFL_BOT_FROZEN = (1 << 8),
EFL_SERVER_ONLY = (1 << 9),
EFL_NO_AUTO_EDICT_ATTACH = (1 << 10),
EFL_DIRTY_ABSTRANSFORM = (1 << 11),
EFL_DIRTY_ABSVELOCITY = (1 << 12),
EFL_DIRTY_ABSANGVELOCITY = (1 << 13),
EFL_DIRTY_SURROUNDING_COLLISION_BOUNDS = (1 << 14),
EFL_DIRTY_SPATIAL_PARTITION = (1 << 15),
EFL_HAS_PLAYER_CHILD = (1 << 16),
EFL_IN_SKYBOX = (1 << 17),
EFL_USE_PARTITION_WHEN_NOT_SOLID = (1 << 18),
EFL_TOUCHING_FLUID = (1 << 19),
EFL_IS_BEING_LIFTED_BY_BARNACLE = (1 << 20),
EFL_NO_ROTORWASH_PUSH = (1 << 21),
EFL_NO_THINK_FUNCTION = (1 << 22),
EFL_NO_GAME_PHYSICS_SIMULATION = (1 << 23),
EFL_CHECK_UNTOUCH = (1 << 24),
EFL_DONTBLOCKLOS = (1 << 25),
EFL_DONTWALKON = (1 << 26),
EFL_NO_DISSOLVE = (1 << 27),
EFL_NO_MEGAPHYSCANNON_RAGDOLL = (1 << 28),
EFL_NO_WATER_VELOCITY_CHANGE = (1 << 29),
EFL_NO_PHYSCANNON_INTERACTION = (1 << 30),
EFL_NO_DAMAGE_FORCES = (1 << 31),
};
const int FX_BLOODSPRAY_DROPS = 0x01;
const int FX_BLOODSPRAY_GORE = 0x02;
const int FX_BLOODSPRAY_CLOUD = 0x04;
const int FX_BLOODSPRAY_ALL = 0xFF;
#define MAX_SCREEN_OVERLAYS 10
enum
{
GROUNDLINK = 0,
TOUCHLINK,
STEPSIMULATION,
MODELSCALE,
POSITIONWATCHER,
PHYSICSPUSHLIST,
VPHYSICSUPDATEAI,
VPHYSICSWATCHER,
NUM_DATAOBJECT_TYPES,
};
class CBaseEntity;
class CBaseEntity;
enum FireBulletsFlags_t
{
FIRE_BULLETS_FIRST_SHOT_ACCURATE = 0x1,
FIRE_BULLETS_DONT_HIT_UNDERWATER = 0x2,
FIRE_BULLETS_ALLOW_WATER_SURFACE_IMPACTS = 0x4,
FIRE_BULLETS_TEMPORARY_DANGER_SOUND = 0x8,
FIRE_BULLETS_NO_PIERCING_SPARK = 0x16,
FIRE_BULLETS_HULL = 0x32,
FIRE_BULLETS_ANGULAR_SPREAD = 0x64,
};
struct FireBulletsInfo_t
{
FireBulletsInfo_t()
{
m_iShots = 1;
m_vecSpread.Init(0, 0, 0);
m_flDistance = 8192;
m_iTracerFreq = 4;
m_flDamage = 0.0f;
m_flPlayerDamage = 0.0f;
m_pAttacker = NULL;
m_nFlags = 0;
m_pAdditionalIgnoreEnt = NULL;
m_flDamageForceScale = 1.0f;
#ifdef _DEBUG
m_iAmmoType = -1;
m_vecSrc.Init(VEC_T_NAN, VEC_T_NAN, VEC_T_NAN);
m_vecDirShooting.Init(VEC_T_NAN, VEC_T_NAN, VEC_T_NAN);
#endif
m_bPrimaryAttack = true;
}
FireBulletsInfo_t(int nShots, const Vector& vecSrc, const Vector& vecDir, const Vector& vecSpread, float flDistance, int nAmmoType, bool bPrimaryAttack = true)
{
m_iShots = nShots;
m_vecSrc = vecSrc;
m_vecDirShooting = vecDir;
m_vecSpread = vecSpread;
m_flDistance = flDistance;
m_iAmmoType = nAmmoType;
m_iTracerFreq = 4;
m_flDamage = 0;
m_flPlayerDamage = 0;
m_pAttacker = NULL;
m_nFlags = 0;
m_pAdditionalIgnoreEnt = NULL;
m_flDamageForceScale = 1.0f;
m_bPrimaryAttack = bPrimaryAttack;
}
int m_iShots;
Vector m_vecSrc;
Vector m_vecDirShooting;
Vector m_vecSpread;
float m_flDistance;
int m_iAmmoType;
int m_iTracerFreq;
float m_flDamage;
float m_flPlayerDamage;
int m_nFlags;
float m_flDamageForceScale;
CBaseEntity* m_pAttacker;
CBaseEntity* m_pAdditionalIgnoreEnt;
bool m_bPrimaryAttack;
};
struct StepSimulationStep
{
int nTickCount;
Vector vecOrigin;
Quaternion qRotation;
};
struct StepSimulationData
{
bool m_bOriginActive;
bool m_bAnglesActive;
StepSimulationStep m_Previous2;
StepSimulationStep m_Previous;
StepSimulationStep m_Discontinuity;
StepSimulationStep m_Next;
QAngle m_angNextRotation;
int m_nLastProcessTickCount;
Vector m_vecNetworkOrigin;
int m_networkCell[3];
QAngle m_angNetworkAngles;
};
struct ModelScale
{
float m_flModelScaleStart;
float m_flModelScaleGoal;
float m_flModelScaleFinishTime;
float m_flModelScaleStartTime;
};
#include "soundflags.h"
struct CSoundParameters;
typedef short HSOUNDSCRIPTHANDLE;
struct EmitSound_t
{
EmitSound_t() :
m_nChannel(0),
m_pSoundName(0),
m_flVolume(VOL_NORM),
m_SoundLevel(SNDLVL_NONE),
m_nFlags(0),
m_nPitch(PITCH_NORM),
m_pOrigin(0),
m_flSoundTime(0.0f),
m_pflSoundDuration(0),
m_bEmitCloseCaption(true),
m_bWarnOnMissingCloseCaption(false),
m_bWarnOnDirectWaveReference(false),
m_nSpeakerEntity(-1),
m_UtlVecSoundOrigin(),
m_hSoundScriptHandle(-1)
{
}
EmitSound_t(const CSoundParameters& src);
int m_nChannel;
char const* m_pSoundName;
float m_flVolume;
soundlevel_t m_SoundLevel;
int m_nFlags;
int m_nPitch;
const Vector* m_pOrigin;
float m_flSoundTime;
float* m_pflSoundDuration;
bool m_bEmitCloseCaption;
bool m_bWarnOnMissingCloseCaption;
bool m_bWarnOnDirectWaveReference;
int m_nSpeakerEntity;
mutable CUtlVector< Vector > m_UtlVecSoundOrigin;
mutable HSOUNDSCRIPTHANDLE m_hSoundScriptHandle;
};
#define MAX_ACTORS_IN_SCENE 16
#define MAX_CONTROL_POINTS 8
#define MAX_CONTROL_POINT_GROUPS 8
#define MAX_PREVIOUS_POINTS 3
#define MAX_CONTROL_POINT_TEAMS 8
#define MAX_CAPLAYOUT_LENGTH 32
#define MAX_ROUND_NAME 32
#define MAX_ROUND_IMAGE_NAME 64
#define TEAMPLAY_ROUND_WIN_SCORE 1
enum
{
CP_WARN_NORMAL = 0,
CP_WARN_FINALCAP,
CP_WARN_NO_ANNOUNCEMENTS
};
#define PREDICTION_ERROR_CHECK_LEVEL 0
#define PREDICTION_ERROR_CHECK_STACKS_FOR_MISSING 0
enum
{
RT_STATE_SETUP,
RT_STATE_NORMAL,
};
enum
{
SIMULATION_TIME_WINDOW_BITS = 8,
};
#define CELL_COUNT( bits ) ( (MAX_COORD_INTEGER*2) / (1 << (bits)) )
#define CELL_COUNT_BITS( bits ) MINIMUM_BITS_NEEDED( CELL_COUNT( bits ) )
#define CELL_BASEENTITY_ORIGIN_CELL_BITS 5
#ifdef GAME_HAS_NO_USE_KEY
#define COMMENTARY_BUTTONS (IN_ATTACK | IN_ATTACK2 | IN_USE)
#else
#define COMMENTARY_BUTTONS (IN_USE)
#endif
bool IsHeadTrackingEnabled();
#define MAX_SPLITSCREEN_PLAYERS 1
inline bool IsSplitScreenSupported()
{
return (MAX_SPLITSCREEN_PLAYERS > 1) ? true : false;
}
enum InvalidatePhysicsBits_t
{
POSITION_CHANGED = 0x1,
ANGLES_CHANGED = 0x2,
VELOCITY_CHANGED = 0x4,
ANIMATION_CHANGED = 0x8,
BOUNDS_CHANGED = 0x10,
SEQUENCE_CHANGED = 0x20,
};
enum Class_T
{
CLASS_NONE = 0,
CLASS_PLAYER,
CLASS_PLAYER_ALLY,
CLASS_PLAYER_ALLY_VITAL,
CLASS_ANTLION,
CLASS_BARNACLE,
CLASS_BLOB,
CLASS_BULLSEYE,
CLASS_CITIZEN_PASSIVE,
CLASS_CITIZEN_REBEL,
CLASS_COMBINE,
CLASS_COMBINE_GUNSHIP,
CLASS_CONSCRIPT,
CLASS_HEADCRAB,
CLASS_MANHACK,
CLASS_METROPOLICE,
CLASS_MILITARY,
CLASS_SCANNER,
CLASS_STALKER,
CLASS_VORTIGAUNT,
CLASS_ZOMBIE,
CLASS_PROTOSNIPER,
CLASS_MISSILE,
CLASS_FLARE,
CLASS_EARTH_FAUNA,
CLASS_HACKED_ROLLERMINE,
CLASS_COMBINE_HUNTER,
LAST_SHARED_ENTITY_CLASS,
};
#define FACTION_NONE 0
#define LAST_SHARED_FACTION (FACTION_NONE)
#define NUM_SHARED_FACTIONS (FACTION_NONE + 1)
#endif

View File

@ -0,0 +1,13 @@
#if !defined ( SHATTERSURFACETYPES_H )
#define SHATTERSURFACETYPES_H
#ifdef _WIN32
#pragma once
#endif
enum ShatterSurface_t
{
SHATTERSURFACE_GLASS = 0,
SHATTERSURFACE_TILE = 1,
};
#endif

227
SpyCustom/sdk/smartptr.h Normal file
View File

@ -0,0 +1,227 @@
#ifndef SMARTPTR_H
#define SMARTPTR_H
#ifdef _WIN32
#pragma once
#endif
class CRefCountAccessor
{
public:
template< class T >
static void AddRef(T* pObj)
{
pObj->AddRef();
}
template< class T >
static void Release(T* pObj)
{
pObj->Release();
}
};
class CRefCountAccessorLongName
{
public:
template< class T >
static void AddRef(T* pObj)
{
pObj->AddReference();
}
template< class T >
static void Release(T* pObj)
{
pObj->ReleaseReference();
}
};
template < typename T >
class CPlainAutoPtr
{
public:
explicit CPlainAutoPtr(T* p = NULL) : m_p(p) {}
~CPlainAutoPtr(void) { Delete(); }
public:
void Delete(void) { delete Detach(); }
private:
CPlainAutoPtr(CPlainAutoPtr const& x);
CPlainAutoPtr& operator = (CPlainAutoPtr const& x);
public:
void Attach(T* p) { m_p = p; }
T* Detach(void) { T* p(m_p); m_p = NULL; return p; }
public:
bool IsValid(void) const { return m_p != NULL; }
T* Get(void) const { return m_p; }
T* operator -> (void) const { return Get(); }
T& operator * (void) const { return *Get(); }
private:
T* m_p;
};
template < typename T >
class CArrayAutoPtr : public CPlainAutoPtr < T >
{
public:
explicit CArrayAutoPtr(T* p = NULL) { this->Attach(p); }
~CArrayAutoPtr(void) { this->Delete(); }
public:
void Delete(void) { delete[] CPlainAutoPtr < T >::Detach(); }
public:
T& operator [] (int k) const { return CPlainAutoPtr < T >::Get()[k]; }
};
template<class T, class RefCountAccessor = CRefCountAccessor>
class CSmartPtr
{
public:
CSmartPtr();
CSmartPtr(T* pObj);
CSmartPtr(const CSmartPtr<T, RefCountAccessor>& other);
~CSmartPtr();
T* operator=(T* pObj);
void operator=(const CSmartPtr<T, RefCountAccessor>& other);
const T* operator->() const;
T* operator->();
bool operator!() const;
bool operator==(const T* pOther) const;
bool IsValid() const;
T* GetObject() const;
void MarkDeleted();
private:
T* m_pObj;
};
template< class T, class RefCountAccessor >
inline CSmartPtr<T, RefCountAccessor>::CSmartPtr()
{
m_pObj = NULL;
}
template< class T, class RefCountAccessor >
inline CSmartPtr<T, RefCountAccessor>::CSmartPtr(T* pObj)
{
m_pObj = NULL;
*this = pObj;
}
template< class T, class RefCountAccessor >
inline CSmartPtr<T, RefCountAccessor>::CSmartPtr(const CSmartPtr<T, RefCountAccessor>& other)
{
m_pObj = NULL;
*this = other;
}
template< class T, class RefCountAccessor >
inline CSmartPtr<T, RefCountAccessor>::~CSmartPtr()
{
if (m_pObj)
{
RefCountAccessor::Release(m_pObj);
}
}
template< class T, class RefCountAccessor >
inline T* CSmartPtr<T, RefCountAccessor>::operator=(T* pObj)
{
if (pObj == m_pObj)
return pObj;
if (pObj)
{
RefCountAccessor::AddRef(pObj);
}
if (m_pObj)
{
RefCountAccessor::Release(m_pObj);
}
m_pObj = pObj;
return pObj;
}
template< class T, class RefCountAccessor >
inline void CSmartPtr<T, RefCountAccessor>::MarkDeleted()
{
m_pObj = NULL;
}
template< class T, class RefCountAccessor >
inline void CSmartPtr<T, RefCountAccessor>::operator=(const CSmartPtr<T, RefCountAccessor>& other)
{
*this = other.m_pObj;
}
template< class T, class RefCountAccessor >
inline const T* CSmartPtr<T, RefCountAccessor>::operator->() const
{
return m_pObj;
}
template< class T, class RefCountAccessor >
inline T* CSmartPtr<T, RefCountAccessor>::operator->()
{
return m_pObj;
}
template< class T, class RefCountAccessor >
inline bool CSmartPtr<T, RefCountAccessor>::operator!() const
{
return !m_pObj;
}
template< class T, class RefCountAccessor >
inline bool CSmartPtr<T, RefCountAccessor>::operator==(const T* pOther) const
{
return m_pObj == pOther;
}
template< class T, class RefCountAccessor >
inline bool CSmartPtr<T, RefCountAccessor>::IsValid() const
{
return m_pObj != NULL;
}
template< class T, class RefCountAccessor >
inline T* CSmartPtr<T, RefCountAccessor>::GetObject() const
{
return m_pObj;
}
template < typename T >
class CAutoPushPop
{
public:
explicit CAutoPushPop(T& var) : m_rVar(var), m_valPop(var) {}
CAutoPushPop(T& var, T const& valPush) : m_rVar(var), m_valPop(var) { m_rVar = valPush; }
CAutoPushPop(T& var, T const& valPush, T const& valPop) : m_rVar(var), m_valPop(var) { m_rVar = valPush; }
~CAutoPushPop() { m_rVar = m_valPop; }
private:
CAutoPushPop(CAutoPushPop const& x);
CAutoPushPop& operator = (CAutoPushPop const& x);
public:
T& Get() { return m_rVar; }
private:
T& m_rVar;
T m_valPop;
};
#endif

161
SpyCustom/sdk/soundflags.h Normal file
View File

@ -0,0 +1,161 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef SOUNDFLAGS_H
#define SOUNDFLAGS_H
#if defined( _WIN32 )
#pragma once
#endif
//-----------------------------------------------------------------------------
// channels
//-----------------------------------------------------------------------------
enum
{
CHAN_REPLACE = -1,
CHAN_AUTO = 0,
CHAN_WEAPON = 1,
CHAN_VOICE = 2,
CHAN_ITEM = 3,
CHAN_BODY = 4,
CHAN_STREAM = 5, // allocate stream channel from the static or dynamic area
CHAN_STATIC = 6, // allocate channel from the static area
CHAN_VOICE2 = 7,
CHAN_VOICE_BASE = 8, // allocate channel for network voice data
CHAN_USER_BASE = (CHAN_VOICE_BASE + 128) // Anything >= this number is allocated to game code.
};
//-----------------------------------------------------------------------------
// common volume values
//-----------------------------------------------------------------------------
#define VOL_NORM 1.0f
//-----------------------------------------------------------------------------
// common attenuation values
//-----------------------------------------------------------------------------
#define ATTN_NONE 0.0f
#define ATTN_NORM 0.8f
#define ATTN_IDLE 2.0f
#define ATTN_STATIC 1.25f
#define ATTN_RICOCHET 1.5f
// HL2 world is 8x bigger now! We want to hear gunfire from farther.
// Don't change this without consulting Kelly or Wedge (sjb).
#define ATTN_GUNFIRE 0.27f
enum soundlevel_t
{
SNDLVL_NONE = 0,
SNDLVL_20dB = 20, // rustling leaves
SNDLVL_25dB = 25, // whispering
SNDLVL_30dB = 30, // library
SNDLVL_35dB = 35,
SNDLVL_40dB = 40,
SNDLVL_45dB = 45, // refrigerator
SNDLVL_50dB = 50, // 3.9 // average home
SNDLVL_55dB = 55, // 3.0
SNDLVL_IDLE = 60, // 2.0
SNDLVL_60dB = 60, // 2.0 // normal conversation, clothes dryer
SNDLVL_65dB = 65, // 1.5 // washing machine, dishwasher
SNDLVL_STATIC = 66, // 1.25
SNDLVL_70dB = 70, // 1.0 // car, vacuum cleaner, mixer, electric sewing machine
SNDLVL_NORM = 75,
SNDLVL_75dB = 75, // 0.8 // busy traffic
SNDLVL_80dB = 80, // 0.7 // mini-bike, alarm clock, noisy restaurant, office tabulator, outboard motor, passing snowmobile
SNDLVL_TALKING = 80, // 0.7
SNDLVL_85dB = 85, // 0.6 // average factory, electric shaver
SNDLVL_90dB = 90, // 0.5 // screaming child, passing motorcycle, convertible ride on frw
SNDLVL_95dB = 95,
SNDLVL_100dB = 100, // 0.4 // subway train, diesel truck, woodworking shop, pneumatic drill, boiler shop, jackhammer
SNDLVL_105dB = 105, // helicopter, power mower
SNDLVL_110dB = 110, // snowmobile drvrs seat, inboard motorboat, sandblasting
SNDLVL_120dB = 120, // auto horn, propeller aircraft
SNDLVL_130dB = 130, // air raid siren
SNDLVL_GUNFIRE = 140, // 0.27 // THRESHOLD OF PAIN, gunshot, jet engine
SNDLVL_140dB = 140, // 0.2
SNDLVL_150dB = 150, // 0.2
SNDLVL_180dB = 180, // rocket launching
// NOTE: Valid soundlevel_t values are 0-255.
// 256-511 are reserved for sounds using goldsrc compatibility attenuation.
};
#define MAX_SNDLVL_BITS 9 // Used to encode 0-255 for regular soundlevel_t's and 256-511 for goldsrc-compatible ones.
#define MIN_SNDLVL_VALUE 0
#define MAX_SNDLVL_VALUE ((1<<MAX_SNDLVL_BITS)-1)
#define ATTN_TO_SNDLVL( a ) (soundlevel_t)(int)((a) ? (50 + 20 / ((float)a)) : 0 )
#define SNDLVL_TO_ATTN( a ) ((a > 50) ? (20.0f / (float)(a - 50)) : 4.0 )
// This is a limit due to network encoding.
// It encodes attenuation * 64 in 8 bits, so the maximum is (255 / 64)
#define MAX_ATTENUATION 3.98f
//-----------------------------------------------------------------------------
// Flags to be or-ed together for the iFlags field
//-----------------------------------------------------------------------------
enum SoundFlags_t
{
SND_NOFLAGS = 0, // to keep the compiler happy
SND_CHANGE_VOL = (1 << 0), // change sound vol
SND_CHANGE_PITCH = (1 << 1), // change sound pitch
SND_STOP = (1 << 2), // stop the sound
SND_SPAWNING = (1 << 3), // we're spawning, used in some cases for ambients
// not sent over net, only a param between dll and server.
SND_DELAY = (1 << 4), // sound has an initial delay
SND_STOP_LOOPING = (1 << 5), // stop all looping sounds on the entity.
SND_SPEAKER = (1 << 6), // being played again by a microphone through a speaker
SND_SHOULDPAUSE = (1 << 7), // this sound should be paused if the game is paused
SND_IGNORE_PHONEMES = (1 << 8),
SND_IGNORE_NAME = (1 << 9), // used to change all sounds emitted by an entity, regardless of scriptname
SND_DO_NOT_OVERWRITE_EXISTING_ON_CHANNEL = (1 << 10),
};
#define SND_FLAG_BITS_ENCODE 11
#define MAX_SOUND_INDEX_BITS 14
#define MAX_SOUNDS (1<<MAX_SOUND_INDEX_BITS)
#if !defined( IN_XBOX_CODELINE )
// +/-4096 msec
#define MAX_SOUND_DELAY_MSEC_ENCODE_BITS (13)
#else
// +/-65536 msec, 64 seconds
#define MAX_SOUND_DELAY_MSEC_ENCODE_BITS (17)
#endif
// Subtract one to leave room for the sign bit
#define MAX_SOUND_DELAY_MSEC (1<<(MAX_SOUND_DELAY_MSEC_ENCODE_BITS-1)) // 4096 msec or about 4 seconds
//-----------------------------------------------------------------------------
// common pitch values
//-----------------------------------------------------------------------------
#define PITCH_NORM 100 // non-pitch shifted
#define PITCH_LOW 95 // other values are possible - 0-255, where 255 is very high
#define PITCH_HIGH 120
#define DEFAULT_SOUND_PACKET_VOLUME 1.0f
#define DEFAULT_SOUND_PACKET_PITCH 100
#define DEFAULT_SOUND_PACKET_DELAY 0.0f
#endif // SOUNDFLAGS_H

5027
SpyCustom/sdk/ssemath.h Normal file

File diff suppressed because it is too large Load Diff

79
SpyCustom/sdk/steam.h Normal file
View File

@ -0,0 +1,79 @@
#pragma once
#include <iostream>
template<typename FuncType>
__forceinline static FuncType CallVFunction(void* ppClass, int index)
{
int* pVTable = *(int**)ppClass;
int dwAddress = pVTable[index];
return (FuncType)(dwAddress);
}
enum EGCResult
{
k_EGCResultOK = 0,
k_EGCResultNoMessage = 1,
k_EGCResultBufferTooSmall = 2,
k_EGCResultNotLoggedOn = 3,
k_EGCResultInvalidMessage = 4,
};
class ISteamGameCoordinator
{
public:
virtual EGCResult GCSendMessage(int unMsgType, const void* pubData, int cubData) = 0;
virtual bool IsMessageAvailable(int* pcubMsgSize) = 0;
virtual EGCResult GCRetrieveMessage(int* punMsgType, void* pubDest, int cubDest, int* pcubMsgSize) = 0;
};
class CSteamID
{
public:
CSteamID()
{
m_steamid.m_comp.m_unAccountID = 0;
m_steamid.m_comp.m_EAccountType = 0;
m_steamid.m_comp.m_EUniverse = 0;
m_steamid.m_comp.m_unAccountInstance = 0;
}
uint32_t GetAccountID() const { return m_steamid.m_comp.m_unAccountID; }
private:
union SteamID_t
{
struct SteamIDComponent_t
{
uint32_t m_unAccountID : 32;
unsigned int m_unAccountInstance : 20;
unsigned int m_EAccountType : 4;
int m_EUniverse : 8;
} m_comp;
uint64_t m_unAll64Bits;
} m_steamid;
};
class ISteamUser
{
public:
virtual uint32_t GetHSteamUser() = 0;
virtual bool BLoggedOn() = 0;
virtual CSteamID GetSteamID() = 0;
};
class ISteamClient
{
public:
ISteamUser* GetISteamUser(void* hSteamUser, void* hSteamPipe, const char* pchVersion)
{
typedef ISteamUser* (__stdcall* func)(void*, void*, const char*);
return CallVFunction<func>(this, 5)(hSteamUser, hSteamPipe, pchVersion);
}
ISteamGameCoordinator* GetISteamGenericInterface(void* hSteamUser, void* hSteamPipe, const char* pchVersion)
{
typedef ISteamGameCoordinator* (__stdcall* func)(void*, void*, const char*);
return CallVFunction<func>(this, 12)(hSteamUser, hSteamPipe, pchVersion);
}
};

145
SpyCustom/sdk/steamtypes.h Normal file
View File

@ -0,0 +1,145 @@
#ifndef STEAMTYPES_H
#define STEAMTYPES_H
#ifdef _WIN32
#pragma once
#endif
#define S_CALLTYPE __cdecl
#ifndef WCHARTYPES_H
typedef unsigned char uint8;
#endif
#if defined( __GNUC__ ) && !defined(POSIX)
#if __GNUC__ < 4
#error "Steamworks requires GCC 4.X (4.2 or 4.4 have been tested)"
#endif
#define POSIX 1
#endif
#if defined(__x86_64__) || defined(_WIN64)
#define X64BITS
#endif
#if !defined(VALVE_BIG_ENDIAN) && defined(_PS3)
#define VALVE_BIG_ENDIAN
#endif
typedef unsigned char uint8;
typedef signed char int8;
#if defined( _WIN32 )
typedef __int16 int16;
typedef unsigned __int16 uint16;
typedef __int32 int32;
typedef unsigned __int32 uint32;
typedef __int64 int64;
typedef unsigned __int64 uint64;
typedef int64 lint64;
typedef uint64 ulint64;
#ifdef X64BITS
typedef __int64 intp;
typedef unsigned __int64 uintp;
#else
typedef __int32 intp;
typedef unsigned __int32 uintp;
#endif
#else
typedef short int16;
typedef unsigned short uint16;
typedef int int32;
typedef unsigned int uint32;
typedef long long int64;
typedef unsigned long long uint64;
typedef long int lint64;
typedef unsigned long int ulint64;
#ifdef X64BITS
typedef long long intp;
typedef unsigned long long uintp;
#else
typedef int intp;
typedef unsigned int uintp;
#endif
#endif
#ifdef __clang__
# define CLANG_ATTR(ATTR) __attribute__((annotate( ATTR )))
#else
# define CLANG_ATTR(ATTR)
#endif
#define METHOD_DESC(DESC) CLANG_ATTR( "desc:" #DESC ";" )
#define IGNOREATTR() CLANG_ATTR( "ignore" )
#define OUT_STRUCT() CLANG_ATTR( "out_struct: ;" )
#define OUT_ARRAY_CALL(COUNTER,FUNCTION,PARAMS) CLANG_ATTR( "out_array_call:" #COUNTER "," #FUNCTION "," #PARAMS ";" )
#define OUT_ARRAY_COUNT(COUNTER, DESC) CLANG_ATTR( "out_array_count:" #COUNTER ";desc:" #DESC )
#define ARRAY_COUNT(COUNTER) CLANG_ATTR( "array_count:" #COUNTER ";" )
#define ARRAY_COUNT_D(COUNTER, DESC) CLANG_ATTR( "array_count:" #COUNTER ";desc:" #DESC )
#define BUFFER_COUNT(COUNTER) CLANG_ATTR( "buffer_count:" #COUNTER ";" )
#define OUT_BUFFER_COUNT(COUNTER) CLANG_ATTR( "out_buffer_count:" #COUNTER ";" )
#define OUT_STRING_COUNT(COUNTER) CLANG_ATTR( "out_string_count:" #COUNTER ";" )
#define DESC(DESC) CLANG_ATTR("desc:" #DESC ";")
const int k_cubSaltSize = 8;
typedef uint8 Salt_t[k_cubSaltSize];
typedef uint64 GID_t;
const GID_t k_GIDNil = 0xffffffffffffffffull;
typedef uint64 JobID_t;
typedef GID_t TxnID_t;
const GID_t k_TxnIDNil = k_GIDNil;
const GID_t k_TxnIDUnknown = 0;
const JobID_t k_JobIDNil = 0xffffffffffffffffull;
typedef uint32 PackageId_t;
const PackageId_t k_uPackageIdFreeSub = 0x0;
const PackageId_t k_uPackageIdInvalid = 0xFFFFFFFF;
typedef uint32 BundleId_t;
const BundleId_t k_uBundleIdInvalid = 0;
typedef uint32 AppId_t;
const AppId_t k_uAppIdInvalid = 0x0;
typedef uint64 AssetClassId_t;
const AssetClassId_t k_ulAssetClassIdInvalid = 0x0;
typedef uint32 PhysicalItemId_t;
const PhysicalItemId_t k_uPhysicalItemIdInvalid = 0x0;
typedef uint32 DepotId_t;
const DepotId_t k_uDepotIdInvalid = 0x0;
typedef uint32 RTime32;
typedef uint32 CellID_t;
const CellID_t k_uCellIDInvalid = 0xFFFFFFFF;
typedef uint64 SteamAPICall_t;
const SteamAPICall_t k_uAPICallInvalid = 0x0;
typedef uint32 AccountID_t;
typedef uint32 PartnerId_t;
const PartnerId_t k_uPartnerIdInvalid = 0;
typedef uint64 ManifestId_t;
const ManifestId_t k_uManifestIdInvalid = 0;
#endif

66
SpyCustom/sdk/string_t.h Normal file
View File

@ -0,0 +1,66 @@
#ifndef STRING_T_H
#define STRING_T_H
#if defined( _WIN32 )
#pragma once
#endif
#ifndef NO_STRING_T
#ifdef WEAK_STRING_T
typedef int string_t;
#define NULL_STRING 0
#define STRING( offset ) ( ( offset ) ? reinterpret_cast<const char *>( offset ) : "" )
#define MAKE_STRING( str ) ( ( *str != 0 ) ? reinterpret_cast<int>( str ) : 0 )
#define IDENT_STRINGS( s1, s2 ) ( *((void **)&(s1)) == *((void **)&(s2)) )
#else
struct string_t
{
public:
bool operator!() const { return (pszValue == NULL); }
bool operator==(const string_t& rhs) const { return (pszValue == rhs.pszValue); }
bool operator!=(const string_t& rhs) const { return (pszValue != rhs.pszValue); }
bool operator<(const string_t& rhs) const { return ((void*)pszValue < (void*)rhs.pszValue); }
const char* ToCStr() const { return (pszValue) ? pszValue : ""; }
protected:
const char* pszValue;
};
struct castable_string_t : public string_t
{
castable_string_t() { pszValue = NULL; }
castable_string_t(const char* pszFrom) { pszValue = (pszFrom && *pszFrom) ? pszFrom : 0; }
};
#define NULL_STRING castable_string_t()
#define STRING( string_t_obj ) (string_t_obj).ToCStr()
#define MAKE_STRING( c_str ) castable_string_t( c_str )
#define IDENT_STRINGS( s1, s2 ) ( *((void **)&(s1)) == *((void **)&(s2)) )
#endif
#else
typedef const char* string_t;
#define NULL_STRING 0
#define STRING( c_str ) ( c_str )
#define MAKE_STRING( c_str ) ( c_str )
#define IDENT_STRINGS( s1, s2 ) ( *((void **)&(s1)) == *((void **)&(s2)) )
#endif
inline void EnsureValidValue(string_t& x) { x = NULL_STRING; }
#endif

465
SpyCustom/sdk/stringpool.h Normal file
View File

@ -0,0 +1,465 @@
#ifndef STRINGPOOL_H
#define STRINGPOOL_H
#if defined( _WIN32 )
#pragma once
#endif
#include "utlrbtree.h"
#include "utlvector.h"
#include "utlbuffer.h"
#include "generichash.h"
enum StringPoolCase_t
{
StringPoolCaseInsensitive,
StringPoolCaseSensitive
};
class CStringPool
{
public:
CStringPool(StringPoolCase_t caseSensitivity = StringPoolCaseInsensitive);
~CStringPool();
unsigned int Count() const;
const char* Allocate(const char* pszValue);
void FreeAll();
const char* Find(const char* pszValue);
protected:
typedef CUtlRBTree<const char*, unsigned short> CStrSet;
CStrSet m_Strings;
};
template<class T>
class CCountedStringPoolBase
{
public:
struct hash_item_t
{
char* pString;
T nNextElement;
unsigned char nReferenceCount;
unsigned char pad;
};
enum
{
INVALID_ELEMENT = 0,
MAX_REFERENCE = 0xFF,
HASH_TABLE_SIZE = 1024
};
CUtlVector<T> m_HashTable;
CUtlVector<hash_item_t> m_Elements;
T m_FreeListStart;
StringPoolCase_t m_caseSensitivity;
public:
CCountedStringPoolBase(StringPoolCase_t caseSensitivity = StringPoolCaseInsensitive);
virtual ~CCountedStringPoolBase();
void FreeAll();
char* FindString(const char* pIntrinsic);
char* ReferenceString(const char* pIntrinsic);
void DereferenceString(const char* pIntrinsic);
T FindStringHandle(const char* pIntrinsic);
T ReferenceStringHandle(const char* pIntrinsic);
char* HandleToString(T handle);
void SpewStrings();
unsigned Hash(const char* pszKey);
bool SaveToBuffer(CUtlBuffer& buffer);
bool RestoreFromBuffer(CUtlBuffer& buffer);
void VerifyNotOverflowed(unsigned int value);
};
typedef CCountedStringPoolBase<unsigned short> CCountedStringPool;
template<class T>
inline CCountedStringPoolBase<T>::CCountedStringPoolBase(StringPoolCase_t caseSensitivity)
{
MEM_ALLOC_CREDIT();
m_HashTable.EnsureCount(HASH_TABLE_SIZE);
for (int i = 0; i < m_HashTable.Count(); i++)
{
m_HashTable[i] = INVALID_ELEMENT;
}
m_FreeListStart = INVALID_ELEMENT;
m_Elements.AddToTail();
m_Elements[0].pString = NULL;
m_Elements[0].nReferenceCount = 0;
m_Elements[0].nNextElement = INVALID_ELEMENT;
m_caseSensitivity = caseSensitivity;
}
template<class T>
inline CCountedStringPoolBase<T>::~CCountedStringPoolBase()
{
FreeAll();
}
template<class T>
inline void CCountedStringPoolBase<T>::FreeAll()
{
int i;
for (i = 0; i < m_HashTable.Count(); i++)
{
m_HashTable[i] = INVALID_ELEMENT;
}
m_FreeListStart = INVALID_ELEMENT;
for (i = 0; i < m_Elements.Count(); i++)
{
if (m_Elements[i].pString)
{
delete[] m_Elements[i].pString;
m_Elements[i].pString = NULL;
m_Elements[i].nReferenceCount = 0;
m_Elements[i].nNextElement = INVALID_ELEMENT;
}
}
m_Elements.RemoveAll();
m_Elements.AddToTail();
m_Elements[0].pString = NULL;
m_Elements[0].nReferenceCount = 0;
m_Elements[0].nNextElement = INVALID_ELEMENT;
}
template<class T>
inline unsigned CCountedStringPoolBase<T>::Hash(const char* pszKey)
{
if (m_caseSensitivity == StringPoolCaseInsensitive)
{
return HashStringCaseless(pszKey);
}
return HashString(pszKey);
}
template<class T>
inline T CCountedStringPoolBase<T>::FindStringHandle(const char* pIntrinsic)
{
if (pIntrinsic == NULL)
return INVALID_ELEMENT;
T nHashBucketIndex = (Hash(pIntrinsic) % HASH_TABLE_SIZE);
T nCurrentBucket = m_HashTable[nHashBucketIndex];
if (nCurrentBucket != INVALID_ELEMENT)
{
for (; nCurrentBucket != INVALID_ELEMENT; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement)
{
if (!Q_stricmp(pIntrinsic, m_Elements[nCurrentBucket].pString))
{
return nCurrentBucket;
}
}
}
return 0;
}
template<class T>
inline char* CCountedStringPoolBase<T>::FindString(const char* pIntrinsic)
{
if (pIntrinsic == NULL)
return NULL;
return m_Elements[FindStringHandle(pIntrinsic)].pString;
}
template<class T>
inline T CCountedStringPoolBase<T>::ReferenceStringHandle(const char* pIntrinsic)
{
if (pIntrinsic == NULL)
return INVALID_ELEMENT;
T nHashBucketIndex = (Hash(pIntrinsic) % HASH_TABLE_SIZE);
T nCurrentBucket = m_HashTable[nHashBucketIndex];
if (nCurrentBucket != INVALID_ELEMENT)
{
for (; nCurrentBucket != INVALID_ELEMENT; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement)
{
if (!Q_stricmp(pIntrinsic, m_Elements[nCurrentBucket].pString))
{
if (m_Elements[nCurrentBucket].nReferenceCount < MAX_REFERENCE)
{
m_Elements[nCurrentBucket].nReferenceCount++;
}
return nCurrentBucket;
}
}
}
if (m_FreeListStart != INVALID_ELEMENT)
{
nCurrentBucket = m_FreeListStart;
m_FreeListStart = m_Elements[nCurrentBucket].nNextElement;
}
else
{
unsigned int newElement = m_Elements.AddToTail();
VerifyNotOverflowed(newElement);
nCurrentBucket = newElement;
}
m_Elements[nCurrentBucket].nReferenceCount = 1;
m_Elements[nCurrentBucket].nNextElement = m_HashTable[nHashBucketIndex];
m_HashTable[nHashBucketIndex] = nCurrentBucket;
m_Elements[nCurrentBucket].pString = new char[Q_strlen(pIntrinsic) + 1];
Q_strcpy(m_Elements[nCurrentBucket].pString, pIntrinsic);
return nCurrentBucket;
}
template<>
inline void CCountedStringPoolBase<unsigned short>::VerifyNotOverflowed(unsigned int value) { Assert(value < 0xffff); }
template<>
inline void CCountedStringPoolBase<unsigned int>::VerifyNotOverflowed(unsigned int value) {}
template<class T>
inline char* CCountedStringPoolBase<T>::ReferenceString(const char* pIntrinsic)
{
if (!pIntrinsic)
return NULL;
return m_Elements[ReferenceStringHandle(pIntrinsic)].pString;
}
template<class T>
inline void CCountedStringPoolBase<T>::DereferenceString(const char* pIntrinsic)
{
if (!pIntrinsic)
return;
T nHashBucketIndex = (Hash(pIntrinsic) % m_HashTable.Count());
T nCurrentBucket = m_HashTable[nHashBucketIndex];
if (nCurrentBucket == INVALID_ELEMENT)
return;
for (T previous = INVALID_ELEMENT; nCurrentBucket != INVALID_ELEMENT; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement)
{
if (!Q_stricmp(pIntrinsic, m_Elements[nCurrentBucket].pString))
{
if (m_Elements[nCurrentBucket].nReferenceCount < MAX_REFERENCE)
{
m_Elements[nCurrentBucket].nReferenceCount--;
}
if (m_Elements[nCurrentBucket].nReferenceCount == 0)
{
if (previous == INVALID_ELEMENT)
{
m_HashTable[nHashBucketIndex] = m_Elements[nCurrentBucket].nNextElement;
}
else
{
m_Elements[previous].nNextElement = m_Elements[nCurrentBucket].nNextElement;
}
delete[] m_Elements[nCurrentBucket].pString;
m_Elements[nCurrentBucket].pString = NULL;
m_Elements[nCurrentBucket].nReferenceCount = 0;
m_Elements[nCurrentBucket].nNextElement = m_FreeListStart;
m_FreeListStart = nCurrentBucket;
break;
}
}
previous = nCurrentBucket;
}
}
template<class T>
inline char* CCountedStringPoolBase<T>::HandleToString(T handle)
{
return m_Elements[handle].pString;
}
template<class T>
inline void CCountedStringPoolBase<T>::SpewStrings()
{
int i;
for (i = 0; i < m_Elements.Count(); i++)
{
char* string = m_Elements[i].pString;
Msg("String %d: ref:%d %s\n", i, m_Elements[i].nReferenceCount, string == NULL ? "EMPTY - ok for slot zero only!" : string);
}
Msg("\n%d total counted strings.", m_Elements.Count());
}
#define STRING_POOL_VERSION MAKEID( 'C', 'S', 'P', '1' )
#define MAX_STRING_SAVE 1024
template<>
inline bool CCountedStringPoolBase<unsigned short>::SaveToBuffer(CUtlBuffer& buffer)
{
if (m_Elements.Count() <= 1)
{
return true;
}
buffer.PutInt(STRING_POOL_VERSION);
buffer.PutUnsignedShort(m_FreeListStart);
buffer.PutInt(m_HashTable.Count());
for (int i = 0; i < m_HashTable.Count(); i++)
{
buffer.PutUnsignedShort(m_HashTable[i]);
}
buffer.PutInt(m_Elements.Count());
for (int i = 1; i < m_Elements.Count(); i++)
{
buffer.PutUnsignedShort(m_Elements[i].nNextElement);
buffer.PutUnsignedChar(m_Elements[i].nReferenceCount);
const char* pString = m_Elements[i].pString;
if (strlen(pString) >= MAX_STRING_SAVE)
{
return false;
}
buffer.PutString(pString ? pString : "");
}
return buffer.IsValid();
}
template<>
inline bool CCountedStringPoolBase<unsigned short>::RestoreFromBuffer(CUtlBuffer& buffer)
{
int signature = buffer.GetInt();
if (signature != STRING_POOL_VERSION)
{
return false;
}
FreeAll();
m_FreeListStart = buffer.GetUnsignedShort();
int hashCount = buffer.GetInt();
m_HashTable.SetCount(hashCount);
for (int i = 0; i < hashCount; i++)
{
m_HashTable[i] = buffer.GetUnsignedShort();
}
int tableCount = buffer.GetInt();
if (tableCount > 1)
{
m_Elements.AddMultipleToTail(tableCount - 1);
}
char tempString[MAX_STRING_SAVE];
for (int i = 1; i < tableCount; i++)
{
m_Elements[i].nNextElement = buffer.GetUnsignedShort();
m_Elements[i].nReferenceCount = buffer.GetUnsignedChar();
buffer.GetString(tempString, sizeof(tempString));
m_Elements[i].pString = strdup(tempString);
}
return buffer.IsValid();
}
template<>
inline bool CCountedStringPoolBase<unsigned int>::SaveToBuffer(CUtlBuffer& buffer)
{
if (m_Elements.Count() <= 1)
{
return true;
}
buffer.PutInt(STRING_POOL_VERSION);
buffer.PutUnsignedInt(m_FreeListStart);
buffer.PutInt(m_HashTable.Count());
for (int i = 0; i < m_HashTable.Count(); i++)
{
buffer.PutUnsignedInt(m_HashTable[i]);
}
buffer.PutInt(m_Elements.Count());
for (int i = 1; i < m_Elements.Count(); i++)
{
buffer.PutUnsignedInt(m_Elements[i].nNextElement);
buffer.PutUnsignedChar(m_Elements[i].nReferenceCount);
const char* pString = m_Elements[i].pString;
if (strlen(pString) >= MAX_STRING_SAVE)
{
return false;
}
buffer.PutString(pString ? pString : "");
}
return buffer.IsValid();
}
template<>
inline bool CCountedStringPoolBase<unsigned int>::RestoreFromBuffer(CUtlBuffer& buffer)
{
int signature = buffer.GetInt();
if (signature != STRING_POOL_VERSION)
{
return false;
}
FreeAll();
m_FreeListStart = buffer.GetUnsignedInt();
int hashCount = buffer.GetInt();
m_HashTable.SetCount(hashCount);
for (int i = 0; i < hashCount; i++)
{
m_HashTable[i] = buffer.GetUnsignedInt();
}
int tableCount = buffer.GetInt();
if (tableCount > 1)
{
m_Elements.AddMultipleToTail(tableCount - 1);
}
char tempString[MAX_STRING_SAVE];
for (int i = 1; i < tableCount; i++)
{
m_Elements[i].nNextElement = buffer.GetUnsignedInt();
m_Elements[i].nReferenceCount = buffer.GetUnsignedChar();
buffer.GetString(tempString, sizeof(tempString));
m_Elements[i].pString = strdup(tempString);
}
return buffer.IsValid();
}
#endif

660
SpyCustom/sdk/strtools.h Normal file
View File

@ -0,0 +1,660 @@
#ifndef TIER1_STRTOOLS_H
#define TIER1_STRTOOLS_H
#include "platform.h"
#include <ctype.h>
#include <stdarg.h>
#ifdef _WIN32
#pragma once
#elif POSIX
#include <wchar.h>
#include <math.h>
#include <wctype.h>
#endif
#include <string.h>
#include <stdlib.h>
#ifdef _WIN64
#define str_size unsigned int
#else
#define str_size size_t
#endif
template< class T, class I > class CUtlMemory;
template< class T, class A > class CUtlVector;
void _V_memset(const char* file, int line, void* dest, int fill, int count);
void _V_memcpy(const char* file, int line, void* dest, const void* src, int count);
void _V_memmove(const char* file, int line, void* dest, const void* src, int count);
int _V_memcmp(const char* file, int line, const void* m1, const void* m2, int count);
int _V_strlen(const char* file, int line, const char* str);
void _V_strcpy(const char* file, int line, char* dest, const char* src);
char* _V_strrchr(const char* file, int line, const char* s, char c);
int _V_strcmp(const char* file, int line, const char* s1, const char* s2);
int _V_wcscmp(const char* file, int line, const wchar_t* s1, const wchar_t* s2);
char* _V_strstr(const char* file, int line, const char* s1, const char* search);
int _V_wcslen(const char* file, int line, const wchar_t* pwch);
wchar_t* _V_wcslower(const char* file, int line, wchar_t* start);
wchar_t* _V_wcsupr(const char* file, int line, wchar_t* start);
char* V_strupr(char* start);
char* V_strlower(char* start);
int V_stricmp(const char* s1, const char* s2);
int V_strncmp(const char* s1, const char* s2, int count);
int V_strnicmp(const char* s1, const char* s2, int n);
#ifdef POSIX
inline char* strupr(char* start)
{
return V_strupr(start);
}
inline char* strlwr(char* start)
{
return V_strlower(start);
}
inline wchar_t* _wcslwr(wchar_t* start)
{
wchar_t* str = start;
while (str && *str)
{
*str = (wchar_t)towlower(static_cast<wint_t>(*str));
str++;
}
return start;
};
inline wchar_t* _wcsupr(wchar_t* start)
{
wchar_t* str = start;
while (str && *str)
{
*str = (wchar_t)towupper(static_cast<wint_t>(*str));
str++;
}
return start;
};
#endif
#ifdef _DEBUG
#define V_memset(dest, fill, count) _V_memset (__FILE__, __LINE__, (dest), (fill), (count))
#define V_memcpy(dest, src, count) _V_memcpy (__FILE__, __LINE__, (dest), (src), (count))
#define V_memmove(dest, src, count) _V_memmove (__FILE__, __LINE__, (dest), (src), (count))
#define V_memcmp(m1, m2, count) _V_memcmp (__FILE__, __LINE__, (m1), (m2), (count))
#define V_strlen(str) _V_strlen (__FILE__, __LINE__, (str))
#define V_strcpy(dest, src) _V_strcpy (__FILE__, __LINE__, (dest), (src))
#define V_strrchr(s, c) _V_strrchr (__FILE__, __LINE__, (s), (c))
#define V_strcmp(s1, s2) _V_strcmp (__FILE__, __LINE__, (s1), (s2))
#define V_wcscmp(s1, s2) _V_wcscmp (__FILE__, __LINE__, (s1), (s2))
#define V_strstr(s1, search ) _V_strstr (__FILE__, __LINE__, (s1), (search) )
#define V_wcslen(pwch) _V_wcslen (__FILE__, __LINE__, (pwch))
#define V_wcslower(start) _V_wcslower (__FILE__, __LINE__, (start))
#define V_wcsupr(start) _V_wcsupr (__FILE__, __LINE__, (start))
#else
inline void V_memset(void* dest, int fill, int count) { memset(dest, fill, count); }
inline void V_memcpy(void* dest, const void* src, int count) { memcpy(dest, src, count); }
inline void V_memmove(void* dest, const void* src, int count) { memmove(dest, src, count); }
inline int V_memcmp(const void* m1, const void* m2, int count) { return memcmp(m1, m2, count); }
inline int V_strlen(const char* str) { return (int)strlen(str); }
inline void V_strcpy(char* dest, const char* src) { strcpy(dest, src); }
inline int V_wcslen(const wchar_t* pwch) { return (int)wcslen(pwch); }
inline char* V_strrchr(const char* s, char c) { return (char*)strrchr(s, c); }
inline int V_strcmp(const char* s1, const char* s2) { return strcmp(s1, s2); }
inline int V_wcscmp(const wchar_t* s1, const wchar_t* s2) { return wcscmp(s1, s2); }
inline char* V_strstr(const char* s1, const char* search) { return (char*)strstr(s1, search); }
inline wchar_t* V_wcslower(wchar_t* start) { return _wcslwr(start); }
inline wchar_t* V_wcsupr(wchar_t* start) { return _wcsupr(start); }
#endif
int V_atoi(const char* str);
int64 V_atoi64(const char* str);
uint64 V_atoui64(const char* str);
float V_atof(const char* str);
char* V_stristr(char* pStr, const char* pSearch);
const char* V_stristr(const char* pStr, const char* pSearch);
const char* V_strnistr(const char* pStr, const char* pSearch, int n);
const char* V_strnchr(const char* pStr, char c, int n);
inline int V_strcasecmp(const char* s1, const char* s2) { return V_stricmp(s1, s2); }
inline int V_strncasecmp(const char* s1, const char* s2, int n) { return V_strnicmp(s1, s2, n); }
void V_qsort_s(void* base, size_t num, size_t width, int(__cdecl* compare)(void*, const void*,
const void*), void* context);
const char* StringAfterPrefix(const char* str, const char* prefix);
const char* StringAfterPrefixCaseSensitive(const char* str, const char* prefix);
inline bool StringHasPrefix(const char* str, const char* prefix) { return StringAfterPrefix(str, prefix) != NULL; }
inline bool StringHasPrefixCaseSensitive(const char* str, const char* prefix) { return StringAfterPrefixCaseSensitive(str, prefix) != NULL; }
void V_normalizeFloatString(char* pFloat);
inline bool V_isdigit(char c)
{
return c >= '0' && c <= '9';
}
inline bool V_isalpha(char c) { return isalpha((unsigned char)c) != 0; }
inline bool V_isalnum(char c) { return isalnum((unsigned char)c) != 0; }
inline bool V_isprint(char c) { return isprint((unsigned char)c) != 0; }
inline bool V_isxdigit(char c) { return isxdigit((unsigned char)c) != 0; }
inline bool V_ispunct(char c) { return ispunct((unsigned char)c) != 0; }
inline bool V_isgraph(char c) { return isgraph((unsigned char)c) != 0; }
inline bool V_isupper(char c) { return isupper((unsigned char)c) != 0; }
inline bool V_islower(char c) { return islower((unsigned char)c) != 0; }
inline bool V_iscntrl(char c) { return iscntrl((unsigned char)c) != 0; }
inline bool V_isspace(char c) { return isspace((unsigned char)c) != 0; }
void V_strncpy(OUT_Z_CAP(maxLenInChars) char* pDest, const char* pSrc, int maxLenInChars);
template <size_t maxLenInChars> void V_strcpy_safe(OUT_Z_ARRAY char(&pDest)[maxLenInChars], const char* pSrc)
{
V_strncpy(pDest, pSrc, (int)maxLenInChars);
}
void V_wcsncpy(OUT_Z_BYTECAP(maxLenInBytes) wchar_t* pDest, wchar_t const* pSrc, int maxLenInBytes);
template <size_t maxLenInChars> void V_wcscpy_safe(OUT_Z_ARRAY wchar_t(&pDest)[maxLenInChars], wchar_t const* pSrc)
{
V_wcsncpy(pDest, pSrc, maxLenInChars * sizeof(*pDest));
}
#define COPY_ALL_CHARACTERS -1
char* V_strncat(INOUT_Z_CAP(cchDest) char* pDest, const char* pSrc, size_t cchDest, int max_chars_to_copy = COPY_ALL_CHARACTERS);
template <size_t cchDest> char* V_strcat_safe(INOUT_Z_ARRAY char(&pDest)[cchDest], const char* pSrc, int nMaxCharsToCopy = COPY_ALL_CHARACTERS)
{
return V_strncat(pDest, pSrc, (int)cchDest, nMaxCharsToCopy);
}
wchar_t* V_wcsncat(INOUT_Z_CAP(cchDest) wchar_t* pDest, const wchar_t* pSrc, size_t cchDest, int nMaxCharsToCopy = COPY_ALL_CHARACTERS);
template <size_t cchDest> wchar_t* V_wcscat_safe(INOUT_Z_ARRAY wchar_t(&pDest)[cchDest], const wchar_t* pSrc, int nMaxCharsToCopy = COPY_ALL_CHARACTERS)
{
return V_wcsncat(pDest, pSrc, (int)cchDest, nMaxCharsToCopy);
}
char* V_strnlwr(INOUT_Z_CAP(cchBuf) char* pBuf, size_t cchBuf);
template <size_t cchDest> char* V_strlwr_safe(INOUT_Z_ARRAY char(&pBuf)[cchDest])
{
return _V_strnlwr(pBuf, (int)cchDest);
}
#ifdef _WIN32
#ifndef _VA_LIST_DEFINED
#ifdef _M_ALPHA
struct va_list
{
char* a0;
int offset;
};
#else
typedef char* va_list;
#endif
#define _VA_LIST_DEFINED
#endif
#elif POSIX
#include <stdarg.h>
#endif
#ifdef _WIN32
#define CORRECT_PATH_SEPARATOR '\\'
#define CORRECT_PATH_SEPARATOR_S "\\"
#define INCORRECT_PATH_SEPARATOR '/'
#define INCORRECT_PATH_SEPARATOR_S "/"
#elif POSIX
#define CORRECT_PATH_SEPARATOR '/'
#define CORRECT_PATH_SEPARATOR_S "/"
#define INCORRECT_PATH_SEPARATOR '\\'
#define INCORRECT_PATH_SEPARATOR_S "\\"
#endif
int V_vsnprintf(OUT_Z_CAP(maxLenInCharacters) char* pDest, int maxLenInCharacters, PRINTF_FORMAT_STRING const char* pFormat, va_list params);
template <size_t maxLenInCharacters> int V_vsprintf_safe(OUT_Z_ARRAY char(&pDest)[maxLenInCharacters], PRINTF_FORMAT_STRING const char* pFormat, va_list params) { return V_vsnprintf(pDest, maxLenInCharacters, pFormat, params); }
int V_snprintf(OUT_Z_CAP(maxLenInChars) char* pDest, int maxLenInChars, PRINTF_FORMAT_STRING const char* pFormat, ...) FMTFUNCTION(3, 4);
template <size_t maxLenInChars> int V_sprintf_safe(OUT_Z_ARRAY char(&pDest)[maxLenInChars], PRINTF_FORMAT_STRING const char* pFormat, ...) FMTFUNCTION(2, 3);
template <size_t maxLenInChars> int V_sprintf_safe(OUT_Z_ARRAY char(&pDest)[maxLenInChars], PRINTF_FORMAT_STRING const char* pFormat, ...)
{
va_list params;
va_start(params, pFormat);
int result = V_vsnprintf(pDest, maxLenInChars, pFormat, params);
va_end(params);
return result;
}
int V_vsnwprintf(OUT_Z_CAP(maxLenInCharacters) wchar_t* pDest, int maxLenInCharacters, PRINTF_FORMAT_STRING const wchar_t* pFormat, va_list params);
template <size_t maxLenInCharacters> int V_vswprintf_safe(OUT_Z_ARRAY wchar_t(&pDest)[maxLenInCharacters], PRINTF_FORMAT_STRING const wchar_t* pFormat, va_list params) { return V_vsnwprintf(pDest, maxLenInCharacters, pFormat, params); }
int V_vsnprintfRet(OUT_Z_CAP(maxLenInCharacters) char* pDest, int maxLenInCharacters, PRINTF_FORMAT_STRING const char* pFormat, va_list params, bool* pbTruncated);
template <size_t maxLenInCharacters> int V_vsprintfRet_safe(OUT_Z_ARRAY char(&pDest)[maxLenInCharacters], PRINTF_FORMAT_STRING const char* pFormat, va_list params, bool* pbTruncated) { return V_vsnprintfRet(pDest, maxLenInCharacters, pFormat, params, pbTruncated); }
int V_snwprintf(OUT_Z_CAP(maxLenInCharacters) wchar_t* pDest, int maxLenInCharacters, PRINTF_FORMAT_STRING const wchar_t* pFormat, ...);
template <size_t maxLenInChars> int V_swprintf_safe(OUT_Z_ARRAY wchar_t(&pDest)[maxLenInChars], PRINTF_FORMAT_STRING const wchar_t* pFormat, ...)
{
va_list params;
va_start(params, pFormat);
int result = V_vsnwprintf(pDest, maxLenInChars, pFormat, params);
va_end(params);
return result;
}
char* V_pretifymem(float value, int digitsafterdecimal = 2, bool usebinaryonek = false);
char* V_pretifynum(int64 value);
int V_UTF8ToUnicode(const char* pUTF8, OUT_Z_BYTECAP(cubDestSizeInBytes) wchar_t* pwchDest, int cubDestSizeInBytes);
int V_UnicodeToUTF8(const wchar_t* pUnicode, OUT_Z_BYTECAP(cubDestSizeInBytes) char* pUTF8, int cubDestSizeInBytes);
int V_UCS2ToUnicode(const ucs2* pUCS2, OUT_Z_BYTECAP(cubDestSizeInBytes) wchar_t* pUnicode, int cubDestSizeInBytes);
int V_UCS2ToUTF8(const ucs2* pUCS2, OUT_Z_BYTECAP(cubDestSizeInBytes) char* pUTF8, int cubDestSizeInBytes);
int V_UnicodeToUCS2(const wchar_t* pUnicode, int cubSrcInBytes, OUT_Z_BYTECAP(cubDestSizeInBytes) char* pUCS2, int cubDestSizeInBytes);
int V_UTF8ToUCS2(const char* pUTF8, int cubSrcInBytes, OUT_Z_BYTECAP(cubDestSizeInBytes) ucs2* pUCS2, int cubDestSizeInBytes);
bool Q_StripPrecedingAndTrailingWhitespace(char* pch);
bool Q_StripPrecedingAndTrailingWhitespaceW(wchar_t* pwch);
bool Q_AggressiveStripPrecedingAndTrailingWhitespace(char* pch);
bool Q_AggressiveStripPrecedingAndTrailingWhitespaceW(wchar_t* pwch);
unsigned char V_nibble(char c);
void V_hextobinary(char const* in, int numchars, byte* out, int maxoutputbytes);
void V_binarytohex(const byte* in, int inputbytes, char* out, int outsize);
void V_FileBase(const char* in, char* out, int maxlen);
void V_StripTrailingSlash(char* ppath);
void V_StripExtension(const char* in, char* out, int outLen);
void V_DefaultExtension(char* path, const char* extension, int pathStringLength);
void V_SetExtension(char* path, const char* extension, int pathStringLength);
void V_StripFilename(char* path);
bool V_StripLastDir(char* dirName, int maxlen);
const char* V_UnqualifiedFileName(const char* in);
void V_ComposeFileName(const char* path, const char* filename, char* dest, int destSize);
bool V_ExtractFilePath(const char* path, char* dest, int destSize);
void V_ExtractFileExtension(const char* path, char* dest, int destSize);
const char* V_GetFileExtension(const char* path);
const char* V_GetFileName(const char* path);
bool V_RemoveDotSlashes(char* pFilename, char separator = CORRECT_PATH_SEPARATOR, bool bRemoveDoubleSlashes = true);
void V_MakeAbsolutePath(char* pOut, int outLen, const char* pPath, const char* pStartingDir = NULL);
bool V_MakeRelativePath(const char* pFullPath, const char* pDirectory, char* pRelativePath, int nBufLen);
void V_FixupPathName(OUT_Z_CAP(nOutLen) char* pOut, size_t nOutLen, const char* pPath);
void V_AppendSlash(INOUT_Z_CAP(strSize) char* pStr, int strSize);
bool V_IsAbsolutePath(IN_Z const char* pPath);
bool V_StrSubst(IN_Z const char* pIn, IN_Z const char* pMatch, const char* pReplaceWith,
OUT_Z_CAP(outLen) char* pOut, int outLen, bool bCaseSensitive = false);
void V_SplitString(IN_Z const char* pString, IN_Z const char* pSeparator, CUtlVector<char*, CUtlMemory<char*, int> >& outStrings);
void V_SplitString2(IN_Z const char* pString, const char** pSeparators, int nSeparators, CUtlVector<char*, CUtlMemory<char*, int> >& outStrings);
bool V_GetCurrentDirectory(OUT_Z_CAP(maxLen) char* pOut, int maxLen);
bool V_SetCurrentDirectory(const char* pDirName);
void V_StrSlice(const char* pStr, int firstChar, int lastCharNonInclusive, OUT_Z_CAP(outSize) char* pOut, int outSize);
void V_StrLeft(const char* pStr, int nChars, OUT_Z_CAP(outSize) char* pOut, int outSize);
void V_StrRight(const char* pStr, int nChars, OUT_Z_CAP(outSize) char* pOut, int outSize);
char* V_AddBackSlashesToSpecialChars(char const* pSrc);
void V_FixSlashes(char* pname, char separator = CORRECT_PATH_SEPARATOR);
void V_FixDoubleSlashes(char* pStr);
void V_strtowcs(const char* pString, int nInSize, OUT_Z_BYTECAP(nOutSizeInBytes) wchar_t* pWString, int nOutSizeInBytes);
void V_wcstostr(const wchar_t* pWString, int nInSize, OUT_Z_CAP(nOutSizeInBytes) char* pString, int nOutSizeInBytes);
inline void V_strcat(INOUT_Z_CAP(cchDest) char* dest, const char* src, int cchDest)
{
V_strncat(dest, src, cchDest, COPY_ALL_CHARACTERS);
}
inline void V_wcscat(INOUT_Z_CAP(cchDest) wchar_t* dest, const wchar_t* src, int cchDest)
{
V_wcsncat(dest, src, cchDest, COPY_ALL_CHARACTERS);
}
template < class NameArray >
int V_GenerateUniqueNameIndex(const char* prefix, const NameArray& nameArray, int startindex = 0)
{
if (prefix == NULL)
return 0;
int freeindex = startindex;
int nNames = nameArray.Count();
for (int i = 0; i < nNames; ++i)
{
const char* pName = nameArray[i];
if (!pName)
continue;
const char* pIndexStr = StringAfterPrefix(pName, prefix);
if (pIndexStr)
{
int index = *pIndexStr ? atoi(pIndexStr) : 1;
if (index >= freeindex)
{
freeindex = index + 1;
}
}
}
return freeindex;
}
template < class NameArray >
bool V_GenerateUniqueName(OUT_Z_CAP(memsize) char* name, int memsize, const char* prefix, const NameArray& nameArray)
{
if (name == NULL || memsize == 0)
return false;
if (prefix == NULL)
{
name[0] = '\0';
return false;
}
int prefixLength = V_strlen(prefix);
if (prefixLength + 1 > memsize)
{
name[0] = '\0';
return false;
}
int i = V_GenerateUniqueNameIndex(prefix, nameArray);
if (i <= 0)
{
V_strncpy(name, prefix, memsize);
return true;
}
int newlen = prefixLength + (int)log10((float)i) + 1;
if (newlen + 1 > memsize)
{
V_strncpy(name, prefix, memsize);
return false;
}
V_snprintf(name, memsize, "%s%d", prefix, i);
return true;
}
class CStrAutoEncode
{
public:
explicit CStrAutoEncode(const char* pch)
{
m_pch = pch;
m_pwch = NULL;
#if !defined( WIN32 ) && !defined(_WIN32)
m_pucs2 = NULL;
#endif
m_bCreatedUTF16 = false;
}
explicit CStrAutoEncode(const wchar_t* pwch)
{
m_pch = NULL;
m_pwch = pwch;
#if !defined( WIN32 ) && !defined(_WIN32)
m_pucs2 = NULL;
#endif
m_bCreatedUTF16 = true;
}
#if !defined(WIN32) && !defined(_WINDOWS) && !defined(_WIN32)
explicit CStrAutoEncode(const ucs2* pwch)
{
m_pch = NULL;
m_pwch = NULL;
m_pucs2 = pwch;
m_bCreatedUTF16 = true;
}
#endif
const char* ToString()
{
PopulateUTF8();
return m_pch;
}
char* ToStringWritable()
{
PopulateUTF8();
return const_cast<char*>(m_pch);
}
const wchar_t* ToWString()
{
PopulateUTF16();
return m_pwch;
}
#if !defined( WIN32 ) && !defined(_WIN32)
const ucs2* ToUCS2String()
{
PopulateUCS2();
return m_pucs2;
}
#endif
wchar_t* ToWStringWritable()
{
PopulateUTF16();
return const_cast<wchar_t*>(m_pwch);
}
~CStrAutoEncode()
{
if (m_bCreatedUTF16)
{
delete[] m_pch;
}
else
{
delete[] m_pwch;
}
}
private:
void PopulateUTF8()
{
if (!m_bCreatedUTF16)
return;
if (m_pwch == NULL)
return;
if (m_pch != NULL)
return;
uint32 cbMax = 4 * static_cast<uint32>(V_wcslen(m_pwch)) + 1;
char* pchTemp = new char[cbMax];
if (V_UnicodeToUTF8(m_pwch, pchTemp, cbMax))
{
uint32 cchAlloc = static_cast<uint32>(V_strlen(pchTemp)) + 1;
char* pchHeap = new char[cchAlloc];
V_strncpy(pchHeap, pchTemp, cchAlloc);
delete[] pchTemp;
m_pch = pchHeap;
}
else
{
delete[] pchTemp;
}
}
void PopulateUTF16()
{
if (m_bCreatedUTF16)
return;
if (m_pch == NULL)
return;
if (m_pwch != NULL)
return;
uint32 cchMax = static_cast<uint32>(V_strlen(m_pch)) + 1;
wchar_t* pwchTemp = new wchar_t[cchMax];
if (V_UTF8ToUnicode(m_pch, pwchTemp, cchMax * sizeof(wchar_t)))
{
uint32 cchAlloc = static_cast<uint32>(V_wcslen(pwchTemp)) + 1;
wchar_t* pwchHeap = new wchar_t[cchAlloc];
V_wcsncpy(pwchHeap, pwchTemp, cchAlloc * sizeof(wchar_t));
delete[] pwchTemp;
m_pwch = pwchHeap;
}
else
{
delete[] pwchTemp;
}
}
#if !defined( WIN32 ) && !defined(_WIN32)
void PopulateUCS2()
{
if (m_pch == NULL)
return;
if (m_pucs2 != NULL)
return;
uint32 cchMax = static_cast<uint32>(V_strlen(m_pch)) + 1;
ucs2* pwchTemp = new ucs2[cchMax];
if (V_UTF8ToUCS2(m_pch, cchMax, pwchTemp, cchMax * sizeof(ucs2)))
{
uint32 cchAlloc = cchMax;
ucs2* pwchHeap = new ucs2[cchAlloc];
memcpy(pwchHeap, pwchTemp, cchAlloc * sizeof(ucs2));
delete[] pwchTemp;
m_pucs2 = pwchHeap;
}
else
{
delete[] pwchTemp;
}
}
#endif
const char* m_pch;
const wchar_t* m_pwch;
#if !defined( WIN32 ) && !defined(_WIN32)
const ucs2* m_pucs2;
#endif
bool m_bCreatedUTF16;
};
void Q_URLEncodeRaw(OUT_Z_CAP(nDestLen) char* pchDest, int nDestLen, const char* pchSource, int nSourceLen);
size_t Q_URLDecodeRaw(OUT_CAP(nDecodeDestLen) char* pchDecodeDest, int nDecodeDestLen, const char* pchEncodedSource, int nEncodedSourceLen);
void Q_URLEncode(OUT_Z_CAP(nDestLen) char* pchDest, int nDestLen, const char* pchSource, int nSourceLen);
size_t Q_URLDecode(OUT_CAP(nDecodeDestLen) char* pchDecodeDest, int nDecodeDestLen, const char* pchEncodedSource, int nEncodedSourceLen);
#if !defined( VSTDLIB_BACKWARD_COMPAT )
#define Q_memset V_memset
#define Q_memcpy V_memcpy
#define Q_memmove V_memmove
#define Q_memcmp V_memcmp
#define Q_strlen V_strlen
#define Q_strcpy V_strcpy
#define Q_strrchr V_strrchr
#define Q_strcmp V_strcmp
#define Q_wcscmp V_wcscmp
#define Q_stricmp V_stricmp
#define Q_strstr V_strstr
#define Q_strupr V_strupr
#define Q_strlower V_strlower
#define Q_wcslen V_wcslen
#define Q_strncmp V_strncmp
#define Q_strcasecmp V_strcasecmp
#define Q_strncasecmp V_strncasecmp
#define Q_strnicmp V_strnicmp
#define Q_atoi V_atoi
#define Q_atoi64 V_atoi64
#define Q_atoui64 V_atoui64
#define Q_atof V_atof
#define Q_stristr V_stristr
#define Q_strnistr V_strnistr
#define Q_strnchr V_strnchr
#define Q_normalizeFloatString V_normalizeFloatString
#define Q_strncpy V_strncpy
#define Q_snprintf V_snprintf
#define Q_snwprintf V_snwprintf
#define Q_wcsncpy V_wcsncpy
#define Q_strncat V_strncat
#define Q_strnlwr V_strnlwr
#define Q_vsnprintf V_vsnprintf
#define Q_vsnprintfRet V_vsnprintfRet
#define Q_pretifymem V_pretifymem
#define Q_pretifynum V_pretifynum
#define Q_UTF8ToUnicode V_UTF8ToUnicode
#define Q_UnicodeToUTF8 V_UnicodeToUTF8
#define Q_hextobinary V_hextobinary
#define Q_binarytohex V_binarytohex
#define Q_FileBase V_FileBase
#define Q_StripTrailingSlash V_StripTrailingSlash
#define Q_StripExtension V_StripExtension
#define Q_DefaultExtension V_DefaultExtension
#define Q_SetExtension V_SetExtension
#define Q_StripFilename V_StripFilename
#define Q_StripLastDir V_StripLastDir
#define Q_UnqualifiedFileName V_UnqualifiedFileName
#define Q_ComposeFileName V_ComposeFileName
#define Q_ExtractFilePath V_ExtractFilePath
#define Q_ExtractFileExtension V_ExtractFileExtension
#define Q_GetFileExtension V_GetFileExtension
#define Q_RemoveDotSlashes V_RemoveDotSlashes
#define Q_MakeAbsolutePath V_MakeAbsolutePath
#define Q_AppendSlash V_AppendSlash
#define Q_IsAbsolutePath V_IsAbsolutePath
#define Q_StrSubst V_StrSubst
#define Q_SplitString V_SplitString
#define Q_SplitString2 V_SplitString2
#define Q_StrSlice V_StrSlice
#define Q_StrLeft V_StrLeft
#define Q_StrRight V_StrRight
#define Q_FixSlashes V_FixSlashes
#define Q_strtowcs V_strtowcs
#define Q_wcstostr V_wcstostr
#define Q_strcat V_strcat
#define Q_GenerateUniqueNameIndex V_GenerateUniqueNameIndex
#define Q_GenerateUniqueName V_GenerateUniqueName
#define Q_MakeRelativePath V_MakeRelativePath
#define Q_qsort_s V_qsort_s
#endif
#endif

2781
SpyCustom/sdk/studio.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,31 @@
#ifndef TEMPENTITY_H
#define TEMPENTITY_H
#ifdef _WIN32
#pragma once
#endif
#define TE_EXPLFLAG_NONE 0x0
#define TE_EXPLFLAG_NOADDITIVE 0x1
#define TE_EXPLFLAG_DLIGHT 0x2
#define TE_EXPLFLAG_NOSOUND 0x4
#define TE_EXPLFLAG_NOPARTICLES 0x8
#define TE_EXPLFLAG_DRAWALPHA 0x10
#define TE_EXPLFLAG_ROTATE 0x20
#define TE_EXPLFLAG_NOFIREBALL 0x40
#define TE_EXPLFLAG_NOFIREBALLSMOKE 0x80
#define TE_EXPLFLAG_ICE 0x100
#define TE_EXPLFLAG_SCALEPARTICLES 0x200
#define TE_BEAMPOINTS 0
#define TE_SPRITE 1
#define TE_BEAMDISK 2
#define TE_BEAMCYLINDER 3
#define TE_BEAMFOLLOW 4
#define TE_BEAMRING 5
#define TE_BEAMSPLINE 6
#define TE_BEAMRINGPOINT 7
#define TE_BEAMLASER 8
#define TE_BEAMTESLA 9
#endif

View File

@ -0,0 +1,36 @@
#ifndef TEXTURE_GROUP_NAMES_H
#define TEXTURE_GROUP_NAMES_H
#ifdef _WIN32
#pragma once
#endif
#define TEXTURE_GROUP_LIGHTMAP "Lightmaps"
#define TEXTURE_GROUP_WORLD "World textures"
#define TEXTURE_GROUP_MODEL "Model textures"
#define TEXTURE_GROUP_VGUI "VGUI textures"
#define TEXTURE_GROUP_PARTICLE "Particle textures"
#define TEXTURE_GROUP_DECAL "Decal textures"
#define TEXTURE_GROUP_SKYBOX "SkyBox textures"
#define TEXTURE_GROUP_CLIENT_EFFECTS "ClientEffect textures"
#define TEXTURE_GROUP_OTHER "Other textures"
#define TEXTURE_GROUP_PRECACHED "Precached"
#define TEXTURE_GROUP_CUBE_MAP "CubeMap textures"
#define TEXTURE_GROUP_RENDER_TARGET "RenderTargets"
#define TEXTURE_GROUP_RUNTIME_COMPOSITE "Runtime Composite"
#define TEXTURE_GROUP_UNACCOUNTED "Unaccounted textures"
#define TEXTURE_GROUP_STATIC_INDEX_BUFFER "Static Indices"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_DISP "Displacement Verts"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_COLOR "Lighting Verts"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_WORLD "World Verts"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_MODELS "Model Verts"
#define TEXTURE_GROUP_STATIC_VERTEX_BUFFER_OTHER "Other Verts"
#define TEXTURE_GROUP_DYNAMIC_INDEX_BUFFER "Dynamic Indices"
#define TEXTURE_GROUP_DYNAMIC_VERTEX_BUFFER "Dynamic Verts"
#define TEXTURE_GROUP_DEPTH_BUFFER "DepthBuffer"
#define TEXTURE_GROUP_VIEW_MODEL "ViewModel"
#define TEXTURE_GROUP_PIXEL_SHADERS "Pixel Shaders"
#define TEXTURE_GROUP_VERTEX_SHADERS "Vertex Shaders"
#define TEXTURE_GROUP_RENDER_TARGET_SURFACE "RenderTarget Surfaces"
#define TEXTURE_GROUP_MORPH_TARGETS "Morph Targets"
#endif

1402
SpyCustom/sdk/threadtools.h Normal file

File diff suppressed because it is too large Load Diff

68
SpyCustom/sdk/tier1.h Normal file
View File

@ -0,0 +1,68 @@
#ifndef TIER1_H
#define TIER1_H
#if defined( _WIN32 )
#pragma once
#endif
#include "iappsystem.h"
#include "convar.h"
void ConnectTier1Libraries(CreateInterfaceFn* pFactoryList, int nFactoryCount);
void DisconnectTier1Libraries();
template< class IInterface, int ConVarFlag = 0 >
class CTier1AppSystem : public CTier0AppSystem< IInterface >
{
typedef CTier0AppSystem< IInterface > BaseClass;
public:
virtual bool Connect(CreateInterfaceFn factory)
{
if (!BaseClass::Connect(factory))
return false;
ConnectTier1Libraries(&factory, 1);
return true;
}
virtual void Disconnect()
{
DisconnectTier1Libraries();
BaseClass::Disconnect();
}
virtual InitReturnVal_t Init()
{
InitReturnVal_t nRetVal = BaseClass::Init();
if (nRetVal != INIT_OK)
return nRetVal;
if (g_pCVar)
{
ConVar_Register(ConVarFlag);
}
return INIT_OK;
}
virtual void Shutdown()
{
if (g_pCVar)
{
ConVar_Unregister();
}
BaseClass::Shutdown();
}
virtual AppSystemTier_t GetTier()
{
return APP_SYSTEM_TIER1;
}
};
#endif

92
SpyCustom/sdk/tier2.h Normal file
View File

@ -0,0 +1,92 @@
#ifndef TIER2_H
#define TIER2_H
#if defined( _WIN32 )
#pragma once
#endif
#include "tier1.h"
void ConnectTier2Libraries(CreateInterfaceFn* pFactoryList, int nFactoryCount);
void DisconnectTier2Libraries();
void InitDefaultFileSystem(void);
void ShutdownDefaultFileSystem(void);
void InitCommandLineProgram(int& argc, char**& argv);
template< class IInterface, int ConVarFlag = 0 >
class CTier2AppSystem : public CTier1AppSystem< IInterface, ConVarFlag >
{
typedef CTier1AppSystem< IInterface, ConVarFlag > BaseClass;
public:
virtual bool Connect(CreateInterfaceFn factory)
{
if (!BaseClass::Connect(factory))
return false;
ConnectTier2Libraries(&factory, 1);
return true;
}
virtual InitReturnVal_t Init()
{
InitReturnVal_t nRetVal = BaseClass::Init();
if (nRetVal != INIT_OK)
return nRetVal;
return INIT_OK;
}
virtual AppSystemTier_t GetTier()
{
return APP_SYSTEM_TIER2;
}
virtual void Shutdown()
{
BaseClass::Shutdown();
}
virtual void Disconnect()
{
DisconnectTier2Libraries();
BaseClass::Disconnect();
}
};
enum FadeMode_t
{
FADE_MODE_NONE = 0,
FADE_MODE_LOW,
FADE_MODE_MED,
FADE_MODE_HIGH,
FADE_MODE_360,
FADE_MODE_PS3,
FADE_MODE_LEVEL,
FADE_MODE_COUNT,
};
struct FadeData_t
{
float m_flPixelMin;
float m_flPixelMax;
float m_flWidth;
float m_flFadeDistScale;
};
extern FadeData_t g_aFadeData[FADE_MODE_COUNT];
extern uint32 g_nResourceFrameCount;
#endif

View File

@ -0,0 +1,65 @@
#ifndef TIER2_LOGGING_H
#define TIER2_LOGGING_H
#if defined( COMPILER_MSVC )
#pragma once
#endif
#include "logging.h"
const int MAX_SIMULTANEOUS_LOGGING_FILE_COUNT = 16;
const int INVALID_LOGGING_FILE_HANDLE = -1;
typedef int LoggingFileHandle_t;
typedef void* FileHandle_t;
#define FILELOGGINGLISTENER_INTERFACE_VERSION "FileLoggingListener001"
abstract_class IFileLoggingListener : public ILoggingListener
{
public:
virtual void Log(const LoggingContext_t * pContext, const char* pMessage) = 0;
virtual LoggingFileHandle_t BeginLoggingToFile(const char* pFilename, const char* pOptions, const char* pPathID = NULL) = 0;
virtual void EndLoggingToFile(LoggingFileHandle_t fileHandle) = 0;
virtual void AssignLogChannel(LoggingChannelID_t channelID, LoggingFileHandle_t loggingFileHandle) = 0;
virtual void UnassignLogChannel(LoggingChannelID_t channelID) = 0;
virtual void AssignAllLogChannels(LoggingFileHandle_t loggingFileHandle) = 0;
virtual void UnassignAllLogChannels() = 0;
};
class CFileLoggingListener : public IFileLoggingListener
{
public:
CFileLoggingListener();
~CFileLoggingListener();
virtual void Log(const LoggingContext_t* pContext, const char* pMessage);
virtual LoggingFileHandle_t BeginLoggingToFile(const char* pFilename, const char* pOptions, const char* pPathID = NULL);
virtual void EndLoggingToFile(LoggingFileHandle_t fileHandle);
virtual void AssignLogChannel(LoggingChannelID_t channelID, LoggingFileHandle_t loggingFileHandle);
virtual void UnassignLogChannel(LoggingChannelID_t channelID);
virtual void AssignAllLogChannels(LoggingFileHandle_t loggingFileHandle);
virtual void UnassignAllLogChannels();
private:
int GetUnusedFileInfo() const;
struct FileInfo_t
{
FileHandle_t m_FileHandle;
bool IsOpen() const { return m_FileHandle != 0; }
void Reset() { m_FileHandle = 0; }
};
FileInfo_t m_OpenFiles[MAX_SIMULTANEOUS_LOGGING_FILE_COUNT];
int m_FileIndices[MAX_LOGGING_CHANNEL_COUNT];
};
#endif

45
SpyCustom/sdk/tier3.h Normal file
View File

@ -0,0 +1,45 @@
#ifndef TIER3_H
#define TIER3_H
#if defined( _WIN32 )
#pragma once
#endif
#include "tier2.h"
void ConnectTier3Libraries(CreateInterfaceFn* pFactoryList, int nFactoryCount);
void DisconnectTier3Libraries();
template< class IInterface, int ConVarFlag = 0 >
class CTier3AppSystem : public CTier2AppSystem< IInterface, ConVarFlag >
{
typedef CTier2AppSystem< IInterface, ConVarFlag > BaseClass;
public:
virtual bool Connect(CreateInterfaceFn factory)
{
if (!BaseClass::Connect(factory))
return false;
ConnectTier3Libraries(&factory, 1);
return true;
}
virtual void Disconnect()
{
DisconnectTier3Libraries();
BaseClass::Disconnect();
}
virtual AppSystemTier_t GetTier()
{
return APP_SYSTEM_TIER3;
}
};
#endif

View File

@ -0,0 +1,50 @@
#ifndef TIMEDEVENT_H
#define TIMEDEVENT_H
#ifdef _WIN32
#pragma once
#endif
class TimedEvent
{
public:
TimedEvent()
{
m_TimeBetweenEvents = -1;
m_fNextEvent = 0;
}
inline void Init(float rate)
{
m_TimeBetweenEvents = 1.0f / rate;
m_fNextEvent = 0;
}
inline void ResetRate(float rate)
{
m_TimeBetweenEvents = 1.0f / rate;
}
inline bool NextEvent(float& curDelta)
{
Assert(m_TimeBetweenEvents != -1);
if (curDelta >= m_fNextEvent)
{
curDelta -= m_fNextEvent;
m_fNextEvent = m_TimeBetweenEvents;
return true;
}
else
{
m_fNextEvent -= curDelta;
return false;
}
}
private:
float m_TimeBetweenEvents;
float m_fNextEvent;
};
#endif

149
SpyCustom/sdk/timeutils.h Normal file
View File

@ -0,0 +1,149 @@
#ifndef TIMEUTILS_H
#define TIMEUTILS_H
#ifdef _WIN32
#pragma once
#endif
#include <limits.h>
#include <math.h>
#include "dbg.h"
enum RoundStyle_t
{
ROUND_NEAREST,
ROUND_DOWN,
ROUND_UP,
};
class DmeTime_t;
class DmeFramerate_t
{
public:
DmeFramerate_t(float fps);
DmeFramerate_t(int fps = 0);
DmeFramerate_t(const DmeFramerate_t& src) : m_num(src.m_num), m_den(src.m_den) {}
void SetFramerate(float flFrameRate);
void SetFramerate(int fps);
void SetFramerateNTSC(int multiplier = 30);
float GetFramesPerSecond() const;
DmeTime_t GetTimePerFrame() const;
bool operator==(DmeFramerate_t f) const { return m_num == f.m_num && m_den == f.m_den; }
bool operator!=(DmeFramerate_t f) const { return m_num != f.m_num && m_den != f.m_den; }
bool operator< (DmeFramerate_t f) const { return m_num * (int)f.m_den < f.m_num* (int)m_den; }
bool operator> (DmeFramerate_t f) const { return m_num * (int)f.m_den > f.m_num * (int)m_den; }
bool operator<=(DmeFramerate_t f) const { return m_num * (int)f.m_den <= f.m_num * (int)m_den; }
bool operator>=(DmeFramerate_t f) const { return m_num * (int)f.m_den >= f.m_num * (int)m_den; }
DmeFramerate_t operator*(int i) const { return DmeFramerate_t(m_num * i, m_den); }
DmeFramerate_t operator/(int i) const { return DmeFramerate_t(m_num, m_den * i); }
DmeFramerate_t operator*=(int i) { Assert(abs(m_num * i) <= USHRT_MAX); m_num *= (unsigned short)i; return *this; }
DmeFramerate_t operator/=(int i) { Assert(abs(m_den * i) <= USHRT_MAX); m_den *= (unsigned short)i; return *this; }
private:
DmeFramerate_t(int nNumerator, int nDenominator);
unsigned short m_num;
unsigned short m_den;
friend class DmeTime_t;
};
#define DMETIME_ZERO DmeTime_t(0)
#define DMETIME_MINDELTA DmeTime_t::MinTimeDelta()
#define DMETIME_MINTIME DmeTime_t::MinTime()
#define DMETIME_MAXTIME DmeTime_t::MaxTime()
#define DMETIME_INVALID DmeTime_t::InvalidTime()
class DmeTime_t
{
public:
DmeTime_t() : m_tms(INT_MIN) {}
explicit DmeTime_t(int tms) : m_tms(tms) {}
explicit DmeTime_t(float sec) : m_tms(RoundSecondsToTMS(sec)) {}
explicit DmeTime_t(double sec) : m_tms(RoundSecondsToTMS(sec)) {}
DmeTime_t(int frame, DmeFramerate_t framerate);
friend bool operator==(DmeTime_t a, DmeTime_t b) { return a.m_tms == b.m_tms; }
friend bool operator!=(DmeTime_t a, DmeTime_t b) { return a.m_tms != b.m_tms; }
friend bool operator< (DmeTime_t a, DmeTime_t b) { return a.m_tms < b.m_tms; }
friend bool operator> (DmeTime_t a, DmeTime_t b) { return a.m_tms > b.m_tms; }
friend bool operator<=(DmeTime_t a, DmeTime_t b) { return a.m_tms <= b.m_tms; }
friend bool operator>=(DmeTime_t a, DmeTime_t b) { return a.m_tms >= b.m_tms; }
friend DmeTime_t operator%(DmeTime_t a, DmeTime_t b) { return DmeTime_t(a.m_tms % b.m_tms); }
friend DmeTime_t operator+(DmeTime_t a, DmeTime_t b) { return DmeTime_t(a.m_tms + b.m_tms); }
friend DmeTime_t operator-(DmeTime_t a, DmeTime_t b) { return DmeTime_t(a.m_tms - b.m_tms); }
DmeTime_t operator-() const { return DmeTime_t(-m_tms); }
DmeTime_t operator+=(DmeTime_t t) { m_tms += t.m_tms; return *this; }
DmeTime_t operator-=(DmeTime_t t) { m_tms -= t.m_tms; return *this; }
friend DmeTime_t operator*(DmeTime_t t, float f) { t *= f; return t; }
friend DmeTime_t operator*(float f, DmeTime_t t) { t *= f; return t; }
friend DmeTime_t operator/(DmeTime_t t, float f) { t /= f; return t; }
friend float operator/(DmeTime_t n, DmeTime_t d) { return float(n.m_tms / double(d.m_tms)); }
DmeTime_t operator*=(float f);
DmeTime_t operator/=(float f);
DmeTime_t operator++() { ++m_tms; return *this; }
DmeTime_t operator--() { --m_tms; return *this; }
DmeTime_t operator++(int) { DmeTime_t t = *this; ++m_tms; return t; }
DmeTime_t operator--(int) { DmeTime_t t = *this; --m_tms; return t; }
bool IsValid() const { return m_tms != INT_MIN; }
static DmeTime_t InvalidTime() { return DmeTime_t(INT_MIN); }
static DmeTime_t MinTime() { return DmeTime_t(INT_MIN + 1); }
static DmeTime_t MaxTime() { return DmeTime_t(INT_MAX); }
static DmeTime_t MinTimeDelta() { return DmeTime_t(1); }
int GetTenthsOfMS() const { return m_tms; }
float GetSeconds() const { return m_tms * 0.0001f; }
void SetTenthsOfMS(int tms) { m_tms = tms; }
void SetSeconds(float sec) { m_tms = RoundSecondsToTMS(sec); }
void Clamp(DmeTime_t lo, DmeTime_t hi);
bool IsInRange(DmeTime_t lo, DmeTime_t hi) const;
friend float GetFractionOfTimeBetween(DmeTime_t t, DmeTime_t start, DmeTime_t end, bool bClamp);
friend float GetFractionOfTime(DmeTime_t t, DmeTime_t duration, bool bClamp);
friend int FrameForTime(DmeTime_t t, DmeFramerate_t framerate);
friend DmeTime_t abs(DmeTime_t t) { return t.m_tms >= 0 ? t : -t; }
int CurrentFrame(DmeFramerate_t framerate, RoundStyle_t roundStyle = ROUND_DOWN) const;
DmeTime_t TimeAtCurrentFrame(DmeFramerate_t framerate, RoundStyle_t roundStyle = ROUND_DOWN) const;
DmeTime_t TimeAtNextFrame(DmeFramerate_t framerate) const;
DmeTime_t TimeAtPrevFrame(DmeFramerate_t framerate) const;
private:
explicit DmeTime_t(int64 tms) : m_tms(int(tms)) {}
static int RoundSecondsToTMS(float sec);
static int RoundSecondsToTMS(double sec);
int m_tms;
};
float GetFractionOfTimeBetween(DmeTime_t t, DmeTime_t start, DmeTime_t end, bool bClamp = false);
float GetFractionOfTime(DmeTime_t t, DmeTime_t duration, bool bClamp = false);
class CUtlBuffer;
bool Serialize(CUtlBuffer& buf, const DmeTime_t& src);
bool Unserialize(CUtlBuffer& buf, DmeTime_t& dest);
#endif

29
SpyCustom/sdk/touchlink.h Normal file
View File

@ -0,0 +1,29 @@
#ifndef TOUCHLINK_H
#define TOUCHLINK_H
#ifdef _WIN32
#pragma once
#endif
enum touchlink_flags_t
{
FTOUCHLINK_START_TOUCH = 0x00000001,
};
struct touchlink_t
{
#if defined( CLIENT_DLL )
C_BaseEntity* entityTouched;
#else
EHANDLE entityTouched;
#endif
int touchStamp;
touchlink_t* nextLink;
touchlink_t* prevLink;
int flags;
};
#define TOUCHSTAMP_EVENT_DRIVEN -1
#endif

48
SpyCustom/sdk/trace.h Normal file
View File

@ -0,0 +1,48 @@
#ifndef TRACE_H
#define TRACE_H
#ifdef _WIN32
#pragma once
#endif
#include "mathlib.h"
#define DISPSURF_FLAG_SURFACE (1<<0)
#define DISPSURF_FLAG_WALKABLE (1<<1)
#define DISPSURF_FLAG_BUILDABLE (1<<2)
#define DISPSURF_FLAG_SURFPROP1 (1<<3)
#define DISPSURF_FLAG_SURFPROP2 (1<<4)
class CBaseTrace
{
public:
bool IsDispSurface(void) { return ((dispFlags & DISPSURF_FLAG_SURFACE) != 0); }
bool IsDispSurfaceWalkable(void) { return ((dispFlags & DISPSURF_FLAG_WALKABLE) != 0); }
bool IsDispSurfaceBuildable(void) { return ((dispFlags & DISPSURF_FLAG_BUILDABLE) != 0); }
bool IsDispSurfaceProp1(void) { return ((dispFlags & DISPSURF_FLAG_SURFPROP1) != 0); }
bool IsDispSurfaceProp2(void) { return ((dispFlags & DISPSURF_FLAG_SURFPROP2) != 0); }
public:
Vector startpos;
Vector endpos;
BYTE plane[20];
float fraction;
int contents;
unsigned short dispFlags;
bool allsolid;
bool startsolid;
CBaseTrace() {}
private:
CBaseTrace(const CBaseTrace& vOther);
};
#endif

948
SpyCustom/sdk/tslist.h Normal file
View File

@ -0,0 +1,948 @@
#ifndef TSLIST_H
#define TSLIST_H
#if defined( _WIN32 )
#pragma once
#pragma warning( push )
#pragma warning( disable : 4700 )
#endif
#if defined( USE_NATIVE_SLIST ) && !defined( _X360 )
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "dbg.h"
#include "threadtools.h"
#include "memalloc.h"
#include "memdbgoff.h"
#if defined( _X360 )
#define USE_NATIVE_SLIST
#endif
#if defined( PLATFORM_64BITS )
#if defined (PLATFORM_WINDOWS)
#else
typedef __int128_t int128;
#define int128_zero() 0
#endif
#define TSLIST_HEAD_ALIGNMENT 16
#define TSLIST_NODE_ALIGNMENT 16
#ifdef POSIX
inline bool ThreadInterlockedAssignIf128(int128 volatile* pDest, const int128& value, const int128& comparand)
{
int128 local_comparand = comparand;
return __sync_bool_compare_and_swap(pDest, local_comparand, value);
}
#endif
inline bool ThreadInterlockedAssignIf64x128(volatile int128* pDest, const int128& value, const int128& comperand)
{
return ThreadInterlockedAssignIf128(pDest, value, comperand);
}
#else
#define TSLIST_HEAD_ALIGNMENT 8
#define TSLIST_NODE_ALIGNMENT 8
inline bool ThreadInterlockedAssignIf64x128(volatile int64* pDest, const int64 value, const int64 comperand)
{
return ThreadInterlockedAssignIf64(pDest, value, comperand);
}
#endif
#ifdef _MSC_VER
#define TSLIST_HEAD_ALIGN DECL_ALIGN(TSLIST_HEAD_ALIGNMENT)
#define TSLIST_NODE_ALIGN DECL_ALIGN(TSLIST_NODE_ALIGNMENT)
#define TSLIST_HEAD_ALIGN_POST
#define TSLIST_NODE_ALIGN_POST
#elif defined( GNUC )
#define TSLIST_HEAD_ALIGN
#define TSLIST_NODE_ALIGN
#define TSLIST_HEAD_ALIGN_POST DECL_ALIGN(TSLIST_HEAD_ALIGNMENT)
#define TSLIST_NODE_ALIGN_POST DECL_ALIGN(TSLIST_NODE_ALIGNMENT)
#elif defined( _PS3 )
#define TSLIST_HEAD_ALIGNMENT 8
#define TSLIST_NODE_ALIGNMENT 8
#define TSLIST_HEAD_ALIGN ALIGN8
#define TSLIST_NODE_ALIGN ALIGN8
#define TSLIST_HEAD_ALIGN_POST ALIGN8_POST
#define TSLIST_NODE_ALIGN_POST ALIGN8_POST
#else
#error
#endif
PLATFORM_INTERFACE bool RunTSQueueTests(int nListSize = 10000, int nTests = 1);
PLATFORM_INTERFACE bool RunTSListTests(int nListSize = 10000, int nTests = 1);
#ifdef USE_NATIVE_SLIST
typedef SLIST_ENTRY TSLNodeBase_t;
typedef SLIST_HEADER TSLHead_t;
#else
struct TSLIST_NODE_ALIGN TSLNodeBase_t
{
TSLNodeBase_t* Next;
} TSLIST_NODE_ALIGN_POST;
union TSLIST_HEAD_ALIGN TSLHead_t
{
struct Value_t
{
TSLNodeBase_t* Next;
#ifdef VALVE_BIG_ENDIAN
int16 Sequence;
int16 Depth;
#else
int16 Depth;
int16 Sequence;
#endif
#ifdef PLATFORM_64BITS
int32 Padding;
#endif
} value;
struct Value32_t
{
TSLNodeBase_t* Next_do_not_use_me;
int32 DepthAndSequence;
} value32;
#ifdef PLATFORM_64BITS
int128 value64x128;
#else
int64 value64x128;
#endif
} TSLIST_HEAD_ALIGN_POST;
#endif
class CTSListBase
{
public:
static void* operator new(size_t size)
{
CTSListBase* pNode = (CTSListBase*)MemAlloc_AllocAlignedFileLine(size, TSLIST_HEAD_ALIGNMENT, __FILE__, __LINE__);
return pNode;
}
static void* operator new(size_t size, int nBlockUse, const char* pFileName, int nLine)
{
CTSListBase* pNode = (CTSListBase*)MemAlloc_AllocAlignedFileLine(size, TSLIST_HEAD_ALIGNMENT, pFileName, nLine);
return pNode;
}
static void operator delete(void* p)
{
MemAlloc_FreeAligned(p);
}
static void operator delete(void* p, int nBlockUse, const char* pFileName, int nLine)
{
MemAlloc_FreeAligned(p);
}
private:
static void* operator new[](size_t size);
static void operator delete[](void* p);
public:
CTSListBase()
{
if (((size_t)&m_Head) % TSLIST_HEAD_ALIGNMENT != 0)
{
Error("CTSListBase: Misaligned list\n");
DebuggerBreak();
}
#ifdef USE_NATIVE_SLIST
InitializeSListHead(&m_Head);
#elif defined(PLATFORM_64BITS)
m_Head.value64x128 = int128_zero();
#else
m_Head.value64x128 = (int64)0;
#endif
}
~CTSListBase()
{
Detach();
}
TSLNodeBase_t* Push(TSLNodeBase_t* pNode)
{
#ifdef _DEBUG
if ((size_t)pNode % TSLIST_NODE_ALIGNMENT != 0)
{
Error("CTSListBase: Misaligned node\n");
DebuggerBreak();
}
#endif
#ifdef USE_NATIVE_SLIST
#ifdef _X360
return (TSLNodeBase_t*)InterlockedPushEntrySListRelease(&m_Head, pNode);
#else
return (TSLNodeBase_t*)InterlockedPushEntrySList(&m_Head, pNode);
#endif
#else
TSLHead_t oldHead;
TSLHead_t newHead;
#if defined( PLATFORM_PS3 ) || defined( PLATFORM_X360 )
__lwsync();
#endif
#ifdef PLATFORM_64BITS
newHead.value.Padding = 0;
#endif
for (;; )
{
oldHead.value64x128 = m_Head.value64x128;
pNode->Next = oldHead.value.Next;
newHead.value.Next = pNode;
newHead.value32.DepthAndSequence = oldHead.value32.DepthAndSequence + 0x10001;
if (ThreadInterlockedAssignIf64x128(&m_Head.value64x128, newHead.value64x128, oldHead.value64x128))
{
break;
}
ThreadPause();
};
return (TSLNodeBase_t*)oldHead.value.Next;
#endif
}
TSLNodeBase_t* Pop()
{
#ifdef USE_NATIVE_SLIST
#ifdef _X360
TSLNodeBase_t* pNode = (TSLNodeBase_t*)InterlockedPopEntrySListAcquire(&m_Head);
#else
TSLNodeBase_t* pNode = (TSLNodeBase_t*)InterlockedPopEntrySList(&m_Head);
#endif
return pNode;
#else
TSLHead_t oldHead;
TSLHead_t newHead;
#ifdef PLATFORM_64BITS
newHead.value.Padding = 0;
#endif
for (;; )
{
oldHead.value64x128 = m_Head.value64x128;
if (!oldHead.value.Next)
return NULL;
newHead.value.Next = oldHead.value.Next->Next;
newHead.value32.DepthAndSequence = oldHead.value32.DepthAndSequence - 1;
if (ThreadInterlockedAssignIf64x128(&m_Head.value64x128, newHead.value64x128, oldHead.value64x128))
{
#if defined( PLATFORM_PS3 ) || defined( PLATFORM_X360 )
__lwsync();
#endif
break;
}
ThreadPause();
};
return (TSLNodeBase_t*)oldHead.value.Next;
#endif
}
TSLNodeBase_t* Detach()
{
#ifdef USE_NATIVE_SLIST
TSLNodeBase_t* pBase = (TSLNodeBase_t*)InterlockedFlushSList(&m_Head);
#if defined( _X360 ) || defined( _PS3 )
__lwsync();
#endif
return pBase;
#else
TSLHead_t oldHead;
TSLHead_t newHead;
#ifdef PLATFORM_64BITS
newHead.value.Padding = 0;
#endif
do
{
ThreadPause();
oldHead.value64x128 = m_Head.value64x128;
if (!oldHead.value.Next)
return NULL;
newHead.value.Next = NULL;
newHead.value32.DepthAndSequence = oldHead.value32.DepthAndSequence & 0xffff0000;
} while (!ThreadInterlockedAssignIf64x128(&m_Head.value64x128, newHead.value64x128, oldHead.value64x128));
return (TSLNodeBase_t*)oldHead.value.Next;
#endif
}
TSLHead_t* AccessUnprotected()
{
return &m_Head;
}
int Count() const
{
#ifdef USE_NATIVE_SLIST
return QueryDepthSList(const_cast<TSLHead_t*>(&m_Head));
#else
return m_Head.value.Depth;
#endif
}
private:
TSLHead_t m_Head;
} TSLIST_HEAD_ALIGN_POST;
template <typename T>
class TSLIST_HEAD_ALIGN CTSSimpleList : public CTSListBase
{
public:
void Push(T* pNode)
{
Assert(sizeof(T) >= sizeof(TSLNodeBase_t));
CTSListBase::Push((TSLNodeBase_t*)pNode);
}
T* Pop()
{
return (T*)CTSListBase::Pop();
}
} TSLIST_HEAD_ALIGN_POST;
template< class T >
class TSLIST_HEAD_ALIGN CTSPool : public CTSListBase
{
struct TSLIST_NODE_ALIGN simpleTSPoolStruct_t : public TSLNodeBase_t
{
T elem;
} TSLIST_NODE_ALIGN_POST;
public:
~CTSPool()
{
Purge();
}
void Purge()
{
simpleTSPoolStruct_t* pNode = NULL;
while (1)
{
pNode = (simpleTSPoolStruct_t*)CTSListBase::Pop();
if (!pNode)
break;
delete pNode;
}
}
void PutObject(T* pInfo)
{
char* pElem = (char*)pInfo;
pElem -= offsetof(simpleTSPoolStruct_t, elem);
simpleTSPoolStruct_t* pNode = (simpleTSPoolStruct_t*)pElem;
CTSListBase::Push(pNode);
}
T* GetObject()
{
simpleTSPoolStruct_t* pNode = (simpleTSPoolStruct_t*)CTSListBase::Pop();
if (!pNode)
{
pNode = new simpleTSPoolStruct_t;
}
return &pNode->elem;
}
FORCEINLINE T* Get()
{
return GetObject();
}
} TSLIST_HEAD_ALIGN_POST;
template <typename T>
class TSLIST_HEAD_ALIGN CTSList : public CTSListBase
{
public:
struct TSLIST_NODE_ALIGN Node_t : public TSLNodeBase_t
{
Node_t() {}
Node_t(const T& init) : elem(init) {}
T elem;
static void* operator new(size_t size)
{
Node_t* pNode = (Node_t*)MemAlloc_AllocAlignedFileLine(size, TSLIST_NODE_ALIGNMENT, __FILE__, __LINE__);
return pNode;
}
static void* operator new(size_t size, int nBlockUse, const char* pFileName, int nLine)
{
Node_t* pNode = (Node_t*)MemAlloc_AllocAlignedFileLine(size, TSLIST_NODE_ALIGNMENT, pFileName, nLine);
return pNode;
}
static void operator delete(void* p)
{
MemAlloc_FreeAligned(p);
}
static void operator delete(void* p, int nBlockUse, const char* pFileName, int nLine)
{
MemAlloc_FreeAligned(p);
}
} TSLIST_NODE_ALIGN_POST;
~CTSList()
{
Purge();
}
void Purge()
{
Node_t* pCurrent = Detach();
Node_t* pNext;
while (pCurrent)
{
pNext = (Node_t*)pCurrent->Next;
delete pCurrent;
pCurrent = pNext;
}
}
void RemoveAll()
{
Purge();
}
Node_t* Push(Node_t* pNode)
{
return (Node_t*)CTSListBase::Push(pNode);
}
Node_t* Pop()
{
return (Node_t*)CTSListBase::Pop();
}
void PushItem(const T& init)
{
Push(new Node_t(init));
}
bool PopItem(T* pResult)
{
Node_t* pNode = Pop();
if (!pNode)
return false;
*pResult = pNode->elem;
delete pNode;
return true;
}
Node_t* Detach()
{
return (Node_t*)CTSListBase::Detach();
}
} TSLIST_HEAD_ALIGN_POST;
template <typename T>
class TSLIST_HEAD_ALIGN CTSListWithFreeList : public CTSListBase
{
public:
struct TSLIST_NODE_ALIGN Node_t : public TSLNodeBase_t
{
Node_t() {}
Node_t(const T& init) : elem(init) {}
T elem;
} TSLIST_NODE_ALIGN_POST;
~CTSListWithFreeList()
{
Purge();
}
void Purge()
{
Node_t* pCurrent = Detach();
Node_t* pNext;
while (pCurrent)
{
pNext = (Node_t*)pCurrent->Next;
delete pCurrent;
pCurrent = pNext;
}
pCurrent = (Node_t*)m_FreeList.Detach();
while (pCurrent)
{
pNext = (Node_t*)pCurrent->Next;
delete pCurrent;
pCurrent = pNext;
}
}
void RemoveAll()
{
Node_t* pCurrent = Detach();
Node_t* pNext;
while (pCurrent)
{
pNext = (Node_t*)pCurrent->Next;
m_FreeList.Push(pCurrent);
pCurrent = pNext;
}
}
Node_t* Push(Node_t* pNode)
{
return (Node_t*)CTSListBase::Push(pNode);
}
Node_t* Pop()
{
return (Node_t*)CTSListBase::Pop();
}
void PushItem(const T& init)
{
Node_t* pNode = (Node_t*)m_FreeList.Pop();
if (!pNode)
{
pNode = new Node_t;
}
pNode->elem = init;
Push(pNode);
}
bool PopItem(T* pResult)
{
Node_t* pNode = Pop();
if (!pNode)
return false;
*pResult = pNode->elem;
m_FreeList.Push(pNode);
return true;
}
Node_t* Detach()
{
return (Node_t*)CTSListBase::Detach();
}
void FreeNode(Node_t* pNode)
{
m_FreeList.Push(pNode);
}
private:
CTSListBase m_FreeList;
} TSLIST_HEAD_ALIGN_POST;
template <typename T, bool bTestOptimizer = false>
class TSLIST_HEAD_ALIGN CTSQueue
{
public:
static void* operator new(size_t size)
{
CTSQueue* pNode = (CTSQueue*)MemAlloc_AllocAlignedFileLine(size, TSLIST_HEAD_ALIGNMENT, __FILE__, __LINE__);
return pNode;
}
static void* operator new(size_t size, int nBlockUse, const char* pFileName, int nLine)
{
CTSQueue* pNode = (CTSQueue*)MemAlloc_AllocAlignedFileLine(size, TSLIST_HEAD_ALIGNMENT, pFileName, nLine);
return pNode;
}
static void operator delete(void* p)
{
MemAlloc_FreeAligned(p);
}
static void operator delete(void* p, int nBlockUse, const char* pFileName, int nLine)
{
MemAlloc_FreeAligned(p);
}
private:
static void* operator new[](size_t size) throw()
{
return NULL;
}
static void operator delete [](void* p)
{
}
public:
struct TSLIST_NODE_ALIGN Node_t
{
static void* operator new(size_t size)
{
Node_t* pNode = (Node_t*)MemAlloc_AllocAlignedFileLine(size, TSLIST_HEAD_ALIGNMENT, __FILE__, __LINE__);
return pNode;
}
static void* operator new(size_t size, int nBlockUse, const char* pFileName, int nLine)
{
Node_t* pNode = (Node_t*)MemAlloc_AllocAlignedFileLine(size, TSLIST_HEAD_ALIGNMENT, pFileName, nLine);
return pNode;
}
static void operator delete(void* p)
{
MemAlloc_FreeAligned(p);
}
static void operator delete(void* p, int nBlockUse, const char* pFileName, int nLine)
{
MemAlloc_FreeAligned(p);
}
Node_t() {}
Node_t(const T& init) : elem(init) {}
Node_t* pNext;
T elem;
} TSLIST_NODE_ALIGN_POST;
union TSLIST_HEAD_ALIGN NodeLink_t
{
static void* operator new(size_t size)
{
NodeLink_t* pNode = (NodeLink_t*)MemAlloc_AllocAlignedFileLine(size, TSLIST_HEAD_ALIGNMENT, __FILE__, __LINE__);
return pNode;
}
static void operator delete(void* p)
{
MemAlloc_FreeAligned(p);
}
struct Value_t
{
Node_t* pNode;
intp sequence;
} value;
#ifdef PLATFORM_64BITS
int128 value64x128;
#else
int64 value64x128;
#endif
} TSLIST_HEAD_ALIGN_POST;
CTSQueue()
{
COMPILE_TIME_ASSERT(sizeof(Node_t) >= sizeof(TSLNodeBase_t));
if (((size_t)&m_Head) % TSLIST_HEAD_ALIGNMENT != 0)
{
Error("CTSQueue: Misaligned queue\n");
DebuggerBreak();
}
if (((size_t)&m_Tail) % TSLIST_HEAD_ALIGNMENT != 0)
{
Error("CTSQueue: Misaligned queue\n");
DebuggerBreak();
}
m_Count = 0;
m_Head.value.sequence = m_Tail.value.sequence = 0;
m_Head.value.pNode = m_Tail.value.pNode = new Node_t;
m_Head.value.pNode->pNext = End();
}
~CTSQueue()
{
Purge();
Assert(m_Count == 0);
Assert(m_Head.value.pNode == m_Tail.value.pNode);
Assert(m_Head.value.pNode->pNext == End());
delete m_Head.value.pNode;
}
void Purge()
{
if (IsDebug())
{
ValidateQueue();
}
Node_t* pNode;
while ((pNode = Pop()) != NULL)
{
delete pNode;
}
while ((pNode = (Node_t*)m_FreeNodes.Pop()) != NULL)
{
delete pNode;
}
Assert(m_Count == 0);
Assert(m_Head.value.pNode == m_Tail.value.pNode);
Assert(m_Head.value.pNode->pNext == End());
m_Head.value.sequence = m_Tail.value.sequence = 0;
}
void RemoveAll()
{
if (IsDebug())
{
ValidateQueue();
}
Node_t* pNode;
while ((pNode = Pop()) != NULL)
{
m_FreeNodes.Push((TSLNodeBase_t*)pNode);
}
}
bool ValidateQueue()
{
if (IsDebug())
{
bool bResult = true;
int nNodes = 0;
if (m_Tail.value.pNode->pNext != End())
{
DebuggerBreakIfDebugging();
bResult = false;
}
if (m_Count == 0)
{
if (m_Head.value.pNode != m_Tail.value.pNode)
{
DebuggerBreakIfDebugging();
bResult = false;
}
}
Node_t* pNode = m_Head.value.pNode;
while (pNode != End())
{
nNodes++;
pNode = pNode->pNext;
}
nNodes--;
if (nNodes != m_Count)
{
DebuggerBreakIfDebugging();
bResult = false;
}
if (!bResult)
{
Msg("Corrupt CTSQueueDetected");
}
return bResult;
}
else
{
return true;
}
}
void FinishPush(Node_t* pNode, const NodeLink_t& oldTail)
{
NodeLink_t newTail;
newTail.value.pNode = pNode;
newTail.value.sequence = oldTail.value.sequence + 1;
ThreadMemoryBarrier();
InterlockedCompareExchangeNodeLink(&m_Tail, newTail, oldTail);
}
Node_t* Push(Node_t* pNode)
{
#ifdef _DEBUG
if ((size_t)pNode % TSLIST_NODE_ALIGNMENT != 0)
{
Error("CTSListBase: Misaligned node\n");
DebuggerBreak();
}
#endif
NodeLink_t oldTail;
pNode->pNext = End();
for (;; )
{
oldTail.value.sequence = m_Tail.value.sequence;
oldTail.value.pNode = m_Tail.value.pNode;
if (InterlockedCompareExchangeNode(&(oldTail.value.pNode->pNext), pNode, End()) == End())
{
break;
}
else
{
FinishPush(oldTail.value.pNode->pNext, oldTail);
}
}
FinishPush(pNode, oldTail);
m_Count++;
return oldTail.value.pNode;
}
Node_t* Pop()
{
#define TSQUEUE_BAD_NODE_LINK ( (Node_t *)INT_TO_POINTER( 0xdeadbeef ) )
NodeLink_t* volatile pHead = &m_Head;
NodeLink_t* volatile pTail = &m_Tail;
Node_t* volatile* pHeadNode = &m_Head.value.pNode;
volatile intp* volatile pHeadSequence = &m_Head.value.sequence;
Node_t* volatile* pTailNode = &pTail->value.pNode;
NodeLink_t head;
NodeLink_t newHead;
Node_t* pNext;
intp tailSequence;
T elem;
for (;; )
{
head.value.sequence = *pHeadSequence;
ThreadMemoryBarrier();
head.value.pNode = *pHeadNode;
tailSequence = pTail->value.sequence;
pNext = head.value.pNode->pNext;
if (!pNext || head.value.sequence != *pHeadSequence)
continue;
if (bTestOptimizer)
{
if (pNext == TSQUEUE_BAD_NODE_LINK)
{
Msg("Bad node link detected\n");
continue;
}
}
if (head.value.pNode == *pTailNode)
{
if (pNext == End())
return NULL;
NodeLink_t& oldTail = head;
oldTail.value.sequence = tailSequence;
FinishPush(pNext, oldTail);
continue;
}
if (pNext != End())
{
elem = pNext->elem;
newHead.value.pNode = pNext;
newHead.value.sequence = head.value.sequence + 1;
if (InterlockedCompareExchangeNodeLink(pHead, newHead, head))
{
ThreadMemoryBarrier();
if (bTestOptimizer)
{
head.value.pNode->pNext = TSQUEUE_BAD_NODE_LINK;
}
break;
}
}
}
m_Count--;
head.value.pNode->elem = elem;
return head.value.pNode;
}
void FreeNode(Node_t* pNode)
{
m_FreeNodes.Push((TSLNodeBase_t*)pNode);
}
void PushItem(const T& init)
{
Node_t* pNode = (Node_t*)m_FreeNodes.Pop();
if (pNode)
{
pNode->elem = init;
}
else
{
pNode = new Node_t(init);
}
Push(pNode);
}
bool PopItem(T* pResult)
{
Node_t* pNode = Pop();
if (!pNode)
return false;
*pResult = pNode->elem;
m_FreeNodes.Push((TSLNodeBase_t*)pNode);
return true;
}
int Count() const
{
return m_Count;
}
private:
Node_t* End() { return (Node_t*)this; }
Node_t* InterlockedCompareExchangeNode(Node_t* volatile* ppNode, Node_t* value, Node_t* comperand)
{
return (Node_t*)::ThreadInterlockedCompareExchangePointer((void**)ppNode, value, comperand);
}
bool InterlockedCompareExchangeNodeLink(NodeLink_t volatile* pLink, const NodeLink_t& value, const NodeLink_t& comperand)
{
return ThreadInterlockedAssignIf64x128(&pLink->value64x128, value.value64x128, comperand.value64x128);
}
NodeLink_t m_Head;
NodeLink_t m_Tail;
CInterlockedInt m_Count;
CTSListBase m_FreeNodes;
} TSLIST_NODE_ALIGN_POST;
#if defined( _WIN32 )
#pragma warning( pop )
#endif
#endif

37
SpyCustom/sdk/uniqueid.h Normal file
View File

@ -0,0 +1,37 @@
#ifndef UNIQUEID_H
#define UNIQUEID_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
struct UniqueId_t;
class CUtlBuffer;
struct UniqueId_t
{
unsigned char m_Value[16];
};
void CreateUniqueId(UniqueId_t* pDest);
void InvalidateUniqueId(UniqueId_t* pDest);
bool IsUniqueIdValid(const UniqueId_t& id);
bool IsUniqueIdEqual(const UniqueId_t& id1, const UniqueId_t& id2);
void UniqueIdToString(const UniqueId_t& id, char* pBuf, int nMaxLen);
bool UniqueIdFromString(UniqueId_t* pDest, const char* pBuf, int nMaxLen = 0);
void CopyUniqueId(const UniqueId_t& src, UniqueId_t* pDest);
bool Serialize(CUtlBuffer& buf, const UniqueId_t& src);
bool Unserialize(CUtlBuffer& buf, UniqueId_t& dest);
inline bool operator ==(const UniqueId_t& lhs, const UniqueId_t& rhs)
{
return !Q_memcmp((void*)&lhs.m_Value[0], (void*)&rhs.m_Value[0], sizeof(lhs.m_Value));
}
#endif

295
SpyCustom/sdk/usercmd.h Normal file
View File

@ -0,0 +1,295 @@
#if !defined( USERCMD_H )
#define USERCMD_H
#ifdef _WIN32
#pragma once
#endif
#include "vector.h"
#include "utlvector.h"
#include "imovehelper.h"
#include "checksum_crc.h"
class bf_read;
class bf_write;
class CEntityGroundContact
{
public:
int entindex;
float minheight;
float maxheight;
};
#ifdef DOTA_DLL
class CUnitOrders
{
public:
CUnitOrders()
{
m_nOrderSequenceNumber = 0;
}
void Reset(void)
{
m_nUnits.RemoveAll();
m_nOrderType = 0;
m_nTargetIndex = 0;
m_vPosition = vec3_origin;
m_nAbilityIndex = 0;
}
int m_nOrderSequenceNumber;
CUtlVector <int> m_nUnits;
int m_nOrderType;
int m_nTargetIndex;
int m_nAbilityIndex;
Vector m_vPosition;
};
#endif
class CUserCmd
{
public:
CUserCmd()
{
Reset();
}
virtual ~CUserCmd() { };
void Reset()
{
command_number = 0;
tick_count = 0;
viewangles.Init();
aimdirection.Init();
forwardmove = 0.0f;
sidemove = 0.0f;
upmove = 0.0f;
buttons = 0;
impulse = 0;
weaponselect = 0;
weaponsubtype = 0;
random_seed = 0;
#ifndef CLIENT_DLL
server_random_seed = 0;
#endif
mousedx = 0;
mousedy = 0;
hasbeenpredicted = false;
#if defined( HL2_DLL ) || defined( HL2_CLIENT_DLL )
entitygroundcontact.RemoveAll();
#endif
#ifdef DOTA_DLL
dota_unitorders.Reset();
#endif
#if defined ( PORTAL2 )
player_held_entity = 0;
held_entity_was_grabbed_through_portal = 0;
command_acknowledgements_pending = 0;
predictedPortalTeleportations = 0;
#endif
headangles.Init();
headoffset.Init();
#if defined( INFESTED_DLL ) || defined( DOTA_DLL )
crosshairtrace = vec3_origin;
#endif
#ifdef INFESTED_DLL
crosshair_entity = 0;
forced_action = 0;
sync_kill_ent = 0;
skill_dest.Init();
skill_dest_ent = 0;
#endif
#if defined( KEEP_COMMAND_REPREDICTION_COUNT )
debug_RepredictionCount = 0;
#endif
}
CUserCmd& operator =(const CUserCmd& src)
{
if (this == &src)
return *this;
command_number = src.command_number;
tick_count = src.tick_count;
viewangles = src.viewangles;
aimdirection = src.aimdirection;
forwardmove = src.forwardmove;
sidemove = src.sidemove;
upmove = src.upmove;
buttons = src.buttons;
impulse = src.impulse;
weaponselect = src.weaponselect;
weaponsubtype = src.weaponsubtype;
random_seed = src.random_seed;
#ifndef CLIENT_DLL
server_random_seed = src.server_random_seed;
#endif
mousedx = src.mousedx;
mousedy = src.mousedy;
hasbeenpredicted = src.hasbeenpredicted;
#if defined( HL2_DLL ) || defined( HL2_CLIENT_DLL )
entitygroundcontact = src.entitygroundcontact;
#endif
#if defined ( PORTAL2 )
player_held_entity = src.player_held_entity;
held_entity_was_grabbed_through_portal = src.held_entity_was_grabbed_through_portal;
command_acknowledgements_pending = src.command_acknowledgements_pending;
predictedPortalTeleportations = src.predictedPortalTeleportations;
#endif
headangles = src.headangles;
headoffset = src.headoffset;
#if defined( INFESTED_DLL ) || defined( DOTA_DLL )
crosshairtrace = src.crosshairtrace;
#endif
#ifdef INFESTED_DLL
crosshair_entity = src.crosshair_entity;
forced_action = src.forced_action;
sync_kill_ent = src.sync_kill_ent;
skill_dest = src.skill_dest;
skill_dest_ent = src.skill_dest_ent;
#endif
#ifdef DOTA_DLL
dota_unitorders = src.dota_unitorders;
#endif
#if defined( KEEP_COMMAND_REPREDICTION_COUNT )
debug_RepredictionCount = src.debug_RepredictionCount;
#endif
return *this;
}
CUserCmd(const CUserCmd& src)
{
*this = src;
}
CRC32_t GetChecksum(void) const
{
CRC32_t crc;
CRC32_Init(&crc);
CRC32_ProcessBuffer(&crc, &command_number, sizeof(command_number));
CRC32_ProcessBuffer(&crc, &tick_count, sizeof(tick_count));
CRC32_ProcessBuffer(&crc, &viewangles, sizeof(viewangles));
CRC32_ProcessBuffer(&crc, &aimdirection, sizeof(aimdirection));
CRC32_ProcessBuffer(&crc, &forwardmove, sizeof(forwardmove));
CRC32_ProcessBuffer(&crc, &sidemove, sizeof(sidemove));
CRC32_ProcessBuffer(&crc, &upmove, sizeof(upmove));
CRC32_ProcessBuffer(&crc, &buttons, sizeof(buttons));
CRC32_ProcessBuffer(&crc, &impulse, sizeof(impulse));
CRC32_ProcessBuffer(&crc, &weaponselect, sizeof(weaponselect));
CRC32_ProcessBuffer(&crc, &weaponsubtype, sizeof(weaponsubtype));
CRC32_ProcessBuffer(&crc, &random_seed, sizeof(random_seed));
CRC32_ProcessBuffer(&crc, &mousedx, sizeof(mousedx));
CRC32_ProcessBuffer(&crc, &mousedy, sizeof(mousedy));
#if defined( INFESTED_DLL ) || defined( DOTA_DLL )
CRC32_ProcessBuffer(&crc, &crosshairtrace, sizeof(crosshairtrace));
#endif
#if defined ( PORTAL2 )
CRC32_ProcessBuffer(&crc, &player_held_entity, sizeof(player_held_entity));
CRC32_ProcessBuffer(&crc, &held_entity_was_grabbed_through_portal, sizeof(held_entity_was_grabbed_through_portal));
CRC32_ProcessBuffer(&crc, &command_acknowledgements_pending, sizeof(command_acknowledgements_pending));
CRC32_ProcessBuffer(&crc, &predictedPortalTeleportations, sizeof(predictedPortalTeleportations));
#endif
#ifdef INFESTED_DLL
CRC32_ProcessBuffer(&crc, &crosshair_entity, sizeof(crosshair_entity));
CRC32_ProcessBuffer(&crc, &forced_action, sizeof(forced_action));
CRC32_ProcessBuffer(&crc, &sync_kill_ent, sizeof(sync_kill_ent));
CRC32_ProcessBuffer(&crc, &skill_dest, sizeof(skill_dest));
CRC32_ProcessBuffer(&crc, &skill_dest_ent, sizeof(skill_dest_ent));
#endif
CRC32_Final(&crc);
return crc;
}
int command_number;
int tick_count;
QAngle viewangles;
Vector aimdirection;
float forwardmove;
float sidemove;
float upmove;
int buttons;
byte impulse;
int weaponselect;
int weaponsubtype;
int random_seed;
#ifndef CLIENT_DLL
int server_random_seed;
#endif
short mousedx;
short mousedy;
bool hasbeenpredicted;
#if defined( HL2_DLL ) || defined( HL2_CLIENT_DLL )
CUtlVector< CEntityGroundContact > entitygroundcontact;
#endif
#if defined ( DOTA_DLL )
CUnitOrders dota_unitorders;
#endif
#if defined ( PORTAL2 )
short player_held_entity;
short held_entity_was_grabbed_through_portal;
unsigned short command_acknowledgements_pending;
uint8 predictedPortalTeleportations;
#endif
QAngle headangles;
Vector headoffset;
#if defined( INFESTED_DLL ) || defined( DOTA_DLL )
Vector crosshairtrace;
#endif
#ifdef INFESTED_DLL
short crosshair_entity;
byte forced_action;
short sync_kill_ent;
Vector skill_dest;
short skill_dest_ent;
#endif
#if defined( KEEP_COMMAND_REPREDICTION_COUNT )
unsigned int debug_RepredictionCount;
#endif
};
void ReadUsercmd(bf_read* buf, CUserCmd* move, CUserCmd* from);
void WriteUsercmd(bf_write* buf, const CUserCmd* to, const CUserCmd* from);
#endif

27
SpyCustom/sdk/userid.h Normal file
View File

@ -0,0 +1,27 @@
#ifndef USERID_H
#define USERID_H
#ifdef _WIN32
#pragma once
#endif
#if !defined( INCLUDED_STEAM_STEAMUSERIDTYPES_H )
#include "SteamCommon.h"
#endif
#define IDTYPE_WON 0
#define IDTYPE_STEAM 1
#define IDTYPE_VALVE 2
#define IDTYPE_HLTV 3
#define IDTYPE_REPLAY 4
typedef struct USERID_s
{
int idtype;
union
{
TSteamGlobalUserID steamid;
} uid;
} USERID_t;
#endif

View File

@ -0,0 +1,294 @@
#ifndef UTLBLOCKMEMORY_H
#define UTLBLOCKMEMORY_H
#ifdef _WIN32
#pragma once
#endif
#include "dbg.h"
#include "platform.h"
#include "mathlib.h"
#include "memalloc.h"
#include "memdbgon.h"
#pragma warning (disable:4100)
#pragma warning (disable:4514)
#ifdef UTBLOCKLMEMORY_TRACK
#define UTLBLOCKMEMORY_TRACK_ALLOC() MemAlloc_RegisterAllocation( "Sum of all UtlBlockMemory", 0, NumAllocated() * sizeof(T), NumAllocated() * sizeof(T), 0 )
#define UTLBLOCKMEMORY_TRACK_FREE() if ( !m_pMemory ) ; else MemAlloc_RegisterDeallocation( "Sum of all UtlBlockMemory", 0, NumAllocated() * sizeof(T), NumAllocated() * sizeof(T), 0 )
#else
#define UTLBLOCKMEMORY_TRACK_ALLOC() ((void)0)
#define UTLBLOCKMEMORY_TRACK_FREE() ((void)0)
#endif
template< class T, class I >
class CUtlBlockMemory
{
public:
CUtlBlockMemory(int nGrowSize = 0, int nInitSize = 0);
~CUtlBlockMemory();
void Init(int nGrowSize = 0, int nInitSize = 0);
T* Base() { return NULL; }
const T* Base() const { return NULL; }
class Iterator_t
{
public:
Iterator_t(I i) : index(i) {}
I index;
bool operator==(const Iterator_t it) const { return index == it.index; }
bool operator!=(const Iterator_t it) const { return index != it.index; }
};
Iterator_t First() const { return Iterator_t(IsIdxValid(0) ? 0 : InvalidIndex()); }
Iterator_t Next(const Iterator_t& it) const { return Iterator_t(IsIdxValid(it.index + 1) ? it.index + 1 : InvalidIndex()); }
I GetIndex(const Iterator_t& it) const { return it.index; }
bool IsIdxAfter(I i, const Iterator_t& it) const { return i > it.index; }
bool IsValidIterator(const Iterator_t& it) const { return IsIdxValid(it.index); }
Iterator_t InvalidIterator() const { return Iterator_t(InvalidIndex()); }
T& operator[](I i);
const T& operator[](I i) const;
T& Element(I i);
const T& Element(I i) const;
bool IsIdxValid(I i) const;
static I InvalidIndex() { return (I)-1; }
void Swap(CUtlBlockMemory< T, I >& mem);
int NumAllocated() const;
int Count() const { return NumAllocated(); }
void Grow(int num = 1);
void EnsureCapacity(int num);
void Purge();
void Purge(int numElements);
protected:
int Index(int major, int minor) const { return (major << m_nIndexShift) | minor; }
int MajorIndex(int i) const { return i >> m_nIndexShift; }
int MinorIndex(int i) const { return i & m_nIndexMask; }
void ChangeSize(int nBlocks);
int NumElementsInBlock() const { return m_nIndexMask + 1; }
T** m_pMemory;
int m_nBlocks;
int m_nIndexMask : 27;
int m_nIndexShift : 5;
};
template< class T, class I >
CUtlBlockMemory<T, I>::CUtlBlockMemory(int nGrowSize, int nInitAllocationCount)
: m_pMemory(0), m_nBlocks(0), m_nIndexMask(0), m_nIndexShift(0)
{
Init(nGrowSize, nInitAllocationCount);
}
template< class T, class I >
CUtlBlockMemory<T, I>::~CUtlBlockMemory()
{
Purge();
}
template< class T, class I >
void CUtlBlockMemory<T, I>::Swap(CUtlBlockMemory< T, I >& mem)
{
swap(m_pMemory, mem.m_pMemory);
swap(m_nBlocks, mem.m_nBlocks);
swap(m_nIndexMask, mem.m_nIndexMask);
swap(m_nIndexShift, mem.m_nIndexShift);
}
template< class T, class I >
void CUtlBlockMemory<T, I>::Init(int nGrowSize , int nInitSize )
{
Purge();
if (nGrowSize == 0)
{
nGrowSize = (127 + sizeof(T)) / sizeof(T);
}
nGrowSize = SmallestPowerOfTwoGreaterOrEqual(nGrowSize);
m_nIndexMask = nGrowSize - 1;
m_nIndexShift = 0;
while (nGrowSize > 1)
{
nGrowSize >>= 1;
++m_nIndexShift;
}
Assert(m_nIndexMask + 1 == (1 << m_nIndexShift));
Grow(nInitSize);
}
template< class T, class I >
inline T& CUtlBlockMemory<T, I>::operator[](I i)
{
Assert(IsIdxValid(i));
T* pBlock = m_pMemory[MajorIndex(i)];
return pBlock[MinorIndex(i)];
}
template< class T, class I >
inline const T& CUtlBlockMemory<T, I>::operator[](I i) const
{
Assert(IsIdxValid(i));
const T* pBlock = m_pMemory[MajorIndex(i)];
return pBlock[MinorIndex(i)];
}
template< class T, class I >
inline T& CUtlBlockMemory<T, I>::Element(I i)
{
Assert(IsIdxValid(i));
T* pBlock = m_pMemory[MajorIndex(i)];
return pBlock[MinorIndex(i)];
}
template< class T, class I >
inline const T& CUtlBlockMemory<T, I>::Element(I i) const
{
Assert(IsIdxValid(i));
const T* pBlock = m_pMemory[MajorIndex(i)];
return pBlock[MinorIndex(i)];
}
template< class T, class I >
inline int CUtlBlockMemory<T, I>::NumAllocated() const
{
return m_nBlocks * NumElementsInBlock();
}
template< class T, class I >
inline bool CUtlBlockMemory<T, I>::IsIdxValid(I i) const
{
return (i >= 0) && (MajorIndex(i) < m_nBlocks);
}
template< class T, class I >
void CUtlBlockMemory<T, I>::Grow(int num)
{
if (num <= 0)
return;
int nBlockSize = NumElementsInBlock();
int nBlocks = (num + nBlockSize - 1) / nBlockSize;
ChangeSize(m_nBlocks + nBlocks);
}
template< class T, class I >
void CUtlBlockMemory<T, I>::ChangeSize(int nBlocks)
{
UTLBLOCKMEMORY_TRACK_FREE();
int nBlocksOld = m_nBlocks;
m_nBlocks = nBlocks;
UTLBLOCKMEMORY_TRACK_ALLOC();
if (m_pMemory)
{
for (int i = m_nBlocks; i < nBlocksOld; ++i)
{
UTLBLOCKMEMORY_TRACK_FREE();
free((void*)m_pMemory[i]);
}
MEM_ALLOC_CREDIT_CLASS();
m_pMemory = (T**)realloc(m_pMemory, m_nBlocks * sizeof(T*));
Assert(m_pMemory);
}
else
{
MEM_ALLOC_CREDIT_CLASS();
m_pMemory = (T**)malloc(m_nBlocks * sizeof(T*));
Assert(m_pMemory);
}
if (!m_pMemory)
{
Error("CUtlBlockMemory overflow!\n");
}
int nBlockSize = NumElementsInBlock();
for (int i = nBlocksOld; i < m_nBlocks; ++i)
{
MEM_ALLOC_CREDIT_CLASS();
m_pMemory[i] = (T*)malloc(nBlockSize * sizeof(T));
Assert(m_pMemory[i]);
}
}
template< class T, class I >
inline void CUtlBlockMemory<T, I>::EnsureCapacity(int num)
{
Grow(num - NumAllocated());
}
template< class T, class I >
void CUtlBlockMemory<T, I>::Purge()
{
if (!m_pMemory)
return;
for (int i = 0; i < m_nBlocks; ++i)
{
UTLBLOCKMEMORY_TRACK_FREE();
free((void*)m_pMemory[i]);
}
m_nBlocks = 0;
UTLBLOCKMEMORY_TRACK_FREE();
free((void*)m_pMemory);
m_pMemory = 0;
}
template< class T, class I >
void CUtlBlockMemory<T, I>::Purge(int numElements)
{
Assert(numElements >= 0);
int nAllocated = NumAllocated();
if (numElements > nAllocated)
{
Assert(numElements <= nAllocated);
return;
}
if (numElements <= 0)
{
Purge();
return;
}
int nBlockSize = NumElementsInBlock();
int nBlocksOld = m_nBlocks;
int nBlocks = (numElements + nBlockSize - 1) / nBlockSize;
if (nBlocks == m_nBlocks)
return;
ChangeSize(nBlocks);
}
#include "memdbgoff.h"
#endif

1157
SpyCustom/sdk/utlbuffer.h Normal file

File diff suppressed because it is too large Load Diff

278
SpyCustom/sdk/utldict.h Normal file
View File

@ -0,0 +1,278 @@
#ifndef UTLDICT_H
#define UTLDICT_H
#ifdef _WIN32
#pragma once
#endif
#include "dbg.h"
#include "utlmap.h"
#include "utlsymbol.h"
#include "memdbgon.h"
enum EDictCompareType
{
k_eDictCompareTypeCaseSensitive = 0,
k_eDictCompareTypeCaseInsensitive = 1,
k_eDictCompareTypeFilenames
};
#define FOR_EACH_DICT( dictName, iteratorName ) \
for( int iteratorName=dictName.First(); iteratorName != dictName.InvalidIndex(); iteratorName = dictName.Next( iteratorName ) )
#define FOR_EACH_DICT_FAST( dictName, iteratorName ) \
for ( int iteratorName = 0; iteratorName < dictName.MaxElement(); ++iteratorName ) if ( !dictName.IsValidIndex( iteratorName ) ) continue; else
template <class T, class I = int >
class CUtlDict
{
public:
typedef const char* KeyType_t;
typedef T ElemType_t;
CUtlDict(int compareType = k_eDictCompareTypeCaseInsensitive, int growSize = 0, int initSize = 0);
~CUtlDict();
void EnsureCapacity(int);
T& Element(I i);
const T& Element(I i) const;
T& operator[](I i);
const T& operator[](I i) const;
char const* GetElementName(I i) const;
void SetElementName(I i, char const* pName);
unsigned int Count() const;
I MaxElement() const;
bool IsValidIndex(I i) const;
static I InvalidIndex();
I Insert(const char* pName, const T& element);
I Insert(const char* pName);
I Find(const char* pName) const;
bool HasElement(const char* pName) const;
void RemoveAt(I i);
void Remove(const char* pName);
void RemoveAll();
void Purge();
void PurgeAndDeleteElements();
I First() const;
I Next(I i) const;
typedef I IndexType_t;
protected:
typedef CUtlMap<const char*, T, I> DictElementMap_t;
DictElementMap_t m_Elements;
};
template <class T, class I>
CUtlDict<T, I>::CUtlDict(int compareType, int growSize, int initSize) : m_Elements(growSize, initSize)
{
if (compareType == k_eDictCompareTypeFilenames)
{
m_Elements.SetLessFunc(CaselessStringLessThanIgnoreSlashes);
}
else if (compareType == k_eDictCompareTypeCaseInsensitive)
{
m_Elements.SetLessFunc(CaselessStringLessThan);
}
else
{
m_Elements.SetLessFunc(StringLessThan);
}
}
template <class T, class I>
CUtlDict<T, I>::~CUtlDict()
{
Purge();
}
template <class T, class I>
inline void CUtlDict<T, I>::EnsureCapacity(int num)
{
return m_Elements.EnsureCapacity(num);
}
template <class T, class I>
inline T& CUtlDict<T, I>::Element(I i)
{
return m_Elements[i];
}
template <class T, class I>
inline const T& CUtlDict<T, I>::Element(I i) const
{
return m_Elements[i];
}
template <class T, class I>
inline char const* CUtlDict<T, I>::GetElementName(I i) const
{
return m_Elements.Key(i);
}
template <class T, class I>
inline T& CUtlDict<T, I>::operator[](I i)
{
return Element(i);
}
template <class T, class I>
inline const T& CUtlDict<T, I>::operator[](I i) const
{
return Element(i);
}
template <class T, class I>
inline void CUtlDict<T, I>::SetElementName(I i, char const* pName)
{
MEM_ALLOC_CREDIT_CLASS();
free(const_cast<char*>(m_Elements.Key(i)));
m_Elements.Reinsert(strdup(pName), i);
}
template <class T, class I>
inline unsigned int CUtlDict<T, I>::Count() const
{
return m_Elements.Count();
}
template <class T, class I>
inline I CUtlDict<T, I>::MaxElement() const
{
return m_Elements.MaxElement();
}
template <class T, class I>
inline bool CUtlDict<T, I>::IsValidIndex(I i) const
{
return m_Elements.IsValidIndex(i);
}
template <class T, class I>
inline I CUtlDict<T, I>::InvalidIndex()
{
return DictElementMap_t::InvalidIndex();
}
template <class T, class I>
void CUtlDict<T, I>::RemoveAt(I elem)
{
free(const_cast<char*>(m_Elements.Key(elem)));
m_Elements.RemoveAt(elem);
}
template <class T, class I> void CUtlDict<T, I>::Remove(const char* search)
{
I node = Find(search);
if (node != InvalidIndex())
{
RemoveAt(node);
}
}
template <class T, class I>
void CUtlDict<T, I>::RemoveAll()
{
typename DictElementMap_t::IndexType_t index = m_Elements.FirstInorder();
while (index != m_Elements.InvalidIndex())
{
const char* p = m_Elements.Key(index);
free(const_cast<char*>(p));
index = m_Elements.NextInorder(index);
}
m_Elements.RemoveAll();
}
template <class T, class I>
void CUtlDict<T, I>::Purge()
{
RemoveAll();
}
template <class T, class I>
void CUtlDict<T, I>::PurgeAndDeleteElements()
{
I index = m_Elements.FirstInorder();
while (index != m_Elements.InvalidIndex())
{
const char* p = m_Elements.Key(index);
free(const_cast<char*>(p));
delete m_Elements[index];
index = m_Elements.NextInorder(index);
}
m_Elements.RemoveAll();
}
template <class T, class I>
I CUtlDict<T, I>::Insert(const char* pName, const T& element)
{
MEM_ALLOC_CREDIT_CLASS();
return m_Elements.Insert(strdup(pName), element);
}
template <class T, class I>
I CUtlDict<T, I>::Insert(const char* pName)
{
MEM_ALLOC_CREDIT_CLASS();
return m_Elements.Insert(strdup(pName));
}
template <class T, class I>
I CUtlDict<T, I>::Find(const char* pName) const
{
MEM_ALLOC_CREDIT_CLASS();
if (pName)
return m_Elements.Find(pName);
else
return InvalidIndex();
}
template <class T, class I>
bool CUtlDict<T, I>::HasElement(const char* pName) const
{
if (pName)
return m_Elements.IsValidIndex(m_Elements.Find(pName));
else
return false;
}
template <class T, class I>
I CUtlDict<T, I>::First() const
{
return m_Elements.FirstInorder();
}
template <class T, class I>
I CUtlDict<T, I>::Next(I i) const
{
return m_Elements.NextInorder(i);
}
#include "memdbgoff.h"
#endif

221
SpyCustom/sdk/utlenvelope.h Normal file
View File

@ -0,0 +1,221 @@
#include "utlstring.h"
#include "basetypes.h"
#ifndef UTLENVELOPE_H
#define UTLENVELOPE_H
#if defined( _WIN32 )
#pragma once
#endif
class CUtlDataEnvelope
{
public:
CUtlDataEnvelope(const void* pData, int nBytes);
CUtlDataEnvelope(const CUtlDataEnvelope& from);
~CUtlDataEnvelope();
CUtlDataEnvelope& operator=(const CUtlDataEnvelope& from);
operator void* ();
operator void* () const;
private:
void Assign(const void* pData, int nBytes);
void Assign(const CUtlDataEnvelope& from);
void Purge();
union
{
byte* m_pData;
byte m_data[4];
};
int m_nBytes;
};
template <typename T>
class CUtlEnvelope : protected CUtlDataEnvelope
{
public:
CUtlEnvelope(const T* pData, int nElems = 1);
CUtlEnvelope(const CUtlEnvelope<T>& from);
CUtlEnvelope<T>& operator=(const CUtlEnvelope<T>& from);
operator T* ();
operator T* () const;
operator void* ();
operator void* () const;
};
template <>
class CUtlEnvelope<const char*>
{
public:
CUtlEnvelope(const char* pData)
{
m_string = pData;
}
CUtlEnvelope(const CUtlEnvelope<const char*>& from)
{
m_string = from.m_string;
}
CUtlEnvelope<const char*>& operator=(const CUtlEnvelope<const char*>& from)
{
m_string = from.m_string;
return *this;
}
operator char* ()
{
return (char*)m_string.Get();
}
operator char* () const
{
return (char*)m_string.Get();
}
operator void* ()
{
return (void*)m_string.Get();
}
operator void* () const
{
return (void*)m_string.Get();
}
private:
CUtlString m_string;
};
#include "memdbgon.h"
inline void CUtlDataEnvelope::Assign(const void* pData, int nBytes)
{
if (pData)
{
m_nBytes = nBytes;
if (m_nBytes > 4)
{
m_pData = new byte[nBytes];
memcpy(m_pData, pData, nBytes);
}
else
{
memcpy(m_data, pData, nBytes);
}
}
else
{
m_pData = NULL;
m_nBytes = 0;
}
}
inline void CUtlDataEnvelope::Assign(const CUtlDataEnvelope& from)
{
Assign(from.operator void* (), from.m_nBytes);
}
inline void CUtlDataEnvelope::Purge()
{
if (m_nBytes > 4)
delete[] m_pData;
m_nBytes = 0;
}
inline CUtlDataEnvelope::CUtlDataEnvelope(const void* pData, int nBytes)
{
Assign(pData, nBytes);
}
inline CUtlDataEnvelope::CUtlDataEnvelope(const CUtlDataEnvelope& from)
{
Assign(from);
}
inline CUtlDataEnvelope::~CUtlDataEnvelope()
{
Purge();
}
inline CUtlDataEnvelope& CUtlDataEnvelope::operator=(const CUtlDataEnvelope& from)
{
Purge();
Assign(from);
return *this;
}
inline CUtlDataEnvelope::operator void* ()
{
if (!m_nBytes)
{
return NULL;
}
return (m_nBytes > 4) ? m_pData : m_data;
}
inline CUtlDataEnvelope::operator void* () const
{
if (!m_nBytes)
{
return NULL;
}
return (m_nBytes > 4) ? (void*)m_pData : (void*)m_data;
}
template <typename T>
inline CUtlEnvelope<T>::CUtlEnvelope(const T* pData, int nElems)
: CUtlDataEnvelope(pData, sizeof(T)* nElems)
{
}
template <typename T>
inline CUtlEnvelope<T>::CUtlEnvelope(const CUtlEnvelope<T>& from)
: CUtlDataEnvelope(from)
{
}
template <typename T>
inline CUtlEnvelope<T>& CUtlEnvelope<T>::operator=(const CUtlEnvelope<T>& from)
{
CUtlDataEnvelope::operator=(from);
return *this;
}
template <typename T>
inline CUtlEnvelope<T>::operator T* ()
{
return (T*)CUtlDataEnvelope::operator void* ();
}
template <typename T>
inline CUtlEnvelope<T>::operator T* () const
{
return (T*)((const_cast<CUtlEnvelope<T>*>(this))->operator T * ());
}
template <typename T>
inline CUtlEnvelope<T>::operator void* ()
{
return CUtlDataEnvelope::operator void* ();
}
template <typename T>
inline CUtlEnvelope<T>::operator void* () const
{
return ((const_cast<CUtlEnvelope<T>*>(this))->operator void* ());
}
#include "memdbgoff.h"
#endif

View File

@ -0,0 +1,302 @@
#ifndef UTLFIXEDMEMORY_H
#define UTLFIXEDMEMORY_H
#ifdef _WIN32
#pragma once
#endif
#include "dbg.h"
#include "platform.h"
#include "memalloc.h"
#include "memdbgon.h"
#pragma warning (disable:4100)
#pragma warning (disable:4514)
#ifdef UTLFIXEDMEMORY_TRACK
#define UTLFIXEDMEMORY_TRACK_ALLOC() MemAlloc_RegisterAllocation( "Sum of all UtlFixedMemory", 0, NumAllocated() * sizeof(T), NumAllocated() * sizeof(T), 0 )
#define UTLFIXEDMEMORY_TRACK_FREE() if ( !m_pMemory ) ; else MemAlloc_RegisterDeallocation( "Sum of all UtlFixedMemory", 0, NumAllocated() * sizeof(T), NumAllocated() * sizeof(T), 0 )
#else
#define UTLFIXEDMEMORY_TRACK_ALLOC() ((void)0)
#define UTLFIXEDMEMORY_TRACK_FREE() ((void)0)
#endif
template< class T >
class CUtlFixedMemory
{
public:
CUtlFixedMemory(int nGrowSize = 0, int nInitSize = 0);
~CUtlFixedMemory();
void Init(int nGrowSize = 0, int nInitSize = 0);
T* Base() { return NULL; }
const T* Base() const { return NULL; }
protected:
struct BlockHeader_t;
public:
class Iterator_t
{
public:
Iterator_t(BlockHeader_t* p, int i) : m_pBlockHeader(p), m_nIndex(i) {}
BlockHeader_t* m_pBlockHeader;
intp m_nIndex;
bool operator==(const Iterator_t it) const { return m_pBlockHeader == it.m_pBlockHeader && m_nIndex == it.m_nIndex; }
bool operator!=(const Iterator_t it) const { return m_pBlockHeader != it.m_pBlockHeader || m_nIndex != it.m_nIndex; }
};
Iterator_t First() const { return m_pBlocks ? Iterator_t(m_pBlocks, 0) : InvalidIterator(); }
Iterator_t Next(const Iterator_t& it) const
{
Assert(IsValidIterator(it));
if (!IsValidIterator(it))
return InvalidIterator();
BlockHeader_t* RESTRICT pHeader = it.m_pBlockHeader;
if (it.m_nIndex + 1 < pHeader->m_nBlockSize)
return Iterator_t(pHeader, it.m_nIndex + 1);
return pHeader->m_pNext ? Iterator_t(pHeader->m_pNext, 0) : InvalidIterator();
}
intp GetIndex(const Iterator_t& it) const
{
Assert(IsValidIterator(it));
if (!IsValidIterator(it))
return InvalidIndex();
return (intp)(HeaderToBlock(it.m_pBlockHeader) + it.m_nIndex);
}
bool IsIdxAfter(intp i, const Iterator_t& it) const
{
Assert(IsValidIterator(it));
if (!IsValidIterator(it))
return false;
if (IsInBlock(i, it.m_pBlockHeader))
return i > GetIndex(it);
for (BlockHeader_t* RESTRICT pbh = it.m_pBlockHeader->m_pNext; pbh; pbh = pbh->m_pNext)
{
if (IsInBlock(i, pbh))
return true;
}
return false;
}
bool IsValidIterator(const Iterator_t& it) const { return it.m_pBlockHeader && it.m_nIndex >= 0 && it.m_nIndex < it.m_pBlockHeader->m_nBlockSize; }
Iterator_t InvalidIterator() const { return Iterator_t(NULL, INVALID_INDEX); }
T& operator[](intp i);
const T& operator[](intp i) const;
T& Element(intp i);
const T& Element(intp i) const;
bool IsIdxValid(intp i) const;
static const intp INVALID_INDEX = 0;
static intp InvalidIndex() { return INVALID_INDEX; }
int NumAllocated() const;
int Count() const { return NumAllocated(); }
void Grow(int num = 1);
void EnsureCapacity(int num);
void Purge();
protected:
void Swap(CUtlFixedMemory< T >& mem);
bool IsInBlock(intp i, BlockHeader_t* pBlockHeader) const
{
T* p = (T*)i;
const T* p0 = HeaderToBlock(pBlockHeader);
return p >= p0 && p < p0 + pBlockHeader->m_nBlockSize;
}
struct BlockHeader_t
{
BlockHeader_t* m_pNext;
intp m_nBlockSize;
};
const T* HeaderToBlock(const BlockHeader_t* pHeader) const { return (T*)(pHeader + 1); }
const BlockHeader_t* BlockToHeader(const T* pBlock) const { return (BlockHeader_t*)(pBlock)-1; }
BlockHeader_t* m_pBlocks;
int m_nAllocationCount;
int m_nGrowSize;
};
template< class T >
CUtlFixedMemory<T>::CUtlFixedMemory(int nGrowSize, int nInitAllocationCount)
: m_pBlocks(0), m_nAllocationCount(0), m_nGrowSize(0)
{
Init(nGrowSize, nInitAllocationCount);
}
template< class T >
CUtlFixedMemory<T>::~CUtlFixedMemory()
{
Purge();
}
template< class T >
void CUtlFixedMemory<T>::Swap(CUtlFixedMemory< T >& mem)
{
V_swap(m_pBlocks, mem.m_pBlocks);
V_swap(m_nAllocationCount, mem.m_nAllocationCount);
V_swap(m_nGrowSize, mem.m_nGrowSize);
}
template< class T >
void CUtlFixedMemory<T>::Init(int nGrowSize , int nInitSize )
{
Purge();
m_nGrowSize = nGrowSize;
Grow(nInitSize);
}
template< class T >
inline T& CUtlFixedMemory<T>::operator[](intp i)
{
Assert(IsIdxValid(i));
return *(T*)i;
}
template< class T >
inline const T& CUtlFixedMemory<T>::operator[](intp i) const
{
Assert(IsIdxValid(i));
return *(T*)i;
}
template< class T >
inline T& CUtlFixedMemory<T>::Element(intp i)
{
Assert(IsIdxValid(i));
return *(T*)i;
}
template< class T >
inline const T& CUtlFixedMemory<T>::Element(intp i) const
{
Assert(IsIdxValid(i));
return *(T*)i;
}
template< class T >
inline int CUtlFixedMemory<T>::NumAllocated() const
{
return m_nAllocationCount;
}
template< class T >
inline bool CUtlFixedMemory<T>::IsIdxValid(intp i) const
{
#ifdef _DEBUG
for (BlockHeader_t* pbh = m_pBlocks; pbh; pbh = pbh->m_pNext)
{
if (IsInBlock(i, pbh))
return true;
}
return false;
#else
return i != InvalidIndex();
#endif
}
template< class T >
void CUtlFixedMemory<T>::Grow(int num)
{
if (num <= 0)
return;
int nBlockSize = m_nGrowSize;
if (nBlockSize == 0)
{
if (m_nAllocationCount)
{
nBlockSize = m_nAllocationCount;
}
else
{
nBlockSize = (31 + sizeof(T)) / sizeof(T);
Assert(nBlockSize);
}
}
if (nBlockSize < num)
{
int n = (num + nBlockSize - 1) / nBlockSize;
Assert(n * nBlockSize >= num);
Assert((n - 1) * nBlockSize < num);
nBlockSize *= n;
}
m_nAllocationCount += nBlockSize;
MEM_ALLOC_CREDIT_CLASS();
BlockHeader_t* RESTRICT pBlockHeader = (BlockHeader_t*)malloc(sizeof(BlockHeader_t) + nBlockSize * sizeof(T));
if (!pBlockHeader)
{
Error("CUtlFixedMemory overflow!\n");
}
pBlockHeader->m_pNext = NULL;
pBlockHeader->m_nBlockSize = nBlockSize;
if (!m_pBlocks)
{
m_pBlocks = pBlockHeader;
}
else
{
#if 1
BlockHeader_t* RESTRICT pbh = m_pBlocks;
while (pbh->m_pNext)
{
pbh = pbh->m_pNext;
}
pbh->m_pNext = pBlockHeader;
#else
pBlockHeader = m_pBlocks;
pBlockHeader->m_pNext = m_pBlocks;
#endif
}
}
template< class T >
inline void CUtlFixedMemory<T>::EnsureCapacity(int num)
{
Grow(num - NumAllocated());
}
template< class T >
void CUtlFixedMemory<T>::Purge()
{
if (!m_pBlocks)
return;
for (BlockHeader_t* pbh = m_pBlocks; pbh; )
{
BlockHeader_t* pFree = pbh;
pbh = pbh->m_pNext;
free(pFree);
}
m_pBlocks = NULL;
m_nAllocationCount = 0;
}
#include "memdbgoff.h"
#endif

92
SpyCustom/sdk/utlflags.h Normal file
View File

@ -0,0 +1,92 @@
#ifndef UTLFLAGS_H
#define UTLFLAGS_H
#ifdef _WIN32
#pragma once
#endif
#include "dbg.h"
template< class T >
class CUtlFlags
{
public:
CUtlFlags(int nInitialFlags = 0);
void SetFlag(int nFlagMask);
void SetFlag(int nFlagMask, bool bEnable);
void ClearFlag(int nFlagMask);
void ClearAllFlags();
bool IsFlagSet(int nFlagMask) const;
bool IsAnyFlagSet() const;
private:
T m_nFlags;
};
template< class T >
CUtlFlags<T>::CUtlFlags(int nInitialFlags)
{
Assert(nInitialFlags == (T)nInitialFlags);
m_nFlags = (T)nInitialFlags;
}
template< class T >
void CUtlFlags<T>::SetFlag(int nFlagMask)
{
Assert(nFlagMask == (T)nFlagMask);
m_nFlags |= (T)nFlagMask;
}
template< class T >
void CUtlFlags<T>::SetFlag(int nFlagMask, bool bEnable)
{
Assert(nFlagMask == (T)nFlagMask);
if (bEnable)
{
m_nFlags |= (T)nFlagMask;
}
else
{
m_nFlags &= ~((T)nFlagMask);
}
}
template< class T >
void CUtlFlags<T>::ClearFlag(int nFlagMask)
{
Assert(nFlagMask == (T)nFlagMask);
m_nFlags &= ~((T)nFlagMask);
}
template< class T >
void CUtlFlags<T>::ClearAllFlags()
{
m_nFlags = 0;
}
template< class T >
bool CUtlFlags<T>::IsFlagSet(int nFlagMask) const
{
Assert(nFlagMask == (T)nFlagMask);
return (m_nFlags & nFlagMask) != 0;
}
template< class T >
bool CUtlFlags<T>::IsAnyFlagSet() const
{
return m_nFlags != 0;
}
#endif

View File

@ -0,0 +1,499 @@
#ifndef UTLHANDLETABLE_H
#define UTLHANDLETABLE_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "utlqueue.h"
typedef unsigned int UtlHandle_t;
#define UTLHANDLE_INVALID ((UtlHandle_t)~0)
template< class T, int HandleBits >
class CUtlHandleTable
{
public:
CUtlHandleTable();
UtlHandle_t AddHandle();
void RemoveHandle(UtlHandle_t h);
void SetHandle(UtlHandle_t h, T* pData);
T* GetHandle(UtlHandle_t h) const;
T* GetHandle(UtlHandle_t h, bool checkValidity) const;
bool IsHandleValid(UtlHandle_t h) const;
unsigned int GetValidHandleCount() const;
unsigned int GetHandleCount() const;
UtlHandle_t GetHandleFromIndex(int i) const;
int GetIndexFromHandle(UtlHandle_t h) const;
void MarkHandleInvalid(UtlHandle_t h);
void MarkHandleValid(UtlHandle_t h);
private:
struct HandleType_t
{
HandleType_t(unsigned int i, unsigned int s) : nIndex(i), nSerial(s)
{
Assert(i < (1 << HandleBits));
Assert(s < (1 << (31 - HandleBits)));
}
unsigned int nIndex : HandleBits;
unsigned int nSerial : 31 - HandleBits;
};
struct EntryType_t
{
EntryType_t() : m_nSerial(0), nInvalid(0), m_pData(0) {}
unsigned int m_nSerial : 31;
unsigned int nInvalid : 1;
T* m_pData;
};
static unsigned int GetSerialNumber(UtlHandle_t handle);
static unsigned int GetListIndex(UtlHandle_t handle);
static UtlHandle_t CreateHandle(unsigned int nSerial, unsigned int nIndex);
const EntryType_t* GetEntry(UtlHandle_t handle, bool checkValidity) const;
unsigned int m_nValidHandles;
CUtlVector< EntryType_t > m_list;
CUtlQueue< int > m_unused;
};
template< class T, int HandleBits >
CUtlHandleTable<T, HandleBits>::CUtlHandleTable() : m_nValidHandles(0)
{
}
template< class T, int HandleBits >
UtlHandle_t CUtlHandleTable<T, HandleBits>::AddHandle()
{
unsigned int nIndex = (m_unused.Count() > 0) ? m_unused.RemoveAtHead() : m_list.AddToTail();
EntryType_t& entry = m_list[nIndex];
entry.nInvalid = 0;
entry.m_pData = NULL;
++m_nValidHandles;
return CreateHandle(entry.m_nSerial, nIndex);
}
template< class T, int HandleBits >
void CUtlHandleTable<T, HandleBits>::RemoveHandle(UtlHandle_t handle)
{
unsigned int nIndex = GetListIndex(handle);
Assert(nIndex < (unsigned int)m_list.Count());
if (nIndex >= (unsigned int)m_list.Count())
return;
EntryType_t& entry = m_list[nIndex];
++entry.m_nSerial;
if (!entry.nInvalid)
{
entry.nInvalid = 1;
--m_nValidHandles;
}
entry.m_pData = NULL;
bool bStopUsing = (entry.m_nSerial >= ((1 << (31 - HandleBits)) - 1));
if (!bStopUsing)
{
m_unused.Insert(nIndex);
}
}
template< class T, int HandleBits >
void CUtlHandleTable<T, HandleBits>::SetHandle(UtlHandle_t handle, T* pData)
{
EntryType_t* entry = const_cast<EntryType_t*>(GetEntry(handle, false));
Assert(entry);
if (entry == NULL)
return;
if (entry->nInvalid)
{
++m_nValidHandles;
entry->nInvalid = 0;
}
entry->m_pData = pData;
}
template< class T, int HandleBits >
T* CUtlHandleTable<T, HandleBits>::GetHandle(UtlHandle_t handle) const
{
const EntryType_t* entry = GetEntry(handle, true);
return entry ? entry->m_pData : NULL;
}
template< class T, int HandleBits >
T* CUtlHandleTable<T, HandleBits>::GetHandle(UtlHandle_t handle, bool checkValidity) const
{
const EntryType_t* entry = GetEntry(handle, checkValidity);
return entry ? entry->m_pData : NULL;
}
template< class T, int HandleBits >
bool CUtlHandleTable<T, HandleBits>::IsHandleValid(UtlHandle_t handle) const
{
if (handle == UTLHANDLE_INVALID)
return false;
unsigned int nIndex = GetListIndex(handle);
AssertOnce(nIndex < (unsigned int)m_list.Count());
if (nIndex >= (unsigned int)m_list.Count())
return false;
const EntryType_t& entry = m_list[nIndex];
if (entry.m_nSerial != GetSerialNumber(handle))
return false;
if (1 == entry.nInvalid)
return false;
return true;
}
template< class T, int HandleBits >
unsigned int CUtlHandleTable<T, HandleBits>::GetValidHandleCount() const
{
return m_nValidHandles;
}
template< class T, int HandleBits >
unsigned int CUtlHandleTable<T, HandleBits>::GetHandleCount() const
{
return m_list.Count();
}
template< class T, int HandleBits >
UtlHandle_t CUtlHandleTable<T, HandleBits>::GetHandleFromIndex(int i) const
{
if (m_list[i].m_pData)
return CreateHandle(m_list[i].m_nSerial, i);
return UTLHANDLE_INVALID;
}
template< class T, int HandleBits >
int CUtlHandleTable<T, HandleBits>::GetIndexFromHandle(UtlHandle_t h) const
{
if (h == UTLHANDLE_INVALID)
return -1;
return GetListIndex(h);
}
template< class T, int HandleBits >
unsigned int CUtlHandleTable<T, HandleBits>::GetSerialNumber(UtlHandle_t handle)
{
return ((HandleType_t*)&handle)->nSerial;
}
template< class T, int HandleBits >
unsigned int CUtlHandleTable<T, HandleBits>::GetListIndex(UtlHandle_t handle)
{
return ((HandleType_t*)&handle)->nIndex;
}
template< class T, int HandleBits >
UtlHandle_t CUtlHandleTable<T, HandleBits>::CreateHandle(unsigned int nSerial, unsigned int nIndex)
{
HandleType_t h(nIndex, nSerial);
return *(UtlHandle_t*)&h;
}
template< class T, int HandleBits >
const typename CUtlHandleTable<T, HandleBits>::EntryType_t* CUtlHandleTable<T, HandleBits>::GetEntry(UtlHandle_t handle, bool checkValidity) const
{
if (handle == UTLHANDLE_INVALID)
return NULL;
unsigned int nIndex = GetListIndex(handle);
Assert(nIndex < (unsigned int)m_list.Count());
if (nIndex >= (unsigned int)m_list.Count())
return NULL;
const EntryType_t& entry = m_list[nIndex];
if (entry.m_nSerial != GetSerialNumber(handle))
return NULL;
if (checkValidity &&
(1 == entry.nInvalid))
return NULL;
return &entry;
}
template< class T, int HandleBits >
void CUtlHandleTable<T, HandleBits>::MarkHandleInvalid(UtlHandle_t handle)
{
if (handle == UTLHANDLE_INVALID)
return;
unsigned int nIndex = GetListIndex(handle);
Assert(nIndex < (unsigned int)m_list.Count());
if (nIndex >= (unsigned int)m_list.Count())
return;
EntryType_t& entry = m_list[nIndex];
if (entry.m_nSerial != GetSerialNumber(handle))
return;
if (!entry.nInvalid)
{
--m_nValidHandles;
entry.nInvalid = 1;
}
}
template< class T, int HandleBits >
void CUtlHandleTable<T, HandleBits>::MarkHandleValid(UtlHandle_t handle)
{
if (handle == UTLHANDLE_INVALID)
return;
unsigned int nIndex = GetListIndex(handle);
Assert(nIndex < (unsigned int)m_list.Count());
if (nIndex >= (unsigned int)m_list.Count())
return;
EntryType_t& entry = m_list[nIndex];
if (entry.m_nSerial != GetSerialNumber(handle))
return;
if (entry.nInvalid)
{
++m_nValidHandles;
entry.nInvalid = 0;
}
}
template< class T >
class CUtlHandle
{
public:
CUtlHandle();
explicit CUtlHandle(T* pObject);
CUtlHandle(UtlHandle_t h);
CUtlHandle(const CUtlHandle<T>& h);
void Set(T* pObject);
void Set(UtlHandle_t h);
const CUtlHandle<T>& operator=(UtlHandle_t h);
const CUtlHandle<T>& operator=(T* pObject);
T* Get();
const T* Get() const;
bool IsValid() const;
operator T* ();
operator UtlHandle_t();
operator bool();
T* operator->();
const T* operator->() const;
bool operator==(CUtlHandle<T> h) const;
bool operator==(T* pObject) const;
bool operator==(UtlHandle_t h) const;
bool operator!=(CUtlHandle<T> h) const;
bool operator!=(T* pObject) const;
bool operator!=(UtlHandle_t h) const;
private:
UtlHandle_t m_handle;
};
template< class T >
CUtlHandle<T>::CUtlHandle() : m_handle(UTLHANDLE_INVALID)
{
}
template< class T >
CUtlHandle<T>::CUtlHandle(T* pObject)
{
Set(pObject);
}
template< class T >
CUtlHandle<T>::CUtlHandle(UtlHandle_t h)
{
m_handle = h;
}
template< class T >
CUtlHandle<T>::CUtlHandle(const CUtlHandle<T>& h)
{
m_handle = h.m_handle;
}
template< class T >
void CUtlHandle<T>::Set(T* pObject)
{
m_handle = pObject ? pObject->GetHandle() : UTLHANDLE_INVALID;
}
template< class T >
void CUtlHandle<T>::Set(UtlHandle_t h)
{
m_handle = h;
}
template< class T >
const CUtlHandle<T>& CUtlHandle<T>::operator=(UtlHandle_t h)
{
Set(h);
return *this;
}
template< class T >
const CUtlHandle<T>& CUtlHandle<T>::operator=(T* pObject)
{
Set(pObject);
return *this;
}
template< class T >
bool CUtlHandle<T>::IsValid() const
{
return T::IsHandleValid(m_handle);
}
template< class T >
T* CUtlHandle<T>::Get()
{
return T::GetPtrFromHandle(m_handle);
}
template< class T >
const T* CUtlHandle<T>::Get() const
{
return T::GetPtrFromHandle(m_handle);
}
template< class T >
CUtlHandle<T>::operator T* ()
{
return Get();
}
template< class T >
CUtlHandle<T>::operator UtlHandle_t()
{
return m_handle;
}
template< class T >
T* CUtlHandle<T>::operator->()
{
return Get();
}
template< class T >
const T* CUtlHandle<T>::operator->() const
{
return Get();
}
template< class T >
CUtlHandle<T>::operator bool()
{
return m_handle != UTLHANDLE_INVALID;
}
template< class T >
bool CUtlHandle<T>::operator==(CUtlHandle<T> h) const
{
return m_handle == h.m_handle;
}
template< class T >
bool CUtlHandle<T>::operator==(T* pObject) const
{
UtlHandle_t h = pObject ? pObject->GetHandle() : UTLHANDLE_INVALID;
return m_handle == h;
}
template< class T >
bool CUtlHandle<T>::operator==(UtlHandle_t h) const
{
return m_handle == h;
}
template< class T >
bool CUtlHandle<T>::operator!=(CUtlHandle<T> h) const
{
return m_handle != h.m_handle;
}
template< class T >
bool CUtlHandle<T>::operator!=(T* pObject) const
{
UtlHandle_t h = pObject ? pObject->GetHandle() : UTLHANDLE_INVALID;
return m_handle != h;
}
template< class T >
bool CUtlHandle<T>::operator!=(UtlHandle_t h) const
{
return m_handle != h;
}
#define DECLARE_HANDLES( _className, _handleBitCount ) \
public: \
UtlHandle_t GetHandle() \
{ \
return m_Handle; \
} \
static _className* GetPtrFromHandle( UtlHandle_t h ) \
{ \
return m_HandleTable.GetHandle( h ); \
} \
static bool IsHandleValid( UtlHandle_t h ) \
{ \
return m_HandleTable.IsHandleValid( h ); \
} \
private: \
UtlHandle_t m_Handle; \
static CUtlHandleTable< _className, _handleBitCount > m_HandleTable
#define IMPLEMENT_HANDLES( _className, _handleBitCount ) \
CUtlHandleTable< _className, _handleBitCount > _className::m_HandleTable;
#define CONSTRUCT_HANDLE( ) \
m_Handle = m_HandleTable.AddHandle(); \
m_HandleTable.SetHandle( m_Handle, this )
#define DESTRUCT_HANDLE() \
m_HandleTable.RemoveHandle( m_Handle ); \
m_Handle = UTLHANDLE_INVALID
#endif

732
SpyCustom/sdk/utlhash.h Normal file
View File

@ -0,0 +1,732 @@
#ifndef UTLHASH_H
#define UTLHASH_H
#pragma once
#include <assert.h>
#include <limits.h>
#include "utlmemory.h"
#include "utlvector.h"
#include "utllinkedlist.h"
#include "commonmacros.h"
#include "generichash.h"
typedef unsigned int UtlHashHandle_t;
template<class Data, typename C = bool (*)(Data const&, Data const&), typename K = unsigned int (*)(Data const&) >
class CUtlHash
{
public:
typedef C CompareFunc_t;
typedef K KeyFunc_t;
CUtlHash(int bucketCount = 0, int growCount = 0, int initCount = 0,
CompareFunc_t compareFunc = 0, KeyFunc_t keyFunc = 0);
~CUtlHash();
static UtlHashHandle_t InvalidHandle(void) { return (UtlHashHandle_t)~0; }
bool IsValidHandle(UtlHashHandle_t handle) const;
int Count(void) const;
void Purge(void);
UtlHashHandle_t Insert(Data const& src);
UtlHashHandle_t Insert(Data const& src, bool* pDidInsert);
UtlHashHandle_t AllocEntryFromKey(Data const& src);
void Remove(UtlHashHandle_t handle);
void RemoveAll();
UtlHashHandle_t Find(Data const& src) const;
Data& Element(UtlHashHandle_t handle);
Data const& Element(UtlHashHandle_t handle) const;
Data& operator[](UtlHashHandle_t handle);
Data const& operator[](UtlHashHandle_t handle) const;
UtlHashHandle_t GetFirstHandle() const;
UtlHashHandle_t GetNextHandle(UtlHashHandle_t h) const;
void Log(const char* filename);
protected:
int GetBucketIndex(UtlHashHandle_t handle) const;
int GetKeyDataIndex(UtlHashHandle_t handle) const;
UtlHashHandle_t BuildHandle(int ndxBucket, int ndxKeyData) const;
bool DoFind(Data const& src, unsigned int* pBucket, int* pIndex) const;
protected:
typedef CUtlVector<Data> HashBucketList_t;
CUtlVector<HashBucketList_t> m_Buckets;
CompareFunc_t m_CompareFunc;
KeyFunc_t m_KeyFunc;
bool m_bPowerOfTwo;
unsigned int m_ModMask;
};
template<class Data, typename C, typename K>
CUtlHash<Data, C, K>::CUtlHash(int bucketCount, int growCount, int initCount,
CompareFunc_t compareFunc, KeyFunc_t keyFunc) :
m_CompareFunc(compareFunc),
m_KeyFunc(keyFunc)
{
m_Buckets.SetSize(bucketCount);
for (int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++)
{
m_Buckets[ndxBucket].SetSize(initCount);
m_Buckets[ndxBucket].SetGrowSize(growCount);
}
m_bPowerOfTwo = IsPowerOfTwo(bucketCount);
m_ModMask = m_bPowerOfTwo ? (bucketCount - 1) : 0;
}
template<class Data, typename C, typename K>
CUtlHash<Data, C, K>::~CUtlHash()
{
Purge();
}
template<class Data, typename C, typename K>
inline bool CUtlHash<Data, C, K>::IsValidHandle(UtlHashHandle_t handle) const
{
int ndxBucket = GetBucketIndex(handle);
int ndxKeyData = GetKeyDataIndex(handle);
if ( (ndxBucket < m_Buckets.Count()))
{
if ( (ndxKeyData < m_Buckets[ndxBucket].Count()))
return true;
}
return false;
}
template<class Data, typename C, typename K>
inline int CUtlHash<Data, C, K>::Count(void) const
{
int count = 0;
int bucketCount = m_Buckets.Count();
for (int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++)
{
count += m_Buckets[ndxBucket].Count();
}
return count;
}
template<class Data, typename C, typename K>
inline int CUtlHash<Data, C, K>::GetBucketIndex(UtlHashHandle_t handle) const
{
return (((handle >> 16) & 0x0000ffff));
}
template<class Data, typename C, typename K>
inline int CUtlHash<Data, C, K>::GetKeyDataIndex(UtlHashHandle_t handle) const
{
return (handle & 0x0000ffff);
}
template<class Data, typename C, typename K>
inline UtlHashHandle_t CUtlHash<Data, C, K>::BuildHandle(int ndxBucket, int ndxKeyData) const
{
assert((ndxBucket >= 0) && (ndxBucket < 65536));
assert((ndxKeyData >= 0) && (ndxKeyData < 65536));
UtlHashHandle_t handle = ndxKeyData;
handle |= (ndxBucket << 16);
return handle;
}
template<class Data, typename C, typename K>
inline void CUtlHash<Data, C, K>::Purge(void)
{
int bucketCount = m_Buckets.Count();
for (int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++)
{
m_Buckets[ndxBucket].Purge();
}
}
template<class Data, typename C, typename K>
inline bool CUtlHash<Data, C, K>::DoFind(Data const& src, unsigned int* pBucket, int* pIndex) const
{
unsigned int key = m_KeyFunc(src);
unsigned int ndxBucket;
if (m_bPowerOfTwo)
{
*pBucket = ndxBucket = (key & m_ModMask);
}
else
{
int bucketCount = m_Buckets.Count();
*pBucket = ndxBucket = key % bucketCount;
}
int ndxKeyData;
const CUtlVector<Data>& bucket = m_Buckets[ndxBucket];
int keyDataCount = bucket.Count();
for (ndxKeyData = 0; ndxKeyData < keyDataCount; ndxKeyData++)
{
if (m_CompareFunc(bucket.Element(ndxKeyData), src))
break;
}
if (ndxKeyData == keyDataCount)
return false;
*pIndex = ndxKeyData;
return true;
}
template<class Data, typename C, typename K>
inline UtlHashHandle_t CUtlHash<Data, C, K>::Find(Data const& src) const
{
unsigned int ndxBucket;
int ndxKeyData;
if (DoFind(src, &ndxBucket, &ndxKeyData))
{
return (BuildHandle(ndxBucket, ndxKeyData));
}
return (InvalidHandle());
}
template<class Data, typename C, typename K>
inline UtlHashHandle_t CUtlHash<Data, C, K>::Insert(Data const& src)
{
unsigned int ndxBucket;
int ndxKeyData;
if (DoFind(src, &ndxBucket, &ndxKeyData))
{
return (BuildHandle(ndxBucket, ndxKeyData));
}
ndxKeyData = m_Buckets[ndxBucket].AddToTail(src);
return (BuildHandle(ndxBucket, ndxKeyData));
}
template<class Data, typename C, typename K>
inline UtlHashHandle_t CUtlHash<Data, C, K>::Insert(Data const& src, bool* pDidInsert)
{
unsigned int ndxBucket;
int ndxKeyData;
if (DoFind(src, &ndxBucket, &ndxKeyData))
{
*pDidInsert = false;
return (BuildHandle(ndxBucket, ndxKeyData));
}
*pDidInsert = true;
ndxKeyData = m_Buckets[ndxBucket].AddToTail(src);
return (BuildHandle(ndxBucket, ndxKeyData));
}
template<class Data, typename C, typename K>
inline UtlHashHandle_t CUtlHash<Data, C, K>::AllocEntryFromKey(Data const& src)
{
unsigned int ndxBucket;
int ndxKeyData;
if (DoFind(src, &ndxBucket, &ndxKeyData))
{
return (BuildHandle(ndxBucket, ndxKeyData));
}
ndxKeyData = m_Buckets[ndxBucket].AddToTail();
return (BuildHandle(ndxBucket, ndxKeyData));
}
template<class Data, typename C, typename K>
inline void CUtlHash<Data, C, K>::Remove(UtlHashHandle_t handle)
{
assert(IsValidHandle(handle));
int ndxBucket = GetBucketIndex(handle);
int ndxKeyData = GetKeyDataIndex(handle);
if (m_Buckets[ndxBucket].IsValidIndex(ndxKeyData))
{
m_Buckets[ndxBucket].FastRemove(ndxKeyData);
}
}
template<class Data, typename C, typename K>
inline void CUtlHash<Data, C, K>::RemoveAll()
{
int bucketCount = m_Buckets.Count();
for (int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++)
{
m_Buckets[ndxBucket].RemoveAll();
}
}
template<class Data, typename C, typename K>
inline Data& CUtlHash<Data, C, K>::Element(UtlHashHandle_t handle)
{
int ndxBucket = GetBucketIndex(handle);
int ndxKeyData = GetKeyDataIndex(handle);
return (m_Buckets[ndxBucket].Element(ndxKeyData));
}
template<class Data, typename C, typename K>
inline Data const& CUtlHash<Data, C, K>::Element(UtlHashHandle_t handle) const
{
int ndxBucket = GetBucketIndex(handle);
int ndxKeyData = GetKeyDataIndex(handle);
return (m_Buckets[ndxBucket].Element(ndxKeyData));
}
template<class Data, typename C, typename K>
inline Data& CUtlHash<Data, C, K>::operator[](UtlHashHandle_t handle)
{
int ndxBucket = GetBucketIndex(handle);
int ndxKeyData = GetKeyDataIndex(handle);
return (m_Buckets[ndxBucket].Element(ndxKeyData));
}
template<class Data, typename C, typename K>
inline Data const& CUtlHash<Data, C, K>::operator[](UtlHashHandle_t handle) const
{
int ndxBucket = GetBucketIndex(handle);
int ndxKeyData = GetKeyDataIndex(handle);
return (m_Buckets[ndxBucket].Element(ndxKeyData));
}
template<class Data, typename C, typename K>
inline UtlHashHandle_t CUtlHash<Data, C, K>::GetFirstHandle() const
{
return GetNextHandle((UtlHashHandle_t)-1);
}
template<class Data, typename C, typename K>
inline UtlHashHandle_t CUtlHash<Data, C, K>::GetNextHandle(UtlHashHandle_t handle) const
{
++handle;
int bi = GetBucketIndex(handle);
int ki = GetKeyDataIndex(handle);
int nBuckets = m_Buckets.Count();
for (; bi < nBuckets; ++bi)
{
if (ki < m_Buckets[bi].Count())
return BuildHandle(bi, ki);
ki = 0;
}
return InvalidHandle();
}
template<class Data, typename C, typename K>
inline void CUtlHash<Data, C, K>::Log(const char* filename)
{
FILE* pDebugFp;
pDebugFp = fopen(filename, "w");
if (!pDebugFp)
return;
int maxBucketSize = 0;
int numBucketsEmpty = 0;
int bucketCount = m_Buckets.Count();
fprintf(pDebugFp, "\n%d Buckets\n", bucketCount);
for (int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++)
{
int count = m_Buckets[ndxBucket].Count();
if (count > maxBucketSize) { maxBucketSize = count; }
if (count == 0)
numBucketsEmpty++;
fprintf(pDebugFp, "Bucket %d: %d\n", ndxBucket, count);
}
fprintf(pDebugFp, "\nBucketHeads Used: %d\n", bucketCount - numBucketsEmpty);
fprintf(pDebugFp, "Max Bucket Size: %d\n", maxBucketSize);
fclose(pDebugFp);
}
typedef int UtlHashFastHandle_t;
#define UTLHASH_POOL_SCALAR 2
class CUtlHashFastNoHash
{
public:
static int Hash(int key, int bucketMask)
{
return (key & bucketMask);
}
};
class CUtlHashFastGenericHash
{
public:
static int Hash(int key, int bucketMask)
{
return (HashIntConventional(key) & bucketMask);
}
};
template<class Data, class HashFuncs = CUtlHashFastNoHash >
class CUtlHashFast
{
public:
CUtlHashFast();
~CUtlHashFast();
void Purge(void);
static UtlHashFastHandle_t InvalidHandle(void) { return (UtlHashFastHandle_t)~0; }
bool Init(int nBucketCount);
int Count(void);
UtlHashFastHandle_t Insert(unsigned int uiKey, const Data& data);
UtlHashFastHandle_t FastInsert(unsigned int uiKey, const Data& data);
void Remove(UtlHashFastHandle_t hHash);
void RemoveAll(void);
UtlHashFastHandle_t Find(unsigned int uiKey);
Data& Element(UtlHashFastHandle_t hHash);
Data const& Element(UtlHashFastHandle_t hHash) const;
Data& operator[](UtlHashFastHandle_t hHash);
Data const& operator[](UtlHashFastHandle_t hHash) const;
template <typename HashData>
struct HashFastData_t_
{
unsigned int m_uiKey;
HashData m_Data;
};
typedef HashFastData_t_<Data> HashFastData_t;
unsigned int m_uiBucketMask;
CUtlVector<UtlHashFastHandle_t> m_aBuckets;
CUtlFixedLinkedList<HashFastData_t> m_aDataPool;
};
template<class Data, class HashFuncs> CUtlHashFast<Data, HashFuncs>::CUtlHashFast()
{
Purge();
}
template<class Data, class HashFuncs> CUtlHashFast<Data, HashFuncs>::~CUtlHashFast()
{
Purge();
}
template<class Data, class HashFuncs> inline void CUtlHashFast<Data, HashFuncs>::Purge(void)
{
m_aBuckets.Purge();
m_aDataPool.Purge();
}
template<class Data, class HashFuncs> bool CUtlHashFast<Data, HashFuncs>::Init(int nBucketCount)
{
if (!IsPowerOfTwo(nBucketCount))
return false;
m_aBuckets.SetSize(nBucketCount);
for (int iBucket = 0; iBucket < nBucketCount; ++iBucket)
{
m_aBuckets[iBucket] = m_aDataPool.InvalidIndex();
}
m_uiBucketMask = nBucketCount - 1;
int nGrowSize = UTLHASH_POOL_SCALAR * nBucketCount;
m_aDataPool.SetGrowSize(nGrowSize);
return true;
}
template<class Data, class HashFuncs> inline int CUtlHashFast<Data, HashFuncs>::Count(void)
{
return m_aDataPool.Count();
}
template<class Data, class HashFuncs> inline UtlHashFastHandle_t CUtlHashFast<Data, HashFuncs>::Insert(unsigned int uiKey, const Data& data)
{
UtlHashFastHandle_t hHash = Find(uiKey);
if (hHash != InvalidHandle())
return hHash;
return FastInsert(uiKey, data);
}
template<class Data, class HashFuncs> inline UtlHashFastHandle_t CUtlHashFast<Data, HashFuncs>::FastInsert(unsigned int uiKey, const Data& data)
{
int iHashData = m_aDataPool.Alloc(true);
HashFastData_t* pHashData = &m_aDataPool[iHashData];
if (!pHashData)
return InvalidHandle();
pHashData->m_uiKey = uiKey;
pHashData->m_Data = data;
int iBucket = HashFuncs::Hash(uiKey, m_uiBucketMask);
m_aDataPool.LinkBefore(m_aBuckets[iBucket], iHashData);
m_aBuckets[iBucket] = iHashData;
return iHashData;
}
template<class Data, class HashFuncs> inline void CUtlHashFast<Data, HashFuncs>::Remove(UtlHashFastHandle_t hHash)
{
int iBucket = HashFuncs::Hash(m_aDataPool[hHash].m_uiKey, m_uiBucketMask);
if (m_aBuckets[iBucket] == hHash)
{
m_aBuckets[iBucket] = m_aDataPool.Next(hHash);
}
else
{
m_aDataPool.Unlink(hHash);
}
m_aDataPool.Remove(hHash);
}
template<class Data, class HashFuncs> inline void CUtlHashFast<Data, HashFuncs>::RemoveAll(void)
{
m_aBuckets.RemoveAll();
m_aDataPool.RemoveAll();
}
template<class Data, class HashFuncs> inline UtlHashFastHandle_t CUtlHashFast<Data, HashFuncs>::Find(unsigned int uiKey)
{
int iBucket = HashFuncs::Hash(uiKey, m_uiBucketMask);
for (int iElement = m_aBuckets[iBucket]; iElement != m_aDataPool.InvalidIndex(); iElement = m_aDataPool.Next(iElement))
{
if (m_aDataPool[iElement].m_uiKey == uiKey)
return iElement;
}
return InvalidHandle();
}
template<class Data, class HashFuncs> inline Data& CUtlHashFast<Data, HashFuncs>::Element(UtlHashFastHandle_t hHash)
{
return (m_aDataPool[hHash].m_Data);
}
template<class Data, class HashFuncs> inline Data const& CUtlHashFast<Data, HashFuncs>::Element(UtlHashFastHandle_t hHash) const
{
return (m_aDataPool[hHash].m_Data);
}
template<class Data, class HashFuncs> inline Data& CUtlHashFast<Data, HashFuncs>::operator[](UtlHashFastHandle_t hHash)
{
return (m_aDataPool[hHash].m_Data);
}
template<class Data, class HashFuncs> inline Data const& CUtlHashFast<Data, HashFuncs>::operator[](UtlHashFastHandle_t hHash) const
{
return (m_aDataPool[hHash].m_Data);
}
typedef int UtlHashFixedHandle_t;
template <int NUM_BUCKETS>
class CUtlHashFixedGenericHash
{
public:
static int Hash(int key, int bucketMask)
{
int hash = HashIntConventional(key);
if (NUM_BUCKETS <= USHRT_MAX)
{
hash ^= (hash >> 16);
}
if (NUM_BUCKETS <= UCHAR_MAX)
{
hash ^= (hash >> 8);
}
return (hash & bucketMask);
}
};
template<class Data, int NUM_BUCKETS, class CHashFuncs = CUtlHashFastNoHash >
class CUtlHashFixed
{
public:
CUtlHashFixed();
~CUtlHashFixed();
void Purge(void);
static UtlHashFixedHandle_t InvalidHandle(void) { return (UtlHashFixedHandle_t)~0; }
int Count(void);
UtlHashFixedHandle_t Insert(unsigned int uiKey, const Data& data);
UtlHashFixedHandle_t FastInsert(unsigned int uiKey, const Data& data);
void Remove(UtlHashFixedHandle_t hHash);
void RemoveAll(void);
UtlHashFixedHandle_t Find(unsigned int uiKey);
Data& Element(UtlHashFixedHandle_t hHash);
Data const& Element(UtlHashFixedHandle_t hHash) const;
Data& operator[](UtlHashFixedHandle_t hHash);
Data const& operator[](UtlHashFixedHandle_t hHash) const;
template <typename Data_t>
struct HashFixedData_t_
{
unsigned int m_uiKey;
Data_t m_Data;
};
typedef HashFixedData_t_<Data> HashFixedData_t;
enum
{
BUCKET_MASK = NUM_BUCKETS - 1
};
CUtlPtrLinkedList<HashFixedData_t> m_aBuckets[NUM_BUCKETS];
int m_nElements;
};
template<class Data, int NUM_BUCKETS, class HashFuncs> CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::CUtlHashFixed()
{
Purge();
}
template<class Data, int NUM_BUCKETS, class HashFuncs> CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::~CUtlHashFixed()
{
Purge();
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline void CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::Purge(void)
{
RemoveAll();
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline int CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::Count(void)
{
return m_nElements;
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline UtlHashFixedHandle_t CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::Insert(unsigned int uiKey, const Data& data)
{
UtlHashFixedHandle_t hHash = Find(uiKey);
if (hHash != InvalidHandle())
return hHash;
return FastInsert(uiKey, data);
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline UtlHashFixedHandle_t CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::FastInsert(unsigned int uiKey, const Data& data)
{
int iBucket = HashFuncs::Hash(uiKey, NUM_BUCKETS - 1);
UtlPtrLinkedListIndex_t iElem = m_aBuckets[iBucket].AddToHead();
HashFixedData_t* pHashData = &m_aBuckets[iBucket][iElem];
Assert((UtlPtrLinkedListIndex_t)pHashData == iElem);
pHashData->m_uiKey = uiKey;
pHashData->m_Data = data;
m_nElements++;
return (UtlHashFixedHandle_t)pHashData;
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline void CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::Remove(UtlHashFixedHandle_t hHash)
{
HashFixedData_t* pHashData = (HashFixedData_t*)hHash;
Assert(Find(pHashData->m_uiKey) != InvalidHandle());
int iBucket = HashFuncs::Hash(pHashData->m_uiKey, NUM_BUCKETS - 1);
m_aBuckets[iBucket].Remove((UtlPtrLinkedListIndex_t)pHashData);
m_nElements--;
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline void CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::RemoveAll(void)
{
for (int i = 0; i < NUM_BUCKETS; i++)
{
m_aBuckets[i].RemoveAll();
}
m_nElements = 0;
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline UtlHashFixedHandle_t CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::Find(unsigned int uiKey)
{
int iBucket = HashFuncs::Hash(uiKey, NUM_BUCKETS - 1);
CUtlPtrLinkedList<HashFixedData_t>& bucket = m_aBuckets[iBucket];
for (UtlPtrLinkedListIndex_t iElement = bucket.Head(); iElement != bucket.InvalidIndex(); iElement = bucket.Next(iElement))
{
if (bucket[iElement].m_uiKey == uiKey)
return (UtlHashFixedHandle_t)iElement;
}
return InvalidHandle();
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline Data& CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::Element(UtlHashFixedHandle_t hHash)
{
return ((HashFixedData_t*)hHash)->m_Data;
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline Data const& CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::Element(UtlHashFixedHandle_t hHash) const
{
return ((HashFixedData_t*)hHash)->m_Data;
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline Data& CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::operator[](UtlHashFixedHandle_t hHash)
{
return ((HashFixedData_t*)hHash)->m_Data;
}
template<class Data, int NUM_BUCKETS, class HashFuncs> inline Data const& CUtlHashFixed<Data, NUM_BUCKETS, HashFuncs>::operator[](UtlHashFixedHandle_t hHash) const
{
return ((HashFixedData_t*)hHash)->m_Data;
}
#endif